public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings
@ 2023-09-20  0:57 Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 01/28] MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions Taylor Beebe
                   ` (27 more replies)
  0 siblings, 28 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel
  Cc: Abner Chang, Andrei Warkentin, Anatol Belski, Andrew Fish,
	Anthony Perard, Ard Biesheuvel, Corvin Köhne, Dandan Bi,
	Eric Dong, Erdem Aktas, Gerd Hoffmann, Guo Dong, Gua Guo,
	James Bottomley, James Lu, Jian J Wang, Jianyong Wu, Jiewen Yao,
	Jordan Justen, Julien Grall, Leif Lindholm, Liming Gao,
	Michael Roth, Min Xu, Peter Grehan, Rahul Kumar, Ray Ni,
	Rebecca Cran, Sami Mujawar, Sean Rhodes, Sunil V L, Tom Lendacky

v4:
-Update the memory protection profiles to align the allocated pools to the
tail guard by default (patch 20).

- Add a patch to create MemoryProtectionConfigLib which consolidates code
for parsing the fw_cfg for the memory protection profile strings (patch 22).

-Move the update to add QemuFwCfgParseString() to its own patch (patch 21).

v3:
- Fix incorrect ordering of the SetMemoryProtectionsLib profile definitions
midway through the patch series by using C99 instantialization.

- Update OvmfPkg to use the Release profile by default.

- Update the method by which platform initialization in OvmfPkg associates
the input FwCfg data with the platform memory protection settings. The new
way will try to match the string in FwCfg with the profile name. If no match
is found, the default profile is used.

- SetMemoryProtectionsLib profile struct definition uses CHAR8 for the
description and name strings instead of CHAR16.

- A new patch has been added to copy the PEI PCD database from the HOB to a
new buffer so HOB memory is not written to.

- Move the call to protect HOB memory after NX and Heap Guard instantialization
has occurred to avoid them overwritting the HOB protections.

v2:
- The previous version required the platform manage the HOB creation
during PEI phase. v2 adds a new library, SetMemoryProtectionsLib, which
offers an interface for setting, locking, and checking the memory protections
for the boot. The settings are still backed by a HOB entry. SetMemoryProtectionsLib
is a PEI/SEC only library as protections must be locked in by DxeHandoff().

- The previous version had a separate MM and DXE library for getting the platform
memory protection settings and populating the global for access. v2 consolidates
these two libraries into a single GetMemoryProtectionsLib which has DXE and MM
instances. The global populated is a union of the MM and DXE settings. The first
4 bytes of the union is the signature used to identify whether the global contains
the DXE or MM settings.

- Add a patch to page-align the DXE allocated HOB list and apply RO and NX
to it during memory protection initialization.

- Add a patch which checks the debug print level before executing the memory
map dump routine. This saves several seconds of boot time on debug builds with
memory protections active.

- Remove unnecessary code consolidation from the patch series to make it easier
to review. The code consolidation will be in a future patch series.

- Add the ability to set the memory protection profile via the fw_cfg QEMU
interface on OvmfPkg platforms. The cfg parsing library needs to be ported to
ArmVirtPkg to enable the same functionality on ARM virtual platforms. ArmVirtPkg
will use the Release protection profile by default.

-Restructure the patch series to ensure bisectability as the memory logic
is transitioned to use the Get and Set libraries one package at a time.
The memory protection PCDs are still removed in this patch series to avoid
confusing the interface and remove the ties to the legacy implementation.

v1:

In the past, memory protection settings were configured via FixedAtBuild PCDs,
which resulted in a build-time configuration of memory mitigations. This
approach limited the flexibility of applying mitigations to the
system and made it difficult to update or adjust the settings post-build.

In a design, the configuration interface has been revised to allow for dynamic
configuration. This is achieved by setting memory protections via a library
interface which stores/updates the memory protection settings in
a GUIDed HOB, which is then consumed during and after DXE handoff.

ArmVirtPkg will use the Release profile.

Reference: https://github.com/tianocore/edk2/pull/4566

Cc: Abner Chang <abner.chang@amd.com>
Cc: Andrei Warkentin <andrei.warkentin@intel.com>
Cc: Anatol Belski <anbelski@linux.microsoft.com>
Cc: Andrew Fish <afish@apple.com>
Cc: Anthony Perard <anthony.perard@citrix.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Corvin Köhne <corvink@freebsd.org>
Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Guo Dong <guo.dong@intel.com>
Cc: Gua Guo <gua.guo@intel.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: James Lu <james.lu@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Jianyong Wu <jianyong.wu@arm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Julien Grall <julien@xen.org>
Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Michael Roth <michael.roth@amd.com>
Cc: Min Xu <min.m.xu@intel.com>
Cc: Peter Grehan <grehan@freebsd.org>
Cc: Rahul Kumar <rahul1.kumar@intel.com> 
Cc: Ray Ni <ray.ni@intel.com>
Cc: Rebecca Cran <rebecca@bsdio.com>
Cc: Sami Mujawar <sami.mujawar@arm.com>
Cc: Sean Rhodes <sean@starlabs.systems>
Cc: Sunil V L <sunilvl@ventanamicro.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>

Taylor Beebe (28):
  MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions
  MdeModulePkg: Define SetMemoryProtectionsLib and
    GetMemoryProtectionsLib
  MdeModulePkg: Add NULL Instances for Get/SetMemoryProtectionsLib
  MdeModulePkg: Implement SetMemoryProtectionsLib and
    GetMemoryProtectionsLib
  MdeModulePkg: Copy PEI PCD Database Into New Buffer
  MdeModulePkg: Apply Protections to the HOB List
  MdeModulePkg: Check Print Level Before Dumping GCD Memory Map
  UefiCpuPkg: Always Set Stack Guard in MpPei Init
  ArmVirtPkg: Add Memory Protection Library Definitions to Platforms
  OvmfPkg: Add Memory Protection Library Definitions to Platforms
  OvmfPkg: Apply Memory Protections via SetMemoryProtectionsLib
  OvmfPkg: Update PeilessStartupLib to use SetMemoryProtectionsLib
  UefiPayloadPkg: Update DXE Handoff to use SetMemoryProtectionsLib
  MdeModulePkg: Update DXE Handoff to use SetMemoryProtectionsLib
  ArmPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs
  EmulatorPkg: Use GetMemoryProtectionsLib instead of Memory Protection
    PCDs
  OvmfPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs
  UefiCpuPkg: Use GetMemoryProtectionsLib instead of Memory Protection
    PCDs
  MdeModulePkg: Use GetMemoryProtectionsLib instead of Memory Protection
    PCDs
  MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  OvmfPkg: Add QemuFwCfgParseString to QemuFwCfgSimpleParserLib
  OvmfPkg: Add MemoryProtectionConfigLib
  OvmfPkg: Enable Choosing Memory Protection Profile via QemuCfg
  ArmVirtPkg: Apply Memory Protections via SetMemoryProtectionsLib
  MdeModulePkg: Delete PCD Profile from SetMemoryProtectionsLib
  OvmfPkg: Delete Memory Protection PCDs
  ArmVirtPkg: Delete Memory Protection PCDs
  MdeModulePkg: Delete Memory Protection PCDs

 ArmPkg/Drivers/CpuDxe/CpuDxe.c                                                           |   5 +-
 ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c                                                |  11 +-
 MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c                                                  |   4 +-
 MdeModulePkg/Core/Dxe/Gcd/Gcd.c                                                          |  22 +-
 MdeModulePkg/Core/Dxe/Mem/HeapGuard.c                                                    |  46 +-
 MdeModulePkg/Core/Dxe/Mem/Page.c                                                         |   2 +-
 MdeModulePkg/Core/Dxe/Mem/Pool.c                                                         |   4 +-
 MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c                                            |  96 ++-
 MdeModulePkg/Core/DxeIplPeim/DxeHandoff.c                                                |   4 +-
 MdeModulePkg/Core/DxeIplPeim/DxeLoad.c                                                   |   2 +
 MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c                                          |   9 +-
 MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c                                           |   6 +-
 MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c                                         |  16 +-
 MdeModulePkg/Core/PiSmmCore/HeapGuard.c                                                  |  29 +-
 MdeModulePkg/Core/PiSmmCore/Pool.c                                                       |   4 +-
 MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.c                | 158 ++++
 MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.c               |  29 +
 MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.c                 | 124 ++++
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c                   | 781 ++++++++++++++++++++
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.c               | 144 ++++
 MdeModulePkg/Universal/PCD/Dxe/Service.c                                                 |   6 +-
 OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c                                                      |   5 +-
 OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.c                    | 118 +++
 OvmfPkg/Library/PeilessStartupLib/DxeLoad.c                                              |   6 +-
 OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c                                       |  22 +-
 OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c                                    |  26 +-
 OvmfPkg/Library/PlatformInitLib/Platform.c                                               |  15 -
 OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParser.c                         |  11 +
 OvmfPkg/PlatformPei/IntelTdx.c                                                           |   2 -
 OvmfPkg/PlatformPei/Platform.c                                                           |  38 +-
 OvmfPkg/QemuVideoDxe/VbeShim.c                                                           |   3 +-
 OvmfPkg/TdxDxe/TdxDxe.c                                                                  |   7 +-
 UefiCpuPkg/CpuDxe/CpuDxe.c                                                               |   2 +-
 UefiCpuPkg/CpuDxe/CpuMp.c                                                                |   2 +-
 UefiCpuPkg/CpuMpPei/CpuMpPei.c                                                           |   8 +-
 UefiCpuPkg/CpuMpPei/CpuPaging.c                                                          |  16 +-
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c       |   6 +-
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c      |  15 +
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c      |  21 +
 UefiCpuPkg/Library/MpInitLib/DxeMpLib.c                                                  |   3 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c                                                 |   2 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c                                       |  13 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c                                                   |   2 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c                                                  |   2 +-
 UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c                                       |  11 +-
 UefiPayloadPkg/UefiPayloadEntry/LoadDxeCore.c                                            |   2 +
 UefiPayloadPkg/UefiPayloadEntry/X64/DxeLoadFunc.c                                        |   8 +-
 UefiPayloadPkg/UefiPayloadEntry/X64/VirtualMemory.c                                      |  15 +-
 ArmPkg/ArmPkg.dsc                                                                        |   1 +
 ArmPkg/Drivers/CpuDxe/CpuDxe.inf                                                         |   2 +-
 ArmVirtPkg/ArmVirt.dsc.inc                                                               |  21 +-
 ArmVirtPkg/ArmVirtCloudHv.dsc                                                            |   5 -
 ArmVirtPkg/ArmVirtQemu.dsc                                                               |   5 -
 ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf                                              |   1 +
 EmulatorPkg/EmulatorPkg.dsc                                                              |   3 +-
 MdeModulePkg/Core/Dxe/DxeMain.h                                                          |   1 +
 MdeModulePkg/Core/Dxe/DxeMain.inf                                                        |   9 +-
 MdeModulePkg/Core/DxeIplPeim/DxeIpl.h                                                    |   3 +
 MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf                                                  |  11 +-
 MdeModulePkg/Core/PiSmmCore/PiSmmCore.h                                                  |   1 +
 MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf                                                |   4 +-
 MdeModulePkg/Include/Guid/MemoryProtectionSettings.h                                     | 216 ++++++
 MdeModulePkg/Include/Library/GetMemoryProtectionsLib.h                                   |  83 +++
 MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h                                   | 157 ++++
 MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf              |  34 +
 MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf             |  25 +
 MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf               |  34 +
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf                 |  37 +
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf             |  25 +
 MdeModulePkg/MdeModulePkg.dec                                                            | 182 +----
 MdeModulePkg/MdeModulePkg.dsc                                                            |   7 +
 MdeModulePkg/MdeModulePkg.uni                                                            | 153 ----
 OvmfPkg/AmdSev/AmdSevX64.dsc                                                             |   4 +-
 OvmfPkg/Bhyve/BhyveX64.dsc                                                               |   4 +-
 OvmfPkg/Bhyve/PlatformPei/PlatformPei.inf                                                |   1 -
 OvmfPkg/CloudHv/CloudHvX64.dsc                                                           |   4 +-
 OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf                                                    |   4 +-
 OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc                                    |  16 +
 OvmfPkg/Include/Library/MemoryProtectionConfigLib.h                                      |  49 ++
 OvmfPkg/Include/Library/PlatformInitLib.h                                                |  13 -
 OvmfPkg/Include/Library/QemuFwCfgSimpleParserLib.h                                       |   8 +
 OvmfPkg/IntelTdx/IntelTdxX64.dsc                                                         |   5 +-
 OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.inf                  |  35 +
 OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf                                  |   6 +-
 OvmfPkg/Microvm/MicrovmX64.dsc                                                           |   5 +-
 OvmfPkg/OvmfPkg.dec                                                                      |   4 +
 OvmfPkg/OvmfPkgIa32.dsc                                                                  |   4 +-
 OvmfPkg/OvmfPkgIa32X64.dsc                                                               |   4 +-
 OvmfPkg/OvmfPkgX64.dsc                                                                   |   4 +-
 OvmfPkg/OvmfXen.dsc                                                                      |   5 +-
 OvmfPkg/PlatformCI/PlatformBuildLib.py                                                   |   8 +
 OvmfPkg/PlatformPei/PlatformPei.inf                                                      |   3 +-
 OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf                                                    |   2 +-
 OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc                                                      |  13 -
 OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc                                                      |   2 +
 OvmfPkg/TdxDxe/TdxDxe.inf                                                                |   1 -
 UefiCpuPkg/CpuDxe/CpuDxe.h                                                               |  11 +-
 UefiCpuPkg/CpuDxe/CpuDxe.inf                                                             |   4 +-
 UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf                                               |   3 -
 UefiCpuPkg/CpuMpPei/CpuMpPei.h                                                           |   3 +-
 UefiCpuPkg/CpuMpPei/CpuMpPei.inf                                                         |   1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf                  |   1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf                  |   1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf               |   1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf                  |   1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h             |  13 +-
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf |   2 +-
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf |   2 +-
 UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf                                            |   3 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf                                             |   3 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h                                           |   9 +-
 UefiCpuPkg/UefiCpuPkg.dec                                                                |   7 +-
 UefiCpuPkg/UefiCpuPkg.dsc                                                                |   2 +
 UefiCpuPkg/UefiCpuPkg.uni                                                                |  10 +-
 UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h                                       |   1 +
 UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf                                     |   9 +-
 UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf                                |   9 +-
 UefiPayloadPkg/UefiPayloadPkg.dsc                                                        |  12 +
 118 files changed, 2523 insertions(+), 692 deletions(-)
 create mode 100644 MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.c
 create mode 100644 MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.c
 create mode 100644 MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.c
 create mode 100644 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
 create mode 100644 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.c
 create mode 100644 OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.c
 create mode 100644 MdeModulePkg/Include/Guid/MemoryProtectionSettings.h
 create mode 100644 MdeModulePkg/Include/Library/GetMemoryProtectionsLib.h
 create mode 100644 MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
 create mode 100644 MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf
 create mode 100644 MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
 create mode 100644 MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf
 create mode 100644 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
 create mode 100644 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf
 create mode 100644 OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
 create mode 100644 OvmfPkg/Include/Library/MemoryProtectionConfigLib.h
 create mode 100644 OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.inf

-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108862): https://edk2.groups.io/g/devel/message/108862
Mute This Topic: https://groups.io/mt/101469937/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 01/28] MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 02/28] MdeModulePkg: Define SetMemoryProtectionsLib and GetMemoryProtectionsLib Taylor Beebe
                   ` (26 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao

These headers provide settings definitions for memory protections,
settings profiles for easily enabling memory protections,
and the GUIDs used for producing the memory protection HOB entry.

The settings options are functionally 1:1 with the existing
PCD bitfield definitions. Instead of setting a fixed at build
PCD, memory protections will be set via a HOB
at runtime.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
---
 MdeModulePkg/Include/Guid/MemoryProtectionSettings.h | 216 ++++++++++++++++++++
 MdeModulePkg/MdeModulePkg.dec                        |   5 +
 2 files changed, 221 insertions(+)

diff --git a/MdeModulePkg/Include/Guid/MemoryProtectionSettings.h b/MdeModulePkg/Include/Guid/MemoryProtectionSettings.h
new file mode 100644
index 000000000000..889e87011fbf
--- /dev/null
+++ b/MdeModulePkg/Include/Guid/MemoryProtectionSettings.h
@@ -0,0 +1,216 @@
+/** @file
+Defines memory protection settings guid and struct for DXE and MM.
+
+Copyright (C) Microsoft Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef MEMORY_PROTECTION_SETTINGS_H_
+#define MEMORY_PROTECTION_SETTINGS_H_
+
+#define OEM_RESERVED_MPS_MEMORY_TYPE  EfiMaxMemoryType
+#define OS_RESERVED_MPS_MEMORY_TYPE   (EfiMaxMemoryType + 1)
+#define MAX_MPS_MEMORY_TYPE           (EfiMaxMemoryType + 2)
+#define MPS_MEMORY_TYPE_BUFFER_SIZE   (MAX_MPS_MEMORY_TYPE * sizeof (BOOLEAN))
+
+// Current DXE iteration of MEMORY_PROTECTION_SETTINGS
+#define DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION  1
+
+// Current MM iteration of MEMORY_PROTECTION_SETTINGS
+#define MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION  1
+
+#define DXE_MEMORY_PROTECTION_SIGNATURE  SIGNATURE_32('D', 'M', 'P', 'S')
+#define MM_MEMORY_PROTECTION_SIGNATURE   SIGNATURE_32('M', 'M', 'P', 'S')
+
+typedef UINT8   MEMORY_PROTECTION_SETTINGS_VERSION;
+typedef UINT32  MEMORY_PROTECTION_SETTINGS_SIGNATURE;
+
+typedef struct {
+  BOOLEAN    Enabled            : 1;
+  BOOLEAN    DisableEndOfDxe    : 1;
+  BOOLEAN    NonstopModeEnabled : 1;
+} DXE_NULL_DETECTION_POLICY;
+
+typedef struct {
+  BOOLEAN    ProtectImageFromUnknown : 1;
+  BOOLEAN    ProtectImageFromFv      : 1;
+} DXE_IMAGE_PROTECTION_POLICY;
+
+typedef struct {
+  BOOLEAN    PageGuardEnabled        : 1;
+  BOOLEAN    PoolGuardEnabled        : 1;
+  BOOLEAN    FreedMemoryGuardEnabled : 1;
+  BOOLEAN    NonstopModeEnabled      : 1;
+  BOOLEAN    GuardAlignedToTail      : 1;
+} DXE_HEAP_GUARD_POLICY;
+
+typedef struct {
+  BOOLEAN    Enabled            : 1;
+  BOOLEAN    NonstopModeEnabled : 1;
+} MM_NULL_DETECTION_POLICY;
+
+typedef struct {
+  BOOLEAN    PageGuardEnabled   : 1;
+  BOOLEAN    PoolGuardEnabled   : 1;
+  BOOLEAN    NonstopModeEnabled : 1;
+  BOOLEAN    GuardAlignedToTail : 1;
+} MM_HEAP_GUARD_POLICY;
+
+typedef struct {
+  BOOLEAN    EnabledForType[MAX_MPS_MEMORY_TYPE];
+} MPS_MEMORY_TYPES;
+
+//
+// Memory Protection Settings struct
+//
+typedef struct {
+  // This signature is used to identify the memory protection settings structure.
+  MEMORY_PROTECTION_SETTINGS_SIGNATURE    Signature;
+
+  // The current version of the structure definition. This is used to ensure there isn't a
+  // definition mismatch if modules have differing iterations of this header. When creating
+  // this struct, use the DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION macro.
+  MEMORY_PROTECTION_SETTINGS_VERSION      StructVersion;
+
+  // If enabled, the page at the top of the stack will be invalidated to catch stack overflow.
+  BOOLEAN                                 CpuStackGuardEnabled;
+
+  // If enabled, the stack will be marked non-executable.
+  BOOLEAN                                 StackExecutionProtectionEnabled;
+
+  // If enabled, accessing the NULL address in UEFI will be caught by marking
+  // the NULL page as not present.
+  //   .NullDetectionEnabled    : Enable NULL pointer detection.
+  //   .DisableEndOfDxe         : Disable NULL pointer detection just after EndOfDxe.
+  //                              This is a workaround for those unsolvable NULL access issues in
+  //                              OptionROM, boot loader, etc. It can also help to avoid unnecessary
+  //                              exception caused by legacy memory (0-4095) access after EndOfDxe,
+  //                              such as Windows 7 boot on Qemu.
+  //   .NonstopModeEnabled      : If enabled the debug flag will be raised when a fault occurs
+  //                              to break into debugger.
+  DXE_NULL_DETECTION_POLICY    NullPointerDetection;
+
+  // Set image protection policy.
+  //
+  //  .ProtectImageFromUnknown          : If set, images from unknown devices will be protected by
+  //                                      DxeCore if they are aligned. The code section becomes
+  //                                      read-only, and the data section becomes non-executable.
+  //  .ProtectImageFromFv               : If set, images from firmware volumes will be protected by
+  //                                      DxeCore if they are aligned. The code section becomes
+  //                                      read-only, and the data section becomes non-executable.
+  DXE_IMAGE_PROTECTION_POLICY    ImageProtection;
+
+  // If a bit is set, memory regions of the associated type will be mapped non-executable.
+  //
+  // The execution protection setting for EfiBootServicesData and EfiConventionalMemory must
+  // be the same.
+  MPS_MEMORY_TYPES               ExecutionProtection;
+
+  //  Configures general heap guard behavior.
+  //
+  //  .PageGuardEnabled         : Enable page guard.
+  //  .PoolGuardEnabled         : Enable pool guard.
+  //  .FreedMemoryGuardEnabled  : Enable freed-memory guard (Use-After-Free memory detection).
+  //  .NonstopModeEnabled       : If enabled the debug flag will be raised when a fault occurs
+  //                              to break into debugger.
+  //  .GuardAlignedToTail       : TRUE if the pool is aligned to tail guard page. If FALSE, the
+  //                              pool is aligned to head guard page.
+  //
+  //  Note:
+  //  a) Due to the limit of pool memory implementation and the alignment
+  //     requirement of UEFI spec, HeapGuard.GuardAlignedToTail is a try-best
+  //     setting which cannot guarantee that the returned pool is exactly
+  //     adjacent to head or tail guard page.
+  //  b) Freed-memory guard and pool/page guard cannot be enabled
+  //     at the same time.
+  DXE_HEAP_GUARD_POLICY    HeapGuard;
+
+  // Indicates which type allocation need guard page.
+  //
+  // If bit is set, a head guard page and a tail guard page will be added just
+  // before and after corresponding type of pages which the allocated pool occupies,
+  // if there's enough free memory for all of them.
+  //
+  // These settings are only valid if HeapGuard.PoolGuardEnabled is TRUE.
+  MPS_MEMORY_TYPES    PoolGuard;
+
+  // Indicates which type allocation need guard page.
+  //
+  // If a bit is set, a head guard page and a tail guard page will be added just
+  // before and after corresponding type of pages allocated if there's enough
+  // free pages for all of them.
+  //
+  // These settings are only valid if HeapGuard.PageGuardEnabled is TRUE.
+  MPS_MEMORY_TYPES    PageGuard;
+} DXE_MEMORY_PROTECTION_SETTINGS;
+
+//
+// Memory Protection Settings struct
+//
+typedef struct {
+  // This signature is used to identify the memory protection settings structure.
+  MEMORY_PROTECTION_SETTINGS_SIGNATURE    Signature;
+
+  // The current version of the structure definition. This is used to ensure there isn't a
+  // definition mismatch if modules have differing iterations of this header. When creating
+  // this struct, use the MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION macro.
+  MEMORY_PROTECTION_SETTINGS_VERSION      StructVersion;
+
+  // If enabled, accessing the NULL address in MM will be caught by marking
+  // the NULL page as not present.
+  //   .NullDetectionEnabled    : Enable NULL pointer detection.
+  //   .NonstopModeEnabled      : If enabled the debug flag will be raised when a fault occurs
+  //                              to break into debugger.
+  MM_NULL_DETECTION_POLICY                NullPointerDetection;
+
+  //  Configures general heap guard behavior.
+  //
+  // Note:
+  //  a) Due to the limit of pool memory implementation and the alignment
+  //     requirement of UEFI spec, HeapGuard.GuardAlignedToTail is a try-best
+  //     setting which cannot guarantee that the returned pool is exactly
+  //     adjacent to head or tail guard page.
+  //
+  //  .PageGuardEnabled          : Enable page guard.
+  //  .PoolGuardEnabled          : Enable pool guard.
+  //  .NonstopModeEnabled        : If enabled the debug flag will be raised when a fault occurs
+  //                               to break into debugger.
+  //  .GuardAlignedToTail        : TRUE if the pool is aligned to tail guard page. If FALSE, the
+  //                               pool is aligned to head guard page.
+  MM_HEAP_GUARD_POLICY    HeapGuard;
+
+  // Indicates which type allocation need guard page.
+  //
+  // If bit is set, a head guard page and a tail guard page will be added just
+  // before and after corresponding type of pages which the allocated pool occupies,
+  // if there's enough free memory for all of them.
+  //
+  // These settings are only valid if PoolGuardEnabled is TRUE in HeapGuard.
+  MPS_MEMORY_TYPES    PoolGuard;
+
+  // Indicates which type allocation need guard page.
+  //
+  // If a bit is set, a head guard page and a tail guard page will be added just
+  // before and after corresponding type of pages allocated if there's enough
+  // free pages for all of them.
+  //
+  // This bitfield is only valid if PageGuardEnabled is TRUE in HeapGuard.
+  MPS_MEMORY_TYPES    PageGuard;
+} MM_MEMORY_PROTECTION_SETTINGS;
+
+typedef struct {
+  // The memory protection settings in the SMM and Standalone MM environment
+  MM_MEMORY_PROTECTION_SETTINGS     Mm;
+  // The memory protection settings in the DXE environment
+  DXE_MEMORY_PROTECTION_SETTINGS    Dxe;
+} MEMORY_PROTECTION_SETTINGS;
+
+#define MEMORY_PROTECTION_SETTINGS_GUID  \
+  { \
+    { 0x9ABFD639, 0xD1D0, 0x4EFF, { 0xBD, 0xB6, 0x7E, 0xC4, 0x19, 0x0D, 0x17, 0xD5 } } \
+  }
+
+extern GUID  gMemoryProtectionSettingsGuid;
+
+#endif
diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index dd182c02fdf6..5e1a0388bed3 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -399,6 +399,11 @@ [Guids]
   ## Include/Guid/EndofS3Resume.h
   gEdkiiEndOfS3ResumeGuid = { 0x96f5296d, 0x05f7, 0x4f3c, {0x84, 0x67, 0xe4, 0x56, 0x89, 0x0e, 0x0c, 0xb5 } }
 
+  ## Memory Protection Settings Guid. Used to create and fetch the memory protection settings HOB entry.
+  #
+  # Include/Guid/MemoryProtectionSettings
+  gMemoryProtectionSettingsGuid = { 0x9ABFD639, 0xD1D0, 0x4EFF, { 0xBD, 0xB6, 0x7E, 0xC4, 0x19, 0x0D, 0x17, 0xD5 }}
+
   ## Used (similar to Variable Services) to communicate policies to the enforcement engine.
   # {DA1B0D11-D1A7-46C4-9DC9-F3714875C6EB}
   gVarCheckPolicyLibMmiHandlerGuid = { 0xda1b0d11, 0xd1a7, 0x46c4, { 0x9d, 0xc9, 0xf3, 0x71, 0x48, 0x75, 0xc6, 0xeb }}
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108863): https://edk2.groups.io/g/devel/message/108863
Mute This Topic: https://groups.io/mt/101469938/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 02/28] MdeModulePkg: Define SetMemoryProtectionsLib and GetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 01/28] MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 03/28] MdeModulePkg: Add NULL Instances for Get/SetMemoryProtectionsLib Taylor Beebe
                   ` (25 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao

SetMemoryProtectionsLib is a PEIM which allows platforms to
apply memory protection settings to the current boot.

GetMemoryProtectionsLib has DXE and MM implementations to allow
platforms to query the current memory protection settings via a
global variable populated by the library Implementations.

The global variable is a union of the MM and DXE settings. the
DXE struct is only valid in a DXE module and the MM struct is
only valid in an SMM or Stanalone MM module.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
---
 MdeModulePkg/Include/Library/GetMemoryProtectionsLib.h |  83 +++++++++++
 MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h | 152 ++++++++++++++++++++
 MdeModulePkg/MdeModulePkg.dec                          |   8 ++
 3 files changed, 243 insertions(+)

diff --git a/MdeModulePkg/Include/Library/GetMemoryProtectionsLib.h b/MdeModulePkg/Include/Library/GetMemoryProtectionsLib.h
new file mode 100644
index 000000000000..c8f7084e9c80
--- /dev/null
+++ b/MdeModulePkg/Include/Library/GetMemoryProtectionsLib.h
@@ -0,0 +1,83 @@
+/** @file
+Library for accessing the platform memory protection settings.
+
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef GET_MEMORY_PROTECTION_SETTINGS_LIB_H_
+#define GET_MEMORY_PROTECTION_SETTINGS_LIB_H_
+
+#include <Library/BaseMemoryLib.h>
+#include <Guid/MemoryProtectionSettings.h>
+
+#pragma pack(1)
+
+typedef union {
+  DXE_MEMORY_PROTECTION_SETTINGS    Dxe;
+  MM_MEMORY_PROTECTION_SETTINGS     Mm;
+} MEMORY_PROTECTION_SETTINGS_UNION;
+
+#pragma pack()
+
+// The global used to access current Memory Protection Settings
+extern MEMORY_PROTECTION_SETTINGS_UNION  gMps;
+
+#define MPS_IS_DXE_SIGNATURE_VALID  (gMps.Dxe.Signature == DXE_MEMORY_PROTECTION_SIGNATURE)
+#define MPS_IS_MM_SIGNATURE_VALID   (gMps.Mm.Signature == MM_MEMORY_PROTECTION_SIGNATURE)
+
+#define IS_DXE_PAGE_GUARD_ACTIVE  (MPS_IS_DXE_SIGNATURE_VALID                                                     &&  \
+                                  !IsZeroBuffer (&gMps.Dxe.PageGuard.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE) &&  \
+                                  gMps.Dxe.HeapGuard.PageGuardEnabled)
+
+#define IS_DXE_POOL_GUARD_ACTIVE  (MPS_IS_DXE_SIGNATURE_VALID                                                     &&  \
+                                  !IsZeroBuffer (&gMps.Dxe.PoolGuard.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE) &&  \
+                                  gMps.Dxe.HeapGuard.PoolGuardEnabled)
+
+#define IS_DXE_EXECUTION_PROTECTION_ACTIVE  (MPS_IS_DXE_SIGNATURE_VALID                                           &&  \
+                                            !IsZeroBuffer (&gMps.Dxe.ExecutionProtection.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE))
+
+#define IS_DXE_IMAGE_PROTECTION_ACTIVE  (MPS_IS_DXE_SIGNATURE_VALID                         &&  \
+                                        (gMps.Dxe.ImageProtection.ProtectImageFromFv        ||  \
+                                         gMps.Dxe.ImageProtection.ProtectImageFromUnknown))
+
+#define IS_DXE_MEMORY_PROTECTION_ACTIVE  (MPS_IS_DXE_SIGNATURE_VALID                  &&  \
+                                         (IS_DXE_PAGE_GUARD_ACTIVE                    ||  \
+                                          IS_DXE_POOL_GUARD_ACTIVE                    ||  \
+                                          IS_DXE_EXECUTION_PROTECTION_ACTIVE          ||  \
+                                          IS_DXE_IMAGE_PROTECTION_ACTIVE              ||  \
+                                          gMps.Dxe.CpuStackGuardEnabled               ||  \
+                                          gMps.Dxe.StackExecutionProtectionEnabled    ||  \
+                                          gMps.Dxe.NullPointerDetection.Enabled       ||  \
+                                          gMps.Dxe.HeapGuard.FreedMemoryGuardEnabled))
+
+#define IS_MM_PAGE_GUARD_ACTIVE  (MPS_IS_MM_SIGNATURE_VALID                                                       &&  \
+                                   gMps.Mm.HeapGuard.PageGuardEnabled                                             &&  \
+                                   !IsZeroBuffer (&gMps.Mm.PageGuard.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE))
+
+#define IS_MM_POOL_GUARD_ACTIVE  (MPS_IS_MM_SIGNATURE_VALID                                                       &&  \
+                                  gMps.Mm.HeapGuard.PoolGuardEnabled                                              &&  \
+                                  !IsZeroBuffer (&gMps.Mm.PoolGuard.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE))
+
+#define IS_MM_MEMORY_PROTECTION_ACTIVE  (MPS_IS_MM_SIGNATURE_VALID              &&  \
+                                        (IS_MM_PAGE_GUARD_ACTIVE                ||  \
+                                         IS_MM_POOL_GUARD_ACTIVE                ||  \
+                                         gMps.Mm.NullPointerDetection.Enabled));
+
+/**
+  Populates gMps global. This function is invoked by the library constructor and only needs to be
+  called if library contructors have not yet been invoked.
+
+  @retval EFI_SUCCESS       gMps global was populated.
+  @retval EFI_NOT_FOUND     The gMemoryProtectionSettingsGuid HOB was not found.
+  @retval EFI_ABORTED       The version number of the DXE or MM memory protection settings was invalid.
+  @retval EFI_UNSUPPORTED   NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+PopulateMpsGlobal (
+  VOID
+  );
+
+#endif
diff --git a/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h b/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
new file mode 100644
index 000000000000..023c987c3c7e
--- /dev/null
+++ b/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
@@ -0,0 +1,152 @@
+/** @file
+Library for creating the MM and DXE memory protection HOB entries.
+
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#ifndef SET_MEMORY_PROTECTION_SETTINGS_LIB_H_
+#define SET_MEMORY_PROTECTION_SETTINGS_LIB_H_
+
+#include <Guid/MemoryProtectionSettings.h>
+
+typedef struct {
+  CHAR8                             *Name;
+  CHAR8                             *Description;
+  DXE_MEMORY_PROTECTION_SETTINGS    Settings;
+} DXE_MEMORY_PROTECTION_PROFILES;
+
+typedef enum {
+  DxeMemoryProtectionSettingsPcd,
+  DxeMemoryProtectionSettingsMax
+} DXE_MEMORY_PROTECTION_PROFILE_INDEX;
+
+typedef struct {
+  CHAR8                            *Name;
+  CHAR8                            *Description;
+  MM_MEMORY_PROTECTION_SETTINGS    Settings;
+} MM_MEMORY_PROTECTION_PROFILES;
+
+typedef enum {
+  MmMemoryProtectionSettingsPcd,
+  MmMemoryProtectionSettingsMax
+} MM_MEMORY_PROTECTION_PROFILE_INDEX;
+
+extern DXE_MEMORY_PROTECTION_PROFILES  DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsMax];
+extern MM_MEMORY_PROTECTION_PROFILES   MmMemoryProtectionProfiles[MmMemoryProtectionSettingsMax];
+
+/**
+  Prevent further changes to the memory protection settings via this
+  library API.
+
+  @retval EFI_SUCCESS           The memory protection settings are locked.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+LockMemoryProtectionSettings (
+  VOID
+  );
+
+/**
+  Sets the DXE memory protection settings. If DxeMps is NULL, the settings will be set based
+  on ProfileIndex.
+
+  @param[in] DxeMps        Pointer to the memory protection settings to publish. If NULL, the
+                           settings will be created based on ProfileIndex.
+  @param[in] ProfileIndex  The index of the memory protection profile to use if DxeMps is NULL.
+
+  @retval EFI_SUCCESS           The memory protection HOB was successfully created.
+  @retval EFI_INVALID_PARAMETER The ProfileIndex was invalid or the version number of the
+                                input DxeMps was not equal to the version currently present
+                                in the settings.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_ACCESS_DENIED     The memory protection settings are locked.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+SetDxeMemoryProtectionSettings (
+  IN DXE_MEMORY_PROTECTION_SETTINGS       *DxeMps OPTIONAL,
+  IN DXE_MEMORY_PROTECTION_PROFILE_INDEX  ProfileIndex
+  );
+
+/**
+  Sets the MM memory protection HOB entry. If MmMps is NULL, the settings will be set based
+  on ProfileIndex.
+
+  @param[in] MmMps         Pointer to the memory protection settings to publish. If NULL, the
+                           settings will be created based on ProfileIndex.
+  @param[in] ProfileIndex  The index of the memory protection profile to use if MmMps is NULL.
+
+  @retval EFI_SUCCESS           The memory protection HOB was successfully created.
+  @retval EFI_OUT_OF_RESOURCES  There was insufficient memory to create the HOB.
+  @retval EFI_INVALID_PARAMETER The ProfileIndex was invalid or the version number of the
+                                input MmMps was not equal to the version currently present
+                                in the settings.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_ACCESS_DENIED     The memory protection settings are locked.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+SetMmMemoryProtectionSettings (
+  IN MM_MEMORY_PROTECTION_SETTINGS       *MmMps OPTIONAL,
+  IN MM_MEMORY_PROTECTION_PROFILE_INDEX  ProfileIndex
+  );
+
+/**
+  Copies the current memory protection settings into the input buffer.
+
+  NOTE: The returned settings may not be the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @param[out] Mps  The memory protection settings pointer to populate.
+
+  @retval EFI_SUCCESS           The memory protection settings were copied
+                                into the input buffer.
+  @retval EFI_INVALID_PARAMETER Mps was NULL.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+GetCurrentMemoryProtectionSettings (
+  OUT MEMORY_PROTECTION_SETTINGS  *Mps
+  );
+
+/**
+  Returns TRUE any form of DXE memory protection is currently active.
+
+  NOTE: The returned value may reflect the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @retval TRUE   DXE Memory protection is active.
+  @retval FALSE  DXE Memory protection is not active.
+**/
+BOOLEAN
+EFIAPI
+IsDxeMemoryProtectionActive (
+  VOID
+  );
+
+/**
+  Returns TRUE any form of MM memory protection is currently active.
+
+  NOTE: The returned value may reflect the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @retval TRUE   MM Memory protection is active.
+  @retval FALSE  MM Memory protection is not active.
+**/
+BOOLEAN
+EFIAPI
+IsMmMemoryProtectionActive (
+  VOID
+  );
+
+#endif
diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index 5e1a0388bed3..6ad0902a1bff 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -164,6 +164,14 @@ [LibraryClasses]
   #
   VariableFlashInfoLib|Include/Library/VariableFlashInfoLib.h
 
+  ## @libraryclass Provides a global for consuming memory protection settings
+  #
+  GetMemoryProtectionsLib|Include/Library/GetMemoryProtectionsLib.h
+
+  ## @libraryclass Library for creating the memory protection settings HOB
+  #
+  SetMemoryProtectionsLib|Include/Library/SetMemoryProtectionsLib.h
+
 [Guids]
   ## MdeModule package token space guid
   # Include/Guid/MdeModulePkgTokenSpace.h
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108864): https://edk2.groups.io/g/devel/message/108864
Mute This Topic: https://groups.io/mt/101469939/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 03/28] MdeModulePkg: Add NULL Instances for Get/SetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 01/28] MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 02/28] MdeModulePkg: Define SetMemoryProtectionsLib and GetMemoryProtectionsLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 04/28] MdeModulePkg: Implement SetMemoryProtectionsLib and GetMemoryProtectionsLib Taylor Beebe
                   ` (24 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao

The NULL instances for GetMemoryProtectionsLib and
SetMemoryProtectionsLib just zero out the memory protections
structure effectively disabling memory protections.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
---
 MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.c   |  29 ++++
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.c   | 144 ++++++++++++++++++++
 MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf |  25 ++++
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf |  25 ++++
 MdeModulePkg/MdeModulePkg.dsc                                                |   4 +
 5 files changed, 227 insertions(+)

diff --git a/MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.c b/MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.c
new file mode 100644
index 000000000000..af341c2c893d
--- /dev/null
+++ b/MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.c
@@ -0,0 +1,29 @@
+/** @file
+NULL implementation for GetMemoryProtectionsLib
+
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Uefi.h>
+#include <Library/GetMemoryProtectionsLib.h>
+
+MEMORY_PROTECTION_SETTINGS_UNION  gMps = { 0 };
+
+/**
+  Populates gMps global. This function is invoked by the library constructor and only needs to be
+  called if library contructors have not yet been invoked.
+
+  @retval EFI_SUCCESS       gMps global was populated.
+  @retval EFI_NOT_FOUND     The gMemoryProtectionSettingsGuid HOB was not found.
+  @retval EFI_ABORTED       The version number of the DXE or MM memory protection settings was invalid.
+  @retval EFI_UNSUPPORTED   NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+PopulateMpsGlobal (
+  VOID
+  )
+{
+  return EFI_UNSUPPORTED;
+}
diff --git a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.c b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.c
new file mode 100644
index 000000000000..0d3a32d70209
--- /dev/null
+++ b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.c
@@ -0,0 +1,144 @@
+/** @file
+Library for setting the memory protection settings for DXE.
+
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Uefi.h>
+#include <Library/SetMemoryProtectionsLib.h>
+
+DXE_MEMORY_PROTECTION_PROFILES  DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsMax] = { 0 };
+MM_MEMORY_PROTECTION_PROFILES   MmMemoryProtectionProfiles[MmMemoryProtectionSettingsMax]   = { 0 };
+
+/**
+  Prevent further changes to the memory protection settings via this
+  library API.
+
+  @retval EFI_SUCCESS           The memory protection settings are locked.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+LockMemoryProtectionSettings (
+  VOID
+  )
+{
+  return EFI_UNSUPPORTED;
+}
+
+/**
+  Sets the DXE memory protection settings. If DxeMps is NULL, the settings will be set based
+  on ProfileIndex.
+
+  @param[in] DxeMps        Pointer to the memory protection settings to publish. If NULL, the
+                           settings will be created based on ProfileIndex.
+  @param[in] ProfileIndex  The index of the memory protection profile to use if DxeMps is NULL.
+
+  @retval EFI_SUCCESS           The memory protection HOB was successfully created.
+  @retval EFI_INVALID_PARAMETER The ProfileIndex was invalid or the version number of the
+                                input DxeMps was not equal to the version currently present
+                                in the settings.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_ACCESS_DENIED     The memory protection settings are locked.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+SetDxeMemoryProtectionSettings (
+  IN DXE_MEMORY_PROTECTION_SETTINGS       *DxeMps OPTIONAL,
+  IN DXE_MEMORY_PROTECTION_PROFILE_INDEX  ProfileIndex
+  )
+{
+  return EFI_UNSUPPORTED;
+}
+
+/**
+  Sets the MM memory protection HOB entry. If MmMps is NULL, the settings will be set based
+  on ProfileIndex.
+
+  @param[in] MmMps         Pointer to the memory protection settings to publish. If NULL, the
+                           settings will be created based on ProfileIndex.
+  @param[in] ProfileIndex  The index of the memory protection profile to use if MmMps is NULL.
+
+  @retval EFI_SUCCESS           The memory protection HOB was successfully created.
+  @retval EFI_OUT_OF_RESOURCES  There was insufficient memory to create the HOB.
+  @retval EFI_INVALID_PARAMETER The ProfileIndex was invalid or the version number of the
+                                input MmMps was not equal to the version currently present
+                                in the settings.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_ACCESS_DENIED     The memory protection settings are locked.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+SetMmMemoryProtectionSettings (
+  IN MM_MEMORY_PROTECTION_SETTINGS       *MmMps OPTIONAL,
+  IN MM_MEMORY_PROTECTION_PROFILE_INDEX  ProfileIndex
+  )
+{
+  return EFI_UNSUPPORTED;
+}
+
+/**
+  Copies the current memory protection settings into the input buffer.
+
+  NOTE: The returned settings may not be the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @param[out] Mps  The memory protection settings pointer to populate.
+
+  @retval EFI_SUCCESS           The memory protection settings were copied
+                                into the input buffer.
+  @retval EFI_INVALID_PARAMETER Mps was NULL.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+GetCurrentMemoryProtectionSettings (
+  OUT MEMORY_PROTECTION_SETTINGS  *Mps
+  )
+{
+  return EFI_UNSUPPORTED;
+}
+
+/**
+  Returns TRUE any form of DXE memory protection is currently active.
+
+  NOTE: The returned value may reflect the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @retval TRUE   DXE Memory protection is active.
+  @retval FALSE  DXE Memory protection is not active.
+**/
+BOOLEAN
+EFIAPI
+IsDxeMemoryProtectionActive (
+  VOID
+  )
+{
+  return FALSE;
+}
+
+/**
+  Returns TRUE any form of MM memory protection is currently active.
+
+  NOTE: The returned value may reflect the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @retval TRUE   MM Memory protection is active.
+  @retval FALSE  MM Memory protection is not active.
+**/
+BOOLEAN
+EFIAPI
+IsMmMemoryProtectionActive (
+  VOID
+  )
+{
+  return FALSE;
+}
diff --git a/MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf b/MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
new file mode 100644
index 000000000000..e7161412d9dc
--- /dev/null
+++ b/MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
@@ -0,0 +1,25 @@
+## @file
+# NULL implementation for GetMemoryProtectionsLib
+#
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = GetMemoryProtectionsLibNull
+  FILE_GUID                      = C21A27EE-37DD-4024-8EDA-8BF5088C8CB1
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = GetMemoryProtectionsLib
+
+#
+#  VALID_ARCHITECTURES           = IA32 X64 AARCH64
+#
+
+[Sources]
+  GetMemoryProtectionsLibNull.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
diff --git a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf
new file mode 100644
index 000000000000..fa660abe3b64
--- /dev/null
+++ b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf
@@ -0,0 +1,25 @@
+## @file
+# Library for setting the memory protection settings for DXE.
+#
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = SetMemoryProtectionsLibNull
+  FILE_GUID                      = CBD02C10-1F4B-4374-A7B2-BB2547C08433
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = SetMemoryProtectionsLib|SEC PEI_CORE PEIM
+
+#
+#  VALID_ARCHITECTURES           = IA32 X64 AARCH64
+#
+
+[Sources]
+  SetMemoryProtectionsLibNull.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
diff --git a/MdeModulePkg/MdeModulePkg.dsc b/MdeModulePkg/MdeModulePkg.dsc
index c7af921782ee..0b5f2414dd72 100644
--- a/MdeModulePkg/MdeModulePkg.dsc
+++ b/MdeModulePkg/MdeModulePkg.dsc
@@ -106,6 +106,8 @@ [LibraryClasses]
   MmUnblockMemoryLib|MdePkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLibNull.inf
   VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf
   IpmiCommandLib|MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
+  SetMemoryProtectionsLib|MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf
 
 [LibraryClasses.EBC.PEIM]
   IoLib|MdePkg/Library/PeiIoLibCpuIo/PeiIoLibCpuIo.inf
@@ -231,6 +233,8 @@ [Components]
   MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf
   MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf
   MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf
+  MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
+  MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf
   MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.inf
   MdeModulePkg/Library/PiSmmCoreSmmServicesTableLib/PiSmmCoreSmmServicesTableLib.inf
   MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108865): https://edk2.groups.io/g/devel/message/108865
Mute This Topic: https://groups.io/mt/101469940/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 04/28] MdeModulePkg: Implement SetMemoryProtectionsLib and GetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (2 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 03/28] MdeModulePkg: Add NULL Instances for Get/SetMemoryProtectionsLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 05/28] MdeModulePkg: Copy PEI PCD Database Into New Buffer Taylor Beebe
                   ` (23 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao

The SetMemoryProtectionsLib implementation has functionality for
setting protections based on a preset profile or a custom DXE/MM
profile passed in by the caller. The implementation also supports
locking the protections (tracked via an extra boolean stored
in the HOB entry) which prevents the protections from being
changed by any other SetMemoryProtectionsLib calls.

The GetMemoryProtectionsLib implementation populates the
gMps global in the library consructor. For cases where the global
needs to be accessed before the constructor is called,
PopulateMpsGlobal() will manually fill out the gMps global.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
---
 MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.c   | 158 ++++++
 MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.c    | 124 +++++
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c      | 534 ++++++++++++++++++++
 MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf |  34 ++
 MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf  |  34 ++
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf    |  48 ++
 MdeModulePkg/MdeModulePkg.dsc                                               |   3 +
 7 files changed, 935 insertions(+)

diff --git a/MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.c b/MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.c
new file mode 100644
index 000000000000..c622a7b99f42
--- /dev/null
+++ b/MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.c
@@ -0,0 +1,158 @@
+/** @file
+Library fills out gMps global for accessing the platform memory protection settings
+
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <PiDxe.h>
+
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
+
+MEMORY_PROTECTION_SETTINGS_UNION  gMps = { 0 };
+
+/**
+  This function checks the memory protection settings for conflicts.
+
+  @param[in]  Mps   Pointer to the memory protection settings to check.
+
+  @retval EFI_SUCCESS           The memory protection settings are consistent.
+  @retval EFI_INVALID_PARAMETER The memory protection settings are not consistent.
+**/
+STATIC
+EFI_STATUS
+DxeMemoryProtectionSettingsConsistencyCheck (
+  IN MEMORY_PROTECTION_SETTINGS  *Mps
+  )
+{
+  if ((Mps->Dxe.HeapGuard.PoolGuardEnabled || Mps->Dxe.HeapGuard.PageGuardEnabled) &&
+      Mps->Dxe.HeapGuard.FreedMemoryGuardEnabled)
+  {
+    DEBUG ((
+      DEBUG_WARN,
+      "%a: - HeapGuard.FreedMemoryGuardEnabled and "
+      "UEFI HeapGuard.PoolGuardEnabled/HeapGuard.PageGuardEnabled "
+      "cannot be active at the same time. Setting all three to ZERO in "
+      "the memory protection settings global.\n",
+      __func__
+      ));
+    ASSERT (
+      !(Mps->Dxe.HeapGuard.FreedMemoryGuardEnabled &&
+        (Mps->Dxe.HeapGuard.PoolGuardEnabled || Mps->Dxe.HeapGuard.PageGuardEnabled))
+      );
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (!IsZeroBuffer (&Mps->Dxe.PoolGuard, MPS_MEMORY_TYPE_BUFFER_SIZE) &&
+      (!(Mps->Dxe.HeapGuard.PoolGuardEnabled)))
+  {
+    DEBUG ((
+      DEBUG_WARN,
+      "%a: - PoolGuard protections are active "
+      "but HeapGuard.PoolGuardEnabled is inactive.\n",
+      __func__
+      ));
+  }
+
+  if (!IsZeroBuffer (&Mps->Dxe.PageGuard, MPS_MEMORY_TYPE_BUFFER_SIZE) &&
+      (!(Mps->Dxe.HeapGuard.PageGuardEnabled)))
+  {
+    DEBUG ((
+      DEBUG_WARN,
+      "%a: - PageGuard protections are active "
+      "but HeapGuard.PageGuardEnabled is inactive\n",
+      __func__
+      ));
+  }
+
+  if (Mps->Dxe.ExecutionProtection.EnabledForType[EfiBootServicesData] !=
+      Mps->Dxe.ExecutionProtection.EnabledForType[EfiConventionalMemory])
+  {
+    DEBUG ((
+      DEBUG_WARN,
+      "%a: - EfiBootServicesData and EfiConventionalMemory must have the same "
+      "ExecutionProtection value. Setting both to ZERO in the memory protection "
+      "settings global.\n",
+      __func__
+      ));
+    ASSERT (
+      Mps->Dxe.ExecutionProtection.EnabledForType[EfiBootServicesData] ==
+      Mps->Dxe.ExecutionProtection.EnabledForType[EfiConventionalMemory]
+      );
+    return EFI_INVALID_PARAMETER;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Populates gMps global. This function is invoked by the library constructor and only needs to be
+  called if library contructors have not yet been invoked.
+
+  @retval EFI_SUCCESS       gMps global was populated.
+  @retval EFI_NOT_FOUND     The gMemoryProtectionSettingsGuid HOB was not found.
+  @retval EFI_ABORTED       The version number of the DXE or MM memory protection settings was invalid.
+  @retval EFI_UNSUPPORTED   NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+PopulateMpsGlobal (
+  VOID
+  )
+{
+  VOID                        *Ptr;
+  MEMORY_PROTECTION_SETTINGS  *Mps;
+
+  Ptr = GetFirstGuidHob (&gMemoryProtectionSettingsGuid);
+
+  if (Ptr != NULL) {
+    Mps = (MEMORY_PROTECTION_SETTINGS *)GET_GUID_HOB_DATA (Ptr);
+    if (Mps->Dxe.StructVersion != DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION) {
+      DEBUG ((
+        DEBUG_ERROR,
+        "%a: - Version number of the DXE Memory Protection Settings is invalid!\n",
+        __func__
+        ));
+      ASSERT (Mps->Dxe.StructVersion == DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION);
+      return EFI_ABORTED;
+    } else if (Mps->Dxe.Signature != DXE_MEMORY_PROTECTION_SIGNATURE) {
+      DEBUG ((
+        DEBUG_ERROR,
+        "%a: - Signature of the DXE Memory Protection Settings is invalid!\n",
+        __func__
+        ));
+      ASSERT (Mps->Dxe.Signature == DXE_MEMORY_PROTECTION_SIGNATURE);
+      return EFI_ABORTED;
+    }
+
+    if (!EFI_ERROR (DxeMemoryProtectionSettingsConsistencyCheck (Mps))) {
+      CopyMem (&gMps.Dxe, &Mps->Dxe, sizeof (DXE_MEMORY_PROTECTION_SETTINGS));
+    }
+  } else {
+    DEBUG ((
+      DEBUG_WARN,
+      "%a: - Memory Protection Settings not found!\n",
+      __func__
+      ));
+    return EFI_NOT_FOUND;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Library constructor used to populate gMps global.
+
+  @retval EFI_SUCCESS   Constructor always returns success;
+**/
+EFI_STATUS
+EFIAPI
+GetDxeMemoryProtectionSettingsConstructor (
+  VOID
+  )
+{
+  PopulateMpsGlobal ();
+  return EFI_SUCCESS;
+}
diff --git a/MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.c b/MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.c
new file mode 100644
index 000000000000..09c289dd8d15
--- /dev/null
+++ b/MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.c
@@ -0,0 +1,124 @@
+/** @file
+Library fills out gMps global for accessing the platform memory protection settings
+
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <PiDxe.h>
+
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
+
+MEMORY_PROTECTION_SETTINGS_UNION  gMps = { 0 };
+
+/**
+  This function checks the memory protection settings for conflicts.
+
+  @param[in]  Mps   Pointer to the memory protection settings to check.
+
+  @retval EFI_SUCCESS           The memory protection settings are consistent.
+  @retval EFI_INVALID_PARAMETER The memory protection settings are not consistent.
+**/
+STATIC
+EFI_STATUS
+MmMemoryProtectionSettingsConsistencyCheck (
+  IN MEMORY_PROTECTION_SETTINGS  *Mps
+  )
+{
+  if (!IsZeroBuffer (&Mps->Mm.PoolGuard, MPS_MEMORY_TYPE_BUFFER_SIZE) &&
+      (!Mps->Mm.HeapGuard.PoolGuardEnabled))
+  {
+    DEBUG ((
+      DEBUG_WARN,
+      "%a: - PoolGuard protections are active "
+      "but HeapGuard.PoolGuardEnabled is inactive.\n",
+      __func__
+      ));
+  }
+
+  if (!IsZeroBuffer (&Mps->Mm.PageGuard, MPS_MEMORY_TYPE_BUFFER_SIZE) &&
+      (!Mps->Mm.HeapGuard.PageGuardEnabled))
+  {
+    DEBUG ((
+      DEBUG_WARN,
+      "%a: - PageGuard protections are active "
+      "but HeapGuard.PageGuardEnabled is inactive\n",
+      __func__
+      ));
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Populates gMps global. This function is invoked by the library constructor and only needs to be
+  called if library contructors have not yet been invoked.
+
+  @retval EFI_SUCCESS       gMps global was populated.
+  @retval EFI_NOT_FOUND     The gMemoryProtectionSettingsGuid HOB was not found.
+  @retval EFI_ABORTED       The version number of the DXE or MM memory protection settings was invalid.
+  @retval EFI_UNSUPPORTED   NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+PopulateMpsGlobal (
+  VOID
+  )
+{
+  VOID                        *Ptr;
+  MEMORY_PROTECTION_SETTINGS  *Mps;
+
+  Ptr = GetFirstGuidHob (&gMemoryProtectionSettingsGuid);
+
+  if (Ptr != NULL) {
+    Mps = (MEMORY_PROTECTION_SETTINGS *)GET_GUID_HOB_DATA (Ptr);
+
+    if (Mps->Mm.StructVersion != MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION) {
+      DEBUG ((
+        DEBUG_ERROR,
+        "%a: - Version number of the MM Memory Protection Settings is invalid!\n",
+        __func__
+        ));
+      ASSERT (Mps->Mm.StructVersion == MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION);
+      return EFI_ABORTED;
+    } else if (Mps->Mm.Signature != MM_MEMORY_PROTECTION_SIGNATURE) {
+      DEBUG ((
+        DEBUG_ERROR,
+        "%a: - Signature of the MM Memory Protection Settings is invalid!\n",
+        __func__
+        ));
+      ASSERT (Mps->Mm.Signature == MM_MEMORY_PROTECTION_SIGNATURE);
+      return EFI_ABORTED;
+    }
+
+    if (!EFI_ERROR (MmMemoryProtectionSettingsConsistencyCheck (Mps))) {
+      CopyMem (&gMps.Mm, &Mps->Mm, sizeof (MM_MEMORY_PROTECTION_SETTINGS));
+    }
+  } else {
+    DEBUG ((
+      DEBUG_WARN,
+      "%a: - Memory Protection Settings not found!\n",
+      __func__
+      ));
+    return EFI_NOT_FOUND;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Library constructor used to populate gMps global.
+
+  @retval EFI_SUCCESS   Constructor always returns success;
+**/
+EFI_STATUS
+EFIAPI
+GetMmMemoryProtectionSettingsConstructor (
+  VOID
+  )
+{
+  PopulateMpsGlobal ();
+  return EFI_SUCCESS;
+}
diff --git a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
new file mode 100644
index 000000000000..13032ec80fbf
--- /dev/null
+++ b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
@@ -0,0 +1,534 @@
+/** @file
+Library for setting the memory protection settings for DXE.
+
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <PiPei.h>
+#include <Library/HobLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/PcdLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
+
+#pragma pack(1)
+
+typedef struct {
+  // Protection settings
+  MEMORY_PROTECTION_SETTINGS    Mps;
+  // Extra byte for tracking if protection settings have been locked
+  BOOLEAN                       MemoryProtectionSettingsLocked;
+} MEMORY_PROTECTION_SETTINGS_PRIVATE;
+
+#pragma pack()
+
+/////////////////////////////
+// DXE PROFILE DEFINITIONS //
+/////////////////////////////
+
+//
+//  A memory profile which uses the fixed at build PCDs defined in MdeModulePkg.dec
+//
+#define DXE_MEMORY_PROTECTION_SETTINGS_PCD                                                                                            \
+{                                                                                                                                     \
+  DXE_MEMORY_PROTECTION_SIGNATURE,                                                                                                    \
+  DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,                                                                                     \
+  FixedPcdGetBool (PcdCpuStackGuard), /* Stack Guard */                                                                               \
+  TRUE,                               /* Stack Execution Protection (MUST BE POPULATED) */                                            \
+  {                                   /* NULL Pointer Detection */                                                                    \
+    .Enabled            = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) != 0),                                         \
+    .DisableEndOfDxe    = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT7) != 0),                                         \
+    .NonstopModeEnabled = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT6) != 0)                                          \
+  },                                                                                                                                  \
+  { /* Image Protection */                                                                                                            \
+    .ProtectImageFromUnknown = ((FixedPcdGet32 (PcdImageProtectionPolicy) & BIT0) != 0),                                              \
+    .ProtectImageFromFv      = ((FixedPcdGet32 (PcdImageProtectionPolicy) & BIT1) != 0)                                               \
+  },                                                                                                                                  \
+  { /* Execution Protection */                                                                                                        \
+    .EnabledForType = {                                                                                                               \
+      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiReservedMemoryType) != 0),        \
+      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiLoaderCode) != 0),                \
+      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiLoaderData) != 0),                \
+      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiBootServicesCode) != 0),          \
+      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiBootServicesData) != 0),          \
+      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiRuntimeServicesCode) != 0),       \
+      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiRuntimeServicesData) != 0),       \
+      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiConventionalMemory) != 0),        \
+      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiUnusableMemory) != 0),            \
+      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiACPIReclaimMemory) != 0),         \
+      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiACPIMemoryNVS) != 0),             \
+      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiMemoryMappedIO) != 0),            \
+      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiMemoryMappedIOPortSpace) != 0),   \
+      [EfiPalCode]                          = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiPalCode) != 0),                   \
+      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiPersistentMemory) != 0),          \
+      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiUnacceptedMemoryType) != 0),      \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & BIT62) != 0),                        \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & BIT63) != 0)                         \
+    }                                                                                                                                 \
+  },                                                                                                                                  \
+  { /* Heap Guard */                                                                                                                  \
+    .PageGuardEnabled                       = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT0) != 0),                                \
+    .PoolGuardEnabled                       = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT1) != 0),                                \
+    .FreedMemoryGuardEnabled                = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT4) != 0),                                \
+    .NonstopModeEnabled                     = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT6) != 0),                                \
+    .GuardAlignedToTail                     = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0)                                 \
+  },                                                                                                                                  \
+  { /* Pool Guard */                                                                                                                  \
+    .EnabledForType = {                                                                                                               \
+      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiReservedMemoryType) != 0),                  \
+      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiLoaderCode) != 0),                          \
+      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiLoaderData) != 0),                          \
+      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiBootServicesCode) != 0),                    \
+      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiBootServicesData) != 0),                    \
+      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiRuntimeServicesCode) != 0),                 \
+      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiRuntimeServicesData) != 0),                 \
+      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiConventionalMemory) != 0),                  \
+      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiUnusableMemory) != 0),                      \
+      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiACPIReclaimMemory) != 0),                   \
+      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiACPIMemoryNVS) != 0),                       \
+      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiMemoryMappedIO) != 0),                      \
+      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiMemoryMappedIOPortSpace) != 0),             \
+      [EfiPalCode]                          = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiPalCode) != 0),                             \
+      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiPersistentMemory) != 0),                    \
+      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiUnacceptedMemoryType) != 0),                \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdHeapGuardPoolType) & BIT62) != 0),                                  \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdHeapGuardPoolType) & BIT63) != 0)                                   \
+    }                                                                                                                                 \
+  },                                                                                                                                  \
+  { /* Page Guard */                                                                                                                  \
+    .EnabledForType = {                                                                                                               \
+      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiReservedMemoryType) != 0),                  \
+      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiLoaderCode) != 0),                          \
+      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiLoaderData) != 0),                          \
+      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiBootServicesCode) != 0),                    \
+      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiBootServicesData) != 0),                    \
+      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiRuntimeServicesCode) != 0),                 \
+      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiRuntimeServicesData) != 0),                 \
+      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiConventionalMemory) != 0),                  \
+      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiUnusableMemory) != 0),                      \
+      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiACPIReclaimMemory) != 0),                   \
+      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiACPIMemoryNVS) != 0),                       \
+      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiMemoryMappedIO) != 0),                      \
+      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiMemoryMappedIOPortSpace) != 0),             \
+      [EfiPalCode]                          = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiPalCode) != 0),                             \
+      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiPersistentMemory) != 0),                    \
+      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiUnacceptedMemoryType) != 0),                \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdHeapGuardPageType) & BIT62) != 0),                                  \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdHeapGuardPageType) & BIT63) != 0)                                   \
+    }                                                                                                                                 \
+  }                                                                                                                                   \
+}
+
+////////////////////////////
+// MM PROFILE DEFINITIONS //
+////////////////////////////
+
+//
+//  A memory profile which uses the fixed at build PCDs defined in MdeModulePkg.dec
+//
+#define MM_MEMORY_PROTECTION_SETTINGS_PCD                                                                                 \
+{                                                                                                                         \
+  MM_MEMORY_PROTECTION_SIGNATURE,                                                                                         \
+  MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,                                                                          \
+  { /* NULL Pointer Detection */                                                                                          \
+    .Enabled            = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0),                             \
+    .NonstopModeEnabled = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT6) != 0)                              \
+  },                                                                                                                      \
+  { /* Heap Guard */                                                                                                      \
+    .PageGuardEnabled                       = ((FixedPcdGet8(PcdHeapGuardPropertyMask) & BIT2) != 0),                     \
+    .PoolGuardEnabled                       = ((FixedPcdGet8(PcdHeapGuardPropertyMask) & BIT3) != 0),                     \
+    .NonstopModeEnabled                     = ((FixedPcdGet8(PcdHeapGuardPropertyMask) & BIT6) != 0),                     \
+    .GuardAlignedToTail                     = ((FixedPcdGet8(PcdHeapGuardPropertyMask) & BIT7) == 0)                      \
+  },                                                                                                                      \
+  { /* Pool Guard */                                                                                                      \
+    .EnabledForType = {                                                                                                   \
+      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiReservedMemoryType) != 0),      \
+      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiLoaderCode) != 0),              \
+      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiLoaderData) != 0),              \
+      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiBootServicesCode) != 0),        \
+      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiBootServicesData) != 0),        \
+      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiRuntimeServicesCode) != 0),     \
+      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiRuntimeServicesData) != 0),     \
+      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiConventionalMemory) != 0),      \
+      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiUnusableMemory) != 0),          \
+      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiACPIReclaimMemory) != 0),       \
+      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiACPIMemoryNVS) != 0),           \
+      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiMemoryMappedIO) != 0),          \
+      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiMemoryMappedIOPortSpace) != 0), \
+      [EfiPalCode]                          = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiPalCode) != 0),                 \
+      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiPersistentMemory) != 0),        \
+      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiUnacceptedMemoryType) != 0),    \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdHeapGuardPoolType) & BIT62) != 0),                      \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdHeapGuardPoolType) & BIT63) != 0)                       \
+    }                                                                                                                     \
+  },                                                                                                                      \
+  { /* Page Guard */                                                                                                      \
+    .EnabledForType = {                                                                                                   \
+      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiReservedMemoryType) != 0),      \
+      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiLoaderCode) != 0),              \
+      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiLoaderData) != 0),              \
+      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiBootServicesCode) != 0),        \
+      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiBootServicesData) != 0),        \
+      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiRuntimeServicesCode) != 0),     \
+      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiRuntimeServicesData) != 0),     \
+      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiConventionalMemory) != 0),      \
+      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiUnusableMemory) != 0),          \
+      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiACPIReclaimMemory) != 0),       \
+      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiACPIMemoryNVS) != 0),           \
+      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiMemoryMappedIO) != 0),          \
+      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiMemoryMappedIOPortSpace) != 0), \
+      [EfiPalCode]                          = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiPalCode) != 0),                 \
+      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiPersistentMemory) != 0),        \
+      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiUnacceptedMemoryType) != 0),    \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdHeapGuardPageType) & BIT62) != 0),                      \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdHeapGuardPageType) & BIT63) != 0)                       \
+    }                                                                                                                     \
+  }                                                                                                                       \
+}
+
+////////////////////////////
+// PROFILE CONFIGURATIONS //
+////////////////////////////
+
+DXE_MEMORY_PROTECTION_PROFILES  DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsMax] = {
+  [DxeMemoryProtectionSettingsPcd] = {
+    .Name        = "Pcd",
+    .Description = "Memory protection settings from PCDs",
+    .Settings    = DXE_MEMORY_PROTECTION_SETTINGS_PCD
+  },
+};
+
+MM_MEMORY_PROTECTION_PROFILES  MmMemoryProtectionProfiles[MmMemoryProtectionSettingsMax] = {
+  [MmMemoryProtectionSettingsPcd] = {
+    .Name        = "Pcd",
+    .Description = "Memory protection settings from PCDs",
+    .Settings    = MM_MEMORY_PROTECTION_SETTINGS_PCD
+  },
+};
+
+/////////////////////////////////////
+//    GET/SET SUPPORT FUNCTIONS    //
+/////////////////////////////////////
+
+/**
+  Gets the memory protection HOB entry. This function will create the entry
+  if it is not found.
+
+  @retval NULL    Unable to create the memory protection HOB entry.
+  @retval Other   Pointer to the memory protection HOB entry.
+**/
+STATIC
+MEMORY_PROTECTION_SETTINGS_PRIVATE *
+GetOrCreateMemoryProtectionSettings (
+  VOID
+  )
+{
+  VOID                                *Ptr;
+  MEMORY_PROTECTION_SETTINGS_PRIVATE  Mpsp;
+
+  Ptr = GetFirstGuidHob (&gMemoryProtectionSettingsGuid);
+
+  if (Ptr != NULL) {
+    return (MEMORY_PROTECTION_SETTINGS_PRIVATE *)GET_GUID_HOB_DATA (Ptr);
+  }
+
+  ZeroMem (&Mpsp, sizeof (Mpsp));
+  Mpsp.Mps.Dxe                                 = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsPcd].Settings;
+  Mpsp.Mps.Mm                                  = MmMemoryProtectionProfiles[MmMemoryProtectionSettingsPcd].Settings;
+  Mpsp.Mps.Dxe.StackExecutionProtectionEnabled = PcdGetBool (PcdSetNxForStack);
+
+  Ptr = BuildGuidDataHob (
+          &gMemoryProtectionSettingsGuid,
+          &Mpsp,
+          sizeof (Mpsp)
+          );
+
+  return (MEMORY_PROTECTION_SETTINGS_PRIVATE *)Ptr;
+}
+
+/**
+  Gets the memory protection HOB entry and checks the version number
+  to ensure it is compatible with this module.
+
+  @retval NULL    Unable to create the memory protection HOB entry.
+  @retval Other   Pointer to the memory protection HOB entry.
+**/
+STATIC
+MEMORY_PROTECTION_SETTINGS_PRIVATE  *
+FetchAndCheckMpsp (
+  VOID
+  )
+{
+  MEMORY_PROTECTION_SETTINGS_PRIVATE  *Mpsp;
+
+  Mpsp = GetOrCreateMemoryProtectionSettings ();
+
+  if (Mpsp == NULL) {
+    return NULL;
+  }
+
+  if (Mpsp->Mps.Dxe.StructVersion != DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "%a: - Version number of the DXE Memory Protection Settings is invalid!\n"
+      "This module was compiled with version %d but the current version is %d.\n",
+      __func__,
+      Mpsp->Mps.Dxe.StructVersion,
+      DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION
+      ));
+    ASSERT (Mpsp->Mps.Dxe.StructVersion == DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION);
+    return NULL;
+  }
+
+  if (Mpsp->Mps.Mm.StructVersion != MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "%a: - Version number of the MM Memory Protection Settings is invalid!\n"
+      "This module was compiled with version %d but the current version is %d.\n",
+      __func__,
+      Mpsp->Mps.Mm.StructVersion,
+      MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION
+      ));
+    ASSERT (Mpsp->Mps.Mm.StructVersion == MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION);
+    return NULL;
+  }
+
+  return Mpsp;
+}
+
+/**
+  Prevent further changes to the memory protection settings via this
+  library API.
+
+  @retval EFI_SUCCESS           The memory protection settings are locked.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+LockMemoryProtectionSettings (
+  VOID
+  )
+{
+  MEMORY_PROTECTION_SETTINGS_PRIVATE  *Mpsp;
+
+  Mpsp = FetchAndCheckMpsp ();
+
+  if (Mpsp  == NULL) {
+    ASSERT (Mpsp != NULL);
+    return EFI_ABORTED;
+  }
+
+  Mpsp->MemoryProtectionSettingsLocked = TRUE;
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Sets the DXE memory protection settings. If DxeMps is NULL, the settings will be set based
+  on ProfileIndex.
+
+  @param[in] DxeMps        Pointer to the memory protection settings to publish. If NULL, the
+                           settings will be created based on ProfileIndex.
+  @param[in] ProfileIndex  The index of the memory protection profile to use if DxeMps is NULL.
+
+  @retval EFI_SUCCESS           The memory protection HOB was successfully created.
+  @retval EFI_INVALID_PARAMETER The ProfileIndex was invalid or the version number of the
+                                input DxeMps was not equal to the version currently present
+                                in the settings.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_ACCESS_DENIED     The memory protection settings are locked.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+SetDxeMemoryProtectionSettings (
+  IN DXE_MEMORY_PROTECTION_SETTINGS       *DxeMps OPTIONAL,
+  IN DXE_MEMORY_PROTECTION_PROFILE_INDEX  ProfileIndex
+  )
+{
+  MEMORY_PROTECTION_SETTINGS_PRIVATE  *Mpsp;
+
+  Mpsp = FetchAndCheckMpsp ();
+
+  if (Mpsp == NULL) {
+    ASSERT (Mpsp != NULL);
+    return EFI_ABORTED;
+  }
+
+  if (Mpsp->MemoryProtectionSettingsLocked) {
+    return EFI_ACCESS_DENIED;
+  }
+
+  if (DxeMps == NULL) {
+    if (ProfileIndex >= DxeMemoryProtectionSettingsMax) {
+      return EFI_INVALID_PARAMETER;
+    }
+
+    DxeMps = &DxeMemoryProtectionProfiles[ProfileIndex].Settings;
+  } else if (DxeMps->StructVersion != Mpsp->Mps.Dxe.StructVersion) {
+    ASSERT (DxeMps->StructVersion == Mpsp->Mps.Dxe.StructVersion);
+    return EFI_INVALID_PARAMETER;
+  }
+
+  CopyMem (&Mpsp->Mps.Dxe, DxeMps, sizeof (DXE_MEMORY_PROTECTION_SETTINGS));
+  return EFI_SUCCESS;
+}
+
+/**
+  Sets the MM memory protection HOB entry. If MmMps is NULL, the settings will be set based
+  on ProfileIndex.
+
+  @param[in] MmMps         Pointer to the memory protection settings to publish. If NULL, the
+                           settings will be created based on ProfileIndex.
+  @param[in] ProfileIndex  The index of the memory protection profile to use if MmMps is NULL.
+
+  @retval EFI_SUCCESS           The memory protection HOB was successfully created.
+  @retval EFI_OUT_OF_RESOURCES  There was insufficient memory to create the HOB.
+  @retval EFI_INVALID_PARAMETER The ProfileIndex was invalid or the version number of the
+                                input MmMps was not equal to the version currently present
+                                in the settings.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_ACCESS_DENIED     The memory protection settings are locked.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+SetMmMemoryProtectionSettings (
+  IN MM_MEMORY_PROTECTION_SETTINGS       *MmMps OPTIONAL,
+  IN MM_MEMORY_PROTECTION_PROFILE_INDEX  ProfileIndex
+  )
+{
+  MEMORY_PROTECTION_SETTINGS_PRIVATE  *Mpsp;
+
+  Mpsp = FetchAndCheckMpsp ();
+
+  if (Mpsp == NULL) {
+    ASSERT (Mpsp != NULL);
+    return EFI_ABORTED;
+  }
+
+  if (Mpsp->MemoryProtectionSettingsLocked) {
+    return EFI_ACCESS_DENIED;
+  }
+
+  if (MmMps == NULL) {
+    if (ProfileIndex >= MmMemoryProtectionSettingsMax) {
+      return EFI_INVALID_PARAMETER;
+    }
+
+    MmMps = &MmMemoryProtectionProfiles[ProfileIndex].Settings;
+  } else if (MmMps->StructVersion != Mpsp->Mps.Mm.StructVersion) {
+    ASSERT (MmMps->StructVersion == Mpsp->Mps.Mm.StructVersion);
+    return EFI_INVALID_PARAMETER;
+  }
+
+  CopyMem (&Mpsp->Mps.Mm, MmMps, sizeof (MM_MEMORY_PROTECTION_SETTINGS));
+  return EFI_SUCCESS;
+}
+
+/**
+  Copies the current memory protection settings into the input buffer.
+
+  NOTE: The returned settings may not be the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @param[out] Mps  The memory protection settings pointer to populate.
+
+  @retval EFI_SUCCESS           The memory protection settings were copied
+                                into the input buffer.
+  @retval EFI_INVALID_PARAMETER Mps was NULL.
+  @retval EFI_ABORTED           Unable to get/create the memory protection settings.
+  @retval EFI_UNSUPPORTED       NULL implementation called.
+**/
+EFI_STATUS
+EFIAPI
+GetCurrentMemoryProtectionSettings (
+  OUT MEMORY_PROTECTION_SETTINGS  *Mps
+  )
+{
+  MEMORY_PROTECTION_SETTINGS_PRIVATE  *Mpsp;
+
+  if (Mps == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  Mpsp = FetchAndCheckMpsp ();
+
+  if (Mpsp == NULL) {
+    ASSERT (Mpsp != NULL);
+    return EFI_ABORTED;
+  }
+
+  CopyMem (Mps, &Mpsp->Mps, sizeof (MEMORY_PROTECTION_SETTINGS));
+  return EFI_SUCCESS;
+}
+
+/**
+  Returns TRUE any form of DXE memory protection is currently active.
+
+  NOTE: The returned value may reflect the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @retval TRUE   DXE Memory protection is active.
+  @retval FALSE  DXE Memory protection is not active.
+**/
+BOOLEAN
+EFIAPI
+IsDxeMemoryProtectionActive (
+  VOID
+  )
+{
+  MEMORY_PROTECTION_SETTINGS_PRIVATE  *Mpsp;
+
+  Mpsp = FetchAndCheckMpsp ();
+
+  if (Mpsp == NULL) {
+    ASSERT (Mpsp != NULL);
+    return FALSE;
+  }
+
+  return Mpsp->Mps.Dxe.CpuStackGuardEnabled                                                                                                     ||
+         Mpsp->Mps.Dxe.StackExecutionProtectionEnabled                                                                                          ||
+         Mpsp->Mps.Dxe.NullPointerDetection.Enabled                                                                                             ||
+         Mpsp->Mps.Dxe.HeapGuard.FreedMemoryGuardEnabled                                                                                        ||
+         Mpsp->Mps.Dxe.ImageProtection.ProtectImageFromFv                                                                                       ||
+         Mpsp->Mps.Dxe.ImageProtection.ProtectImageFromUnknown                                                                                  ||
+         !IsZeroBuffer (&Mpsp->Mps.Dxe.ExecutionProtection.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE)                                         ||
+         (Mpsp->Mps.Dxe.HeapGuard.PageGuardEnabled && !IsZeroBuffer (&Mpsp->Mps.Dxe.PageGuard.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE))     ||
+         (Mpsp->Mps.Dxe.HeapGuard.PoolGuardEnabled && !IsZeroBuffer (&Mpsp->Mps.Dxe.PoolGuard.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE));
+}
+
+/**
+  Returns TRUE any form of MM memory protection is currently active.
+
+  NOTE: The returned value may reflect the final settings used by the
+        platform on this boot. Unless LockMemoryProtectionSettings() has
+        been called, settings may be modified by drivers until DXE handoff.
+
+  @retval TRUE   MM Memory protection is active.
+  @retval FALSE  MM Memory protection is not active.
+**/
+BOOLEAN
+EFIAPI
+IsMmMemoryProtectionActive (
+  VOID
+  )
+{
+  MEMORY_PROTECTION_SETTINGS_PRIVATE  *Mpsp;
+
+  Mpsp = FetchAndCheckMpsp ();
+
+  if (Mpsp == NULL) {
+    ASSERT (Mpsp != NULL);
+    return FALSE;
+  }
+
+  return Mpsp->Mps.Mm.NullPointerDetection.Enabled                                                                                          ||
+         (Mpsp->Mps.Mm.HeapGuard.PageGuardEnabled && !IsZeroBuffer (&Mpsp->Mps.Mm.PageGuard.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE))   ||
+         (Mpsp->Mps.Dxe.HeapGuard.PoolGuardEnabled && !IsZeroBuffer (&Mpsp->Mps.Mm.PoolGuard.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE));
+}
diff --git a/MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf b/MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf
new file mode 100644
index 000000000000..b2949a8a5b0b
--- /dev/null
+++ b/MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf
@@ -0,0 +1,34 @@
+## @file
+# Library fills out gMps global for accessing the platform memory protection settings
+#
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = DxeGetMemoryProtectionsLib
+  FILE_GUID                      = 723A3FA5-1B77-4E83-8978-C768829F7BE4
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = GetMemoryProtectionsLib|DXE_CORE DXE_DRIVER UEFI_APPLICATION UEFI_DRIVER
+  CONSTRUCTOR                    = GetDxeMemoryProtectionSettingsConstructor
+
+#
+#  VALID_ARCHITECTURES           = IA32 X64 AARCH64
+#
+
+[Sources]
+  DxeGetMemoryProtectionsLib.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+
+[LibraryClasses]
+  HobLib
+  DebugLib
+  BaseMemoryLib
+
+[Guids]
+  gMemoryProtectionSettingsGuid
diff --git a/MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf b/MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf
new file mode 100644
index 000000000000..328eb4c78139
--- /dev/null
+++ b/MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf
@@ -0,0 +1,34 @@
+## @file
+# Library fills out gMps global for accessing the platform memory protection settings
+#
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = MmGetMemoryProtectionsLib
+  FILE_GUID                      = 719D6FAE-7EF1-429B-9A00-D5C50E4BB15A
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = GetMemoryProtectionsLib|SMM_CORE DXE_SMM_DRIVER MM_CORE_STANDALONE MM_STANDALONE
+  CONSTRUCTOR                    = GetMmMemoryProtectionSettingsConstructor
+
+#
+#  VALID_ARCHITECTURES           = IA32 X64 AARCH64
+#
+
+[Sources]
+  MmGetMemoryProtectionsLib.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+
+[LibraryClasses]
+  HobLib
+  DebugLib
+  BaseMemoryLib
+
+[Guids]
+  gMemoryProtectionSettingsGuid
diff --git a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
new file mode 100644
index 000000000000..2e4a9a66ac68
--- /dev/null
+++ b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
@@ -0,0 +1,48 @@
+## @file
+# Library for setting the memory protection settings for DXE.
+#
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = SetMemoryProtectionsLib
+  FILE_GUID                      = DDA7DD34-0D3E-48FC-B4AE-A25581A40317
+  MODULE_TYPE                    = PEIM
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = SetMemoryProtectionsLib|SEC PEI_CORE PEIM
+
+#
+#  VALID_ARCHITECTURES           = IA32 X64 AARCH64
+#
+
+[Sources]
+  SetMemoryProtectionsLib.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+
+[LibraryClasses]
+  BaseMemoryLib
+  BaseLib
+  HobLib
+  DebugLib
+  PcdLib
+
+[Pcd]
+  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask
+  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard
+  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy
+  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack
+  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy
+
+[Guids]
+  gMemoryProtectionSettingsGuid
+
+[BuildOptions]
+  GCC:*_*_*_CC_FLAGS = -Wno-missing-braces
diff --git a/MdeModulePkg/MdeModulePkg.dsc b/MdeModulePkg/MdeModulePkg.dsc
index 0b5f2414dd72..919379b2a1b9 100644
--- a/MdeModulePkg/MdeModulePkg.dsc
+++ b/MdeModulePkg/MdeModulePkg.dsc
@@ -233,7 +233,10 @@ [Components]
   MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf
   MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf
   MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf
+  MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf
+  MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf
   MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
+  MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
   MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf
   MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.inf
   MdeModulePkg/Library/PiSmmCoreSmmServicesTableLib/PiSmmCoreSmmServicesTableLib.inf
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108866): https://edk2.groups.io/g/devel/message/108866
Mute This Topic: https://groups.io/mt/101469941/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 05/28] MdeModulePkg: Copy PEI PCD Database Into New Buffer
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (3 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 04/28] MdeModulePkg: Implement SetMemoryProtectionsLib and GetMemoryProtectionsLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 06/28] MdeModulePkg: Apply Protections to the HOB List Taylor Beebe
                   ` (22 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao, Dandan Bi

HOB memory should not be written to in DXE phase. This patch
copies the PCD database from PEI into a new buffer so updates
to dynamic PCDs don't write to HOB memory.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Dandan Bi <dandan.bi@intel.com>
---
 MdeModulePkg/Universal/PCD/Dxe/Service.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/MdeModulePkg/Universal/PCD/Dxe/Service.c b/MdeModulePkg/Universal/PCD/Dxe/Service.c
index 1ae06a639c43..0feb11142545 100644
--- a/MdeModulePkg/Universal/PCD/Dxe/Service.c
+++ b/MdeModulePkg/Universal/PCD/Dxe/Service.c
@@ -885,15 +885,17 @@ BuildPcdDxeDataBase (
     // be NULL. If it is NULL, we just copy over the DXE Default
     // Value to PCD Database.
     //
-    PeiDatabase = (PEI_PCD_DATABASE *)GET_GUID_HOB_DATA (GuidHob);
+    PeiDatabase = AllocateCopyPool ((UINTN)GET_GUID_HOB_DATA_SIZE (GuidHob), GET_GUID_HOB_DATA (GuidHob));
+    ASSERT (PeiDatabase != NULL);
 
     //
     // Get next one that stores full PEI data
     //
     GuidHob = GetNextGuidHob (&gPcdDataBaseHobGuid, GET_NEXT_HOB (GuidHob));
     if (GuidHob != NULL) {
-      mPeiPcdDbBinary = (PEI_PCD_DATABASE *)GET_GUID_HOB_DATA (GuidHob);
       mPeiPcdDbSize   = (UINTN)GET_GUID_HOB_DATA_SIZE (GuidHob);
+      mPeiPcdDbBinary = (PEI_PCD_DATABASE *)AllocateCopyPool (mPeiPcdDbSize, GET_GUID_HOB_DATA (GuidHob));
+      ASSERT (mPeiPcdDbBinary != NULL);
     }
 
     //
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108867): https://edk2.groups.io/g/devel/message/108867
Mute This Topic: https://groups.io/mt/101469942/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 06/28] MdeModulePkg: Apply Protections to the HOB List
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (4 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 05/28] MdeModulePkg: Copy PEI PCD Database Into New Buffer Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 07/28] MdeModulePkg: Check Print Level Before Dumping GCD Memory Map Taylor Beebe
                   ` (21 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao, Dandan Bi

Because the platform memory protection settings will be stored
in the HOB, the HOB list should be marked read-only and non-executable
as soon as possible in boot.

This patch page-aligns the allocated HOB list in DXE and marks
it RO/NX during memory protection initialization.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Dandan Bi <dandan.bi@intel.com>
---
 MdeModulePkg/Core/Dxe/Gcd/Gcd.c               | 18 ++++++------
 MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c | 29 ++++++++++++++++++++
 2 files changed, 38 insertions(+), 9 deletions(-)

diff --git a/MdeModulePkg/Core/Dxe/Gcd/Gcd.c b/MdeModulePkg/Core/Dxe/Gcd/Gcd.c
index 792cd2e0af23..72bd036eab1e 100644
--- a/MdeModulePkg/Core/Dxe/Gcd/Gcd.c
+++ b/MdeModulePkg/Core/Dxe/Gcd/Gcd.c
@@ -2764,21 +2764,21 @@ CoreInitializeGcdServices (
   }
 
   //
-  // Relocate HOB List to an allocated pool buffer.
+  // Relocate HOB List to allocated pages.
   // The relocation should be at after all the tested memory resources added
   // (except the memory space that covers HOB List) to the memory services,
   // because the memory resource found in CoreInitializeMemoryServices()
   // may have not enough remaining resource for HOB List.
   //
-  NewHobList = AllocateCopyPool (
-                 (UINTN)PhitHob->EfiFreeMemoryBottom - (UINTN)(*HobStart),
-                 *HobStart
-                 );
-  ASSERT (NewHobList != NULL);
-
-  *HobStart = NewHobList;
-  gHobList  = NewHobList;
+  NewHobList = AllocatePages (EFI_SIZE_TO_PAGES ((UINTN)PhitHob->EfiFreeMemoryBottom - (UINTN)(*HobStart)));
+  if (NewHobList != NULL) {
+    CopyMem (NewHobList, *HobStart, (UINTN)PhitHob->EfiFreeMemoryBottom - (UINTN)(*HobStart));
+    *HobStart = NewHobList;
+  } else {
+    ASSERT (NewHobList != NULL);
+  }
 
+  gHobList = *HobStart;
   if (MemorySpaceMapHobList != NULL) {
     //
     // Add and allocate the memory space that covers HOB List to the memory services
diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c
index 7cc829b17402..94ed3111688b 100644
--- a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c
+++ b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c
@@ -967,6 +967,32 @@ InitializeDxeNxMemoryProtectionPolicy (
   }
 }
 
+/**
+  Mark the HOB list as read-only and non-executable.
+**/
+STATIC
+VOID
+ProtectHobList (
+  VOID
+  )
+{
+  EFI_PEI_HOB_POINTERS  Hob;
+
+  Hob.Raw = GetHobList ();
+
+  // Find the end of the HOB list.
+  while (!END_OF_HOB_LIST (Hob)) {
+    Hob.Raw = GET_NEXT_HOB (Hob);
+  }
+
+  // Protect the HOB list.
+  SetUefiImageMemoryAttributes (
+    (UINTN)gHobList,
+    ALIGN_VALUE (((UINTN)Hob.Raw + GET_HOB_LENGTH (Hob)) - (UINTN)GetHobList (), EFI_PAGE_SIZE),
+    EFI_MEMORY_XP | EFI_MEMORY_RO
+    );
+}
+
 /**
   A notification for CPU_ARCH protocol.
 
@@ -1007,6 +1033,9 @@ MemoryProtectionCpuArchProtocolNotify (
   //
   HeapGuardCpuArchProtocolNotify ();
 
+  // Mark the HOB list XP and RO.
+  ProtectHobList ();
+
   if (mImageProtectionPolicy == 0) {
     goto Done;
   }
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108868): https://edk2.groups.io/g/devel/message/108868
Mute This Topic: https://groups.io/mt/101469943/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 07/28] MdeModulePkg: Check Print Level Before Dumping GCD Memory Map
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (5 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 06/28] MdeModulePkg: Apply Protections to the HOB List Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 08/28] UefiCpuPkg: Always Set Stack Guard in MpPei Init Taylor Beebe
                   ` (20 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao, Dandan Bi

When page/pool protections are active, the GCD sync process takes
quite a bit longer than normal. This behavior is primarily due to
a function which dumps the GCD memory map to the console. This
dump function runs only on DEBUG builds but will iterate through
the GCD memory map dozens of times even when the print level doesn't
include DEBUG_GCD. This patch adds a check for the DEBUG_GCD print
level before dumping the GCD memory map which saves several seconds
during boot when page/pool protections are active.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Dandan Bi <dandan.bi@intel.com>
---
 MdeModulePkg/Core/Dxe/Gcd/Gcd.c   | 4 ++++
 MdeModulePkg/Core/Dxe/DxeMain.inf | 1 +
 2 files changed, 5 insertions(+)

diff --git a/MdeModulePkg/Core/Dxe/Gcd/Gcd.c b/MdeModulePkg/Core/Dxe/Gcd/Gcd.c
index 72bd036eab1e..392586d5b17c 100644
--- a/MdeModulePkg/Core/Dxe/Gcd/Gcd.c
+++ b/MdeModulePkg/Core/Dxe/Gcd/Gcd.c
@@ -150,6 +150,10 @@ CoreDumpGcdMemorySpaceMap (
   EFI_GCD_MEMORY_SPACE_DESCRIPTOR  *MemorySpaceMap;
   UINTN                            Index;
 
+  if ((PcdGet32 (PcdDebugPrintErrorLevel) & DEBUG_GCD) == 0) {
+    return;
+  }
+
   Status = CoreGetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap);
   ASSERT (Status == EFI_SUCCESS && MemorySpaceMap != NULL);
 
diff --git a/MdeModulePkg/Core/Dxe/DxeMain.inf b/MdeModulePkg/Core/Dxe/DxeMain.inf
index 35d5bf0dee6f..6c896a0e7f0f 100644
--- a/MdeModulePkg/Core/Dxe/DxeMain.inf
+++ b/MdeModulePkg/Core/Dxe/DxeMain.inf
@@ -187,6 +187,7 @@ [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask                   ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                           ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdFwVolDxeMaxEncapsulationDepth           ## CONSUMES
+  gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel                          ## CONSUMES
 
 # [Hob]
 # RESOURCE_DESCRIPTOR   ## CONSUMES
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108869): https://edk2.groups.io/g/devel/message/108869
Mute This Topic: https://groups.io/mt/101469944/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 08/28] UefiCpuPkg: Always Set Stack Guard in MpPei Init
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (6 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 07/28] MdeModulePkg: Check Print Level Before Dumping GCD Memory Map Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 09/28] ArmVirtPkg: Add Memory Protection Library Definitions to Platforms Taylor Beebe
                   ` (19 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Eric Dong, Ray Ni, Rahul Kumar, Gerd Hoffmann

Memory protection is not set in PEI and ingested during and
after DXE handoff. This paradigm means that the platform cannot
reliably query the stack guard setting during MpInit. Because the
execution path of PEI consistent and no third party
code is executed, setting the stack guard in MpInit on every
boot should be fine.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
---
 UefiCpuPkg/CpuMpPei/CpuMpPei.c   |  8 +++-----
 UefiCpuPkg/CpuMpPei/CpuPaging.c  | 16 ++++++++--------
 UefiCpuPkg/CpuMpPei/CpuMpPei.h   |  3 ++-
 UefiCpuPkg/CpuMpPei/CpuMpPei.inf |  1 -
 4 files changed, 13 insertions(+), 15 deletions(-)

diff --git a/UefiCpuPkg/CpuMpPei/CpuMpPei.c b/UefiCpuPkg/CpuMpPei/CpuMpPei.c
index b504bea3cfeb..ca0c6bdb4b21 100644
--- a/UefiCpuPkg/CpuMpPei/CpuMpPei.c
+++ b/UefiCpuPkg/CpuMpPei/CpuMpPei.c
@@ -469,10 +469,6 @@ InitializeMpExceptionStackSwitchHandlers (
   EFI_STATUS                      Status;
   UINT8                           *Buffer;
 
-  if (!PcdGetBool (PcdCpuStackGuard)) {
-    return;
-  }
-
   Status = MpInitLibGetNumberOfProcessors (&NumberOfProcessors, NULL);
   ASSERT_EFI_ERROR (Status);
 
@@ -589,7 +585,9 @@ InitializeCpuMpWorker (
   //
   // Special initialization for the sake of Stack Guard
   //
-  InitializeMpExceptionStackSwitchHandlers ();
+  if (mInitStackGuard) {
+    InitializeMpExceptionStackSwitchHandlers ();
+  }
 
   //
   // Update and publish CPU BIST information
diff --git a/UefiCpuPkg/CpuMpPei/CpuPaging.c b/UefiCpuPkg/CpuMpPei/CpuPaging.c
index b7ddb0005b6f..0ab8ceeee8a6 100644
--- a/UefiCpuPkg/CpuMpPei/CpuPaging.c
+++ b/UefiCpuPkg/CpuMpPei/CpuPaging.c
@@ -68,6 +68,8 @@ EFI_PEI_NOTIFY_DESCRIPTOR  mPostMemNotifyList[] = {
   }
 };
 
+BOOLEAN  mInitStackGuard = FALSE;
+
 /**
   The function will check if IA32 PAE is supported.
 
@@ -532,7 +534,7 @@ SetupStackGuardPage (
 }
 
 /**
-  Enable/setup stack guard for each processor if PcdCpuStackGuard is set to TRUE.
+  Enable/setup stack guard for each processor.
 
   Doing this in the memory-discovered callback is to make sure the Stack Guard
   feature to cover as most PEI code as possible.
@@ -553,7 +555,6 @@ MemoryDiscoveredPpiNotifyCallback (
   )
 {
   EFI_STATUS              Status;
-  BOOLEAN                 InitStackGuard;
   EDKII_MIGRATED_FV_INFO  *MigratedFvInfo;
   EFI_PEI_HOB_POINTERS    Hob;
   IA32_CR0                Cr0;
@@ -563,11 +564,10 @@ MemoryDiscoveredPpiNotifyCallback (
   // initialization later will not contain paging information and then fail
   // the task switch (for the sake of stack switch).
   //
-  InitStackGuard = FALSE;
-  Hob.Raw        = NULL;
+  Hob.Raw = NULL;
   if (IsIa32PaeSupported ()) {
-    Hob.Raw        = GetFirstGuidHob (&gEdkiiMigratedFvInfoGuid);
-    InitStackGuard = PcdGetBool (PcdCpuStackGuard);
+    Hob.Raw         = GetFirstGuidHob (&gEdkiiMigratedFvInfoGuid);
+    mInitStackGuard = TRUE;
   }
 
   //
@@ -575,7 +575,7 @@ MemoryDiscoveredPpiNotifyCallback (
   // is to enable paging if it is not enabled (only in 32bit mode).
   //
   Cr0.UintN = AsmReadCr0 ();
-  if ((Cr0.Bits.PG == 0) && (InitStackGuard || (Hob.Raw != NULL))) {
+  if ((Cr0.Bits.PG == 0) && (mInitStackGuard || (Hob.Raw != NULL))) {
     ASSERT (sizeof (UINTN) == sizeof (UINT32));
 
     Status = EnablePaePageTable ();
@@ -588,7 +588,7 @@ MemoryDiscoveredPpiNotifyCallback (
   Status = InitializeCpuMpWorker ((CONST EFI_PEI_SERVICES **)PeiServices);
   ASSERT_EFI_ERROR (Status);
 
-  if (InitStackGuard) {
+  if (mInitStackGuard) {
     SetupStackGuardPage ();
   }
 
diff --git a/UefiCpuPkg/CpuMpPei/CpuMpPei.h b/UefiCpuPkg/CpuMpPei/CpuMpPei.h
index 1b9a94e18fdf..d0db4e480e13 100644
--- a/UefiCpuPkg/CpuMpPei/CpuMpPei.h
+++ b/UefiCpuPkg/CpuMpPei/CpuMpPei.h
@@ -31,6 +31,7 @@
 #include <Library/CpuPageTableLib.h>
 
 extern EFI_PEI_PPI_DESCRIPTOR  mPeiCpuMpPpiDesc;
+extern BOOLEAN                 mInitStackGuard;
 
 /**
   This service retrieves the number of logical processor in the platform
@@ -426,7 +427,7 @@ InitializeCpuMpWorker (
   );
 
 /**
-  Enable/setup stack guard for each processor if PcdCpuStackGuard is set to TRUE.
+  Enable/setup stack guard for each processor.
 
   Doing this in the memory-discovered callback is to make sure the Stack Guard
   feature to cover as most PEI code as possible.
diff --git a/UefiCpuPkg/CpuMpPei/CpuMpPei.inf b/UefiCpuPkg/CpuMpPei/CpuMpPei.inf
index 865be5627e85..6a987754120a 100644
--- a/UefiCpuPkg/CpuMpPei/CpuMpPei.inf
+++ b/UefiCpuPkg/CpuMpPei/CpuMpPei.inf
@@ -64,7 +64,6 @@ [Ppis]
 
 [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                       ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList              ## SOMETIMES_CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize                    ## SOMETIMES_CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuApStackSize                           ## SOMETIMES_CONSUMES
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108870): https://edk2.groups.io/g/devel/message/108870
Mute This Topic: https://groups.io/mt/101469946/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 09/28] ArmVirtPkg: Add Memory Protection Library Definitions to Platforms
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (7 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 08/28] UefiCpuPkg: Always Set Stack Guard in MpPei Init Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 10/28] OvmfPkg: " Taylor Beebe
                   ` (18 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Leif Lindholm, Sami Mujawar, Gerd Hoffmann,
	Julien Grall

Add library classes for SetMemoryProtectionsLib and
GetMemoryProtectionsLib to ArmVirtPkg.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Sami Mujawar <sami.mujawar@arm.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Julien Grall <julien@xen.org>
---
 ArmVirtPkg/ArmVirt.dsc.inc | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc
index 3f7bac6bf33a..f76601503cd9 100644
--- a/ArmVirtPkg/ArmVirt.dsc.inc
+++ b/ArmVirtPkg/ArmVirt.dsc.inc
@@ -156,6 +156,12 @@ [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   RngLib|MdeModulePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
 
+  #
+  # Memory Protection Libraries for setting and getting memory protection settings
+  #
+  SetMemoryProtectionsLib|MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf
+
   #
   # Secure Boot dependencies
   #
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108871): https://edk2.groups.io/g/devel/message/108871
Mute This Topic: https://groups.io/mt/101469947/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 10/28] OvmfPkg: Add Memory Protection Library Definitions to Platforms
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (8 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 09/28] ArmVirtPkg: Add Memory Protection Library Definitions to Platforms Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 11/28] OvmfPkg: Apply Memory Protections via SetMemoryProtectionsLib Taylor Beebe
                   ` (17 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Rebecca Cran, Peter Grehan, Corvin Köhne, Jianyong Wu,
	Anatol Belski, Anthony Perard, Julien Grall

Add library classes for SetMemoryProtectionsLib and
GetMemoryProtectionsLib to OvmfPkg platfomrs.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rebecca Cran <rebecca@bsdio.com>
Cc: Peter Grehan <grehan@freebsd.org>
Cc: Corvin Köhne <corvink@freebsd.org>
Cc: Jianyong Wu <jianyong.wu@arm.com>
Cc: Anatol Belski <anbelski@linux.microsoft.com>
Cc: Anthony Perard <anthony.perard@citrix.com>
Cc: Julien Grall <julien@xen.org>
---
 OvmfPkg/AmdSev/AmdSevX64.dsc                          |  1 +
 OvmfPkg/Bhyve/BhyveX64.dsc                            |  1 +
 OvmfPkg/CloudHv/CloudHvX64.dsc                        |  1 +
 OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc | 15 +++++++++++++++
 OvmfPkg/IntelTdx/IntelTdxX64.dsc                      |  2 ++
 OvmfPkg/Microvm/MicrovmX64.dsc                        |  2 ++
 OvmfPkg/OvmfPkgIa32.dsc                               |  1 +
 OvmfPkg/OvmfPkgIa32X64.dsc                            |  1 +
 OvmfPkg/OvmfPkgX64.dsc                                |  1 +
 OvmfPkg/OvmfXen.dsc                                   |  2 ++
 OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc                   |  2 ++
 11 files changed, 29 insertions(+)

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index 302c90e7c2b4..b67b50b833b9 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -203,6 +203,7 @@ [LibraryClasses]
   S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf
 
 !include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
 
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc
index 6693342c5f6e..5af5831196f6 100644
--- a/OvmfPkg/Bhyve/BhyveX64.dsc
+++ b/OvmfPkg/Bhyve/BhyveX64.dsc
@@ -229,6 +229,7 @@ [LibraryClasses]
   XenPlatformLib|OvmfPkg/Library/XenPlatformLib/XenPlatformLib.inf
 
 !include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
 
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc
index 35942e02df93..c550ebcd659e 100644
--- a/OvmfPkg/CloudHv/CloudHvX64.dsc
+++ b/OvmfPkg/CloudHv/CloudHvX64.dsc
@@ -239,6 +239,7 @@ [LibraryClasses]
   OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf
 
 !include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
 
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
diff --git a/OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc b/OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
new file mode 100644
index 000000000000..049fdef3f0c1
--- /dev/null
+++ b/OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
@@ -0,0 +1,15 @@
+##
+#    SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+#
+# Memory Protection Libraries
+#
+[LibraryClasses.common]
+  SetMemoryProtectionsLib|MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
+
+[LibraryClasses.common.SMM_CORE, LibraryClasses.common.DXE_SMM_DRIVER, LibraryClasses.common.MM_CORE_STANDALONE, LibraryClasses.common.MM_STANDALONE]
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf
+
+[LibraryClasses.common.DXE_CORE, LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION, LibraryClasses.common.UEFI_DRIVER]
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf
diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
index 182ec3705dd3..a3370f45940c 100644
--- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
@@ -211,6 +211,8 @@ [LibraryClasses]
   Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibNull/DxeTcg2PhysicalPresenceLib.inf
   TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf
 
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
+
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf
diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index 0f26f2a9a97d..da5a4862bfdc 100644
--- a/OvmfPkg/Microvm/MicrovmX64.dsc
+++ b/OvmfPkg/Microvm/MicrovmX64.dsc
@@ -238,6 +238,8 @@ [LibraryClasses]
   Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibNull/DxeTcg2PhysicalPresenceLib.inf
   TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf
 
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
+
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   CcExitLib|OvmfPkg/Library/CcExitLib/CcExitLib.inf
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index fcd3a3fda5f2..d4d14b69ef1d 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -246,6 +246,7 @@ [LibraryClasses]
   OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf
 
 !include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
 
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index d0ae0b996d66..674010323df1 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -251,6 +251,7 @@ [LibraryClasses]
   OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf
 
 !include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
 
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index a6811eee557e..08b70d76d292 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -267,6 +267,7 @@ [LibraryClasses]
   OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf
 
 !include OvmfPkg/Include/Dsc/OvmfTpmLibs.dsc.inc
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
 
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc
index ccd3a873c714..d80e20a151d7 100644
--- a/OvmfPkg/OvmfXen.dsc
+++ b/OvmfPkg/OvmfXen.dsc
@@ -231,6 +231,8 @@ [LibraryClasses]
   DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
 !endif
 
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
+
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf
diff --git a/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc b/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc
index 34b2037824f1..dd25a34796e5 100644
--- a/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc
+++ b/OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc
@@ -112,6 +112,8 @@ [LibraryClasses.common]
   TpmPlatformHierarchyLib|SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLibNull/PeiDxeTpmPlatformHierarchyLib.inf
 !endif
 
+!include OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
+
 [LibraryClasses.common.DXE_DRIVER]
   AcpiPlatformLib|OvmfPkg/Library/AcpiPlatformLib/DxeAcpiPlatformLib.inf
   ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108872): https://edk2.groups.io/g/devel/message/108872
Mute This Topic: https://groups.io/mt/101469948/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 11/28] OvmfPkg: Apply Memory Protections via SetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (9 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 10/28] OvmfPkg: " Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 12/28] OvmfPkg: Update PeilessStartupLib to use SetMemoryProtectionsLib Taylor Beebe
                   ` (16 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann

Use SetMemoryProtectionsLib to set the memory protections for
the platform in both normal and PEI-less boot. The protections
set are equivalent to the PCD settings and the ability to set
NxForStack via QemuCfg is preserved. Once the transition to use
SetMemoryProtectionsLib and GetMemoryProtectionsLib is complete
in the rest of EDK2, the mechanics of setting protections in
OvmfPkg will be updated and the memory protection PCDs will
be deleted.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
---
 OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c      | 15 +++++++++++++--
 OvmfPkg/PlatformPei/Platform.c                          | 15 +++++++++++++--
 OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf |  3 +++
 OvmfPkg/PlatformPei/PlatformPei.inf                     |  1 +
 4 files changed, 30 insertions(+), 4 deletions(-)

diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
index 1632a2317718..cf645aad3246 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
@@ -14,10 +14,13 @@
 #include <Protocol/DebugSupport.h>
 #include <Library/TdxLib.h>
 #include <IndustryStandard/Tdx.h>
+#include <Library/PcdLib.h>
 #include <Library/PrePiLib.h>
 #include <Library/PeilessStartupLib.h>
 #include <Library/PlatformInitLib.h>
 #include <Library/TdxHelperLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
+#include <Library/QemuFwCfgSimpleParserLib.h>
 #include <ConfidentialComputingGuestAttr.h>
 #include <Guid/MemoryTypeInformation.h>
 #include <OvmfPlatforms.h>
@@ -42,7 +45,9 @@ InitializePlatform (
   EFI_HOB_PLATFORM_INFO  *PlatformInfoHob
   )
 {
-  VOID  *VariableStore;
+  VOID                            *VariableStore;
+  DXE_MEMORY_PROTECTION_SETTINGS  DxeSettings;
+  MM_MEMORY_PROTECTION_SETTINGS   MmSettings;
 
   DEBUG ((DEBUG_INFO, "InitializePlatform in Pei-less boot\n"));
   PlatformDebugDumpCmos ();
@@ -104,7 +109,13 @@ InitializePlatform (
 
   PlatformMemMapInitialization (PlatformInfoHob);
 
-  PlatformNoexecDxeInitialization (PlatformInfoHob);
+  DxeSettings                                 = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsPcd].Settings;
+  MmSettings                                  = MmMemoryProtectionProfiles[MmMemoryProtectionSettingsPcd].Settings;
+  DxeSettings.StackExecutionProtectionEnabled = PcdGetBool (PcdSetNxForStack);
+  QemuFwCfgParseBool ("opt/ovmf/PcdSetNxForStack", &DxeSettings.StackExecutionProtectionEnabled);
+
+  SetDxeMemoryProtectionSettings (&DxeSettings, DxeMemoryProtectionSettingsPcd);
+  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsPcd);
 
   if (TdIsEnabled ()) {
     PlatformInfoHob->PcdConfidentialComputingGuestAttr = CCAttrIntelTdx;
diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c
index f5dc41c3a8c4..bcd8d3a1be14 100644
--- a/OvmfPkg/PlatformPei/Platform.c
+++ b/OvmfPkg/PlatformPei/Platform.c
@@ -38,6 +38,7 @@
 #include <IndustryStandard/QemuCpuHotplug.h>
 #include <Library/MemEncryptSevLib.h>
 #include <OvmfPlatforms.h>
+#include <Library/SetMemoryProtectionsLib.h>
 
 #include "Platform.h"
 
@@ -304,8 +305,10 @@ InitializePlatform (
   IN CONST EFI_PEI_SERVICES     **PeiServices
   )
 {
-  EFI_HOB_PLATFORM_INFO  *PlatformInfoHob;
-  EFI_STATUS             Status;
+  EFI_HOB_PLATFORM_INFO           *PlatformInfoHob;
+  EFI_STATUS                      Status;
+  DXE_MEMORY_PROTECTION_SETTINGS  DxeSettings;
+  MM_MEMORY_PROTECTION_SETTINGS   MmSettings;
 
   DEBUG ((DEBUG_INFO, "Platform PEIM Loaded\n"));
   PlatformInfoHob = BuildPlatformInfoHob ();
@@ -342,6 +345,14 @@ InitializePlatform (
 
   PublishPeiMemory (PlatformInfoHob);
 
+  DxeSettings                                 = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsPcd].Settings;
+  MmSettings                                  = MmMemoryProtectionProfiles[MmMemoryProtectionSettingsPcd].Settings;
+  DxeSettings.StackExecutionProtectionEnabled = PcdGetBool (PcdSetNxForStack);
+  QemuFwCfgParseBool ("opt/ovmf/PcdSetNxForStack", &DxeSettings.StackExecutionProtectionEnabled);
+
+  SetDxeMemoryProtectionSettings (&DxeSettings, DxeMemoryProtectionSettingsPcd);
+  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsPcd);
+
   PlatformQemuUc32BaseInitialization (PlatformInfoHob);
 
   InitializeRamRegions (PlatformInfoHob);
diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
index 585d50463748..f0a8a5a56df4 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
@@ -56,6 +56,8 @@ [LibraryClasses]
   PrePiLib
   QemuFwCfgLib
   PlatformInitLib
+  SetMemoryProtectionsLib
+  QemuFwCfgSimpleParserLib
 
 [Guids]
   gEfiHobMemoryAllocModuleGuid
@@ -81,6 +83,7 @@ [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy       ## SOMETIMES_CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack                       ## CONSUMES
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize
   gUefiOvmfPkgTokenSpaceGuid.PcdSecureBootSupported
diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf
index 3934aeed9514..6b8442d12b2c 100644
--- a/OvmfPkg/PlatformPei/PlatformPei.inf
+++ b/OvmfPkg/PlatformPei/PlatformPei.inf
@@ -65,6 +65,7 @@ [LibraryClasses]
   PcdLib
   CcExitLib
   PlatformInitLib
+  SetMemoryProtectionsLib
 
 [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108873): https://edk2.groups.io/g/devel/message/108873
Mute This Topic: https://groups.io/mt/101469949/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 12/28] OvmfPkg: Update PeilessStartupLib to use SetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (10 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 11/28] OvmfPkg: Apply Memory Protections via SetMemoryProtectionsLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 13/28] UefiPayloadPkg: Update DXE Handoff " Taylor Beebe
                   ` (15 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann

This patch updates the DXE Handoff in PEI-less Startup to use
SetMemoryProtectionsLib to get the platform memory protection settings
and build the page tables based on the applied protections.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
---
 OvmfPkg/Library/PeilessStartupLib/DxeLoad.c             |  6 +++++-
 OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c   | 13 ++++++++-----
 OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf |  4 ----
 3 files changed, 13 insertions(+), 10 deletions(-)

diff --git a/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c b/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c
index d34690eb8a0b..f8ff53876369 100644
--- a/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c
+++ b/OvmfPkg/Library/PeilessStartupLib/DxeLoad.c
@@ -20,9 +20,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Library/PrePiLib.h>
 #include "X64/PageTables.h"
 #include <Library/ReportStatusCodeLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
 
 #define STACK_SIZE  0x20000
-extern EFI_GUID  gEfiNonCcFvGuid;
+extern EFI_GUID             gEfiNonCcFvGuid;
+MEMORY_PROTECTION_SETTINGS  mMps = { 0 };
 
 /**
    Transfers control to DxeCore.
@@ -42,6 +44,8 @@ HandOffToDxeCore (
   VOID   *TopOfStack;
   UINTN  PageTables;
 
+  GetCurrentMemoryProtectionSettings (&mMps);
+
   //
   // Clear page 0 and mark it as allocated if NULL pointer detection is enabled.
   //
diff --git a/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c b/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c
index e2c1bac5e059..41521e3d3d71 100644
--- a/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c
+++ b/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c
@@ -17,6 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Library/PcdLib.h>
 #include <Guid/MemoryTypeInformation.h>
 #include <Guid/MemoryAllocationHob.h>
+#include <Library/SetMemoryProtectionsLib.h>
 #include <Register/Intel/Cpuid.h>
 #include <Library/PlatformInitLib.h>
 #include "PageTables.h"
@@ -45,6 +46,8 @@ UINT64  mLevelSize[5] = {
   SIZE_512GB
 };
 
+extern MEMORY_PROTECTION_SETTINGS  mMps;
+
 BOOLEAN
 IsSetNxForStack (
   VOID
@@ -142,7 +145,7 @@ IsNullDetectionEnabled (
   VOID
   )
 {
-  return ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) != 0);
+  return mMps.Dxe.NullPointerDetection.Enabled;
 }
 
 /**
@@ -197,8 +200,8 @@ IsEnableNonExecNeeded (
   // Features controlled by Following PCDs need this feature to be enabled.
   //
   return (IsSetNxForStack () ||
-          FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) != 0 ||
-          PcdGet32 (PcdImageProtectionPolicy) != 0);
+          !IsZeroBuffer (&mMps.Dxe.ExecutionProtection.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE) ||
+          (mMps.Dxe.ImageProtection.ProtectImageFromFv || mMps.Dxe.ImageProtection.ProtectImageFromUnknown));
 }
 
 /**
@@ -241,7 +244,7 @@ ToSplitPageTable (
     return TRUE;
   }
 
-  if (FixedPcdGetBool (PcdCpuStackGuard)) {
+  if (mMps.Dxe.CpuStackGuardEnabled) {
     if ((StackBase >= Address) && (StackBase < (Address + Size))) {
       return TRUE;
     }
@@ -427,7 +430,7 @@ Split2MPageTo4K (
     PageTableEntry->Bits.ReadWrite = 1;
 
     if ((IsNullDetectionEnabled () && (PhysicalAddress4K == 0)) ||
-        (FixedPcdGetBool (PcdCpuStackGuard) && (PhysicalAddress4K == StackBase)))
+        (mMps.Dxe.CpuStackGuardEnabled && (PhysicalAddress4K == StackBase)))
     {
       PageTableEntry->Bits.Present = 0;
     } else {
diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
index f0a8a5a56df4..47bd42d23d11 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
@@ -77,12 +77,8 @@ [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbSize
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBase
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplBuildPageTables       ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard               ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable              ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy       ## SOMETIMES_CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack                       ## CONSUMES
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108874): https://edk2.groups.io/g/devel/message/108874
Mute This Topic: https://groups.io/mt/101469950/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 13/28] UefiPayloadPkg: Update DXE Handoff to use SetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (11 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 12/28] OvmfPkg: Update PeilessStartupLib to use SetMemoryProtectionsLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 14/28] MdeModulePkg: " Taylor Beebe
                   ` (14 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Guo Dong, Sean Rhodes, James Lu, Gua Guo

Update the DXE handoff logic in UefiPayloadPkg to use
SetMemoryProtectionsLib to fetch the platform memory protection
settings and reference them when creating the page tables.

Because the protection profile is equivalent to the PCD settings
even when the platform does not explicitly set a profile, this
updated does not cause a torn state.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Guo Dong <guo.dong@intel.com>
Cc: Sean Rhodes <sean@starlabs.systems>
Cc: James Lu <james.lu@intel.com>
Cc: Gua Guo <gua.guo@intel.com>
---
 UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c        | 11 +++++++++--
 UefiPayloadPkg/UefiPayloadEntry/LoadDxeCore.c             |  2 ++
 UefiPayloadPkg/UefiPayloadEntry/X64/DxeLoadFunc.c         |  8 ++++++--
 UefiPayloadPkg/UefiPayloadEntry/X64/VirtualMemory.c       | 15 +++++++++------
 UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h        |  1 +
 UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf      |  9 +--------
 UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf |  9 +--------
 UefiPayloadPkg/UefiPayloadPkg.dsc                         | 12 ++++++++++++
 8 files changed, 41 insertions(+), 26 deletions(-)

diff --git a/UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c b/UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c
index 61a9f01ec9e7..4ede962e6544 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c
+++ b/UefiPayloadPkg/UefiPayloadEntry/Ia32/DxeLoadFunc.c
@@ -78,6 +78,8 @@ GLOBAL_REMOVE_IF_UNREFERENCED  IA32_DESCRIPTOR  gLidtDescriptor = {
   0
 };
 
+extern MEMORY_PROTECTION_SETTINGS  mMps;
+
 /**
   Allocates and fills in the Page Directory and Page Table Entries to
   establish a 4G page table.
@@ -227,11 +229,14 @@ ToBuildPageTable (
     return TRUE;
   }
 
-  if (PcdGet8 (PcdHeapGuardPropertyMask) != 0) {
+  if (mMps.Dxe.HeapGuard.PageGuardEnabled ||
+      mMps.Dxe.HeapGuard.PageGuardEnabled ||
+      mMps.Dxe.HeapGuard.FreedMemoryGuardEnabled)
+  {
     return TRUE;
   }
 
-  if (PcdGetBool (PcdCpuStackGuard)) {
+  if (mMps.Dxe.CpuStackGuardEnabled) {
     return TRUE;
   }
 
@@ -268,6 +273,8 @@ HandOffToDxeCore (
   UINT32                   Index;
   X64_IDT_TABLE            *IdtTableForX64;
 
+  GetCurrentMemoryProtectionSettings (&mMps);
+
   //
   // Clear page 0 and mark it as allocated if NULL pointer detection is enabled.
   //
diff --git a/UefiPayloadPkg/UefiPayloadEntry/LoadDxeCore.c b/UefiPayloadPkg/UefiPayloadEntry/LoadDxeCore.c
index 898d610951fa..a4074346c059 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/LoadDxeCore.c
+++ b/UefiPayloadPkg/UefiPayloadEntry/LoadDxeCore.c
@@ -8,6 +8,8 @@
 
 #include "UefiPayloadEntry.h"
 
+MEMORY_PROTECTION_SETTINGS  mMps = { 0 };
+
 /**
   Allocate pages for code.
 
diff --git a/UefiPayloadPkg/UefiPayloadEntry/X64/DxeLoadFunc.c b/UefiPayloadPkg/UefiPayloadEntry/X64/DxeLoadFunc.c
index 346e3feb0459..002ae6e5ab97 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/X64/DxeLoadFunc.c
+++ b/UefiPayloadPkg/UefiPayloadEntry/X64/DxeLoadFunc.c
@@ -17,6 +17,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include "UefiPayloadEntry.h"
 #define STACK_SIZE  0x20000
 
+extern MEMORY_PROTECTION_SETTINGS  mMps;
+
 /**
    Transfers control to DxeCore.
 
@@ -40,6 +42,8 @@ HandOffToDxeCore (
   VOID   *GhcbBase;
   UINTN  GhcbSize;
 
+  GetCurrentMemoryProtectionSettings (&mMps);
+
   //
   // Clear page 0 and mark it as allocated if NULL pointer detection is enabled.
   //
@@ -83,8 +87,8 @@ HandOffToDxeCore (
     // Set NX for stack feature also require PcdDxeIplBuildPageTables be TRUE
     // for the DxeIpl and the DxeCore are both X64.
     //
-    ASSERT (PcdGetBool (PcdSetNxForStack) == FALSE);
-    ASSERT (PcdGetBool (PcdCpuStackGuard) == FALSE);
+    ASSERT (!mMps.Dxe.StackExecutionProtectionEnabled);
+    ASSERT (!mMps.Dxe.CpuStackGuardEnabled);
   }
 
   if (FeaturePcdGet (PcdDxeIplBuildPageTables)) {
diff --git a/UefiPayloadPkg/UefiPayloadEntry/X64/VirtualMemory.c b/UefiPayloadPkg/UefiPayloadEntry/X64/VirtualMemory.c
index 1899404b244c..6a986c82cc4b 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/X64/VirtualMemory.c
+++ b/UefiPayloadPkg/UefiPayloadEntry/X64/VirtualMemory.c
@@ -27,11 +27,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Library/DebugLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <Library/MemoryAllocationLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
 #include <Library/PcdLib.h>
 #include <Library/HobLib.h>
 #include <Register/Intel/Cpuid.h>
 #include "VirtualMemory.h"
 
+extern MEMORY_PROTECTION_SETTINGS  mMps;
+
 //
 // Global variable to keep track current available memory used as page table.
 //
@@ -115,7 +118,7 @@ IsNullDetectionEnabled (
   VOID
   )
 {
-  return ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) != 0);
+  return mMps.Dxe.NullPointerDetection.Enabled;
 }
 
 /**
@@ -169,9 +172,9 @@ IsEnableNonExecNeeded (
   // XD flag (BIT63) in page table entry is only valid if IA32_EFER.NXE is set.
   // Features controlled by Following PCDs need this feature to be enabled.
   //
-  return (PcdGetBool (PcdSetNxForStack) ||
-          PcdGet64 (PcdDxeNxMemoryProtectionPolicy) != 0 ||
-          PcdGet32 (PcdImageProtectionPolicy) != 0);
+  return (mMps.Dxe.StackExecutionProtectionEnabled ||
+          !IsZeroBuffer (&mMps.Dxe.ExecutionProtection.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE) ||
+          (mMps.Dxe.ImageProtection.ProtectImageFromFv || mMps.Dxe.ImageProtection.ProtectImageFromUnknown));
 }
 
 /**
@@ -399,14 +402,14 @@ Split2MPageTo4K (
     PageTableEntry->Bits.ReadWrite = 1;
 
     if ((IsNullDetectionEnabled () && (PhysicalAddress4K == 0)) ||
-        (PcdGetBool (PcdCpuStackGuard) && (PhysicalAddress4K == StackBase)))
+        (mMps.Dxe.CpuStackGuardEnabled && (PhysicalAddress4K == StackBase)))
     {
       PageTableEntry->Bits.Present = 0;
     } else {
       PageTableEntry->Bits.Present = 1;
     }
 
-    if (  PcdGetBool (PcdSetNxForStack)
+    if (  mMps.Dxe.StackExecutionProtectionEnabled
        && (PhysicalAddress4K >= StackBase)
        && (PhysicalAddress4K < StackBase + StackSize))
     {
diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
index ad8a9fd22b66..c966f3583c77 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
+++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
@@ -13,6 +13,7 @@
 
 #include <Library/BaseLib.h>
 #include <Library/BaseMemoryLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
 #include <Library/MemoryAllocationLib.h>
 #include <Library/DebugLib.h>
 #include <Library/PeCoffLib.h>
diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf
index e2af8a4b7c1b..589dd9d3a99c 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf
+++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf
@@ -55,6 +55,7 @@ [LibraryClasses]
   PeCoffLib
   PlatformSupportLib
   CpuLib
+  SetMemoryProtectionsLib
 
 [Guids]
   gEfiMemoryTypeInformationGuid
@@ -76,9 +77,6 @@ [FeaturePcd.X64]
 [Pcd.IA32,Pcd.X64]
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable                      ## SOMETIMES_CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                       ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbBase                            ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbSize                            ## CONSUMES
 
@@ -91,8 +89,3 @@ [Pcd.IA32,Pcd.X64]
   gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType
   gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData
   gUefiPayloadPkgTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode
-
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack               ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy       ## SOMETIMES_CONSUMES
-
diff --git a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf
index 5112cdc1e5df..3e99011e0ac6 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf
+++ b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf
@@ -53,6 +53,7 @@ [LibraryClasses]
   HobLib
   PeCoffLib
   CpuLib
+  SetMemoryProtectionsLib
 
 [Guids]
   gEfiMemoryTypeInformationGuid
@@ -81,17 +82,9 @@ [Pcd.IA32,Pcd.X64]
   gUefiPayloadPkgTokenSpaceGuid.PcdPcdDriverFile
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable                      ## SOMETIMES_CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                       ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbBase                            ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbSize                            ## CONSUMES
 
   gUefiPayloadPkgTokenSpaceGuid.PcdPayloadFdMemBase
   gUefiPayloadPkgTokenSpaceGuid.PcdPayloadFdMemSize
   gUefiPayloadPkgTokenSpaceGuid.PcdSystemMemoryUefiRegionSize
-
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack               ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy       ## SOMETIMES_CONSUMES
-
diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc
index 47812048ddcf..b00d75ba08db 100644
--- a/UefiPayloadPkg/UefiPayloadPkg.dsc
+++ b/UefiPayloadPkg/UefiPayloadPkg.dsc
@@ -312,6 +312,18 @@ [LibraryClasses]
   CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf
   ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
 
+#
+# Memory Protection Libraries
+#
+[LibraryClasses.common]
+  SetMemoryProtectionsLib|MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
+
+[LibraryClasses.common.SMM_CORE, LibraryClasses.common.DXE_SMM_DRIVER]
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf
+
+[LibraryClasses.common.DXE_CORE, LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION, LibraryClasses.common.UEFI_DRIVER]
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/DxeGetMemoryProtectionsLib.inf
+
 [LibraryClasses.common]
 !if $(BOOTSPLASH_IMAGE)
   SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108875): https://edk2.groups.io/g/devel/message/108875
Mute This Topic: https://groups.io/mt/101469951/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 14/28] MdeModulePkg: Update DXE Handoff to use SetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (12 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 13/28] UefiPayloadPkg: Update DXE Handoff " Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 15/28] ArmPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs Taylor Beebe
                   ` (13 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao, Dandan Bi

Update the DXE handoff logic in MdeModulePkg to use
SetMemoryProtectionsLib to fetch the platform memory protection
settings and reference them when creating the page tables.

Because the protection profile is equivalent to the PCD settings
even when the platform does not explicitly set a profile, this
updated does not cause a torn state.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Dandan Bi <dandan.bi@intel.com>
---
 MdeModulePkg/Core/DxeIplPeim/DxeHandoff.c        |  4 +++-
 MdeModulePkg/Core/DxeIplPeim/DxeLoad.c           |  2 ++
 MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c  |  9 +++++++--
 MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c   |  6 ++++--
 MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c | 16 ++++++++--------
 MdeModulePkg/Core/DxeIplPeim/DxeIpl.h            |  3 +++
 MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf          | 11 +----------
 7 files changed, 28 insertions(+), 23 deletions(-)

diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeHandoff.c b/MdeModulePkg/Core/DxeIplPeim/DxeHandoff.c
index 60400da3521a..9f7ed2069a46 100644
--- a/MdeModulePkg/Core/DxeIplPeim/DxeHandoff.c
+++ b/MdeModulePkg/Core/DxeIplPeim/DxeHandoff.c
@@ -33,13 +33,15 @@ HandOffToDxeCore (
   EFI_STATUS                  Status;
   EDKII_MEMORY_ATTRIBUTE_PPI  *MemoryPpi;
 
+  GetCurrentMemoryProtectionSettings (&mMps);
+
   //
   // Allocate 128KB for the Stack
   //
   BaseOfStack = AllocatePages (EFI_SIZE_TO_PAGES (STACK_SIZE));
   ASSERT (BaseOfStack != NULL);
 
-  if (PcdGetBool (PcdSetNxForStack)) {
+  if (mMps.Dxe.StackExecutionProtectionEnabled) {
     Status = PeiServicesLocatePpi (
                &gEdkiiMemoryAttributePpiGuid,
                0,
diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeLoad.c b/MdeModulePkg/Core/DxeIplPeim/DxeLoad.c
index 2c19f1a507ba..0789dbca6ad8 100644
--- a/MdeModulePkg/Core/DxeIplPeim/DxeLoad.c
+++ b/MdeModulePkg/Core/DxeIplPeim/DxeLoad.c
@@ -50,6 +50,8 @@ CONST EFI_PEI_NOTIFY_DESCRIPTOR  mMemoryDiscoveredNotifyList = {
   InstallIplPermanentMemoryPpis
 };
 
+MEMORY_PROTECTION_SETTINGS  mMps = { 0 };
+
 /**
   Entry point of DXE IPL PEIM.
 
diff --git a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c
index 4bc7b749b0fc..762c288d5924 100644
--- a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c
+++ b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c
@@ -219,11 +219,14 @@ ToBuildPageTable (
     return TRUE;
   }
 
-  if (PcdGet8 (PcdHeapGuardPropertyMask) != 0) {
+  if (mMps.Dxe.HeapGuard.PageGuardEnabled ||
+      mMps.Dxe.HeapGuard.PoolGuardEnabled ||
+      mMps.Dxe.HeapGuard.FreedMemoryGuardEnabled)
+  {
     return TRUE;
   }
 
-  if (PcdGetBool (PcdCpuStackGuard)) {
+  if (mMps.Dxe.CpuStackGuardEnabled) {
     return TRUE;
   }
 
@@ -265,6 +268,8 @@ HandOffToDxeCore (
   EFI_PEI_VECTOR_HANDOFF_INFO_PPI  *VectorHandoffInfoPpi;
   BOOLEAN                          BuildPageTablesIa32Pae;
 
+  GetCurrentMemoryProtectionSettings (&mMps);
+
   //
   // Clear page 0 and mark it as allocated if NULL pointer detection is enabled.
   //
diff --git a/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c
index fa2050cf023a..7e17a963e9ff 100644
--- a/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c
+++ b/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c
@@ -36,6 +36,8 @@ HandOffToDxeCore (
   VOID                             *GhcbBase;
   UINTN                            GhcbSize;
 
+  GetCurrentMemoryProtectionSettings (&mMps);
+
   //
   // Clear page 0 and mark it as allocated if NULL pointer detection is enabled.
   //
@@ -104,8 +106,8 @@ HandOffToDxeCore (
     // Set NX for stack feature also require PcdDxeIplBuildPageTables be TRUE
     // for the DxeIpl and the DxeCore are both X64.
     //
-    ASSERT (PcdGetBool (PcdSetNxForStack) == FALSE);
-    ASSERT (PcdGetBool (PcdCpuStackGuard) == FALSE);
+    ASSERT (!mMps.Dxe.StackExecutionProtectionEnabled);
+    ASSERT (!mMps.Dxe.CpuStackGuardEnabled);
   }
 
   //
diff --git a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c b/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c
index 980c2002d4f5..2c75702d6a25 100644
--- a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c
+++ b/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c
@@ -109,7 +109,7 @@ IsNullDetectionEnabled (
   VOID
   )
 {
-  return ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) != 0);
+  return mMps.Dxe.NullPointerDetection.Enabled;
 }
 
 /**
@@ -163,9 +163,9 @@ IsEnableNonExecNeeded (
   // XD flag (BIT63) in page table entry is only valid if IA32_EFER.NXE is set.
   // Features controlled by Following PCDs need this feature to be enabled.
   //
-  return (PcdGetBool (PcdSetNxForStack) ||
-          PcdGet64 (PcdDxeNxMemoryProtectionPolicy) != 0 ||
-          PcdGet32 (PcdImageProtectionPolicy) != 0);
+  return (mMps.Dxe.StackExecutionProtectionEnabled ||
+          !IsZeroBuffer (&mMps.Dxe.ExecutionProtection.EnabledForType, MPS_MEMORY_TYPE_BUFFER_SIZE) ||
+          mMps.Dxe.ImageProtection.ProtectImageFromFv || mMps.Dxe.ImageProtection.ProtectImageFromUnknown);
 }
 
 /**
@@ -214,13 +214,13 @@ ToSplitPageTable (
     return TRUE;
   }
 
-  if (PcdGetBool (PcdCpuStackGuard)) {
+  if (mMps.Dxe.CpuStackGuardEnabled) {
     if ((StackBase >= Address) && (StackBase < (Address + Size))) {
       return TRUE;
     }
   }
 
-  if (PcdGetBool (PcdSetNxForStack)) {
+  if (mMps.Dxe.StackExecutionProtectionEnabled) {
     if ((Address < StackBase + StackSize) && ((Address + Size) > StackBase)) {
       return TRUE;
     }
@@ -403,14 +403,14 @@ Split2MPageTo4K (
     PageTableEntry->Bits.ReadWrite = 1;
 
     if ((IsNullDetectionEnabled () && (PhysicalAddress4K == 0)) ||
-        (PcdGetBool (PcdCpuStackGuard) && (PhysicalAddress4K == StackBase)))
+        (mMps.Dxe.CpuStackGuardEnabled && (PhysicalAddress4K == StackBase)))
     {
       PageTableEntry->Bits.Present = 0;
     } else {
       PageTableEntry->Bits.Present = 1;
     }
 
-    if (  PcdGetBool (PcdSetNxForStack)
+    if (  mMps.Dxe.StackExecutionProtectionEnabled
        && (PhysicalAddress4K >= StackBase)
        && (PhysicalAddress4K < StackBase + StackSize))
     {
diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h
index 2f015befceca..f6826349c378 100644
--- a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h
+++ b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h
@@ -37,6 +37,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Library/UefiDecompressLib.h>
 #include <Library/ExtractGuidedSectionLib.h>
 #include <Library/BaseMemoryLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
 #include <Library/MemoryAllocationLib.h>
 #include <Library/PcdLib.h>
 #include <Library/DebugAgentLib.h>
@@ -46,6 +47,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #define STACK_SIZE      0x20000
 #define BSP_STORE_SIZE  0x4000
 
+extern MEMORY_PROTECTION_SETTINGS  mMps;
+
 //
 // This PPI is installed to indicate the end of the PEI usage of memory
 //
diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
index f1990eac7760..ccbf5c36d7f6 100644
--- a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
+++ b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
@@ -67,6 +67,7 @@ [LibraryClasses]
   DebugAgentLib
   PeiServicesTablePointerLib
   PerformanceLib
+  SetMemoryProtectionsLib
 
 [Ppis]
   gEfiDxeIplPpiGuid                      ## PRODUCES
@@ -101,20 +102,10 @@ [FeaturePcd]
 [Pcd.IA32,Pcd.X64]
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable                      ## SOMETIMES_CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                       ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse5LevelPageTable                  ## SOMETIMES_CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbBase                            ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbSize                            ## CONSUMES
 
-[Pcd.IA32,Pcd.X64,Pcd.ARM,Pcd.AARCH64]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy       ## SOMETIMES_CONSUMES
-
-[Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack               ## SOMETIMES_CONSUMES
-
 [Depex]
   gEfiPeiLoadFilePpiGuid AND gEfiPeiMasterBootModePpiGuid
 
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108876): https://edk2.groups.io/g/devel/message/108876
Mute This Topic: https://groups.io/mt/101469952/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 15/28] ArmPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (13 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 14/28] MdeModulePkg: " Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 16/28] EmulatorPkg: " Taylor Beebe
                   ` (12 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Leif Lindholm, Ard Biesheuvel, Sami Mujawar

Replace references to the memory protection PCDs to instead
check the platform protections via GetMemoryProtectionsLib.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Sami Mujawar <sami.mujawar@arm.com>
---
 ArmPkg/Drivers/CpuDxe/CpuDxe.c   | 5 ++---
 ArmPkg/ArmPkg.dsc                | 1 +
 ArmPkg/Drivers/CpuDxe/CpuDxe.inf | 2 +-
 3 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/ArmPkg/Drivers/CpuDxe/CpuDxe.c b/ArmPkg/Drivers/CpuDxe/CpuDxe.c
index fc63e527846a..8a25e78dfebd 100644
--- a/ArmPkg/Drivers/CpuDxe/CpuDxe.c
+++ b/ArmPkg/Drivers/CpuDxe/CpuDxe.c
@@ -12,6 +12,7 @@
 #include <Guid/IdleLoopEvent.h>
 
 #include <Library/MemoryAllocationLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
 
 BOOLEAN  mIsFlushingGCD;
 
@@ -241,7 +242,6 @@ RemapUnusedMemoryNx (
   VOID
   )
 {
-  UINT64                 TestBit;
   UINTN                  MemoryMapSize;
   UINTN                  MapKey;
   UINTN                  DescriptorSize;
@@ -251,8 +251,7 @@ RemapUnusedMemoryNx (
   EFI_MEMORY_DESCRIPTOR  *MemoryMapEnd;
   EFI_STATUS             Status;
 
-  TestBit = LShiftU64 (1, EfiBootServicesData);
-  if ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy) & TestBit) == 0) {
+  if (!gMps.Dxe.ExecutionProtection.EnabledForType[EfiBootServicesData]) {
     return;
   }
 
diff --git a/ArmPkg/ArmPkg.dsc b/ArmPkg/ArmPkg.dsc
index 6dd91e694192..1e34ef95b7cb 100644
--- a/ArmPkg/ArmPkg.dsc
+++ b/ArmPkg/ArmPkg.dsc
@@ -57,6 +57,7 @@ [LibraryClasses.common]
   PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
   PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
   PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
 
   UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf
   HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf
diff --git a/ArmPkg/Drivers/CpuDxe/CpuDxe.inf b/ArmPkg/Drivers/CpuDxe/CpuDxe.inf
index 7d8132200e64..4d0a3de99546 100644
--- a/ArmPkg/Drivers/CpuDxe/CpuDxe.inf
+++ b/ArmPkg/Drivers/CpuDxe/CpuDxe.inf
@@ -46,6 +46,7 @@ [LibraryClasses]
   CpuExceptionHandlerLib
   DebugLib
   DefaultExceptionHandlerLib
+  GetMemoryProtectionsLib
   DxeServicesTableLib
   HobLib
   MemoryAllocationLib
@@ -65,7 +66,6 @@ [Guids]
 
 [Pcd.common]
   gArmTokenSpaceGuid.PcdVFPEnabled
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy
 
 [FeaturePcd.common]
   gArmTokenSpaceGuid.PcdDebuggerExceptionSupport
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108877): https://edk2.groups.io/g/devel/message/108877
Mute This Topic: https://groups.io/mt/101469954/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 16/28] EmulatorPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (14 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 15/28] ArmPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 17/28] OvmfPkg: " Taylor Beebe
                   ` (11 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Andrew Fish, Ray Ni

Replace references to the memory protection PCDs to instead
check the platform protections via GetMemoryProtectionsLib.

Because the protection profile is equivalent to the PCD settings,
this updated does not cause a torn state.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Andrew Fish <afish@apple.com>
Cc: Ray Ni <ray.ni@intel.com>
---
 EmulatorPkg/EmulatorPkg.dsc | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/EmulatorPkg/EmulatorPkg.dsc b/EmulatorPkg/EmulatorPkg.dsc
index b14654739b54..2784c6edbbdf 100644
--- a/EmulatorPkg/EmulatorPkg.dsc
+++ b/EmulatorPkg/EmulatorPkg.dsc
@@ -126,6 +126,8 @@ [LibraryClasses]
   SortLib|MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf
   ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf
   FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
+  SetMemoryProtectionsLib|MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf
 
 !if $(SECURE_BOOT_ENABLE) == TRUE
   RngLib|MdeModulePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
@@ -216,7 +218,6 @@ [PcdsFeatureFlag]
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplBuildPageTables|FALSE
 
 [PcdsFixedAtBuild]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy|0x00000000
   gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE
   gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000040
   gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x0f
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108878): https://edk2.groups.io/g/devel/message/108878
Mute This Topic: https://groups.io/mt/101469956/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 17/28] OvmfPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (15 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 16/28] EmulatorPkg: " Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 18/28] UefiCpuPkg: " Taylor Beebe
                   ` (10 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Leif Lindholm, Abner Chang

Replace references to the memory protection PCDs to instead
check the platform protections via GetMemoryProtectionsLib.

Because the protection profile is equivalent to the PCD settings,
this updated does not cause a torn state.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Abner Chang <abner.chang@amd.com>
---
 OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c   | 5 ++---
 OvmfPkg/QemuVideoDxe/VbeShim.c        | 3 ++-
 OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf | 4 +---
 OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf | 2 +-
 4 files changed, 6 insertions(+), 8 deletions(-)

diff --git a/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c b/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c
index 779bf5c827f5..2bef34427341 100644
--- a/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c
+++ b/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.c
@@ -13,6 +13,7 @@
 #include <Library/DxeServicesTableLib.h>
 #include <Library/PcdLib.h>
 #include <Library/UefiBootServicesTableLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
 
 #include <Protocol/Cpu.h>
 #include <Protocol/FdtClient.h>
@@ -148,9 +149,7 @@ InitializeHighMemDxe (
         // on the page table mappings by going through the cpu arch protocol.
         //
         Attributes = EFI_MEMORY_WB;
-        if ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy) &
-             (1U << (UINT32)EfiConventionalMemory)) != 0)
-        {
+        if (gMps.Dxe.ExecutionProtection.EnabledForType[EfiConventionalMemory]) {
           Attributes |= EFI_MEMORY_XP;
         }
 
diff --git a/OvmfPkg/QemuVideoDxe/VbeShim.c b/OvmfPkg/QemuVideoDxe/VbeShim.c
index 8f151b96f9a5..a60e409f50de 100644
--- a/OvmfPkg/QemuVideoDxe/VbeShim.c
+++ b/OvmfPkg/QemuVideoDxe/VbeShim.c
@@ -19,6 +19,7 @@
 #include <Library/DebugLib.h>
 #include <Library/PciLib.h>
 #include <Library/PrintLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
 #include <OvmfPlatforms.h>
 
 #include "Qemu.h"
@@ -69,7 +70,7 @@ InstallVbeShim (
   UINTN                 Printed;
   VBE_MODE_INFO         *VbeModeInfo;
 
-  if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & (BIT0|BIT7)) == BIT0) {
+  if (gMps.Dxe.NullPointerDetection.Enabled && !gMps.Dxe.NullPointerDetection.DisableEndOfDxe) {
     DEBUG ((
       DEBUG_WARN,
       "%a: page 0 protected, not installing VBE shim\n",
diff --git a/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf b/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf
index c7dde9f455f2..40cbbe1c39af 100644
--- a/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf
+++ b/OvmfPkg/Fdt/HighMemDxe/HighMemDxe.inf
@@ -33,13 +33,11 @@ [LibraryClasses]
   PcdLib
   UefiBootServicesTableLib
   UefiDriverEntryPoint
+  GetMemoryProtectionsLib
 
 [Protocols]
   gEfiCpuArchProtocolGuid                 ## CONSUMES
   gFdtClientProtocolGuid                  ## CONSUMES
 
-[Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy
-
 [Depex]
   gEfiCpuArchProtocolGuid AND gFdtClientProtocolGuid
diff --git a/OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf b/OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
index 43a6e07faa88..15693ce85674 100644
--- a/OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
+++ b/OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
@@ -55,6 +55,7 @@ [LibraryClasses]
   UefiBootServicesTableLib
   UefiDriverEntryPoint
   UefiLib
+  GetMemoryProtectionsLib
 
 [Protocols]
   gEfiGraphicsOutputProtocolGuid                # PROTOCOL BY_START
@@ -64,6 +65,5 @@ [Protocols]
 [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId
   gUefiOvmfPkgTokenSpaceGuid.PcdVideoResolutionSource
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask
   gEfiMdeModulePkgTokenSpaceGuid.PcdVideoHorizontalResolution
   gEfiMdeModulePkgTokenSpaceGuid.PcdVideoVerticalResolution
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108879): https://edk2.groups.io/g/devel/message/108879
Mute This Topic: https://groups.io/mt/101469957/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 18/28] UefiCpuPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (16 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 17/28] OvmfPkg: " Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 19/28] MdeModulePkg: " Taylor Beebe
                   ` (9 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Eric Dong, Ray Ni, Rahul Kumar, Gerd Hoffmann

Replace references to the memory protection PCDs to instead
check the platform protections via GetMemoryProtectionsLib.

Because the protection profile is equivalent to the PCD settings,
this updated does not cause a torn state.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
---
 UefiCpuPkg/CpuDxe/CpuDxe.c                                                               |  2 +-
 UefiCpuPkg/CpuDxe/CpuMp.c                                                                |  2 +-
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c       |  6 +-----
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c      | 15 ++++++++++++++
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c      | 21 ++++++++++++++++++++
 UefiCpuPkg/Library/MpInitLib/DxeMpLib.c                                                  |  3 ++-
 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c                                                 |  2 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c                                       | 13 ++++++------
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c                                                   |  2 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c                                                  |  2 +-
 UefiCpuPkg/CpuDxe/CpuDxe.h                                                               | 11 ++++++----
 UefiCpuPkg/CpuDxe/CpuDxe.inf                                                             |  4 +---
 UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf                                               |  3 ---
 UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf                  |  1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf                  |  1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf               |  1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf                  |  1 -
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h             | 13 +++++++++++-
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf |  2 +-
 UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf |  2 +-
 UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf                                            |  3 ++-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf                                             |  3 +--
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h                                           |  9 +++++----
 UefiCpuPkg/UefiCpuPkg.dec                                                                |  7 +++----
 UefiCpuPkg/UefiCpuPkg.dsc                                                                |  2 ++
 UefiCpuPkg/UefiCpuPkg.uni                                                                | 10 ++++------
 26 files changed, 90 insertions(+), 51 deletions(-)

diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.c b/UefiCpuPkg/CpuDxe/CpuDxe.c
index 804ef5d1fe8e..b12c43f4c1d4 100644
--- a/UefiCpuPkg/CpuDxe/CpuDxe.c
+++ b/UefiCpuPkg/CpuDxe/CpuDxe.c
@@ -399,7 +399,7 @@ CpuSetMemoryAttributes (
   // During memory attributes updating, new pages may be allocated to setup
   // smaller granularity of page table. Page allocation action might then cause
   // another calling of CpuSetMemoryAttributes() recursively, due to memory
-  // protection policy configured (such as PcdDxeNxMemoryProtectionPolicy).
+  // protection policy configured (such as the DXE NX Protection Policy).
   // Since this driver will always protect memory used as page table by itself,
   // there's no need to apply protection policy requested from memory service.
   // So it's safe to just return EFI_SUCCESS if this time of calling is caused
diff --git a/UefiCpuPkg/CpuDxe/CpuMp.c b/UefiCpuPkg/CpuDxe/CpuMp.c
index e7575d9b8062..d8f978eec09d 100644
--- a/UefiCpuPkg/CpuDxe/CpuMp.c
+++ b/UefiCpuPkg/CpuDxe/CpuMp.c
@@ -734,7 +734,7 @@ InitializeMpExceptionHandlers (
   //
   // Setup stack switch for Stack Guard feature.
   //
-  if (PcdGetBool (PcdCpuStackGuard)) {
+  if (gMps.Dxe.CpuStackGuardEnabled) {
     InitializeMpExceptionStackSwitchHandlers ();
   }
 }
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c
index 9ba70c5b7340..fe74b0e0eaae 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTestCommon.c
@@ -743,10 +743,6 @@ TestCpuStackGuardInBspAndAp (
   VOID                            *NewIdtr;
   UINTN                           *CpuStackBaseBuffer;
 
-  if (!PcdGetBool (PcdCpuStackGuard)) {
-    return UNIT_TEST_PASSED;
-  }
-
   //
   // Get MP Service Protocol
   //
@@ -846,7 +842,7 @@ AddCommonTestCase (
   AddTestCase (CpuExceptionLibUnitTestSuite, "Check if exception handler can be registered/unregistered for GP and PF", "TestRegisterHandlerForGPAndPF", TestRegisterHandlerForGPAndPF, NULL, NULL, NULL);
 
   AddTestCase (CpuExceptionLibUnitTestSuite, "Check if Cpu Context is consistent before and after exception.", "TestCpuContextConsistency", TestCpuContextConsistency, NULL, NULL, NULL);
-  AddTestCase (CpuExceptionLibUnitTestSuite, "Check if stack overflow is captured by CpuStackGuard in Bsp and AP", "TestCpuStackGuardInBspAndAp", TestCpuStackGuardInBspAndAp, NULL, NULL, NULL);
+  AddTestCase (CpuExceptionLibUnitTestSuite, "Check if stack overflow is captured by CpuStackGuard in Bsp and AP", "TestCpuStackGuardInBspAndAp", TestCpuStackGuardInBspAndAp, IsStackGuardEnabled, NULL, NULL);
 
   return EFI_SUCCESS;
 }
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c
index 1cec3ed809d9..c1de3a6663ae 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerUnitTest.c
@@ -8,6 +8,7 @@
 
 #include "CpuExceptionHandlerTest.h"
 #include <Library/UefiBootServicesTableLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
 #include <Protocol/Timer.h>
 
 /**
@@ -145,6 +146,20 @@ GetMpServices (
   return gBS->LocateProtocol (&gEfiMpServiceProtocolGuid, NULL, (VOID **)&MpServices->Protocol);
 }
 
+/**
+  Checks if stack guard is enabled.
+
+  @param[in] Context The unit test context
+**/
+UNIT_TEST_STATUS
+EFIAPI
+IsStackGuardEnabled (
+  IN UNIT_TEST_CONTEXT  Context
+  )
+{
+  return gMps.Dxe.CpuStackGuardEnabled;
+}
+
 /**
   Entry for CpuExceptionHandlerDxeTest driver.
 
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c
index d9408d2f5e2f..763268f55314 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerUnitTest.c
@@ -10,6 +10,7 @@
 #include <Library/PeimEntryPoint.h>
 #include <Library/PeiServicesLib.h>
 #include <Library/PeiServicesTablePointerLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
 
 /**
   Initialize Bsp Idt with a new Idt table and return the IA32_DESCRIPTOR buffer.
@@ -152,6 +153,26 @@ GetMpServices (
   return PeiServicesLocatePpi (&gEdkiiPeiMpServices2PpiGuid, 0, NULL, (VOID **)&MpServices->Ppi);
 }
 
+/**
+  Checks if stack guard is enabled.
+
+  @param[in] Context The unit test context
+**/
+UNIT_TEST_STATUS
+EFIAPI
+IsStackGuardEnabled (
+  IN UNIT_TEST_CONTEXT  Context
+  )
+{
+  MEMORY_PROTECTION_SETTINGS  Mps;
+
+  if (!EFI_ERROR (GetCurrentMemoryProtectionSettings (&Mps))) {
+    return Mps.Dxe.CpuStackGuardEnabled;
+  }
+
+  return FALSE;
+}
+
 /**
   Entry point of CpuExceptionHandlerPeiTest PEIM.
 
diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c
index 57ddb86600a7..551a7924fad3 100644
--- a/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c
+++ b/UefiCpuPkg/Library/MpInitLib/DxeMpLib.c
@@ -13,6 +13,7 @@
 #include <Library/DebugAgentLib.h>
 #include <Library/DxeServicesTableLib.h>
 #include <Library/CcExitLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
 #include <Register/Amd/Fam17Msr.h>
 #include <Register/Amd/Ghcb.h>
 
@@ -497,7 +498,7 @@ InitMpGlobalData (
     return;
   }
 
-  if (PcdGetBool (PcdCpuStackGuard)) {
+  if (gMps.Dxe.CpuStackGuardEnabled) {
     //
     // One extra page at the bottom of the stack is needed for Guard page.
     //
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c
index b11264ce4aa7..7e6c9899b069 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c
@@ -160,7 +160,7 @@ SmiPFHandler (
     //
     // If NULL pointer was just accessed
     //
-    if (((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0) &&
+    if (gMps.Mm.NullPointerDetection.Enabled &&
         (PFAddress < EFI_PAGE_SIZE))
     {
       DumpCpuContext (InterruptType, SystemContext);
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c
index 6f498666157e..4c02749c174e 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c
@@ -1679,7 +1679,7 @@ GenSmmPageTable (
     }
   }
 
-  if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0) {
+  if (gMps.Mm.NullPointerDetection.Enabled) {
     //
     // Mark [0, 4k] as non-present
     //
@@ -1834,13 +1834,13 @@ IfReadOnlyPageTableNeeded (
   //
   // Don't mark page table memory as read-only if
   //  - no restriction on access to non-SMRAM memory; or
-  //  - SMM heap guard feature enabled; or
-  //      BIT2: SMM page guard enabled
-  //      BIT3: SMM pool guard enabled
+  //  - SMM page guard enabled
+  //  - SMM pool guard enabled
   //  - SMM profile feature enabled
   //
   if (!IsRestrictedMemoryAccess () ||
-      ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) ||
+      IS_MM_PAGE_GUARD_ACTIVE ||
+      IS_MM_POOL_GUARD_ACTIVE ||
       FeaturePcdGet (PcdCpuSmmProfileEnable))
   {
     if (sizeof (UINTN) == sizeof (UINT64)) {
@@ -1849,7 +1849,8 @@ IfReadOnlyPageTableNeeded (
       //
       ASSERT (
         !(IsRestrictedMemoryAccess () &&
-          (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0)
+          (IS_MM_PAGE_GUARD_ACTIVE ||
+           IS_MM_POOL_GUARD_ACTIVE))
         );
 
       //
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c
index 7ac3c66f911c..4f48e0c4f399 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c
@@ -610,7 +610,7 @@ InitPaging (
   //
   // [0, 4k] may be non-present.
   //
-  PreviousAddress = ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0) ? BASE_4KB : 0;
+  PreviousAddress = (gMps.Mm.NullPointerDetection.Enabled) ? BASE_4KB : 0;
 
   DEBUG ((DEBUG_INFO, "Patch page table start ...\n"));
   if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c
index ddd9be66b53f..10e26cd72f6d 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c
@@ -932,7 +932,7 @@ SmiPFHandler (
     //
     // If NULL pointer was just accessed
     //
-    if (((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0) &&
+    if (gMps.Mm.NullPointerDetection.Enabled &&
         (PFAddress < EFI_PAGE_SIZE))
     {
       DumpCpuContext (InterruptType, SystemContext);
diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.h b/UefiCpuPkg/CpuDxe/CpuDxe.h
index 0e7d88dd357c..a0284c562fa1 100644
--- a/UefiCpuPkg/CpuDxe/CpuDxe.h
+++ b/UefiCpuPkg/CpuDxe/CpuDxe.h
@@ -35,15 +35,18 @@
 #include <Library/ReportStatusCodeLib.h>
 #include <Library/MpInitLib.h>
 #include <Library/TimerLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
 
 #include <Guid/IdleLoopEvent.h>
 #include <Guid/VectorHandoffTable.h>
 
-#define HEAP_GUARD_NONSTOP_MODE       \
-        ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT6|BIT4|BIT1|BIT0)) > BIT6)
+#define HEAP_GUARD_NONSTOP_MODE      (gMps.Dxe.HeapGuard.NonstopModeEnabled        &&  \
+                                     (IS_DXE_PAGE_GUARD_ACTIVE                     ||  \
+                                      IS_DXE_POOL_GUARD_ACTIVE                     ||  \
+                                      gMps.Dxe.HeapGuard.FreedMemoryGuardEnabled))     \
 
-#define NULL_DETECTION_NONSTOP_MODE   \
-        ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & (BIT6|BIT0)) > BIT6)
+#define NULL_DETECTION_NONSTOP_MODE  (gMps.Dxe.NullPointerDetection.Enabled &&         \
+                                      gMps.Dxe.NullPointerDetection.NonstopModeEnabled)
 
 /**
   Flush CPU data cache. If the instruction cache is fully coherent
diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.inf b/UefiCpuPkg/CpuDxe/CpuDxe.inf
index 1d3e9f8cdb29..85387c3ecdf2 100644
--- a/UefiCpuPkg/CpuDxe/CpuDxe.inf
+++ b/UefiCpuPkg/CpuDxe/CpuDxe.inf
@@ -40,6 +40,7 @@ [LibraryClasses]
   MpInitLib
   TimerLib
   PeCoffGetEntryPointLib
+  GetMemoryProtectionsLib
 
 [Sources]
   CpuDxe.c
@@ -74,9 +75,6 @@ [Ppis]
 
 [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                       ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList              ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize                    ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdTdxSharedBitMask                    ## CONSUMES
diff --git a/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf
index 9d9a5ef8f247..262f9e6d9d5a 100644
--- a/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf
+++ b/UefiCpuPkg/CpuDxeRiscV64/CpuDxeRiscV64.inf
@@ -56,9 +56,6 @@ [Ppis]
   gEfiSecPlatformInformationPpiGuid             ## UNDEFINED # HOB
 
 [Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                       ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList              ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize                    ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuCoreCrystalClockFrequency             ## CONSUMES
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf
index fdbebadab93d..1fddf15b70bd 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf
@@ -39,7 +39,6 @@ [Sources.common]
   DxeException.c
 
 [Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard
   gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList
   gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize
 
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
index 3bcaff5c5fe4..348f7ed56c99 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
@@ -55,7 +55,6 @@ [LibraryClasses]
   CcExitLib
 
 [Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard    # CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize
   gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList
 
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf
index e7b1144f6941..0217c983d7c6 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf
@@ -51,7 +51,6 @@ [LibraryClasses]
   CcExitLib
 
 [Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard
   gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList
   gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize
 
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf
index 27f0b96fa9e9..6dc09b447ff0 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf
@@ -54,7 +54,6 @@ [LibraryClasses]
   CcExitLib
 
 [Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard
   gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList
   gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize
 
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h
index bad3387db5bc..47bde8574b32 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/CpuExceptionHandlerTest.h
@@ -27,7 +27,7 @@
     In this test case, stack overflow is triggered by a funtion which calls itself continuously. This test case triggers stack
     overflow in both BSP and AP. All AP use same Idt with Bsp. The expectation is:
       1. PF exception is triggered (leading to a DF if sepereated stack is not prepared for PF) when Rsp <= StackBase + SIZE_4KB
-         since [StackBase, StackBase + SIZE_4KB] is marked as not present in page table when PcdCpuStackGuard is TRUE.
+         since [StackBase, StackBase + SIZE_4KB] is marked as not present in page table when CpuStackGuard is TRUE.
       2. Stack for PF/DF exception handler in both Bsp and AP is succussfully switched by InitializeSeparateExceptionStacks.
 
 **/
@@ -342,4 +342,15 @@ CpuStackGuardExceptionHandler (
   IN EFI_SYSTEM_CONTEXT  SystemContext
   );
 
+/**
+  Checks if stack guard is enabled.
+
+  @param[in] Context The unit test context
+**/
+UNIT_TEST_STATUS
+EFIAPI
+IsStackGuardEnabled (
+  IN UNIT_TEST_CONTEXT  Context
+  );
+
 #endif
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf
index a904eb250475..09c00fce8627 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf
@@ -43,12 +43,12 @@ [LibraryClasses]
   HobLib
   UefiBootServicesTableLib
   CpuPageTableLib
+  GetMemoryProtectionsLib
 
 [Guids]
   gEfiHobMemoryAllocStackGuid
 
 [Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard       ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuApStackSize           ## CONSUMES
 
 [Protocols]
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf
index 25f8f8dbe0e9..41fa759bf31e 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/PeiCpuExceptionHandlerLibUnitTest.inf
@@ -48,9 +48,9 @@ [LibraryClasses]
   PeiServicesLib
   CpuPageTableLib
   PeiServicesTablePointerLib
+  SetMemoryProtectionsLib
 
 [Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard   ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdCpuApStackSize       ## CONSUMES
 
 [Ppis]
diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf
index 55e46d4a1fad..8edc7227d108 100644
--- a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf
+++ b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf
@@ -58,6 +58,8 @@ [LibraryClasses]
   PcdLib
   CcExitLib
   MicrocodeLib
+  GetMemoryProtectionsLib
+
 [LibraryClasses.X64]
   CpuPageTableLib
 
@@ -82,6 +84,5 @@ [Pcd]
   gUefiCpuPkgTokenSpaceGuid.PcdGhcbHypervisorFeatures                  ## CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdSevEsWorkAreaBase                       ## SOMETIMES_CONSUMES
   gUefiCpuPkgTokenSpaceGuid.PcdFirstTimeWakeUpAPsBySipi                ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                      ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbBase                           ## CONSUMES
   gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr           ## CONSUMES
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf
index 5d52ed7d1329..56f64873fe50 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf
@@ -103,6 +103,7 @@ [LibraryClasses]
   PerformanceLib
   CpuPageTableLib
   MmSaveStateLib
+  GetMemoryProtectionsLib
 
 [Protocols]
   gEfiSmmAccess2ProtocolGuid               ## CONSUMES
@@ -146,8 +147,6 @@ [Pcd]
   gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesInitOnS3Resume           ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable                   ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
   gEfiMdePkgTokenSpaceGuid.PcdControlFlowEnforcementPropertyMask        ## CONSUMES
 
 [FixedPcd]
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h
index 964dd5281780..1ac91d9d3ce4 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfileInternal.h
@@ -15,6 +15,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Library/DxeServicesTableLib.h>
 #include <Library/CpuLib.h>
 #include <IndustryStandard/Acpi.h>
+#include <Library/GetMemoryProtectionsLib.h>
 
 #include "SmmProfileArch.h"
 
@@ -57,11 +58,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #define   MSR_DEBUG_CTL_BTINT  0x100
 #define MSR_DS_AREA            0x600
 
-#define HEAP_GUARD_NONSTOP_MODE      \
-        ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT6|BIT3|BIT2)) > BIT6)
+#define HEAP_GUARD_NONSTOP_MODE  (gMps.Mm.HeapGuard.NonstopModeEnabled                  &&  \
+                                 (IS_MM_PAGE_GUARD_ACTIVE ||  IS_MM_POOL_GUARD_ACTIVE))
 
-#define NULL_DETECTION_NONSTOP_MODE  \
-        ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & (BIT6|BIT1)) > BIT6)
+#define NULL_DETECTION_NONSTOP_MODE  (gMps.Mm.NullPointerDetection.NonstopModeEnabled   &&  \
+                                      gMps.Mm.NullPointerDetection.Enabled)
 
 typedef struct {
   EFI_PHYSICAL_ADDRESS    Base;
diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec
index 68473fc640e6..8c667269ad7f 100644
--- a/UefiCpuPkg/UefiCpuPkg.dec
+++ b/UefiCpuPkg/UefiCpuPkg.dec
@@ -192,13 +192,13 @@ [PcdsFeatureFlag]
 
 [PcdsFixedAtBuild]
   ## List of exception vectors which need switching stack.
-  #  This PCD will only take into effect if PcdCpuStackGuard is enabled.
+  #  This PCD will only take into effect if the CPU Stack Guard is enabled.
   #  By default exception #DD(8), #PF(14) are supported.
   # @Prompt Specify exception vectors which need switching stack.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList|{0x08, 0x0E}|VOID*|0x30002000
 
   ## Size of good stack for an exception.
-  #  This PCD will only take into effect if PcdCpuStackGuard is enabled.
+  #  This PCD will only take into effect if the CPU Stack Guard is enabled.
   # @Prompt Specify size of good stack of exception which need switching stack.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize|2048|UINT32|0x30002001
 
@@ -388,9 +388,8 @@ [PcdsFixedAtBuild.X64, PcdsPatchableInModule.X64, PcdsDynamic.X64, PcdsDynamicEx
   #  and the memory occupied by page table is protected by page table itself as read-only.
   #  In X64 build, it cannot be enabled at the same time with SMM profile feature (PcdCpuSmmProfileEnable).
   #  In X64 build, it could not be enabled also at the same time with heap guard feature for SMM
-  #  (PcdHeapGuardPropertyMask in MdeModulePkg).
   #  In IA32 build, page table memory is not marked as read-only when either SMM profile feature (PcdCpuSmmProfileEnable)
-  #  or heap guard feature for SMM (PcdHeapGuardPropertyMask in MdeModulePkg) is enabled.
+  #  or heap guard feature for SMM is enabled.
   #   TRUE  - Access to non-SMRAM memory is restricted to reserved, runtime and ACPI NVS type after SmmReadyToLock.<BR>
   #   FALSE - Access to any type of non-SMRAM memory after SmmReadyToLock is allowed.<BR>
   # @Prompt Access to non-SMRAM memory is restricted to reserved, runtime and ACPI NVS type after SmmReadyToLock.
diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index 074fd774616d..2dbb8394b382 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -66,6 +66,8 @@ [LibraryClasses]
   UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf
   UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf
   UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf
+  GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/GetMemoryProtectionsLibNull.inf
+  SetMemoryProtectionsLib|MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLibNull.inf
 
 [LibraryClasses.common.SEC]
   PlatformSecLib|UefiCpuPkg/Library/PlatformSecLibNull/PlatformSecLibNull.inf
diff --git a/UefiCpuPkg/UefiCpuPkg.uni b/UefiCpuPkg/UefiCpuPkg.uni
index d17bcfd10c7a..5719917a041e 100644
--- a/UefiCpuPkg/UefiCpuPkg.uni
+++ b/UefiCpuPkg/UefiCpuPkg.uni
@@ -170,8 +170,7 @@
                                                                                      "If enabled, SMM will not use on-demand paging. SMM will build static page table for all memory.\n"
                                                                                      "This flag only impacts X64 build, because SMM always builds static page table for IA32.\n"
                                                                                      "It could not be enabled at the same time with SMM profile feature (PcdCpuSmmProfileEnable).\n"
-                                                                                     "It could not be enabled also at the same time with heap guard feature for SMM\n"
-                                                                                     "(PcdHeapGuardPropertyMask in MdeModulePkg).<BR><BR>\n"
+                                                                                     "It could not be enabled also at the same time with heap guard feature for SMM.<BR><BR>\n"
                                                                                      "TRUE  - SMM uses static page table for all memory.<BR>\n"
                                                                                      "FALSE - SMM uses static page table for below 4G memory and use on-demand paging for above 4G memory.<BR>"
 
@@ -217,9 +216,8 @@
                                                                                             "and the memory occupied by page table is protected by page table itself as read-only.<BR>\n"
                                                                                             "In X64 build, it cannot be enabled at the same time with SMM profile feature (PcdCpuSmmProfileEnable).<BR>\n"
                                                                                             "In X64 build, it could not be enabled also at the same time with heap guard feature for SMM<BR>\n"
-                                                                                            "(PcdHeapGuardPropertyMask in MdeModulePkg).<BR>\n"
                                                                                             "In IA32 build, page table memory is not marked as read-only when either SMM profile feature (PcdCpuSmmProfileEnable)<BR>\n"
-                                                                                            "or heap guard feature for SMM (PcdHeapGuardPropertyMask in MdeModulePkg) is enabled.<BR>\n"
+                                                                                            "or heap guard feature for SMM is enabled.<BR>\n"
                                                                                             "TRUE  - Access to non-SMRAM memory is restricted to reserved, runtime and ACPI NVS type after SmmReadyToLock.<BR>\n"
                                                                                             "FALSE - Access to any type of non-SMRAM memory after SmmReadyToLock is allowed.<BR>"
 
@@ -266,13 +264,13 @@
 #string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuStackSwitchExceptionList_PROMPT  #language en-US "Specify exception vectors which need switching stack."
 
 #string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuStackSwitchExceptionList_HELP  #language en-US "List of exception vectors which need switching stack.\n"
-                                                                                           "This PCD will only take into effect if PcdCpuStackGuard is enabled.n"
+                                                                                           "This PCD will only take into effect if the CPU Stack Guard is enabled.n"
                                                                                            "By default exception #DD(8), #PF(14) are supported.n"
 
 #string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuKnownGoodStackSize_PROMPT  #language en-US "Specify size of good stack of exception which need switching stack."
 
 #string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuKnownGoodStackSize_HELP  #language en-US "Size of good stack for an exception.\n"
-                                                                                     "This PCD will only take into effect if PcdCpuStackGuard is enabled.\n"
+                                                                                     "This PCD will only take into effect if the CPU Stack Guard is enabled.\n"
 
 #string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuCoreCrystalClockFrequency_PROMPT  #language en-US "Specifies CPUID Leaf 0x15 Time Stamp Counter and Nominal Core Crystal Clock Frequency."
 
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108880): https://edk2.groups.io/g/devel/message/108880
Mute This Topic: https://groups.io/mt/101469958/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 19/28] MdeModulePkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (17 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 18/28] UefiCpuPkg: " Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib Taylor Beebe
                   ` (8 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao, Dandan Bi

Replace references to the memory protection PCDs to instead
check the platform protections via GetMemoryProtectionsLib.

Because the protection profile is equivalent to the PCD settings,
this updated does not cause a torn state.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Dandan Bi <dandan.bi@intel.com>
---
 MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c       |  4 +-
 MdeModulePkg/Core/Dxe/Mem/HeapGuard.c         | 46 ++++++++------
 MdeModulePkg/Core/Dxe/Mem/Page.c              |  2 +-
 MdeModulePkg/Core/Dxe/Mem/Pool.c              |  4 +-
 MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c | 67 +++++++++++---------
 MdeModulePkg/Core/PiSmmCore/HeapGuard.c       | 29 ++++-----
 MdeModulePkg/Core/PiSmmCore/Pool.c            |  4 +-
 MdeModulePkg/Core/Dxe/DxeMain.h               |  1 +
 MdeModulePkg/Core/Dxe/DxeMain.inf             |  8 +--
 MdeModulePkg/Core/PiSmmCore/PiSmmCore.h       |  1 +
 MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf     |  4 +-
 11 files changed, 87 insertions(+), 83 deletions(-)

diff --git a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c
index 0e0f9769b99d..66cb2fcf2ff7 100644
--- a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c
+++ b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c
@@ -256,10 +256,12 @@ DxeMain (
   Status = InitializeCpuExceptionHandlers (VectorInfoList);
   ASSERT_EFI_ERROR (Status);
 
+  PopulateMpsGlobal ();
+
   //
   // Setup Stack Guard
   //
-  if (PcdGetBool (PcdCpuStackGuard)) {
+  if (gMps.Dxe.CpuStackGuardEnabled) {
     Status = InitializeSeparateExceptionStacks (NULL, NULL);
     ASSERT_EFI_ERROR (Status);
   }
diff --git a/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c b/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c
index 0c0ca61872b4..59d8f36c89b7 100644
--- a/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c
+++ b/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c
@@ -553,7 +553,7 @@ UnsetGuardPage (
   // memory.
   //
   Attributes = 0;
-  if ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy) & (1 << EfiConventionalMemory)) != 0) {
+  if (gMps.Dxe.ExecutionProtection.EnabledForType[EfiConventionalMemory]) {
     Attributes |= EFI_MEMORY_XP;
   }
 
@@ -590,38 +590,48 @@ IsMemoryTypeToGuard (
   IN UINT8              PageOrPool
   )
 {
-  UINT64  TestBit;
+  UINT32  MpsMemoryType;
   UINT64  ConfigBit;
 
   if (AllocateType == AllocateAddress) {
     return FALSE;
   }
 
-  if ((PcdGet8 (PcdHeapGuardPropertyMask) & PageOrPool) == 0) {
+  ConfigBit  = gMps.Dxe.HeapGuard.PageGuardEnabled ? GUARD_HEAP_TYPE_PAGE : 0;
+  ConfigBit |= gMps.Dxe.HeapGuard.PoolGuardEnabled ? GUARD_HEAP_TYPE_POOL : 0;
+  ConfigBit |= gMps.Dxe.HeapGuard.FreedMemoryGuardEnabled ? GUARD_HEAP_TYPE_FREED : 0;
+
+  if ((PageOrPool & ConfigBit) == 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 (((PageOrPool & GUARD_HEAP_TYPE_FREED) != 0) && gMps.Dxe.HeapGuard.FreedMemoryGuardEnabled) {
+    return TRUE;
   }
 
   if ((UINT32)MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) {
-    TestBit = BIT63;
+    MpsMemoryType = OS_RESERVED_MPS_MEMORY_TYPE;
   } else if ((UINT32)MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) {
-    TestBit = BIT62;
+    MpsMemoryType = OEM_RESERVED_MPS_MEMORY_TYPE;
   } else if (MemoryType < EfiMaxMemoryType) {
-    TestBit = LShiftU64 (1, MemoryType);
+    MpsMemoryType = MemoryType;
   } else if (MemoryType == EfiMaxMemoryType) {
-    TestBit = (UINT64)-1;
+    return (((PageOrPool & GUARD_HEAP_TYPE_PAGE) != 0) && IS_DXE_PAGE_GUARD_ACTIVE) ||
+           (((PageOrPool & GUARD_HEAP_TYPE_POOL) != 0) && IS_DXE_POOL_GUARD_ACTIVE) ||
+           (((PageOrPool & GUARD_HEAP_TYPE_FREED) != 0) && gMps.Dxe.HeapGuard.FreedMemoryGuardEnabled);
   } else {
-    TestBit = 0;
+    return FALSE;
   }
 
-  return ((ConfigBit & TestBit) != 0);
+  if (((PageOrPool & GUARD_HEAP_TYPE_PAGE) != 0) && gMps.Dxe.PageGuard.EnabledForType[MpsMemoryType]) {
+    return TRUE;
+  }
+
+  if (((PageOrPool & GUARD_HEAP_TYPE_POOL) != 0) && gMps.Dxe.PoolGuard.EnabledForType[MpsMemoryType]) {
+    return TRUE;
+  }
+
+  return FALSE;
 }
 
 /**
@@ -835,7 +845,7 @@ AdjustMemoryS (
   // indicated to put the pool near the Tail Guard, we need extra bytes to
   // make sure alignment of the returned pool address.
   //
-  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0) {
+  if (gMps.Dxe.HeapGuard.GuardAlignedToTail) {
     SizeRequested = ALIGN_VALUE (SizeRequested, 8);
   }
 
@@ -1019,7 +1029,7 @@ AdjustPoolHeadA (
   IN UINTN                 Size
   )
 {
-  if ((Memory == 0) || ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0)) {
+  if ((Memory == 0) || (!gMps.Dxe.HeapGuard.GuardAlignedToTail)) {
     //
     // Pool head is put near the head Guard
     //
@@ -1050,7 +1060,7 @@ AdjustPoolHeadF (
   IN UINTN                 Size
   )
 {
-  if ((Memory == 0) || ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0)) {
+  if ((Memory == 0) || (!gMps.Dxe.HeapGuard.GuardAlignedToTail)) {
     //
     // Pool head is put near the head Guard
     //
diff --git a/MdeModulePkg/Core/Dxe/Mem/Page.c b/MdeModulePkg/Core/Dxe/Mem/Page.c
index 6497af573353..05c18a413b80 100644
--- a/MdeModulePkg/Core/Dxe/Mem/Page.c
+++ b/MdeModulePkg/Core/Dxe/Mem/Page.c
@@ -181,7 +181,7 @@ CoreAddRange (
   // used for other purposes.
   //
   if ((Type == EfiConventionalMemory) && (Start == 0) && (End >= EFI_PAGE_SIZE - 1)) {
-    if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) == 0) {
+    if (!gMps.Dxe.NullPointerDetection.Enabled) {
       SetMem ((VOID *)(UINTN)Start, EFI_PAGE_SIZE, 0);
     }
   }
diff --git a/MdeModulePkg/Core/Dxe/Mem/Pool.c b/MdeModulePkg/Core/Dxe/Mem/Pool.c
index 716dd045f9fd..ae1e8b67db10 100644
--- a/MdeModulePkg/Core/Dxe/Mem/Pool.c
+++ b/MdeModulePkg/Core/Dxe/Mem/Pool.c
@@ -385,7 +385,7 @@ CoreAllocatePoolI (
   //
 
   HasPoolTail = !(NeedGuard &&
-                  ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));
+                  gMps.Dxe.HeapGuard.GuardAlignedToTail);
   PageAsPool = (IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED) && !mOnGuarding);
 
   //
@@ -717,7 +717,7 @@ CoreFreePoolI (
   IsGuarded = IsPoolTypeToGuard (Head->Type) &&
               IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Head);
   HasPoolTail = !(IsGuarded &&
-                  ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));
+                  gMps.Dxe.HeapGuard.GuardAlignedToTail);
   PageAsPool = (Head->Signature == POOLPAGE_HEAD_SIGNATURE);
 
   if (HasPoolTail) {
diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c
index 94ed3111688b..215a9f254065 100644
--- a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c
+++ b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c
@@ -9,7 +9,7 @@
   2) This policy is applied only if the UEFI image meets the page alignment
      requirement.
   3) This policy is applied only if the Source UEFI image matches the
-     PcdImageProtectionPolicy definition.
+     Image Protection Policy definition.
   4) This policy is not applied to the non-PE image region.
 
   The DxeCore calls CpuArchProtocol->SetMemoryAttributes() to protect
@@ -60,7 +60,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \
   ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size)))
 
-UINT32  mImageProtectionPolicy;
+STATIC BOOLEAN  mIsExecutionProtectionActive = FALSE;
+
+STATIC BOOLEAN  mIsPageOrPoolGuardActive = FALSE;
 
 extern LIST_ENTRY  mGcdMemorySpaceMap;
 
@@ -149,11 +151,13 @@ GetProtectionPolicyFromImageType (
   IN UINT32  ImageType
   )
 {
-  if ((ImageType & mImageProtectionPolicy) == 0) {
-    return DO_NOT_PROTECT;
-  } else {
+  if (((ImageType == IMAGE_UNKNOWN) && gMps.Dxe.ImageProtection.ProtectImageFromUnknown) ||
+      ((ImageType == IMAGE_FROM_FV) && gMps.Dxe.ImageProtection.ProtectImageFromFv))
+  {
     return PROTECT_IF_ALIGNED_ELSE_ALLOW;
   }
+
+  return DO_NOT_PROTECT;
 }
 
 /**
@@ -611,7 +615,7 @@ UnprotectUefiImage (
   IMAGE_PROPERTIES_RECORD  *ImageRecord;
   LIST_ENTRY               *ImageRecordLink;
 
-  if (PcdGet32 (PcdImageProtectionPolicy) != 0) {
+  if (IS_DXE_IMAGE_PROTECTION_ACTIVE) {
     for (ImageRecordLink = mProtectedImageRecordList.ForwardLink;
          ImageRecordLink != &mProtectedImageRecordList;
          ImageRecordLink = ImageRecordLink->ForwardLink)
@@ -648,21 +652,23 @@ GetPermissionAttributeForMemoryType (
   IN EFI_MEMORY_TYPE  MemoryType
   )
 {
-  UINT64  TestBit;
+  UINT32  TestMemoryType;
 
   if ((UINT32)MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) {
-    TestBit = BIT63;
+    TestMemoryType = OS_RESERVED_MPS_MEMORY_TYPE;
   } else if ((UINT32)MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) {
-    TestBit = BIT62;
+    TestMemoryType = OEM_RESERVED_MPS_MEMORY_TYPE;
+  } else if (MemoryType >= EfiMaxMemoryType) {
+    return EFI_MEMORY_XP;
   } else {
-    TestBit = LShiftU64 (1, MemoryType);
+    TestMemoryType = MemoryType;
   }
 
-  if ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy) & TestBit) != 0) {
+  if (gMps.Dxe.ExecutionProtection.EnabledForType[TestMemoryType]) {
     return EFI_MEMORY_XP;
-  } else {
-    return 0;
   }
+
+  return 0;
 }
 
 /**
@@ -772,7 +778,7 @@ MergeMemoryMapForProtectionPolicy (
 
 /**
   Remove exec permissions from all regions whose type is identified by
-  PcdDxeNxMemoryProtectionPolicy.
+  the DXE Execution Protection Policy.
 **/
 STATIC
 VOID
@@ -827,7 +833,7 @@ InitializeDxeNxMemoryProtectionPolicy (
   ASSERT_EFI_ERROR (Status);
 
   StackBase = 0;
-  if (PcdGetBool (PcdCpuStackGuard)) {
+  if (gMps.Dxe.CpuStackGuardEnabled) {
     //
     // Get the base of stack from Hob.
     //
@@ -885,7 +891,7 @@ InitializeDxeNxMemoryProtectionPolicy (
       // enabled.
       //
       if ((MemoryMapEntry->PhysicalStart == 0) &&
-          (PcdGet8 (PcdNullPointerDetectionPropertyMask) != 0))
+          (gMps.Dxe.NullPointerDetection.Enabled))
       {
         ASSERT (MemoryMapEntry->NumberOfPages > 0);
         SetUefiImageMemoryAttributes (
@@ -903,7 +909,7 @@ InitializeDxeNxMemoryProtectionPolicy (
           ((StackBase >= MemoryMapEntry->PhysicalStart) &&
            (StackBase <  MemoryMapEntry->PhysicalStart +
             LShiftU64 (MemoryMapEntry->NumberOfPages, EFI_PAGE_SHIFT))) &&
-          PcdGetBool (PcdCpuStackGuard))
+          gMps.Dxe.CpuStackGuardEnabled)
       {
         SetUefiImageMemoryAttributes (
           StackBase,
@@ -1024,7 +1030,7 @@ MemoryProtectionCpuArchProtocolNotify (
   //
   // Apply the memory protection policy on non-BScode/RTcode regions.
   //
-  if (PcdGet64 (PcdDxeNxMemoryProtectionPolicy) != 0) {
+  if (IS_DXE_EXECUTION_PROTECTION_ACTIVE) {
     InitializeDxeNxMemoryProtectionPolicy ();
   }
 
@@ -1036,7 +1042,7 @@ MemoryProtectionCpuArchProtocolNotify (
   // Mark the HOB list XP and RO.
   ProtectHobList ();
 
-  if (mImageProtectionPolicy == 0) {
+  if (!IS_DXE_IMAGE_PROTECTION_ACTIVE) {
     goto Done;
   }
 
@@ -1099,7 +1105,7 @@ MemoryProtectionExitBootServicesCallback (
   // delay setting protections on RT code pages until after SetVirtualAddressMap().
   // OS may set protection on RT based upon EFI_MEMORY_ATTRIBUTES_TABLE later.
   //
-  if (mImageProtectionPolicy != 0) {
+  if (IS_DXE_IMAGE_PROTECTION_ACTIVE) {
     for (Link = gRuntime->ImageHead.ForwardLink; Link != &gRuntime->ImageHead; Link = Link->ForwardLink) {
       RuntimeImage = BASE_CR (Link, EFI_RUNTIME_IMAGE_ENTRY, Link);
       SetUefiImageMemoryAttributes ((UINT64)(UINTN)RuntimeImage->ImageBase, ALIGN_VALUE (RuntimeImage->ImageSize, EFI_PAGE_SIZE), 0);
@@ -1173,19 +1179,20 @@ CoreInitializeMemoryProtection (
   EFI_EVENT   EndOfDxeEvent;
   VOID        *Registration;
 
-  mImageProtectionPolicy = PcdGet32 (PcdImageProtectionPolicy);
+  mIsExecutionProtectionActive = IS_DXE_EXECUTION_PROTECTION_ACTIVE;
+  mIsPageOrPoolGuardActive     = IS_DXE_PAGE_GUARD_ACTIVE || IS_DXE_POOL_GUARD_ACTIVE;
 
   InitializeListHead (&mProtectedImageRecordList);
 
   //
-  // Sanity check the PcdDxeNxMemoryProtectionPolicy setting:
+  // Sanity check the DXE NX protection policy setting:
   // - code regions should have no EFI_MEMORY_XP attribute
   // - EfiConventionalMemory and EfiBootServicesData should use the
   //   same attribute
   //
-  ASSERT ((GetPermissionAttributeForMemoryType (EfiBootServicesCode) & EFI_MEMORY_XP) == 0);
-  ASSERT ((GetPermissionAttributeForMemoryType (EfiRuntimeServicesCode) & EFI_MEMORY_XP) == 0);
-  ASSERT ((GetPermissionAttributeForMemoryType (EfiLoaderCode) & EFI_MEMORY_XP) == 0);
+  ASSERT (!gMps.Dxe.ExecutionProtection.EnabledForType[EfiLoaderCode]);
+  ASSERT (!gMps.Dxe.ExecutionProtection.EnabledForType[EfiBootServicesCode]);
+  ASSERT (!gMps.Dxe.ExecutionProtection.EnabledForType[EfiRuntimeServicesCode]);
   ASSERT (
     GetPermissionAttributeForMemoryType (EfiBootServicesData) ==
     GetPermissionAttributeForMemoryType (EfiConventionalMemory)
@@ -1213,9 +1220,7 @@ CoreInitializeMemoryProtection (
   //
   // Register a callback to disable NULL pointer detection at EndOfDxe
   //
-  if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & (BIT0|BIT7))
-      == (BIT0|BIT7))
-  {
+  if (gMps.Dxe.NullPointerDetection.Enabled && gMps.Dxe.NullPointerDetection.DisableEndOfDxe) {
     Status = CoreCreateEventEx (
                EVT_NOTIFY_SIGNAL,
                TPL_NOTIFY,
@@ -1279,7 +1284,7 @@ ApplyMemoryProtectionPolicy (
   UINT64  NewAttributes;
 
   //
-  // The policy configured in PcdDxeNxMemoryProtectionPolicy
+  // The policy configured in DXE Execution Protection Policy
   // does not apply to allocations performed in SMM mode.
   //
   if (IsInSmm ()) {
@@ -1298,7 +1303,7 @@ ApplyMemoryProtectionPolicy (
   //
   // Check if a DXE memory protection policy has been configured
   //
-  if (PcdGet64 (PcdDxeNxMemoryProtectionPolicy) == 0) {
+  if (!mIsExecutionProtectionActive) {
     return EFI_SUCCESS;
   }
 
@@ -1306,7 +1311,7 @@ ApplyMemoryProtectionPolicy (
   // Don't overwrite Guard pages, which should be the first and/or last page,
   // if any.
   //
-  if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_PAGE|GUARD_HEAP_TYPE_POOL)) {
+  if (mIsPageOrPoolGuardActive) {
     if (IsGuardPage (Memory)) {
       Memory += EFI_PAGE_SIZE;
       Length -= EFI_PAGE_SIZE;
diff --git a/MdeModulePkg/Core/PiSmmCore/HeapGuard.c b/MdeModulePkg/Core/PiSmmCore/HeapGuard.c
index 25310122ca1b..eac38e699c30 100644
--- a/MdeModulePkg/Core/PiSmmCore/HeapGuard.c
+++ b/MdeModulePkg/Core/PiSmmCore/HeapGuard.c
@@ -592,36 +592,29 @@ IsMemoryTypeToGuard (
   IN UINT8              PageOrPool
   )
 {
-  UINT64  TestBit;
   UINT64  ConfigBit;
 
-  if (  ((PcdGet8 (PcdHeapGuardPropertyMask) & PageOrPool) == 0)
+  ConfigBit  = gMps.Mm.HeapGuard.PageGuardEnabled ? GUARD_HEAP_TYPE_PAGE : 0;
+  ConfigBit |= gMps.Mm.HeapGuard.PoolGuardEnabled ? GUARD_HEAP_TYPE_POOL : 0;
+
+  if (  ((ConfigBit & 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);
+    return (((PageOrPool & GUARD_HEAP_TYPE_PAGE) != 0) && gMps.Mm.PageGuard.EnabledForType[MemoryType]) ||
+           (((PageOrPool & GUARD_HEAP_TYPE_POOL) != 0) && gMps.Mm.PoolGuard.EnabledForType[MemoryType]);
   } else if (MemoryType == EfiMaxMemoryType) {
-    TestBit = (UINT64)-1;
-  } else {
-    TestBit = 0;
+    return (((PageOrPool & GUARD_HEAP_TYPE_PAGE) != 0) && IS_MM_PAGE_GUARD_ACTIVE) ||
+           (((PageOrPool & GUARD_HEAP_TYPE_POOL) != 0) && IS_MM_POOL_GUARD_ACTIVE);
   }
 
-  return ((ConfigBit & TestBit) != 0);
+  return FALSE;
 }
 
 /**
@@ -951,7 +944,7 @@ AdjustPoolHeadA (
   IN UINTN                 Size
   )
 {
-  if ((Memory == 0) || ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0)) {
+  if ((Memory == 0) || (!gMps.Mm.HeapGuard.GuardAlignedToTail)) {
     //
     // Pool head is put near the head Guard
     //
@@ -977,7 +970,7 @@ AdjustPoolHeadF (
   IN EFI_PHYSICAL_ADDRESS  Memory
   )
 {
-  if ((Memory == 0) || ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0)) {
+  if ((Memory == 0) || (!gMps.Mm.HeapGuard.GuardAlignedToTail)) {
     //
     // Pool head is put near the head Guard
     //
diff --git a/MdeModulePkg/Core/PiSmmCore/Pool.c b/MdeModulePkg/Core/PiSmmCore/Pool.c
index e1ff40a8ea55..991efaf33bdd 100644
--- a/MdeModulePkg/Core/PiSmmCore/Pool.c
+++ b/MdeModulePkg/Core/PiSmmCore/Pool.c
@@ -258,7 +258,7 @@ SmmInternalAllocatePool (
 
   NeedGuard   = IsPoolTypeToGuard (PoolType);
   HasPoolTail = !(NeedGuard &&
-                  ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));
+                  gMps.Mm.HeapGuard.GuardAlignedToTail);
 
   //
   // Adjust the size by the pool header & tail overhead
@@ -392,7 +392,7 @@ SmmInternalFreePool (
   MemoryGuarded = IsHeapGuardEnabled () &&
                   IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)FreePoolHdr);
   HasPoolTail = !(MemoryGuarded &&
-                  ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));
+                  gMps.Mm.HeapGuard.GuardAlignedToTail);
 
   if (HasPoolTail) {
     PoolTail = HEAD_TO_TAIL (&FreePoolHdr->Header);
diff --git a/MdeModulePkg/Core/Dxe/DxeMain.h b/MdeModulePkg/Core/Dxe/DxeMain.h
index 43daa037be44..8b8b97666f38 100644
--- a/MdeModulePkg/Core/Dxe/DxeMain.h
+++ b/MdeModulePkg/Core/Dxe/DxeMain.h
@@ -84,6 +84,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Library/DxeServicesLib.h>
 #include <Library/DebugAgentLib.h>
 #include <Library/CpuExceptionHandlerLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
 
 //
 // attributes for reserved memory before it is promoted to system memory
diff --git a/MdeModulePkg/Core/Dxe/DxeMain.inf b/MdeModulePkg/Core/Dxe/DxeMain.inf
index 6c896a0e7f0f..ddbbee5f68ce 100644
--- a/MdeModulePkg/Core/Dxe/DxeMain.inf
+++ b/MdeModulePkg/Core/Dxe/DxeMain.inf
@@ -94,6 +94,7 @@ [LibraryClasses]
   DebugAgentLib
   CpuExceptionHandlerLib
   PcdLib
+  GetMemoryProtectionsLib
 
 [Guids]
   gEfiEventMemoryMapChangeGuid                  ## PRODUCES             ## Event
@@ -179,13 +180,6 @@ [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfileMemoryType                 ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfilePropertyMask               ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfileDriverPath                 ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy                   ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy             ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask        ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType                       ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType                       ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask                   ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                           ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdFwVolDxeMaxEncapsulationDepth           ## CONSUMES
   gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel                          ## CONSUMES
 
diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h
index b8a490a8c3b5..2fabed0670e0 100644
--- a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h
+++ b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h
@@ -55,6 +55,7 @@
 #include <Library/HobLib.h>
 #include <Library/SmmMemLib.h>
 #include <Library/SafeIntLib.h>
+#include <Library/GetMemoryProtectionsLib.h>
 
 #include "PiSmmCorePrivateData.h"
 #include "HeapGuard.h"
diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf
index 3df44b38f13c..4586ec39d7c7 100644
--- a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf
+++ b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf
@@ -61,6 +61,7 @@ [LibraryClasses]
   HobLib
   SmmMemLib
   SafeIntLib
+  GetMemoryProtectionsLib
 
 [Protocols]
   gEfiDxeSmmReadyToLockProtocolGuid             ## UNDEFINED # SmiHandlerRegister
@@ -94,9 +95,6 @@ [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfilePropertyMask           ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfileDriverPath             ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmiHandlerProfilePropertyMask       ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType                   ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType                   ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable                        ## CONSUMES
 
 [Guids]
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108881): https://edk2.groups.io/g/devel/message/108881
Mute This Topic: https://groups.io/mt/101469959/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (18 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 19/28] MdeModulePkg: " Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-27  8:19   ` Gerd Hoffmann
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 21/28] OvmfPkg: Add QemuFwCfgParseString to QemuFwCfgSimpleParserLib Taylor Beebe
                   ` (7 subsequent siblings)
  27 siblings, 1 reply; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao

Now that the EDK2 tree uses GetMemoryProtectionsLib to query
the platform memory protection settings, we can add additional
profiles to SetMemoryProtectionsLib to give plaforms more options
for setting memory protections.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
---
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c | 417 +++++++++++++++++++-
 MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h                 |   7 +
 2 files changed, 422 insertions(+), 2 deletions(-)

diff --git a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
index 13032ec80fbf..5f054504b75e 100644
--- a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
+++ b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
@@ -28,6 +28,227 @@ typedef struct {
 // DXE PROFILE DEFINITIONS //
 /////////////////////////////
 
+//
+//  A memory profile with strict settings ideal for development scenarios.
+//
+#define DXE_MEMORY_PROTECTION_SETTINGS_DEBUG          \
+{                                                     \
+  DXE_MEMORY_PROTECTION_SIGNATURE,                    \
+  DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,     \
+  TRUE, /* Stack Guard */                             \
+  TRUE, /* Stack Execution Protection */              \
+  {     /* NULL Pointer Detection */                  \
+    .Enabled                                = TRUE,   \
+    .DisableEndOfDxe                        = FALSE,  \
+    .NonstopModeEnabled                     = TRUE    \
+  },                                                  \
+  { /* Image Protection */                            \
+    .ProtectImageFromUnknown                = TRUE,   \
+    .ProtectImageFromFv                     = TRUE    \
+  },                                                  \
+  { /* Execution Protection */                        \
+    .EnabledForType = {                               \
+      [EfiReservedMemoryType]               = TRUE,   \
+      [EfiLoaderCode]                       = FALSE,  \
+      [EfiLoaderData]                       = TRUE,   \
+      [EfiBootServicesCode]                 = FALSE,  \
+      [EfiBootServicesData]                 = TRUE,   \
+      [EfiRuntimeServicesCode]              = FALSE,  \
+      [EfiRuntimeServicesData]              = TRUE,   \
+      [EfiConventionalMemory]               = TRUE,   \
+      [EfiUnusableMemory]                   = TRUE,   \
+      [EfiACPIReclaimMemory]                = TRUE,   \
+      [EfiACPIMemoryNVS]                    = TRUE,   \
+      [EfiMemoryMappedIO]                   = TRUE,   \
+      [EfiMemoryMappedIOPortSpace]          = TRUE,   \
+      [EfiPalCode]                          = TRUE,   \
+      [EfiPersistentMemory]                 = FALSE,  \
+      [EfiUnacceptedMemoryType]             = TRUE,   \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = TRUE,   \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = TRUE    \
+    }                                                 \
+  },                                                  \
+  { /* Heap Guard */                                  \
+    .PageGuardEnabled                       = TRUE,   \
+    .PoolGuardEnabled                       = TRUE,   \
+    .FreedMemoryGuardEnabled                = FALSE,  \
+    .NonstopModeEnabled                     = TRUE,   \
+    .GuardAlignedToTail                     = TRUE    \
+  },                                                  \
+  { /* Pool Guard */                                  \
+    .EnabledForType = {                               \
+      [EfiReservedMemoryType]               = TRUE,   \
+      [EfiLoaderCode]                       = TRUE,   \
+      [EfiLoaderData]                       = TRUE,   \
+      [EfiBootServicesCode]                 = TRUE,   \
+      [EfiBootServicesData]                 = TRUE,   \
+      [EfiRuntimeServicesCode]              = TRUE,   \
+      [EfiRuntimeServicesData]              = TRUE,   \
+      [EfiConventionalMemory]               = FALSE,  \
+      [EfiUnusableMemory]                   = TRUE,   \
+      [EfiACPIReclaimMemory]                = TRUE,   \
+      [EfiACPIMemoryNVS]                    = TRUE,   \
+      [EfiMemoryMappedIO]                   = TRUE,   \
+      [EfiMemoryMappedIOPortSpace]          = TRUE,   \
+      [EfiPalCode]                          = TRUE,   \
+      [EfiPersistentMemory]                 = FALSE,  \
+      [EfiUnacceptedMemoryType]             = TRUE,   \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = TRUE,   \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = TRUE    \
+    }                                                 \
+  },                                                  \
+  { /* Page Guard */                                  \
+    .EnabledForType = {                               \
+      [EfiReservedMemoryType]               = TRUE,   \
+      [EfiLoaderCode]                       = TRUE,   \
+      [EfiLoaderData]                       = TRUE,   \
+      [EfiBootServicesCode]                 = TRUE,   \
+      [EfiBootServicesData]                 = TRUE,   \
+      [EfiRuntimeServicesCode]              = TRUE,   \
+      [EfiRuntimeServicesData]              = TRUE,   \
+      [EfiConventionalMemory]               = FALSE,  \
+      [EfiUnusableMemory]                   = TRUE,   \
+      [EfiACPIReclaimMemory]                = TRUE,   \
+      [EfiACPIMemoryNVS]                    = TRUE,   \
+      [EfiMemoryMappedIO]                   = TRUE,   \
+      [EfiMemoryMappedIOPortSpace]          = TRUE,   \
+      [EfiPalCode]                          = TRUE,   \
+      [EfiPersistentMemory]                 = FALSE,  \
+      [EfiUnacceptedMemoryType]             = TRUE,   \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = TRUE,   \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = TRUE    \
+    }                                                 \
+  }                                                   \
+}
+
+//
+//  A memory profile recommended for production. Compared to the debug
+//  settings, this profile removes the pool guards and uses page guards
+//  for fewer memory types.
+//
+#define DXE_MEMORY_PROTECTION_SETTINGS_PROD_MODE      \
+{                                                     \
+  DXE_MEMORY_PROTECTION_SIGNATURE,                    \
+  DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,     \
+  TRUE, /* Stack Guard */                             \
+  TRUE, /* Stack Execution Protection */              \
+  {     /* NULL Pointer Detection */                  \
+    .Enabled                                = TRUE,   \
+    .DisableEndOfDxe                        = FALSE,  \
+    .NonstopModeEnabled                     = FALSE   \
+  },                                                  \
+  { /* Image Protection */                            \
+    .ProtectImageFromUnknown                = FALSE,  \
+    .ProtectImageFromFv                     = TRUE    \
+  },                                                  \
+  { /* Execution Protection */                        \
+    .EnabledForType = {                               \
+      [EfiReservedMemoryType]               = TRUE,   \
+      [EfiLoaderCode]                       = FALSE,  \
+      [EfiLoaderData]                       = TRUE,   \
+      [EfiBootServicesCode]                 = FALSE,  \
+      [EfiBootServicesData]                 = TRUE,   \
+      [EfiRuntimeServicesCode]              = FALSE,  \
+      [EfiRuntimeServicesData]              = TRUE,   \
+      [EfiConventionalMemory]               = TRUE,   \
+      [EfiUnusableMemory]                   = TRUE,   \
+      [EfiACPIReclaimMemory]                = TRUE,   \
+      [EfiACPIMemoryNVS]                    = TRUE,   \
+      [EfiMemoryMappedIO]                   = TRUE,   \
+      [EfiMemoryMappedIOPortSpace]          = TRUE,   \
+      [EfiPalCode]                          = TRUE,   \
+      [EfiPersistentMemory]                 = FALSE,  \
+      [EfiUnacceptedMemoryType]             = TRUE,   \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = TRUE,   \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = TRUE    \
+    }                                                 \
+  },                                                  \
+  { /* Heap Guard */                                  \
+    .PageGuardEnabled                       = TRUE,   \
+    .PoolGuardEnabled                       = FALSE,  \
+    .FreedMemoryGuardEnabled                = FALSE,  \
+    .NonstopModeEnabled                     = FALSE,  \
+    .GuardAlignedToTail                     = TRUE    \
+  },                                                  \
+  { /* Pool Guard */                                  \
+    0                                                 \
+  },                                                  \
+  { /* Page Guard */                                  \
+    .EnabledForType = {                               \
+      [EfiReservedMemoryType]               = FALSE,  \
+      [EfiLoaderCode]                       = FALSE,  \
+      [EfiLoaderData]                       = FALSE,  \
+      [EfiBootServicesCode]                 = FALSE,  \
+      [EfiBootServicesData]                 = TRUE,   \
+      [EfiRuntimeServicesCode]              = FALSE,  \
+      [EfiRuntimeServicesData]              = TRUE,   \
+      [EfiConventionalMemory]               = FALSE,  \
+      [EfiUnusableMemory]                   = FALSE,  \
+      [EfiACPIReclaimMemory]                = FALSE,  \
+      [EfiACPIMemoryNVS]                    = FALSE,  \
+      [EfiMemoryMappedIO]                   = FALSE,  \
+      [EfiMemoryMappedIOPortSpace]          = FALSE,  \
+      [EfiPalCode]                          = FALSE,  \
+      [EfiPersistentMemory]                 = FALSE,  \
+      [EfiUnacceptedMemoryType]             = FALSE,  \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = FALSE,  \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = FALSE   \
+    }                                                 \
+  }                                                   \
+}
+
+//
+//  A memory profile which mirrors DXE_MEMORY_PROTECTION_SETTINGS_PROD_MODE
+//  but doesn't include page guards.
+//
+#define DXE_MEMORY_PROTECTION_SETTINGS_PROD_MODE_NO_PAGE_GUARDS   \
+{                                                                 \
+  DXE_MEMORY_PROTECTION_SIGNATURE,                                \
+  DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,                 \
+  TRUE, /* Stack Guard */                                         \
+  TRUE, /* Stack Execution Protection */                          \
+  {     /* NULL Pointer Detection */                              \
+    .Enabled                                = TRUE,               \
+    .DisableEndOfDxe                        = FALSE,              \
+    .NonstopModeEnabled                     = FALSE               \
+  },                                                              \
+  { /* Image Protection */                                        \
+    .ProtectImageFromUnknown                = FALSE,              \
+    .ProtectImageFromFv                     = TRUE                \
+  },                                                              \
+  { /* Execution Protection */                                    \
+    .EnabledForType = {                                           \
+      [EfiReservedMemoryType]               = TRUE,               \
+      [EfiLoaderCode]                       = FALSE,              \
+      [EfiLoaderData]                       = TRUE,               \
+      [EfiBootServicesCode]                 = FALSE,              \
+      [EfiBootServicesData]                 = TRUE,               \
+      [EfiRuntimeServicesCode]              = FALSE,              \
+      [EfiRuntimeServicesData]              = TRUE,               \
+      [EfiConventionalMemory]               = TRUE,               \
+      [EfiUnusableMemory]                   = TRUE,               \
+      [EfiACPIReclaimMemory]                = TRUE,               \
+      [EfiACPIMemoryNVS]                    = TRUE,               \
+      [EfiMemoryMappedIO]                   = TRUE,               \
+      [EfiMemoryMappedIOPortSpace]          = TRUE,               \
+      [EfiPalCode]                          = TRUE,               \
+      [EfiPersistentMemory]                 = FALSE,              \
+      [EfiUnacceptedMemoryType]             = TRUE,               \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]        = TRUE,               \
+      [OS_RESERVED_MPS_MEMORY_TYPE]         = TRUE                \
+    }                                                             \
+  },                                                              \
+  { /* Heap Guard */                                              \
+    0                                                             \
+  },                                                              \
+  { /* Pool Guard */                                              \
+    0                                                             \
+  },                                                              \
+  { /* Page Guard */                                              \
+    0                                                             \
+  }                                                               \
+}
+
 //
 //  A memory profile which uses the fixed at build PCDs defined in MdeModulePkg.dec
 //
@@ -121,10 +342,146 @@ typedef struct {
   }                                                                                                                                   \
 }
 
+//
+//  A memory profile which disables all DXE memory protection settings.
+//
+#define DXE_MEMORY_PROTECTION_SETTINGS_OFF            \
+{                                                     \
+  DXE_MEMORY_PROTECTION_SIGNATURE,                    \
+  DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,     \
+  FALSE, /* Stack Guard */                            \
+  FALSE, /* Stack Execution Protection */             \
+  {      /* NULL Pointer Detection */                 \
+    0                                                 \
+  },                                                  \
+  { /* Image Protection */                            \
+    0                                                 \
+  },                                                  \
+  { /* Execution Protection */                        \
+    0                                                 \
+  },                                                  \
+  { /* Heap Guard */                                  \
+    0                                                 \
+  },                                                  \
+  { /* Pool Guard */                                  \
+    0                                                 \
+  },                                                  \
+  { /* Page Guard */                                  \
+    0                                                 \
+  }                                                   \
+}
+
 ////////////////////////////
 // MM PROFILE DEFINITIONS //
 ////////////////////////////
 
+//
+//  A memory profile ideal for development scenarios.
+//
+#define MM_MEMORY_PROTECTION_SETTINGS_DEBUG        \
+{                                                  \
+  MM_MEMORY_PROTECTION_SIGNATURE,                  \
+  MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,   \
+  { /* NULL Pointer Detection */                   \
+    .Enabled                             = TRUE,   \
+    .NonstopModeEnabled                  = TRUE    \
+  },                                               \
+  { /* Heap Guard */                               \
+    .PageGuardEnabled                    = TRUE,   \
+    .PoolGuardEnabled                    = TRUE,   \
+    .NonstopModeEnabled                  = TRUE,   \
+    .GuardAlignedToTail                  = TRUE    \
+  },                                               \
+  { /* Pool Guard */                               \
+    .EnabledForType = {                            \
+      [EfiReservedMemoryType]            = FALSE,  \
+      [EfiLoaderCode]                    = FALSE,  \
+      [EfiLoaderData]                    = FALSE,  \
+      [EfiBootServicesCode]              = FALSE,  \
+      [EfiBootServicesData]              = TRUE,   \
+      [EfiRuntimeServicesCode]           = FALSE,  \
+      [EfiRuntimeServicesData]           = TRUE,   \
+      [EfiConventionalMemory]            = FALSE,  \
+      [EfiUnusableMemory]                = FALSE,  \
+      [EfiACPIReclaimMemory]             = FALSE,  \
+      [EfiACPIMemoryNVS]                 = FALSE,  \
+      [EfiMemoryMappedIO]                = FALSE,  \
+      [EfiMemoryMappedIOPortSpace]       = FALSE,  \
+      [EfiPalCode]                       = FALSE,  \
+      [EfiPersistentMemory]              = FALSE,  \
+      [EfiUnacceptedMemoryType]          = FALSE,  \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]     = FALSE,  \
+      [OS_RESERVED_MPS_MEMORY_TYPE]      = FALSE   \
+    }                                              \
+  },                                               \
+  { /* Page Guard */                               \
+    .EnabledForType = {                            \
+      [EfiReservedMemoryType]            = FALSE,  \
+      [EfiLoaderCode]                    = FALSE,  \
+      [EfiLoaderData]                    = FALSE,  \
+      [EfiBootServicesCode]              = FALSE,  \
+      [EfiBootServicesData]              = TRUE,   \
+      [EfiRuntimeServicesCode]           = FALSE,  \
+      [EfiRuntimeServicesData]           = TRUE,   \
+      [EfiConventionalMemory]            = FALSE,  \
+      [EfiUnusableMemory]                = FALSE,  \
+      [EfiACPIReclaimMemory]             = FALSE,  \
+      [EfiACPIMemoryNVS]                 = FALSE,  \
+      [EfiMemoryMappedIO]                = FALSE,  \
+      [EfiMemoryMappedIOPortSpace]       = FALSE,  \
+      [EfiPalCode]                       = FALSE,  \
+      [EfiPersistentMemory]              = FALSE,  \
+      [EfiUnacceptedMemoryType]          = FALSE,  \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]     = FALSE,  \
+      [OS_RESERVED_MPS_MEMORY_TYPE]      = FALSE   \
+    }                                              \
+  }                                                \
+}
+
+//
+//  A memory profile ideal for production scenarios.
+//
+#define MM_MEMORY_PROTECTION_SETTINGS_PROD_MODE    \
+{                                                  \
+  MM_MEMORY_PROTECTION_SIGNATURE,                  \
+  MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,   \
+  { /* NULL Pointer Detection */                   \
+    .Enabled                             = TRUE,   \
+    .NonstopModeEnabled                  = FALSE   \
+  },                                               \
+  { /* Heap Guard */                               \
+    .PageGuardEnabled                    = TRUE,   \
+    .PoolGuardEnabled                    = FALSE,  \
+    .NonstopModeEnabled                  = FALSE,  \
+    .GuardAlignedToTail                  = TRUE    \
+  },                                               \
+  { /* Pool Guard */                               \
+    0                                              \
+  },                                               \
+  { /* Page Guard */                               \
+    .EnabledForType = {                            \
+      [EfiReservedMemoryType]            = FALSE,  \
+      [EfiLoaderCode]                    = FALSE,  \
+      [EfiLoaderData]                    = FALSE,  \
+      [EfiBootServicesCode]              = FALSE,  \
+      [EfiBootServicesData]              = TRUE,   \
+      [EfiRuntimeServicesCode]           = FALSE,  \
+      [EfiRuntimeServicesData]           = TRUE,   \
+      [EfiConventionalMemory]            = FALSE,  \
+      [EfiUnusableMemory]                = FALSE,  \
+      [EfiACPIReclaimMemory]             = FALSE,  \
+      [EfiACPIMemoryNVS]                 = FALSE,  \
+      [EfiMemoryMappedIO]                = FALSE,  \
+      [EfiMemoryMappedIOPortSpace]       = FALSE,  \
+      [EfiPalCode]                       = FALSE,  \
+      [EfiPersistentMemory]              = FALSE,  \
+      [EfiUnacceptedMemoryType]          = FALSE,  \
+      [OEM_RESERVED_MPS_MEMORY_TYPE]     = FALSE,  \
+      [OS_RESERVED_MPS_MEMORY_TYPE]      = FALSE   \
+    }                                              \
+  }                                                \
+}
+
 //
 //  A memory profile which uses the fixed at build PCDs defined in MdeModulePkg.dec
 //
@@ -188,24 +545,80 @@ typedef struct {
   }                                                                                                                       \
 }
 
+//
+//  A memory profile which disables all MM memory protection settings.
+//
+#define MM_MEMORY_PROTECTION_SETTINGS_OFF           \
+{                                                   \
+  MM_MEMORY_PROTECTION_SIGNATURE,                   \
+  MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,    \
+  { /* NULL Pointer Detection */                    \
+    0                                               \
+  },                                                \
+  { /* Heap Guard */                                \
+    0                                               \
+  },                                                \
+  { /* Pool Guard */                                \
+    0                                               \
+  },                                                \
+  { /* Page Guard */                                \
+    0                                               \
+  }                                                 \
+}
+
 ////////////////////////////
 // PROFILE CONFIGURATIONS //
 ////////////////////////////
 
 DXE_MEMORY_PROTECTION_PROFILES  DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsMax] = {
-  [DxeMemoryProtectionSettingsPcd] = {
+  [DxeMemoryProtectionSettingsDebug] =               {
+    .Name        = "Debug",
+    .Description = "Development profile ideal for debug scenarios",
+    .Settings    = DXE_MEMORY_PROTECTION_SETTINGS_DEBUG
+  },
+  [DxeMemoryProtectionSettingsRelease] =             {
+    .Name        = "Release",
+    .Description = "Release profile recommended for production scenarios",
+    .Settings    = DXE_MEMORY_PROTECTION_SETTINGS_PROD_MODE
+  },
+  [DxeMemoryProtectionSettingsReleaseNoPageGuards] = {
+    .Name        = "ReleaseNoPageGuards",
+    .Description = "Release profile without page guards recommended for performance sensitive production scenarios",
+    .Settings    = DXE_MEMORY_PROTECTION_SETTINGS_PROD_MODE_NO_PAGE_GUARDS
+  },
+  [DxeMemoryProtectionSettingsPcd] =                 {
     .Name        = "Pcd",
     .Description = "Memory protection settings from PCDs",
     .Settings    = DXE_MEMORY_PROTECTION_SETTINGS_PCD
   },
+  [DxeMemoryProtectionSettingsOff] =                 {
+    .Name        = "Off",
+    .Description = "Disables all memory protection settings",
+    .Settings    = DXE_MEMORY_PROTECTION_SETTINGS_OFF
+  }
 };
 
 MM_MEMORY_PROTECTION_PROFILES  MmMemoryProtectionProfiles[MmMemoryProtectionSettingsMax] = {
-  [MmMemoryProtectionSettingsPcd] = {
+  [MmMemoryProtectionSettingsDebug] =   {
+    .Name        = "Debug",
+    .Description = "Development profile ideal for debug scenarios",
+    .Settings    = MM_MEMORY_PROTECTION_SETTINGS_DEBUG
+  },
+  [MmMemoryProtectionSettingsRelease] = {
+    .Name        = "Release",
+    .Description = "Release profile recommended for production scenarios",
+    .Settings    = MM_MEMORY_PROTECTION_SETTINGS_PROD_MODE
+  },
+  [MmMemoryProtectionSettingsPcd] =     {
     .Name        = "Pcd",
     .Description = "Memory protection settings from PCDs",
     .Settings    = MM_MEMORY_PROTECTION_SETTINGS_PCD
   },
+  [MmMemoryProtectionSettingsOff] =     {
+    .Name        = "Off",
+    .Description = "Disables all memory protection settings",
+    .Settings    = MM_MEMORY_PROTECTION_SETTINGS_OFF
+  }
 };
 
 /////////////////////////////////////
diff --git a/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h b/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
index 023c987c3c7e..f4665130b0b3 100644
--- a/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
+++ b/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
@@ -17,6 +17,10 @@ typedef struct {
 } DXE_MEMORY_PROTECTION_PROFILES;
 
 typedef enum {
+  DxeMemoryProtectionSettingsDebug = 0,
+  DxeMemoryProtectionSettingsRelease,
+  DxeMemoryProtectionSettingsReleaseNoPageGuards,
+  DxeMemoryProtectionSettingsOff,
   DxeMemoryProtectionSettingsPcd,
   DxeMemoryProtectionSettingsMax
 } DXE_MEMORY_PROTECTION_PROFILE_INDEX;
@@ -28,6 +32,9 @@ typedef struct {
 } MM_MEMORY_PROTECTION_PROFILES;
 
 typedef enum {
+  MmMemoryProtectionSettingsDebug = 0,
+  MmMemoryProtectionSettingsRelease,
+  MmMemoryProtectionSettingsOff,
   MmMemoryProtectionSettingsPcd,
   MmMemoryProtectionSettingsMax
 } MM_MEMORY_PROTECTION_PROFILE_INDEX;
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108882): https://edk2.groups.io/g/devel/message/108882
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 21/28] OvmfPkg: Add QemuFwCfgParseString to QemuFwCfgSimpleParserLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (19 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 22/28] OvmfPkg: Add MemoryProtectionConfigLib Taylor Beebe
                   ` (6 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann

QemuFwCfgParseString allows reading strings from the fw_cfg file.
This function is needed for parsing the memory protection profile
name.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
---
 OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParser.c | 11 +++++++++++
 OvmfPkg/Include/Library/QemuFwCfgSimpleParserLib.h               |  8 ++++++++
 2 files changed, 19 insertions(+)

diff --git a/OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParser.c b/OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParser.c
index c9e0091b82d1..63c8711a9f2e 100644
--- a/OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParser.c
+++ b/OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParser.c
@@ -426,3 +426,14 @@ QemuFwCfgParseUintn (
   *Value = (UINTN)Uint64;
   return RETURN_SUCCESS;
 }
+
+RETURN_STATUS
+EFIAPI
+QemuFwCfgParseString (
+  IN     CONST CHAR8  *FileName,
+  IN OUT UINTN        *BufferSize,
+  OUT    CHAR8        *Buffer
+  )
+{
+  return QemuFwCfgGetAsString (FileName, BufferSize, Buffer);
+}
diff --git a/OvmfPkg/Include/Library/QemuFwCfgSimpleParserLib.h b/OvmfPkg/Include/Library/QemuFwCfgSimpleParserLib.h
index bcbf3bc4fc96..ea9fcf7b402e 100644
--- a/OvmfPkg/Include/Library/QemuFwCfgSimpleParserLib.h
+++ b/OvmfPkg/Include/Library/QemuFwCfgSimpleParserLib.h
@@ -125,4 +125,12 @@ QemuFwCfgParseUintn (
   OUT UINTN        *Value
   );
 
+RETURN_STATUS
+EFIAPI
+QemuFwCfgParseString (
+  IN     CONST CHAR8  *FileName,
+  IN OUT UINTN        *BufferSize,
+  OUT    CHAR8        *Buffer
+  );
+
 #endif // QEMU_FW_CFG_SIMPLE_PARSER_LIB_H_
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108883): https://edk2.groups.io/g/devel/message/108883
Mute This Topic: https://groups.io/mt/101469961/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 22/28] OvmfPkg: Add MemoryProtectionConfigLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (20 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 21/28] OvmfPkg: Add QemuFwCfgParseString to QemuFwCfgSimpleParserLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 23/28] OvmfPkg: Enable Choosing Memory Protection Profile via QemuCfg Taylor Beebe
                   ` (5 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann

MemoryProtectionConfigLib enables parsing the fw_cfg for the
memory protection profile.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
---
 OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.c   | 118 ++++++++++++++++++++
 OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc                   |   1 +
 OvmfPkg/Include/Library/MemoryProtectionConfigLib.h                     |  49 ++++++++
 OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.inf |  35 ++++++
 OvmfPkg/OvmfPkg.dec                                                     |   4 +
 5 files changed, 207 insertions(+)

diff --git a/OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.c b/OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.c
new file mode 100644
index 000000000000..b568665f407c
--- /dev/null
+++ b/OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.c
@@ -0,0 +1,118 @@
+/** @file
+  Parses the fw_cfg file for the DXE and MM memory protection settings profile.
+
+  Copyright (c) Microsoft Corporation.
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Uefi.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/QemuFwCfgSimpleParserLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
+
+#define DXE_MEMORY_PROTECTION_PROFILE_FWCFG_FILE \
+  "opt/org.tianocore/DxeMemoryProtectionProfile"
+
+#define MM_MEMORY_PROTECTION_PROFILE_FWCFG_FILE \
+  "opt/org.tianocore/MmMemoryProtectionProfile"
+
+/**
+  Parses the fw_cfg file for the MM memory protection settings profile.
+
+  @param[in] MmSettings  The MM memory protection settings profile to populate.
+
+  @retval EFI_SUCCESS             The MM memory protection settings profile was populated.
+  @retval EFI_INVALID_PARAMETER   MmSettings is NULL.
+  @retval EFI_ABORTED             The MM memory protection settings profile name found in
+                                  fw_cfg was invalid.
+  @retval EFI_NOT_FOUND           The MM memory protection settings profile was not found.
+**/
+EFI_STATUS
+EFIAPI
+ParseFwCfgMmMemoryProtectionSettings (
+  IN MM_MEMORY_PROTECTION_SETTINGS  *MmSettings
+  )
+{
+  CHAR8  String[100];
+  UINTN  StringSize;
+  UINTN  Index;
+
+  if (MmSettings == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  StringSize = sizeof (String);
+
+  if (!EFI_ERROR (QemuFwCfgParseString (MM_MEMORY_PROTECTION_PROFILE_FWCFG_FILE, &StringSize, String))) {
+    Index = 0;
+    do {
+      if (AsciiStriCmp (MmMemoryProtectionProfiles[Index].Name, String) == 0) {
+        DEBUG ((DEBUG_INFO, "Setting MM Memory Protection Profile: %a\n", String));
+        break;
+      }
+    } while (++Index < MmMemoryProtectionSettingsMax);
+
+    if (Index >= MmMemoryProtectionSettingsMax) {
+      DEBUG ((DEBUG_ERROR, "Invalid MM memory protection profile: %a\n", String));
+      ASSERT (Index < MmMemoryProtectionSettingsMax);
+      return EFI_ABORTED;
+    } else {
+      CopyMem (MmSettings, &MmMemoryProtectionProfiles[Index].Settings, sizeof (MM_MEMORY_PROTECTION_SETTINGS));
+      return EFI_SUCCESS;
+    }
+  }
+
+  return EFI_NOT_FOUND;
+}
+
+/**
+  Parses the fw_cfg file for the DXE memory protection settings profile.
+
+  @param[in] DxeSettings  The DXE memory protection settings profile to populate.
+
+  @retval EFI_SUCCESS             The DXE memory protection settings profile was populated.
+  @retval EFI_INVALID_PARAMETER   DxeSettings is NULL.
+  @retval EFI_ABORTED             The DXE memory protection settings profile name found in
+                                  fw_cfg was invalid.
+  @retval EFI_NOT_FOUND           The DXE memory protection settings profile was not found.
+**/
+EFI_STATUS
+EFIAPI
+ParseFwCfgDxeMemoryProtectionSettings (
+  IN DXE_MEMORY_PROTECTION_SETTINGS  *DxeSettings
+  )
+{
+  CHAR8  String[100];
+  UINTN  StringSize;
+  UINTN  Index;
+
+  if (DxeSettings == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  StringSize = sizeof (String);
+
+  if (!EFI_ERROR (QemuFwCfgParseString (DXE_MEMORY_PROTECTION_PROFILE_FWCFG_FILE, &StringSize, String))) {
+    Index = 0;
+    do {
+      if (AsciiStriCmp (DxeMemoryProtectionProfiles[Index].Name, String) == 0) {
+        DEBUG ((DEBUG_INFO, "Setting DXE Memory Protection Profile: %a\n", String));
+        break;
+      }
+    } while (++Index < DxeMemoryProtectionSettingsMax);
+
+    if (Index >= DxeMemoryProtectionSettingsMax) {
+      DEBUG ((DEBUG_ERROR, "Invalid DXE memory protection profile: %a\n", String));
+      ASSERT (Index < DxeMemoryProtectionSettingsMax);
+      return EFI_ABORTED;
+    } else {
+      CopyMem (DxeSettings, &DxeMemoryProtectionProfiles[Index].Settings, sizeof (DXE_MEMORY_PROTECTION_SETTINGS));
+      return EFI_SUCCESS;
+    }
+  }
+
+  return EFI_NOT_FOUND;
+}
diff --git a/OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc b/OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
index 049fdef3f0c1..fcd8ef23c5a5 100644
--- a/OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
+++ b/OvmfPkg/Include/Dsc/MemoryProtectionLibraries.dsc.inc
@@ -7,6 +7,7 @@
 #
 [LibraryClasses.common]
   SetMemoryProtectionsLib|MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
+  MemoryProtectionConfigLib|OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.inf
 
 [LibraryClasses.common.SMM_CORE, LibraryClasses.common.DXE_SMM_DRIVER, LibraryClasses.common.MM_CORE_STANDALONE, LibraryClasses.common.MM_STANDALONE]
   GetMemoryProtectionsLib|MdeModulePkg/Library/GetMemoryProtectionsLib/MmGetMemoryProtectionsLib.inf
diff --git a/OvmfPkg/Include/Library/MemoryProtectionConfigLib.h b/OvmfPkg/Include/Library/MemoryProtectionConfigLib.h
new file mode 100644
index 000000000000..d30de58001c3
--- /dev/null
+++ b/OvmfPkg/Include/Library/MemoryProtectionConfigLib.h
@@ -0,0 +1,49 @@
+/** @file
+  Parses the fw_cfg file for the DXE and MM memory protection settings profile.
+
+  Copyright (c) Microsoft Corporation.
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#ifndef MEMORY_PROTECTION_CONFIG_LIB_H_
+#define MEMORY_PROTECTION_CONFIG_LIB_H_
+
+#include <Uefi.h>
+
+#include <Library/SetMemoryProtectionsLib.h>
+
+/**
+  Parses the fw_cfg file for the MM memory protection settings profile.
+
+  @param[in] MmSettings  The MM memory protection settings profile to populate.
+
+  @retval EFI_SUCCESS             The MM memory protection settings profile was populated.
+  @retval EFI_INVALID_PARAMETER   MmSettings is NULL.
+  @retval EFI_ABORTED             The MM memory protection settings profile name found in
+                                  fw_cfg was invalid.
+  @retval EFI_NOT_FOUND           The MM memory protection settings profile was not found.
+**/
+EFI_STATUS
+EFIAPI
+ParseFwCfgMmMemoryProtectionSettings (
+  IN MM_MEMORY_PROTECTION_SETTINGS  *MmSettings
+  );
+
+/**
+  Parses the fw_cfg file for the DXE memory protection settings profile.
+
+  @param[in] DxeSettings  The DXE memory protection settings profile to populate.
+
+  @retval EFI_SUCCESS             The DXE memory protection settings profile was populated.
+  @retval EFI_INVALID_PARAMETER   DxeSettings is NULL.
+  @retval EFI_ABORTED             The DXE memory protection settings profile name found in
+                                  fw_cfg was invalid.
+  @retval EFI_NOT_FOUND           The DXE memory protection settings profile was not found.
+**/
+EFI_STATUS
+EFIAPI
+ParseFwCfgDxeMemoryProtectionSettings (
+  IN DXE_MEMORY_PROTECTION_SETTINGS  *DxeSettings
+  );
+
+#endif
diff --git a/OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.inf b/OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.inf
new file mode 100644
index 000000000000..0ff431752901
--- /dev/null
+++ b/OvmfPkg/Library/MemoryProtectionConfigLib/MemoryProtectionConfigLib.inf
@@ -0,0 +1,35 @@
+## @file
+# Parses the fw_cfg file for the DXE and MM memory protection settings profile.
+#
+# Copyright (c) Microsoft Corporation.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = MemoryProtectionConfigLib
+  FILE_GUID                      = 865BFF85-CC3A-43E7-82E1-36E1894BC8EF
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = MemoryProtectionConfigLib|SEC PEI_CORE PEIM
+
+#
+# The following information is for reference only and not required by the build
+# tools.
+#
+#  VALID_ARCHITECTURES           = IA32 X64 ARM AARCH64
+#
+
+[Sources]
+  MemoryProtectionConfigLib.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+  OvmfPkg/OvmfPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  BaseMemoryLib
+  DebugLib
+  QemuFwCfgSimpleParserLib
diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec
index e3861e5c1b39..126be04ca302 100644
--- a/OvmfPkg/OvmfPkg.dec
+++ b/OvmfPkg/OvmfPkg.dec
@@ -42,6 +42,10 @@ [LibraryClasses]
   #
   MemEncryptTdxLib|Include/Library/MemEncryptTdxLib.h
 
+  ## @libraryclass  Declares helper functions for parsing fw_cfg for
+  #                 the memory protection profile strings
+  MemoryProtectionConfigLib|Include/Library/MemoryProtectionConfigLib.h
+
   ##  @libraryclass  Handle TPL changes within nested interrupt handlers
   #
   NestedInterruptTplLib|Include/Library/NestedInterruptTplLib.h
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108884): https://edk2.groups.io/g/devel/message/108884
Mute This Topic: https://groups.io/mt/101469962/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 23/28] OvmfPkg: Enable Choosing Memory Protection Profile via QemuCfg
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (21 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 22/28] OvmfPkg: Add MemoryProtectionConfigLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 24/28] ArmVirtPkg: Apply Memory Protections via SetMemoryProtectionsLib Taylor Beebe
                   ` (4 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Rebecca Cran, Peter Grehan, Corvin Köhne

Now that the EDK2 tree uses GetMemoryProtectionsLib to query
the platform memory protection settings, OvmfPkg can be updated
to use QemuCfg to set the entire memory protection profile instead
of just SetNxForStack.

For example, the following will set the DXE memory protection to
the RELEASE preset.
-fw_cfg name=opt/org.tianocore/DxeMemoryProtectionProfile,string=release

The following will set the MM memory protection to
the RELEASE preset.
-fw_cfg name=opt/org.tianocore/MmMemoryProtectionProfile,string=release

For users of Stuart, DXE_MEMORY_PROTECTION_PROFILE=release and
MM_MEMORY_PROTECTION_PROFILE=release are equivalent to the above
examples.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rebecca Cran <rebecca@bsdio.com>
Cc: Peter Grehan <grehan@freebsd.org>
Cc: Corvin Köhne <corvink@freebsd.org>
---
 OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c      | 21 +++++++-----
 OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c   | 13 +-------
 OvmfPkg/Library/PlatformInitLib/Platform.c              | 15 ---------
 OvmfPkg/PlatformPei/IntelTdx.c                          |  2 --
 OvmfPkg/PlatformPei/Platform.c                          | 35 ++++++++------------
 OvmfPkg/TdxDxe/TdxDxe.c                                 |  7 ++--
 OvmfPkg/Include/Library/PlatformInitLib.h               | 13 --------
 OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf |  2 +-
 OvmfPkg/PlatformCI/PlatformBuildLib.py                  |  8 +++++
 OvmfPkg/PlatformPei/PlatformPei.inf                     |  1 +
 10 files changed, 39 insertions(+), 78 deletions(-)

diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
index cf645aad3246..2f8fd51f3fc5 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
@@ -20,7 +20,7 @@
 #include <Library/PlatformInitLib.h>
 #include <Library/TdxHelperLib.h>
 #include <Library/SetMemoryProtectionsLib.h>
-#include <Library/QemuFwCfgSimpleParserLib.h>
+#include <Library/MemoryProtectionConfigLib.h>
 #include <ConfidentialComputingGuestAttr.h>
 #include <Guid/MemoryTypeInformation.h>
 #include <OvmfPlatforms.h>
@@ -109,18 +109,23 @@ InitializePlatform (
 
   PlatformMemMapInitialization (PlatformInfoHob);
 
-  DxeSettings                                 = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsPcd].Settings;
-  MmSettings                                  = MmMemoryProtectionProfiles[MmMemoryProtectionSettingsPcd].Settings;
-  DxeSettings.StackExecutionProtectionEnabled = PcdGetBool (PcdSetNxForStack);
-  QemuFwCfgParseBool ("opt/ovmf/PcdSetNxForStack", &DxeSettings.StackExecutionProtectionEnabled);
+  if (EFI_ERROR (ParseFwCfgDxeMemoryProtectionSettings (&DxeSettings))) {
+    DxeSettings = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsRelease].Settings;
+  }
 
-  SetDxeMemoryProtectionSettings (&DxeSettings, DxeMemoryProtectionSettingsPcd);
-  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsPcd);
+  if (EFI_ERROR (ParseFwCfgMmMemoryProtectionSettings (&MmSettings))) {
+    MmSettings = MmMemoryProtectionProfiles[MmMemoryProtectionSettingsOff].Settings;
+  }
+
+  // Always disable NullPointerDetection in EndOfDxe phase for shim compatability
+  DxeSettings.NullPointerDetection.DisableEndOfDxe = TRUE;
+
+  SetDxeMemoryProtectionSettings (&DxeSettings, DxeMemoryProtectionSettingsRelease);
+  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsOff);
 
   if (TdIsEnabled ()) {
     PlatformInfoHob->PcdConfidentialComputingGuestAttr = CCAttrIntelTdx;
     PlatformInfoHob->PcdTdxSharedBitMask               = TdSharedPageMask ();
-    PlatformInfoHob->PcdSetNxForStack                  = TRUE;
   }
 
   PlatformMiscInitialization (PlatformInfoHob);
diff --git a/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c b/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c
index 41521e3d3d71..7ae9b5743810 100644
--- a/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c
+++ b/OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c
@@ -53,18 +53,7 @@ IsSetNxForStack (
   VOID
   )
 {
-  EFI_HOB_GUID_TYPE      *GuidHob;
-  EFI_HOB_PLATFORM_INFO  *PlatformInfo;
-
-  GuidHob = GetFirstGuidHob (&gUefiOvmfPkgPlatformInfoGuid);
-  if (GuidHob == NULL) {
-    ASSERT (FALSE);
-    return FALSE;
-  }
-
-  PlatformInfo = (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob);
-
-  return PlatformInfo->PcdSetNxForStack;
+  return mMps.Dxe.StackExecutionProtectionEnabled;
 }
 
 /**
diff --git a/OvmfPkg/Library/PlatformInitLib/Platform.c b/OvmfPkg/Library/PlatformInitLib/Platform.c
index f48bf16ae300..bc9becc4016e 100644
--- a/OvmfPkg/Library/PlatformInitLib/Platform.c
+++ b/OvmfPkg/Library/PlatformInitLib/Platform.c
@@ -249,21 +249,6 @@ PlatformMemMapInitialization (
   PlatformInfoHob->PcdPciIoSize = PciIoSize;
 }
 
-/**
- * Fetch "opt/ovmf/PcdSetNxForStack" from QEMU
- *
- * @param Setting     The pointer to the setting of "/opt/ovmf/PcdSetNxForStack".
- * @return EFI_SUCCESS  Successfully fetch the settings.
- */
-EFI_STATUS
-EFIAPI
-PlatformNoexecDxeInitialization (
-  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob
-  )
-{
-  return QemuFwCfgParseBool ("opt/ovmf/PcdSetNxForStack", &PlatformInfoHob->PcdSetNxForStack);
-}
-
 VOID
 PciExBarInitialization (
   VOID
diff --git a/OvmfPkg/PlatformPei/IntelTdx.c b/OvmfPkg/PlatformPei/IntelTdx.c
index 3d625cabd844..1cb6729e56e6 100644
--- a/OvmfPkg/PlatformPei/IntelTdx.c
+++ b/OvmfPkg/PlatformPei/IntelTdx.c
@@ -48,7 +48,5 @@ IntelTdxInitialize (
   PcdStatus = PcdSet64S (PcdTdxSharedBitMask, TdSharedPageMask ());
   ASSERT_RETURN_ERROR (PcdStatus);
 
-  PcdStatus = PcdSetBoolS (PcdSetNxForStack, TRUE);
-  ASSERT_RETURN_ERROR (PcdStatus);
  #endif
 }
diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c
index bcd8d3a1be14..0df1277f34c4 100644
--- a/OvmfPkg/PlatformPei/Platform.c
+++ b/OvmfPkg/PlatformPei/Platform.c
@@ -39,6 +39,7 @@
 #include <Library/MemEncryptSevLib.h>
 #include <OvmfPlatforms.h>
 #include <Library/SetMemoryProtectionsLib.h>
+#include <Library/MemoryProtectionConfigLib.h>
 
 #include "Platform.h"
 
@@ -74,21 +75,6 @@ MemMapInitialization (
   ASSERT_RETURN_ERROR (PcdStatus);
 }
 
-STATIC
-VOID
-NoexecDxeInitialization (
-  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob
-  )
-{
-  RETURN_STATUS  Status;
-
-  Status = PlatformNoexecDxeInitialization (PlatformInfoHob);
-  if (!RETURN_ERROR (Status)) {
-    Status = PcdSetBoolS (PcdSetNxForStack, PlatformInfoHob->PcdSetNxForStack);
-    ASSERT_RETURN_ERROR (Status);
-  }
-}
-
 static const UINT8  EmptyFdt[] = {
   0xd0, 0x0d, 0xfe, 0xed, 0x00, 0x00, 0x00, 0x48,
   0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x48,
@@ -345,13 +331,19 @@ InitializePlatform (
 
   PublishPeiMemory (PlatformInfoHob);
 
-  DxeSettings                                 = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsPcd].Settings;
-  MmSettings                                  = MmMemoryProtectionProfiles[MmMemoryProtectionSettingsPcd].Settings;
-  DxeSettings.StackExecutionProtectionEnabled = PcdGetBool (PcdSetNxForStack);
-  QemuFwCfgParseBool ("opt/ovmf/PcdSetNxForStack", &DxeSettings.StackExecutionProtectionEnabled);
+  if (EFI_ERROR (ParseFwCfgDxeMemoryProtectionSettings (&DxeSettings))) {
+    DxeSettings = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsRelease].Settings;
+  }
 
-  SetDxeMemoryProtectionSettings (&DxeSettings, DxeMemoryProtectionSettingsPcd);
-  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsPcd);
+  if (EFI_ERROR (ParseFwCfgMmMemoryProtectionSettings (&MmSettings))) {
+    MmSettings = MmMemoryProtectionProfiles[MmMemoryProtectionSettingsOff].Settings;
+  }
+
+  // Always disable NullPointerDetection in EndOfDxe phase for shim compatability
+  DxeSettings.NullPointerDetection.DisableEndOfDxe = TRUE;
+
+  SetDxeMemoryProtectionSettings (&DxeSettings, DxeMemoryProtectionSettingsRelease);
+  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsOff);
 
   PlatformQemuUc32BaseInitialization (PlatformInfoHob);
 
@@ -365,7 +357,6 @@ InitializePlatform (
     PeiFvInitialization (PlatformInfoHob);
     MemTypeInfoInitialization (PlatformInfoHob);
     MemMapInitialization (PlatformInfoHob);
-    NoexecDxeInitialization (PlatformInfoHob);
   }
 
   InstallClearCacheCallback ();
diff --git a/OvmfPkg/TdxDxe/TdxDxe.c b/OvmfPkg/TdxDxe/TdxDxe.c
index 30732f421bb6..5e497ba66227 100644
--- a/OvmfPkg/TdxDxe/TdxDxe.c
+++ b/OvmfPkg/TdxDxe/TdxDxe.c
@@ -131,15 +131,12 @@ SetPcdSettings (
 
   PcdStatus = PcdSet64S (PcdConfidentialComputingGuestAttr, PlatformInfoHob->PcdConfidentialComputingGuestAttr);
   ASSERT_RETURN_ERROR (PcdStatus);
-  PcdStatus = PcdSetBoolS (PcdSetNxForStack, PlatformInfoHob->PcdSetNxForStack);
-  ASSERT_RETURN_ERROR (PcdStatus);
 
   DEBUG ((
     DEBUG_INFO,
-    "HostBridgeDevId=0x%x, CCAttr=0x%x, SetNxForStack=%x\n",
+    "HostBridgeDevId=0x%x, CCAttr=0x%x\n",
     PlatformInfoHob->HostBridgeDevId,
-    PlatformInfoHob->PcdConfidentialComputingGuestAttr,
-    PlatformInfoHob->PcdSetNxForStack
+    PlatformInfoHob->PcdConfidentialComputingGuestAttr
     ));
 
   PcdStatus = PcdSet32S (PcdCpuBootLogicalProcessorNumber, PlatformInfoHob->PcdCpuBootLogicalProcessorNumber);
diff --git a/OvmfPkg/Include/Library/PlatformInitLib.h b/OvmfPkg/Include/Library/PlatformInitLib.h
index 57b18b94d9b8..b2468f206321 100644
--- a/OvmfPkg/Include/Library/PlatformInitLib.h
+++ b/OvmfPkg/Include/Library/PlatformInitLib.h
@@ -32,7 +32,6 @@ typedef struct {
   UINT32               Uc32Base;
   UINT32               Uc32Size;
 
-  BOOLEAN              PcdSetNxForStack;
   UINT64               PcdTdxSharedBitMask;
 
   UINT64               PcdPciMmio64Base;
@@ -182,18 +181,6 @@ PlatformMemMapInitialization (
   IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob
   );
 
-/**
- * Fetch "opt/ovmf/PcdSetNxForStack" from QEMU
- *
- * @param Setting     The pointer to the setting of "/opt/ovmf/PcdSetNxForStack".
- * @return EFI_SUCCESS  Successfully fetch the settings.
- */
-EFI_STATUS
-EFIAPI
-PlatformNoexecDxeInitialization (
-  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob
-  );
-
 VOID
 EFIAPI
 PlatformMiscInitialization (
diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
index 47bd42d23d11..a6d7b53f52cf 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
@@ -57,7 +57,7 @@ [LibraryClasses]
   QemuFwCfgLib
   PlatformInitLib
   SetMemoryProtectionsLib
-  QemuFwCfgSimpleParserLib
+  MemoryProtectionConfigLib
 
 [Guids]
   gEfiHobMemoryAllocModuleGuid
diff --git a/OvmfPkg/PlatformCI/PlatformBuildLib.py b/OvmfPkg/PlatformCI/PlatformBuildLib.py
index f829738cdda4..0d5d39c078d0 100644
--- a/OvmfPkg/PlatformCI/PlatformBuildLib.py
+++ b/OvmfPkg/PlatformCI/PlatformBuildLib.py
@@ -183,6 +183,8 @@ class PlatformBuilder( UefiBuilder, BuildSettingsManager):
         VirtualDrive = os.path.join(self.env.GetValue("BUILD_OUTPUT_BASE"), "VirtualDrive")
         os.makedirs(VirtualDrive, exist_ok=True)
         OutputPath_FV = os.path.join(self.env.GetValue("BUILD_OUTPUT_BASE"), "FV")
+        DxeMemoryProtection = self.env.GetValue("DXE_MEMORY_PROTECTION_PROFILE", "")
+        MmMemoryProtection = self.env.GetValue("MM_MEMORY_PROTECTION_PROFILE", "")
 
         if (self.env.GetValue("QEMU_SKIP") and
             self.env.GetValue("QEMU_SKIP").upper() == "TRUE"):
@@ -199,6 +201,12 @@ class PlatformBuilder( UefiBuilder, BuildSettingsManager):
         args += " -smp 4"
         args += f" -drive file=fat:rw:{VirtualDrive},format=raw,media=disk" # Mount disk with startup.nsh
 
+        if (DxeMemoryProtection.lower() != ""):
+            args += " -fw_cfg name=opt/org.tianocore/DxeMemoryProtectionProfile,string=" + DxeMemoryProtection.lower()
+
+        if (MmMemoryProtection.lower() != ""):
+            args += " -fw_cfg name=opt/org.tianocore/MmMemoryProtectionProfile,string=" + MmMemoryProtection.lower()
+
         if (self.env.GetValue("QEMU_HEADLESS").upper() == "TRUE"):
             args += " -display none"  # no graphics
 
diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf
index 6b8442d12b2c..fbaa6bdc8ee5 100644
--- a/OvmfPkg/PlatformPei/PlatformPei.inf
+++ b/OvmfPkg/PlatformPei/PlatformPei.inf
@@ -66,6 +66,7 @@ [LibraryClasses]
   CcExitLib
   PlatformInitLib
   SetMemoryProtectionsLib
+  MemoryProtectionConfigLib
 
 [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108885): https://edk2.groups.io/g/devel/message/108885
Mute This Topic: https://groups.io/mt/101469963/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 24/28] ArmVirtPkg: Apply Memory Protections via SetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (22 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 23/28] OvmfPkg: Enable Choosing Memory Protection Profile via QemuCfg Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 25/28] MdeModulePkg: Delete PCD Profile from SetMemoryProtectionsLib Taylor Beebe
                   ` (3 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm, Sami Mujawar, Gerd Hoffmann

Set the memory protections on Arm virtual platforms. Because
the QemuFg parser is not currently available in ArmVirtPkg, use
the RELEASE profile by default.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Sami Mujawar <sami.mujawar@arm.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
---
 ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c   | 11 +++++++++--
 ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf |  1 +
 2 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c b/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c
index ef88a9df1d62..90718d05abe8 100644
--- a/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c
+++ b/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.c
@@ -11,6 +11,7 @@
 #include <Library/ArmPlatformLib.h>
 #include <Library/DebugLib.h>
 #include <Library/HobLib.h>
+#include <Library/SetMemoryProtectionsLib.h>
 #include <Library/PeimEntryPoint.h>
 #include <Library/PeiServicesLib.h>
 #include <Library/PcdLib.h>
@@ -76,8 +77,9 @@ InitializeMemory (
   IN CONST EFI_PEI_SERVICES     **PeiServices
   )
 {
-  UINTN       UefiMemoryBase;
-  EFI_STATUS  Status;
+  UINTN                           UefiMemoryBase;
+  EFI_STATUS                      Status;
+  DXE_MEMORY_PROTECTION_SETTINGS  DxeSettings;
 
   ASSERT (FixedPcdGet64 (PcdSystemMemoryBase) < (UINT64)MAX_ALLOC_ADDRESS);
 
@@ -100,5 +102,10 @@ InitializeMemory (
              );
   ASSERT_EFI_ERROR (Status);
 
+  DxeSettings                                      = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsRelease].Settings;
+  DxeSettings.NullPointerDetection.DisableEndOfDxe = TRUE;
+
+  SetDxeMemoryProtectionSettings (&DxeSettings, DxeMemoryProtectionSettingsRelease);
+
   return Status;
 }
diff --git a/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf b/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf
index 2039f71a0ebe..d13325a89e14 100644
--- a/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf
+++ b/ArmVirtPkg/MemoryInitPei/MemoryInitPeim.inf
@@ -34,6 +34,7 @@ [LibraryClasses]
   ArmLib
   ArmPlatformLib
   MemoryInitPeiLib
+  SetMemoryProtectionsLib
 
 [Guids]
   gEfiMemoryTypeInformationGuid
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108886): https://edk2.groups.io/g/devel/message/108886
Mute This Topic: https://groups.io/mt/101469964/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 25/28] MdeModulePkg: Delete PCD Profile from SetMemoryProtectionsLib
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (23 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 24/28] ArmVirtPkg: Apply Memory Protections via SetMemoryProtectionsLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 26/28] OvmfPkg: Delete Memory Protection PCDs Taylor Beebe
                   ` (2 subsequent siblings)
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao

Now that the transition to use SetMemoryProtectionsLib and
GetMemoryProtectionsLib is complete, delete the PCD profile
to avoid confusing the interface. All memory protection settings
will now be set and consumed via the libraries.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
---
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c   | 174 +-------------------
 MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h                   |   2 -
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf |  11 --
 3 files changed, 4 insertions(+), 183 deletions(-)

diff --git a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
index 5f054504b75e..5d5c7b9f37b2 100644
--- a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
+++ b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
@@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
 #include <Library/BaseMemoryLib.h>
-#include <Library/PcdLib.h>
 #include <Library/SetMemoryProtectionsLib.h>
 
 #pragma pack(1)
@@ -249,99 +248,6 @@ typedef struct {
   }                                                               \
 }
 
-//
-//  A memory profile which uses the fixed at build PCDs defined in MdeModulePkg.dec
-//
-#define DXE_MEMORY_PROTECTION_SETTINGS_PCD                                                                                            \
-{                                                                                                                                     \
-  DXE_MEMORY_PROTECTION_SIGNATURE,                                                                                                    \
-  DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,                                                                                     \
-  FixedPcdGetBool (PcdCpuStackGuard), /* Stack Guard */                                                                               \
-  TRUE,                               /* Stack Execution Protection (MUST BE POPULATED) */                                            \
-  {                                   /* NULL Pointer Detection */                                                                    \
-    .Enabled            = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) != 0),                                         \
-    .DisableEndOfDxe    = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT7) != 0),                                         \
-    .NonstopModeEnabled = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT6) != 0)                                          \
-  },                                                                                                                                  \
-  { /* Image Protection */                                                                                                            \
-    .ProtectImageFromUnknown = ((FixedPcdGet32 (PcdImageProtectionPolicy) & BIT0) != 0),                                              \
-    .ProtectImageFromFv      = ((FixedPcdGet32 (PcdImageProtectionPolicy) & BIT1) != 0)                                               \
-  },                                                                                                                                  \
-  { /* Execution Protection */                                                                                                        \
-    .EnabledForType = {                                                                                                               \
-      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiReservedMemoryType) != 0),        \
-      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiLoaderCode) != 0),                \
-      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiLoaderData) != 0),                \
-      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiBootServicesCode) != 0),          \
-      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiBootServicesData) != 0),          \
-      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiRuntimeServicesCode) != 0),       \
-      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiRuntimeServicesData) != 0),       \
-      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiConventionalMemory) != 0),        \
-      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiUnusableMemory) != 0),            \
-      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiACPIReclaimMemory) != 0),         \
-      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiACPIMemoryNVS) != 0),             \
-      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiMemoryMappedIO) != 0),            \
-      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiMemoryMappedIOPortSpace) != 0),   \
-      [EfiPalCode]                          = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiPalCode) != 0),                   \
-      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiPersistentMemory) != 0),          \
-      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & EfiUnacceptedMemoryType) != 0),      \
-      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & BIT62) != 0),                        \
-      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) & BIT63) != 0)                         \
-    }                                                                                                                                 \
-  },                                                                                                                                  \
-  { /* Heap Guard */                                                                                                                  \
-    .PageGuardEnabled                       = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT0) != 0),                                \
-    .PoolGuardEnabled                       = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT1) != 0),                                \
-    .FreedMemoryGuardEnabled                = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT4) != 0),                                \
-    .NonstopModeEnabled                     = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT6) != 0),                                \
-    .GuardAlignedToTail                     = ((FixedPcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0)                                 \
-  },                                                                                                                                  \
-  { /* Pool Guard */                                                                                                                  \
-    .EnabledForType = {                                                                                                               \
-      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiReservedMemoryType) != 0),                  \
-      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiLoaderCode) != 0),                          \
-      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiLoaderData) != 0),                          \
-      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiBootServicesCode) != 0),                    \
-      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiBootServicesData) != 0),                    \
-      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiRuntimeServicesCode) != 0),                 \
-      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiRuntimeServicesData) != 0),                 \
-      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiConventionalMemory) != 0),                  \
-      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiUnusableMemory) != 0),                      \
-      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiACPIReclaimMemory) != 0),                   \
-      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiACPIMemoryNVS) != 0),                       \
-      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiMemoryMappedIO) != 0),                      \
-      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiMemoryMappedIOPortSpace) != 0),             \
-      [EfiPalCode]                          = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiPalCode) != 0),                             \
-      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiPersistentMemory) != 0),                    \
-      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiUnacceptedMemoryType) != 0),                \
-      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdHeapGuardPoolType) & BIT62) != 0),                                  \
-      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdHeapGuardPoolType) & BIT63) != 0)                                   \
-    }                                                                                                                                 \
-  },                                                                                                                                  \
-  { /* Page Guard */                                                                                                                  \
-    .EnabledForType = {                                                                                                               \
-      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiReservedMemoryType) != 0),                  \
-      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiLoaderCode) != 0),                          \
-      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiLoaderData) != 0),                          \
-      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiBootServicesCode) != 0),                    \
-      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiBootServicesData) != 0),                    \
-      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiRuntimeServicesCode) != 0),                 \
-      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiRuntimeServicesData) != 0),                 \
-      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiConventionalMemory) != 0),                  \
-      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiUnusableMemory) != 0),                      \
-      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiACPIReclaimMemory) != 0),                   \
-      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiACPIMemoryNVS) != 0),                       \
-      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiMemoryMappedIO) != 0),                      \
-      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiMemoryMappedIOPortSpace) != 0),             \
-      [EfiPalCode]                          = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiPalCode) != 0),                             \
-      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiPersistentMemory) != 0),                    \
-      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiUnacceptedMemoryType) != 0),                \
-      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdHeapGuardPageType) & BIT62) != 0),                                  \
-      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdHeapGuardPageType) & BIT63) != 0)                                   \
-    }                                                                                                                                 \
-  }                                                                                                                                   \
-}
-
 //
 //  A memory profile which disables all DXE memory protection settings.
 //
@@ -482,69 +388,6 @@ typedef struct {
   }                                                \
 }
 
-//
-//  A memory profile which uses the fixed at build PCDs defined in MdeModulePkg.dec
-//
-#define MM_MEMORY_PROTECTION_SETTINGS_PCD                                                                                 \
-{                                                                                                                         \
-  MM_MEMORY_PROTECTION_SIGNATURE,                                                                                         \
-  MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION,                                                                          \
-  { /* NULL Pointer Detection */                                                                                          \
-    .Enabled            = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0),                             \
-    .NonstopModeEnabled = ((FixedPcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT6) != 0)                              \
-  },                                                                                                                      \
-  { /* Heap Guard */                                                                                                      \
-    .PageGuardEnabled                       = ((FixedPcdGet8(PcdHeapGuardPropertyMask) & BIT2) != 0),                     \
-    .PoolGuardEnabled                       = ((FixedPcdGet8(PcdHeapGuardPropertyMask) & BIT3) != 0),                     \
-    .NonstopModeEnabled                     = ((FixedPcdGet8(PcdHeapGuardPropertyMask) & BIT6) != 0),                     \
-    .GuardAlignedToTail                     = ((FixedPcdGet8(PcdHeapGuardPropertyMask) & BIT7) == 0)                      \
-  },                                                                                                                      \
-  { /* Pool Guard */                                                                                                      \
-    .EnabledForType = {                                                                                                   \
-      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiReservedMemoryType) != 0),      \
-      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiLoaderCode) != 0),              \
-      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiLoaderData) != 0),              \
-      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiBootServicesCode) != 0),        \
-      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiBootServicesData) != 0),        \
-      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiRuntimeServicesCode) != 0),     \
-      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiRuntimeServicesData) != 0),     \
-      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiConventionalMemory) != 0),      \
-      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiUnusableMemory) != 0),          \
-      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiACPIReclaimMemory) != 0),       \
-      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiACPIMemoryNVS) != 0),           \
-      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiMemoryMappedIO) != 0),          \
-      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiMemoryMappedIOPortSpace) != 0), \
-      [EfiPalCode]                          = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiPalCode) != 0),                 \
-      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiPersistentMemory) != 0),        \
-      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdHeapGuardPoolType) & EfiUnacceptedMemoryType) != 0),    \
-      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdHeapGuardPoolType) & BIT62) != 0),                      \
-      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdHeapGuardPoolType) & BIT63) != 0)                       \
-    }                                                                                                                     \
-  },                                                                                                                      \
-  { /* Page Guard */                                                                                                      \
-    .EnabledForType = {                                                                                                   \
-      [EfiReservedMemoryType]               = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiReservedMemoryType) != 0),      \
-      [EfiLoaderCode]                       = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiLoaderCode) != 0),              \
-      [EfiLoaderData]                       = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiLoaderData) != 0),              \
-      [EfiBootServicesCode]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiBootServicesCode) != 0),        \
-      [EfiBootServicesData]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiBootServicesData) != 0),        \
-      [EfiRuntimeServicesCode]              = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiRuntimeServicesCode) != 0),     \
-      [EfiRuntimeServicesData]              = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiRuntimeServicesData) != 0),     \
-      [EfiConventionalMemory]               = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiConventionalMemory) != 0),      \
-      [EfiUnusableMemory]                   = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiUnusableMemory) != 0),          \
-      [EfiACPIReclaimMemory]                = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiACPIReclaimMemory) != 0),       \
-      [EfiACPIMemoryNVS]                    = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiACPIMemoryNVS) != 0),           \
-      [EfiMemoryMappedIO]                   = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiMemoryMappedIO) != 0),          \
-      [EfiMemoryMappedIOPortSpace]          = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiMemoryMappedIOPortSpace) != 0), \
-      [EfiPalCode]                          = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiPalCode) != 0),                 \
-      [EfiPersistentMemory]                 = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiPersistentMemory) != 0),        \
-      [EfiUnacceptedMemoryType]             = ((FixedPcdGet64 (PcdHeapGuardPageType) & EfiUnacceptedMemoryType) != 0),    \
-      [OEM_RESERVED_MPS_MEMORY_TYPE]        = ((FixedPcdGet64 (PcdHeapGuardPageType) & BIT62) != 0),                      \
-      [OS_RESERVED_MPS_MEMORY_TYPE]         = ((FixedPcdGet64 (PcdHeapGuardPageType) & BIT63) != 0)                       \
-    }                                                                                                                     \
-  }                                                                                                                       \
-}
-
 //
 //  A memory profile which disables all MM memory protection settings.
 //
@@ -586,11 +429,6 @@ DXE_MEMORY_PROTECTION_PROFILES  DxeMemoryProtectionProfiles[DxeMemoryProtectionS
     .Description = "Release profile without page guards recommended for performance sensitive production scenarios",
     .Settings    = DXE_MEMORY_PROTECTION_SETTINGS_PROD_MODE_NO_PAGE_GUARDS
   },
-  [DxeMemoryProtectionSettingsPcd] =                 {
-    .Name        = "Pcd",
-    .Description = "Memory protection settings from PCDs",
-    .Settings    = DXE_MEMORY_PROTECTION_SETTINGS_PCD
-  },
   [DxeMemoryProtectionSettingsOff] =                 {
     .Name        = "Off",
     .Description = "Disables all memory protection settings",
@@ -609,11 +447,6 @@ MM_MEMORY_PROTECTION_PROFILES  MmMemoryProtectionProfiles[MmMemoryProtectionSett
     .Description = "Release profile recommended for production scenarios",
     .Settings    = MM_MEMORY_PROTECTION_SETTINGS_PROD_MODE
   },
-  [MmMemoryProtectionSettingsPcd] =     {
-    .Name        = "Pcd",
-    .Description = "Memory protection settings from PCDs",
-    .Settings    = MM_MEMORY_PROTECTION_SETTINGS_PCD
-  },
   [MmMemoryProtectionSettingsOff] =     {
     .Name        = "Off",
     .Description = "Disables all memory protection settings",
@@ -648,9 +481,10 @@ GetOrCreateMemoryProtectionSettings (
   }
 
   ZeroMem (&Mpsp, sizeof (Mpsp));
-  Mpsp.Mps.Dxe                                 = DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsPcd].Settings;
-  Mpsp.Mps.Mm                                  = MmMemoryProtectionProfiles[MmMemoryProtectionSettingsPcd].Settings;
-  Mpsp.Mps.Dxe.StackExecutionProtectionEnabled = PcdGetBool (PcdSetNxForStack);
+  Mpsp.Mps.Dxe.StructVersion = DXE_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION;
+  Mpsp.Mps.Dxe.Signature     = DXE_MEMORY_PROTECTION_SIGNATURE;
+  Mpsp.Mps.Mm.StructVersion  = MM_MEMORY_PROTECTION_SETTINGS_CURRENT_VERSION;
+  Mpsp.Mps.Mm.Signature      = MM_MEMORY_PROTECTION_SIGNATURE;
 
   Ptr = BuildGuidDataHob (
           &gMemoryProtectionSettingsGuid,
diff --git a/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h b/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
index f4665130b0b3..0b6495c3cc3a 100644
--- a/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
+++ b/MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h
@@ -21,7 +21,6 @@ typedef enum {
   DxeMemoryProtectionSettingsRelease,
   DxeMemoryProtectionSettingsReleaseNoPageGuards,
   DxeMemoryProtectionSettingsOff,
-  DxeMemoryProtectionSettingsPcd,
   DxeMemoryProtectionSettingsMax
 } DXE_MEMORY_PROTECTION_PROFILE_INDEX;
 
@@ -35,7 +34,6 @@ typedef enum {
   MmMemoryProtectionSettingsDebug = 0,
   MmMemoryProtectionSettingsRelease,
   MmMemoryProtectionSettingsOff,
-  MmMemoryProtectionSettingsPcd,
   MmMemoryProtectionSettingsMax
 } MM_MEMORY_PROTECTION_PROFILE_INDEX;
 
diff --git a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
index 2e4a9a66ac68..830d151a8378 100644
--- a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
+++ b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.inf
@@ -29,17 +29,6 @@ [LibraryClasses]
   BaseLib
   HobLib
   DebugLib
-  PcdLib
-
-[Pcd]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy
 
 [Guids]
   gMemoryProtectionSettingsGuid
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108887): https://edk2.groups.io/g/devel/message/108887
Mute This Topic: https://groups.io/mt/101469965/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 26/28] OvmfPkg: Delete Memory Protection PCDs
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (24 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 25/28] MdeModulePkg: Delete PCD Profile from SetMemoryProtectionsLib Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 27/28] ArmVirtPkg: " Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 28/28] MdeModulePkg: " Taylor Beebe
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel
  Cc: Ard Biesheuvel, Jiewen Yao, Jordan Justen, Gerd Hoffmann,
	Rebecca Cran, Peter Grehan, Corvin Köhne, Jianyong Wu,
	Anatol Belski, Anthony Perard, Julien Grall, Erdem Aktas,
	James Bottomley, Min Xu, Tom Lendacky, Michael Roth, Sunil V L,
	Andrei Warkentin

Now that the transition to use SetMemoryProtectionsLib and
GetMemoryProtectionsLib is complete, delete the memory protection PCDs
to avoid confusing the interface. All memory protection settings
will now be set and consumed via the libraries.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jordan Justen <jordan.l.justen@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rebecca Cran <rebecca@bsdio.com>
Cc: Peter Grehan <grehan@freebsd.org>
Cc: Corvin Köhne <corvink@freebsd.org>
Cc: Jianyong Wu <jianyong.wu@arm.com>
Cc: Anatol Belski <anbelski@linux.microsoft.com>
Cc: Anthony Perard <anthony.perard@citrix.com>
Cc: Julien Grall <julien@xen.org>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Min Xu <min.m.xu@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Michael Roth <michael.roth@amd.com>
Cc: Sunil V L <sunilvl@ventanamicro.com>
Cc: Andrei Warkentin <andrei.warkentin@intel.com>
---
 OvmfPkg/AmdSev/AmdSevX64.dsc                            |  3 ---
 OvmfPkg/Bhyve/BhyveX64.dsc                              |  3 ---
 OvmfPkg/Bhyve/PlatformPei/PlatformPei.inf               |  1 -
 OvmfPkg/CloudHv/CloudHvX64.dsc                          |  3 ---
 OvmfPkg/IntelTdx/IntelTdxX64.dsc                        |  3 ---
 OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf |  1 -
 OvmfPkg/Microvm/MicrovmX64.dsc                          |  3 ---
 OvmfPkg/OvmfPkgIa32.dsc                                 |  3 ---
 OvmfPkg/OvmfPkgIa32X64.dsc                              |  3 ---
 OvmfPkg/OvmfPkgX64.dsc                                  |  3 ---
 OvmfPkg/OvmfXen.dsc                                     |  3 ---
 OvmfPkg/PlatformPei/PlatformPei.inf                     |  1 -
 OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc                     | 13 -------------
 OvmfPkg/TdxDxe/TdxDxe.inf                               |  1 -
 14 files changed, 44 deletions(-)

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index b67b50b833b9..46a74e4f8ee8 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -516,9 +516,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
-
   # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
   gUefiCpuPkgTokenSpaceGuid.PcdCpuBootLogicalProcessorNumber|0
diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc
index 5af5831196f6..21baa47d2526 100644
--- a/OvmfPkg/Bhyve/BhyveX64.dsc
+++ b/OvmfPkg/Bhyve/BhyveX64.dsc
@@ -550,9 +550,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
-
   # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
   gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000
diff --git a/OvmfPkg/Bhyve/PlatformPei/PlatformPei.inf b/OvmfPkg/Bhyve/PlatformPei/PlatformPei.inf
index 07570d4e30ca..07f032941404 100644
--- a/OvmfPkg/Bhyve/PlatformPei/PlatformPei.inf
+++ b/OvmfPkg/Bhyve/PlatformPei/PlatformPei.inf
@@ -89,7 +89,6 @@ [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack
   gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask
   gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy
diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc
index c550ebcd659e..b8d643dfda3c 100644
--- a/OvmfPkg/CloudHv/CloudHvX64.dsc
+++ b/OvmfPkg/CloudHv/CloudHvX64.dsc
@@ -600,9 +600,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
-
   # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
   gUefiCpuPkgTokenSpaceGuid.PcdCpuBootLogicalProcessorNumber|0
diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
index a3370f45940c..513727ae98ff 100644
--- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
@@ -511,9 +511,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|TRUE
-
   # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
   gUefiCpuPkgTokenSpaceGuid.PcdCpuBootLogicalProcessorNumber|0
diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
index a6d7b53f52cf..009bee69e405 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
@@ -79,7 +79,6 @@ [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplBuildPageTables       ## CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable              ## SOMETIMES_CONSUMES
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack                       ## CONSUMES
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize
   gUefiOvmfPkgTokenSpaceGuid.PcdSecureBootSupported
diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index da5a4862bfdc..78f2ab64a60d 100644
--- a/OvmfPkg/Microvm/MicrovmX64.dsc
+++ b/OvmfPkg/Microvm/MicrovmX64.dsc
@@ -623,9 +623,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
-
   # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
   gUefiCpuPkgTokenSpaceGuid.PcdCpuBootLogicalProcessorNumber|0
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index d4d14b69ef1d..0f2b1812a821 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -634,9 +634,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
-
   # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
   gUefiCpuPkgTokenSpaceGuid.PcdCpuBootLogicalProcessorNumber|0
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 674010323df1..6180d267067a 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -652,9 +652,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
-
   # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
   gUefiCpuPkgTokenSpaceGuid.PcdCpuBootLogicalProcessorNumber|0
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index 08b70d76d292..937488b043f4 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -670,9 +670,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
-
   # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
   gUefiCpuPkgTokenSpaceGuid.PcdCpuBootLogicalProcessorNumber|0
diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc
index d80e20a151d7..e3631202238b 100644
--- a/OvmfPkg/OvmfXen.dsc
+++ b/OvmfPkg/OvmfXen.dsc
@@ -506,9 +506,6 @@ [PcdsDynamicDefault]
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
   gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
 
-  # Noexec settings for DXE.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
-
   # Set memory encryption mask
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0
 
diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf
index fbaa6bdc8ee5..3085f4f46a50 100644
--- a/OvmfPkg/PlatformPei/PlatformPei.inf
+++ b/OvmfPkg/PlatformPei/PlatformPei.inf
@@ -104,7 +104,6 @@ [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack
   gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask
   gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbBase
diff --git a/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc b/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc
index fe320525153f..57304c40766a 100644
--- a/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc
+++ b/OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc
@@ -271,19 +271,6 @@ [PcdsFixedAtBuild.common]
   gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode|20
   gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData|0
 
-  #
-  # Enable strict image permissions for all images. (This applies
-  # only to images that were built with >= 4 KB section alignment.)
-  #
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy|0x3
-
-  #
-  # Enable NX memory protection for all non-code regions, including OEM and OS
-  # reserved ones, with the exception of LoaderData regions, of which OS loaders
-  # (i.e., GRUB) may assume that its contents are executable.
-  #
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy|0xC000000000007FD5
-
 [Components.common]
   #
   # Ramdisk support
diff --git a/OvmfPkg/TdxDxe/TdxDxe.inf b/OvmfPkg/TdxDxe/TdxDxe.inf
index 9793562884c7..42317228c1aa 100644
--- a/OvmfPkg/TdxDxe/TdxDxe.inf
+++ b/OvmfPkg/TdxDxe/TdxDxe.inf
@@ -68,6 +68,5 @@ [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress
   gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr
   gEfiMdeModulePkgTokenSpaceGuid.PcdTdxSharedBitMask
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack
   gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved
   gUefiOvmfPkgTokenSpaceGuid.PcdTdxAcceptPageSize
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108888): https://edk2.groups.io/g/devel/message/108888
Mute This Topic: https://groups.io/mt/101469966/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 27/28] ArmVirtPkg: Delete Memory Protection PCDs
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (25 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 26/28] OvmfPkg: Delete Memory Protection PCDs Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 28/28] MdeModulePkg: " Taylor Beebe
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm, Sami Mujawar, Gerd Hoffmann

Now that the transition to use SetMemoryProtectionsLib and
GetMemoryProtectionsLib is complete, delete the memory protection PCDs
to avoid confusing the interface. All memory protection settings
will now be set and consumed via the libraries.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Leif Lindholm <quic_llindhol@quicinc.com>
Cc: Sami Mujawar <sami.mujawar@arm.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
---
 ArmVirtPkg/ArmVirt.dsc.inc    | 15 ---------------
 ArmVirtPkg/ArmVirtCloudHv.dsc |  5 -----
 ArmVirtPkg/ArmVirtQemu.dsc    |  5 -----
 3 files changed, 25 deletions(-)

diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc
index f76601503cd9..9b9d18a6e6c1 100644
--- a/ArmVirtPkg/ArmVirt.dsc.inc
+++ b/ArmVirtPkg/ArmVirt.dsc.inc
@@ -360,21 +360,6 @@ [PcdsFixedAtBuild.common]
   gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderCode|20
   gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiLoaderData|0
 
-  #
-  # Enable strict image permissions for all images. (This applies
-  # only to images that were built with >= 4 KB section alignment.)
-  #
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy|0x3
-
-  #
-  # Enable NX memory protection for all non-code regions, including OEM and OS
-  # reserved ones, with the exception of LoaderData regions, of which OS loaders
-  # (i.e., GRUB) may assume that its contents are executable.
-  #
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy|0xC000000000007FD5
-
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard|TRUE
-
 [Components.common]
   #
   # Ramdisk support
diff --git a/ArmVirtPkg/ArmVirtCloudHv.dsc b/ArmVirtPkg/ArmVirtCloudHv.dsc
index 2cb89ce10cf6..c87b71ccc28e 100644
--- a/ArmVirtPkg/ArmVirtCloudHv.dsc
+++ b/ArmVirtPkg/ArmVirtCloudHv.dsc
@@ -140,11 +140,6 @@ [PcdsFixedAtBuild.common]
   #
   gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|16
 
-  #
-  # Enable the non-executable DXE stack. (This gets set up by DxeIpl)
-  #
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|TRUE
-
 !if $(SECURE_BOOT_ENABLE) == TRUE
   # override the default values from SecurityPkg to ensure images from all sources are verified in secure boot
   gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x04
diff --git a/ArmVirtPkg/ArmVirtQemu.dsc b/ArmVirtPkg/ArmVirtQemu.dsc
index 30e3cfc8b9cc..7dedbd912b2c 100644
--- a/ArmVirtPkg/ArmVirtQemu.dsc
+++ b/ArmVirtPkg/ArmVirtQemu.dsc
@@ -212,11 +212,6 @@ [PcdsFixedAtBuild.common]
   #
   gEmbeddedTokenSpaceGuid.PcdPrePiCpuIoSize|16
 
-  #
-  # Enable the non-executable DXE stack. (This gets set up by DxeIpl)
-  #
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|TRUE
-
 !if $(SECURE_BOOT_ENABLE) == TRUE
   # override the default values from SecurityPkg to ensure images from all sources are verified in secure boot
   gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x04
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108889): https://edk2.groups.io/g/devel/message/108889
Mute This Topic: https://groups.io/mt/101469967/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* [edk2-devel] [PATCH v4 28/28] MdeModulePkg: Delete Memory Protection PCDs
  2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
                   ` (26 preceding siblings ...)
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 27/28] ArmVirtPkg: " Taylor Beebe
@ 2023-09-20  0:57 ` Taylor Beebe
  27 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-09-20  0:57 UTC (permalink / raw)
  To: devel; +Cc: Jian J Wang, Liming Gao

Now that the transition to use SetMemoryProtectionsLib and
GetMemoryProtectionsLib is complete, delete the memory protection PCDs
to avoid confusing the interface. All memory protection settings
will now be set and consumed via the libraries.

Signed-off-by: Taylor Beebe <taylor.d.beebe@gmail.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
---
 MdeModulePkg/MdeModulePkg.dec | 169 --------------------
 MdeModulePkg/MdeModulePkg.uni | 153 ------------------
 2 files changed, 322 deletions(-)

diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index 6ad0902a1bff..5aed6a787739 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -1007,119 +1007,12 @@ [PcdsFixedAtBuild]
   # @ValidList  0x80000006 | 0x03058002
   gEfiMdeModulePkgTokenSpaceGuid.PcdErrorCodeSetVariable|0x03058002|UINT32|0x30001040
 
-  ## Mask to control the NULL address detection in code for different phases.
-  #  If enabled, accessing NULL address in UEFI or SMM code can be caught.<BR><BR>
-  #    BIT0    - Enable NULL pointer detection for UEFI.<BR>
-  #    BIT1    - Enable NULL pointer detection for SMM.<BR>
-  #    BIT2..5 - Reserved for future uses.<BR>
-  #    BIT6    - Enable non-stop mode.<BR>
-  #    BIT7    - Disable NULL pointer detection just after EndOfDxe. <BR>
-  #              This is a workaround for those unsolvable NULL access issues in
-  #              OptionROM, boot loader, etc. It can also help to avoid unnecessary
-  #              exception caused by legacy memory (0-4095) access after EndOfDxe,
-  #              such as Windows 7 boot on Qemu.<BR>
-  # @Prompt Enable NULL address detection.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask|0x0|UINT8|0x30001050
-
   ## Init Value in Temp Stack to be shared between SEC and PEI_CORE
   # SEC fills the full temp stack with this values. When switch stack, PeiCore can check
   # this value in the temp stack to know how many stack has been used.
   # @Prompt Init Value in Temp Stack
   gEfiMdeModulePkgTokenSpaceGuid.PcdInitValueInTempStack|0x5AA55AA5|UINT32|0x30001051
 
-  ## Indicates which type allocation need guard page.
-  #
-  # If a bit is set, a head guard page and a tail guard page will be added just
-  # before and after corresponding type of pages allocated if there's enough
-  # free pages for all of them. The page allocation for the type related to
-  # cleared bits keeps the same as ususal.
-  #
-  # This PCD is only valid if BIT0 and/or BIT2 are set in PcdHeapGuardPropertyMask.
-  #
-  # 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.
-  #
-  # If a bit is set, a head guard page and a tail guard page will be added just
-  # before and after corresponding type of pages which the allocated pool occupies,
-  # if there's enough free memory for all of them. The pool allocation for the
-  # type related to cleared bits keeps the same as ususal.
-  #
-  # This PCD is only valid if BIT1 and/or BIT3 are set in PcdHeapGuardPropertyMask.
-  #
-  # 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.
-  #
-  # Note:
-  #   a) Heap Guard is for debug purpose and should not be enabled in product
-  #      BIOS.
-  #   b) Due to the limit of pool memory implementation and the alignment
-  #      requirement of UEFI spec, BIT7 is a try-best setting which cannot
-  #      guarantee that the returned pool is exactly adjacent to head guard
-  #      page or tail guard page.
-  #   c) UEFI freed-memory guard and UEFI pool/page guard cannot be enabled
-  #      at the same time.
-  #
-  #   BIT0 - Enable UEFI page guard.<BR>
-  #   BIT1 - Enable UEFI pool guard.<BR>
-  #   BIT2 - Enable SMM page guard.<BR>
-  #   BIT3 - Enable SMM pool guard.<BR>
-  #   BIT4 - Enable UEFI freed-memory guard (Use-After-Free memory detection).<BR>
-  #   BIT6 - Enable non-stop mode.<BR>
-  #   BIT7 - The direction of Guard Page for Pool Guard.
-  #          0 - The returned pool is near the tail guard page.<BR>
-  #          1 - The returned pool is near the head guard page.<BR>
-  # @Prompt The Heap Guard feature mask
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask|0x0|UINT8|0x30001054
-
-  ## Indicates if UEFI Stack Guard will be enabled.
-  #  If enabled, stack overflow in UEFI can be caught, preventing chaotic consequences.<BR><BR>
-  #   TRUE  - UEFI Stack Guard will be enabled.<BR>
-  #   FALSE - UEFI Stack Guard will be disabled.<BR>
-  # @Prompt Enable UEFI Stack Guard.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard|FALSE|BOOLEAN|0x30001055
-
   ## Indicate debug level of Trace Hub.
   #   0x0 - TraceHubDebugLevelError.<BR>
   #   0x1 - TraceHubDebugLevelErrorWarning.<BR>
@@ -1396,54 +1289,6 @@ [PcdsFixedAtBuild, PcdsPatchableInModule]
   # @Prompt Memory profile driver path.
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfileDriverPath|{0x0}|VOID*|0x00001043
 
-  ## Set image protection policy. The policy is bitwise.
-  #  If a bit is set, the image will be protected by DxeCore if it is aligned.
-  #   The code section becomes read-only, and the data section becomes non-executable.
-  #  If a bit is clear, nothing will be done to image code/data sections.<BR><BR>
-  #    BIT0       - Image from unknown device. <BR>
-  #    BIT1       - Image from firmware volume.<BR>
-  #  <BR>
-  #  Note: If a bit is cleared, the data section could be still non-executable if
-  #  PcdDxeNxMemoryProtectionPolicy is enabled for EfiLoaderData, EfiBootServicesData
-  #  and/or EfiRuntimeServicesData.<BR>
-  #  <BR>
-  # @Prompt Set image protection policy.
-  # @ValidRange 0x80000002 | 0x00000000 - 0x0000001F
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy|0x00000002|UINT32|0x00001047
-
-  ## Set DXE memory protection policy. The policy is bitwise.
-  #  If a bit is set, memory regions of the associated type will be mapped
-  #  non-executable.<BR>
-  #  If a bit is cleared, nothing will be done to associated type of memory.<BR>
-  #  <BR>
-  # Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>
-  #  EfiReservedMemoryType          0x0001<BR>
-  #  EfiLoaderCode                  0x0002<BR>
-  #  EfiLoaderData                  0x0004<BR>
-  #  EfiBootServicesCode            0x0008<BR>
-  #  EfiBootServicesData            0x0010<BR>
-  #  EfiRuntimeServicesCode         0x0020<BR>
-  #  EfiRuntimeServicesData         0x0040<BR>
-  #  EfiConventionalMemory          0x0080<BR>
-  #  EfiUnusableMemory              0x0100<BR>
-  #  EfiACPIReclaimMemory           0x0200<BR>
-  #  EfiACPIMemoryNVS               0x0400<BR>
-  #  EfiMemoryMappedIO              0x0800<BR>
-  #  EfiMemoryMappedIOPortSpace     0x1000<BR>
-  #  EfiPalCode                     0x2000<BR>
-  #  EfiPersistentMemory            0x4000<BR>
-  #  OEM Reserved       0x4000000000000000<BR>
-  #  OS Reserved        0x8000000000000000<BR>
-  #
-  # NOTE: User must NOT set NX protection for EfiLoaderCode / EfiBootServicesCode / EfiRuntimeServicesCode. <BR>
-  #       User MUST set the same NX protection for EfiBootServicesData and EfiConventionalMemory. <BR>
-  #
-  # e.g. 0x7FD5 can be used for all memory except Code. <BR>
-  # e.g. 0x7BD4 can be used for all memory except Code and ACPINVS/Reserved. <BR>
-  #
-  # @Prompt Set DXE memory protection policy.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy|0x0000000|UINT64|0x00001048
-
   ## PCI Serial Device Info. It is an array of Device, Function, and Power Management
   #  information that describes the path that contains zero or more PCI to PCI bridges
   #  followed by a PCI serial device.  Each array entry is 4-bytes in length.  The
@@ -2032,20 +1877,6 @@ [PcdsFixedAtBuild, PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx]
   # @Prompt Default Creator Revision for ACPI table creation.
   gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorRevision|0x01000013|UINT32|0x30001038
 
-  ## Indicates if to set NX for stack.<BR><BR>
-  #  For the DxeIpl and the DxeCore are both X64, set NX for stack feature also require PcdDxeIplBuildPageTables be TRUE.<BR>
-  #  For the DxeIpl and the DxeCore are both IA32 (PcdDxeIplSwitchToLongMode is FALSE), set NX for stack feature also require
-  #  IA32 PAE is supported and Execute Disable Bit is available.<BR>
-  #  <BR>
-  #   TRUE  - Set NX for stack.<BR>
-  #   FALSE - Do nothing for stack.<BR>
-  #  <BR>
-  #  Note: If this PCD is set to FALSE, NX could be still applied to stack due to PcdDxeNxMemoryProtectionPolicy enabled for
-  #  EfiBootServicesData.<BR>
-  #  <BR>
-  # @Prompt Set NX for stack.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE|BOOLEAN|0x0001006f
-
   ## This PCD specifies the PCI-based SD/MMC host controller mmio base address.
   # Define the mmio base address of the pci-based SD/MMC host controller. If there are multiple SD/MMC
   # host controllers, their mmio base addresses are calculated one by one from this base address.
diff --git a/MdeModulePkg/MdeModulePkg.uni b/MdeModulePkg/MdeModulePkg.uni
index a17d34d60b21..afbbc44761ca 100644
--- a/MdeModulePkg/MdeModulePkg.uni
+++ b/MdeModulePkg/MdeModulePkg.uni
@@ -330,16 +330,6 @@
 
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdSerialRegisterStride_HELP  #language en-US "The number of bytes between registers in serial device.  The default is 1 byte."
 
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdSetNxForStack_PROMPT  #language en-US "Set NX for stack"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdSetNxForStack_HELP  #language en-US "Indicates if to set NX for stack.<BR><BR>"
-                                                                                  "For the DxeIpl and the DxeCore are both X64, set NX for stack feature also require PcdDxeIplBuildPageTables be TRUE.<BR>"
-                                                                                  "For the DxeIpl and the DxeCore are both IA32 (PcdDxeIplSwitchToLongMode is FALSE), set NX for stack feature also require"
-                                                                                  "IA32 PAE is supported and Execute Disable Bit is available.<BR>"
-                                                                                  "TRUE  - Set NX for stack.<BR>"
-                                                                                  "FALSE - Do nothing for stack.<BR>"
-                                                                                  "Note: If this PCD is set to FALSE, NX could be still applied to stack due to PcdDxeNxMemoryProtectionPolicy enabled for EfiBootServicesData.<BR>"
-
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdAcpiS3Enable_PROMPT  #language en-US "ACPI S3 Enable"
 
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdAcpiS3Enable_HELP  #language en-US "Indicates if ACPI S3 will be enabled.<BR><BR>"
@@ -1096,51 +1086,6 @@
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdSmiHandlerProfilePropertyMask_HELP  #language en-US "The mask is used to control SmiHandlerProfile behavior.<BR><BR>\n"
                                                                                                   "BIT0 - Enable SmiHandlerProfile.<BR>"
 
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdImageProtectionPolicy_PROMPT  #language en-US "Set image protection policy."
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdImageProtectionPolicy_HELP  #language en-US "Set image protection policy. The policy is bitwise.\n"
-                                                                                          "If a bit is set, the image will be protected by DxeCore if it is aligned.\n"
-                                                                                          "The code section becomes read-only, and the data section becomes non-executable.\n"
-                                                                                          "If a bit is clear, nothing will be done to image code/data sections.<BR><BR>\n"
-                                                                                          "BIT0       - Image from unknown device. <BR>\n"
-                                                                                          "BIT1       - Image from firmware volume.<BR>"
-                                                                                          "Note: If a bit is cleared, the data section could be still non-executable if\n"
-                                                                                          "PcdDxeNxMemoryProtectionPolicy is enabled for EfiLoaderData, EfiBootServicesData\n"
-                                                                                          "and/or EfiRuntimeServicesData.<BR>"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdDxeNxMemoryProtectionPolicy_PROMPT  #language en-US "Set DXE memory protection policy."
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdDxeNxMemoryProtectionPolicy_HELP  #language en-US "Set DXE memory protection policy. The policy is bitwise.\n"
-                                                                                                "If a bit is set, memory regions of the associated type will be mapped\n"
-                                                                                                "non-executable.<BR>\n"
-                                                                                                "If a bit is cleared, nothing will be done to associated type of memory.<BR><BR>\n"
-                                                                                                "\n"
-                                                                                                "Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>\n"
-                                                                                                "EfiReservedMemoryType          0x0001<BR>\n"
-                                                                                                "EfiLoaderCode                  0x0002<BR>\n"
-                                                                                                "EfiLoaderData                  0x0004<BR>\n"
-                                                                                                "EfiBootServicesCode            0x0008<BR>\n"
-                                                                                                "EfiBootServicesData            0x0010<BR>\n"
-                                                                                                "EfiRuntimeServicesCode         0x0020<BR>\n"
-                                                                                                "EfiRuntimeServicesData         0x0040<BR>\n"
-                                                                                                "EfiConventionalMemory          0x0080<BR>\n"
-                                                                                                "EfiUnusableMemory              0x0100<BR>\n"
-                                                                                                "EfiACPIReclaimMemory           0x0200<BR>\n"
-                                                                                                "EfiACPIMemoryNVS               0x0400<BR>\n"
-                                                                                                "EfiMemoryMappedIO              0x0800<BR>\n"
-                                                                                                "EfiMemoryMappedIOPortSpace     0x1000<BR>\n"
-                                                                                                "EfiPalCode                     0x2000<BR>\n"
-                                                                                                "EfiPersistentMemory            0x4000<BR>\n"
-                                                                                                "OEM Reserved       0x4000000000000000<BR>\n"
-                                                                                                "OS Reserved        0x8000000000000000<BR>\n"
-                                                                                                "\n"
-                                                                                                "NOTE: User must NOT set NX protection for EfiLoaderCode / EfiBootServicesCode / EfiRuntimeServicesCode. <BR>\n"
-                                                                                                "User MUST set the same NX protection for EfiBootServicesData and EfiConventionalMemory. <BR>\n"
-                                                                                                "\n"
-                                                                                                "e.g. 0x7FD5 can be used for all memory except Code. <BR>\n"
-                                                                                                "e.g. 0x7BD4 can be used for all memory except Code and ACPINVS/Reserved. <BR>\n"
-                                                                                                ""
-
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdPteMemoryEncryptionAddressOrMask_PROMPT  #language en-US "The address mask when memory encryption is enabled."
 
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdPteMemoryEncryptionAddressOrMask_HELP  #language en-US "This PCD holds the address mask for page table entries when memory encryption is\n"
@@ -1186,110 +1131,12 @@
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdCodRelocationDevPath_HELP  #language en-US   "Full device path of platform specific device to store Capsule On Disk temp relocation file.<BR>"
                                                                                            "If this PCD is set, Capsule On Disk temp relocation file will be stored in the device specified by this PCD, instead of the EFI System Partition that stores capsule image file."
 
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdNullPointerDetectionPropertyMask_PROMPT  #language en-US "Enable NULL pointer detection"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdNullPointerDetectionPropertyMask_HELP    #language en-US "Mask to control the NULL address detection in code for different phases.\n"
-                                                                                                       " If enabled, accessing NULL address in UEFI or SMM code can be caught.\n\n"
-                                                                                                       "   BIT0    - Enable NULL pointer detection for UEFI.\n"
-                                                                                                       "   BIT1    - Enable NULL pointer detection for SMM.\n"
-                                                                                                       "   BIT2..6 - Reserved for future uses.\n"
-                                                                                                       "   BIT7    - Disable NULL pointer detection just after EndOfDxe."
-                                                                                                       " This is a workaround for those unsolvable NULL access issues in"
-                                                                                                       " OptionROM, boot loader, etc. It can also help to avoid unnecessary"
-                                                                                                       " exception caused by legacy memory (0-4095) access after EndOfDxe,"
-                                                                                                       " such as Windows 7 boot on Qemu.\n"
-
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdInitValueInTempStack_PROMPT  #language en-US "Init Value in Temp Stack"
 
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdInitValueInTempStack_HELP    #language en-US "Init Value in Temp Stack to be shared between SEC and PEI_CORE\n"
                                                                                            "SEC fills the full temp stack with this values. When switch stack, PeiCore can check\n"
                                                                                            "this value in the temp stack to know how many stack has been used.\n"
 
-#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\n"
-                                                                                        " If a bit is set, a head guard page and a tail guard page will be added just\n"
-                                                                                        " before and after corresponding type of pages allocated if there's enough\n"
-                                                                                        " free pages for all of them. The page allocation for the type related to\n"
-                                                                                        " cleared bits keeps the same as ususal.\n\n"
-                                                                                        " This PCD is only valid if BIT0 and/or BIT2 are set in PcdHeapGuardPropertyMask.\n\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\n"
-                                                                                        " If a bit is set, a head guard page and a tail guard page will be added just\n"
-                                                                                        " before and after corresponding type of pages which the allocated pool occupies,\n"
-                                                                                        " if there's enough free memory for all of them. The pool allocation for the\n"
-                                                                                        " type related to cleared bits keeps the same as ususal.\n\n"
-                                                                                        " This PCD is only valid if BIT1 and/or BIT3 are set in PcdHeapGuardPropertyMask.\n\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"
-                                                                                            " Note:\n"
-                                                                                            "   a) Heap Guard is for debug purpose and should not be enabled in product"
-                                                                                            "      BIOS.\n"
-                                                                                            "   b) Due to the limit of pool memory implementation and the alignment"
-                                                                                            "      requirement of UEFI spec, BIT7 is a try-best setting which cannot"
-                                                                                            "      guarantee that the returned pool is exactly adjacent to head guard"
-                                                                                            "      page or tail guard page.\n"
-                                                                                            "   c) UEFI freed-memory guard and UEFI pool/page guard cannot be enabled"
-                                                                                            "      at the same time.\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"
-                                                                                            "   BIT4 - Enable UEFI freed-memory guard (Use-After-Free memory detection).<BR>\n"
-                                                                                            "   BIT7 - The direction of Guard Page for Pool Guard.\n"
-                                                                                            "          0 - The returned pool is near the tail guard page.<BR>\n"
-                                                                                            "          1 - The returned pool is near the head guard page.<BR>"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdCpuStackGuard_PROMPT  #language en-US "Enable UEFI Stack Guard"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdCpuStackGuard_HELP    #language en-US "Indicates if UEFI Stack Guard will be enabled.\n"
-                                                                                    "  If enabled, stack overflow in UEFI can be caught, preventing chaotic consequences.<BR><BR>\n"
-                                                                                    "   TRUE  - UEFI Stack Guard will be enabled.<BR>\n"
-                                                                                    "   FALSE - UEFI Stack Guard will be disabled.<BR>"
-
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdTraceHubDebugLevel_PROMPT  #language en-US "Debug level of Trace Hub."
 
 #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdTraceHubDebugLevel_HELP    #language en-US "Indicate debug level of Trace Hub"
-- 
2.42.0.windows.2



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108890): https://edk2.groups.io/g/devel/message/108890
Mute This Topic: https://groups.io/mt/101469968/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-09-20  0:57 ` [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib Taylor Beebe
@ 2023-09-27  8:19   ` Gerd Hoffmann
  2023-09-29 19:52     ` Taylor Beebe
  0 siblings, 1 reply; 38+ messages in thread
From: Gerd Hoffmann @ 2023-09-27  8:19 UTC (permalink / raw)
  To: devel, taylor.d.beebe; +Cc: Jian J Wang, Liming Gao

On Tue, Sep 19, 2023 at 05:57:43PM -0700, Taylor Beebe wrote:
> Now that the EDK2 tree uses GetMemoryProtectionsLib to query
> the platform memory protection settings, we can add additional
> profiles to SetMemoryProtectionsLib to give plaforms more options
> for setting memory protections.

What is the recommended way to add more profiles?

Specifically I have a bunch of linux test cases failing when testing
this series, which is most likely causes by older + broken grub versions
(which are known to use EfiLoaderData for code).

So I think I need a "GrubCompat" profile which has
ExecutionProtection.EnabledForType[EfiLoaderData] = FALSE
but is otherwise identical to the production profile.

Should that go into SetMemoryProtectionsLib?
Or MemoryProtectionConfigLib?

take care,
  Gerd



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109113): https://edk2.groups.io/g/devel/message/109113
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-09-27  8:19   ` Gerd Hoffmann
@ 2023-09-29 19:52     ` Taylor Beebe
  2023-10-04  8:46       ` Gerd Hoffmann
  0 siblings, 1 reply; 38+ messages in thread
From: Taylor Beebe @ 2023-09-29 19:52 UTC (permalink / raw)
  To: Gerd Hoffmann, devel; +Cc: Jian J Wang, Liming Gao

Sorry for the slow reply :)


Additional profiles which fit general use cases can be added to

SetMemoryProtectionsLib, but because this is a profile for grub

compatibility I'd say it's better suited for platform code making

MemoryProtectionConfigLib in OvmfPkg the best spot.

I'll add an additional static profile array to MemoryProtectionConfigLib

and have logic loop through both to see if a profile matches. I'll

add the GrubCompat profile you outlined to this new profile array.


I can also update ArmVirtPkg to disable execution protection

for EfiLoaderData by default until fw_cfg parsing

support is added to ArmVirtPkg. Let me know if you think

this is necessary.


Thanks for the feedback :)


-Taylor

On 9/27/23 1:19 AM, Gerd Hoffmann wrote:
> On Tue, Sep 19, 2023 at 05:57:43PM -0700, Taylor Beebe wrote:
>> Now that the EDK2 tree uses GetMemoryProtectionsLib to query
>> the platform memory protection settings, we can add additional
>> profiles to SetMemoryProtectionsLib to give plaforms more options
>> for setting memory protections.
> What is the recommended way to add more profiles?
>
> Specifically I have a bunch of linux test cases failing when testing
> this series, which is most likely causes by older + broken grub versions
> (which are known to use EfiLoaderData for code).
>
> So I think I need a "GrubCompat" profile which has
> ExecutionProtection.EnabledForType[EfiLoaderData] = FALSE
> but is otherwise identical to the production profile.
>
> Should that go into SetMemoryProtectionsLib?
> Or MemoryProtectionConfigLib?
>
> take care,
>    Gerd
>


-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109215): https://edk2.groups.io/g/devel/message/109215
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-09-29 19:52     ` Taylor Beebe
@ 2023-10-04  8:46       ` Gerd Hoffmann
  2023-10-04 16:31         ` Taylor Beebe
  0 siblings, 1 reply; 38+ messages in thread
From: Gerd Hoffmann @ 2023-10-04  8:46 UTC (permalink / raw)
  To: Taylor Beebe; +Cc: devel, Jian J Wang, Liming Gao

On Fri, Sep 29, 2023 at 12:52:35PM -0700, Taylor Beebe wrote:
> Sorry for the slow reply :)
> 
> 
> Additional profiles which fit general use cases can be added to
> SetMemoryProtectionsLib, but because this is a profile for grub
> compatibility I'd say it's better suited for platform code making
> MemoryProtectionConfigLib in OvmfPkg the best spot.
> I'll add an additional static profile array to MemoryProtectionConfigLib
> and have logic loop through both to see if a profile matches. I'll
> add the GrubCompat profile you outlined to this new profile array.

Sounds good to me.

> I can also update ArmVirtPkg to disable execution protection
> for EfiLoaderData by default until fw_cfg parsing
> support is added to ArmVirtPkg. Let me know if you think
> this is necessary.

With MemoryProtectionConfigLib adding fw_cfg parsing support to
ArmVirtPkg should be easy, so maybe just do that?

take care,
  Gerd



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109310): https://edk2.groups.io/g/devel/message/109310
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-10-04  8:46       ` Gerd Hoffmann
@ 2023-10-04 16:31         ` Taylor Beebe
  2023-10-05  8:20           ` Laszlo Ersek
  0 siblings, 1 reply; 38+ messages in thread
From: Taylor Beebe @ 2023-10-04 16:31 UTC (permalink / raw)
  To: Gerd Hoffmann; +Cc: devel, Jian J Wang, Liming Gao


On 10/4/23 1:46 AM, Gerd Hoffmann wrote:
> On Fri, Sep 29, 2023 at 12:52:35PM -0700, Taylor Beebe wrote:
>> I can also update ArmVirtPkg to disable execution protection
>> for EfiLoaderData by default until fw_cfg parsing
>> support is added to ArmVirtPkg. Let me know if you think
>> this is necessary.
> With MemoryProtectionConfigLib adding fw_cfg parsing support to
> ArmVirtPkg should be easy, so maybe just do that?

 From what I see, the QemuFwCfgLib instance compatible with Arm requires

UefiBootServicesTableLib so fw_cfg cannot be parsed early enough to set

the memory protection policy on ArmVirt.


An Arm compatible PEIM instance of QemuFwCfgLib will need to be created.

I'm happy to look into it, but I don't want to hang up this patch series on

that addition. Instead, I'll set the protection policy for ArmVirtPkg to the

equivalent of the new GrubCompat profile in this series.


Please let me know if I'm missing an obvious route to PEI fw_cfg

parsing on Arm.


-Taylor



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109328): https://edk2.groups.io/g/devel/message/109328
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-10-04 16:31         ` Taylor Beebe
@ 2023-10-05  8:20           ` Laszlo Ersek
  2023-10-05  9:29             ` Gerd Hoffmann
  0 siblings, 1 reply; 38+ messages in thread
From: Laszlo Ersek @ 2023-10-05  8:20 UTC (permalink / raw)
  To: devel, taylor.d.beebe, Gerd Hoffmann, Ard Biesheuvel
  Cc: Jian J Wang, Liming Gao, Nhi Pham, Oliver Steffen

On 10/4/23 18:31, Taylor Beebe wrote:
> 
> On 10/4/23 1:46 AM, Gerd Hoffmann wrote:
>> On Fri, Sep 29, 2023 at 12:52:35PM -0700, Taylor Beebe wrote:
>>> I can also update ArmVirtPkg to disable execution protection
>>> for EfiLoaderData by default until fw_cfg parsing
>>> support is added to ArmVirtPkg. Let me know if you think
>>> this is necessary.
>> With MemoryProtectionConfigLib adding fw_cfg parsing support to
>> ArmVirtPkg should be easy, so maybe just do that?
> 
> From what I see, the QemuFwCfgLib instance compatible with Arm requires
> UefiBootServicesTableLib so fw_cfg cannot be parsed early enough to set
> the memory protection policy on ArmVirt.

QemuFwCfgLibMmio is DXE_DRIVER and UEFI_DRIVER only; it depends on (a)
the FDT client protocol, (b) MMIO accesses (that is, page tables).

On x86, PEI can use IO ports (no page tables), but that's not available
on ARM. I don't recall off-hand where / when exactly page tables are set
up during ArmVirtQemu boot.

You'd probably have to do something similar to
"ArmVirtPkg/Library/PlatformPeiLib/PlatformPeiLib.c" and
"ArmVirtPkg/Library/FdtPL011SerialPortLib/EarlyFdtPL011SerialPortLib.c"
-- parse the FDT on every fw_cfg access for the MMIO registers, then use
those registers to fetch the profile name, and do all that early enough
to configure the page protections -- so possibly *before*, or as a part
of, creating the page tables in the first place.

> An Arm compatible PEIM instance of QemuFwCfgLib will need to be created.
> I'm happy to look into it, but I don't want to hang up this patch series on
> that addition. Instead, I'll set the protection policy for ArmVirtPkg to
> the equivalent of the new GrubCompat profile in this series.

Can you base the default policy (i.e., the one that takes effect in the
absence of fw_cfg) on a PCD?

Such a PCD could be fixed-at-build, but I think it might even be
DynamicHII (compare commit 7e5f1b673870,
"ArmVirtPkg/PlatformHasAcpiDtDxe: allow guest level ACPI disable
override", 2017-03-31). That would have the benefit that people could
set a default at build time, with the --pcd build option. With
DynamicHII, the default could be stored in a non-volatile UEFI variable,
and ArmVirtQemu does have PEI-time (read-only) variable access.

Well, one argument against DynamicHII is that you'd want to prevent
later phases of the firmware from overwriting that variable, so you'd
have to get into variable policy / locking whatnot. So I'd suggest
picking the default profile from a fixed-at-build PCD (impossible to
overwrite "from the inside", and still enables the build-time --pcd
switch, for setting the platform default), *plus* fw-cfg for dynamic
configuration.

(Sorry I don't know anything about your series; it's possible you
already set the platform default via PCDs.)

I think platform builders should have the choice of picking a default
profile at build time; neither the Release (?) nor the GrubCompat
profile will fit everyone. I agree the *DEC* default should be the
strictest, but --pcd should be able to override that at build time, even
if -fw_cfg will allow for totally dynamic configuration too.

Laszlo

> Please let me know if I'm missing an obvious route to PEI fw_cfg
> parsing on Arm.
> 
> 
> -Taylor
> 
> 
> 
> 
> 
> 



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109344): https://edk2.groups.io/g/devel/message/109344
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/leave/12367111/7686176/1913456212/xyzzy [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-10-05  8:20           ` Laszlo Ersek
@ 2023-10-05  9:29             ` Gerd Hoffmann
  2023-10-05 10:23               ` Gerd Hoffmann
  0 siblings, 1 reply; 38+ messages in thread
From: Gerd Hoffmann @ 2023-10-05  9:29 UTC (permalink / raw)
  To: Laszlo Ersek
  Cc: devel, taylor.d.beebe, Ard Biesheuvel, Jian J Wang, Liming Gao,
	Nhi Pham, Oliver Steffen

  Hi,

> On x86, PEI can use IO ports (no page tables), but that's not available
> on ARM. I don't recall off-hand where / when exactly page tables are set
> up during ArmVirtQemu boot.

It also changed roughly one year ago, Ard updated the arm platform setup
to turn on paging much earlier (for w^x and IIRC also fix some caching
problems).  I think PEI runs with paging already enabled these days.

> > An Arm compatible PEIM instance of QemuFwCfgLib will need to be created.
> > I'm happy to look into it, but I don't want to hang up this patch series on
> > that addition. Instead, I'll set the protection policy for ArmVirtPkg to
> > the equivalent of the new GrubCompat profile in this series.
> 
> Can you base the default policy (i.e., the one that takes effect in the
> absence of fw_cfg) on a PCD?

That would be nice indeed.

take care,
  Gerd



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109346): https://edk2.groups.io/g/devel/message/109346
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-10-05  9:29             ` Gerd Hoffmann
@ 2023-10-05 10:23               ` Gerd Hoffmann
  2023-10-05 12:57                 ` Laszlo Ersek
  0 siblings, 1 reply; 38+ messages in thread
From: Gerd Hoffmann @ 2023-10-05 10:23 UTC (permalink / raw)
  To: devel
  Cc: Laszlo Ersek, taylor.d.beebe, Ard Biesheuvel, Jian J Wang,
	Liming Gao, Nhi Pham, Oliver Steffen

  Hi,

> > > An Arm compatible PEIM instance of QemuFwCfgLib will need to be created.
> > > I'm happy to look into it, but I don't want to hang up this patch series on
> > > that addition. Instead, I'll set the protection policy for ArmVirtPkg to
> > > the equivalent of the new GrubCompat profile in this series.
> > 
> > Can you base the default policy (i.e., the one that takes effect in the
> > absence of fw_cfg) on a PCD?
> 
> That would be nice indeed.

While being at it:  Does it make sense to have *two* defaults, one for
secureboot=on (strict) and one for secureboot=off (compat) ?

take care,
  Gerd



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109349): https://edk2.groups.io/g/devel/message/109349
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-10-05 10:23               ` Gerd Hoffmann
@ 2023-10-05 12:57                 ` Laszlo Ersek
  2023-10-08 20:26                   ` Taylor Beebe
  0 siblings, 1 reply; 38+ messages in thread
From: Laszlo Ersek @ 2023-10-05 12:57 UTC (permalink / raw)
  To: Gerd Hoffmann, devel
  Cc: taylor.d.beebe, Ard Biesheuvel, Jian J Wang, Liming Gao, Nhi Pham,
	Oliver Steffen

On 10/5/23 12:23, Gerd Hoffmann wrote:
>   Hi,
> 
>>>> An Arm compatible PEIM instance of QemuFwCfgLib will need to be created.
>>>> I'm happy to look into it, but I don't want to hang up this patch series on
>>>> that addition. Instead, I'll set the protection policy for ArmVirtPkg to
>>>> the equivalent of the new GrubCompat profile in this series.
>>>
>>> Can you base the default policy (i.e., the one that takes effect in the
>>> absence of fw_cfg) on a PCD?
>>
>> That would be nice indeed.
> 
> While being at it:  Does it make sense to have *two* defaults, one for
> secureboot=on (strict) and one for secureboot=off (compat) ?

I'm not sure, for now we can't enforce truly secure secure boot anyway.

Laszlo



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109354): https://edk2.groups.io/g/devel/message/109354
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/leave/12367111/7686176/1913456212/xyzzy [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

* Re: [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib
  2023-10-05 12:57                 ` Laszlo Ersek
@ 2023-10-08 20:26                   ` Taylor Beebe
  0 siblings, 0 replies; 38+ messages in thread
From: Taylor Beebe @ 2023-10-08 20:26 UTC (permalink / raw)
  To: Laszlo Ersek, Gerd Hoffmann, devel
  Cc: Ard Biesheuvel, Jian J Wang, Liming Gao, Nhi Pham, Oliver Steffen

I appreciate the suggestions on how to add PEI fw_cfg parsing support -- 
it should speed up the investigation/implementation.


The focus of this series is a more-or-less lateral update from the PCDs 
to the new interface, and even then this transitional series

has grown quite long and still has zero reviewed-bys 3 months in. There 
are many more functional and test updates to come which

can be done in parallel once this series is complete. The currently 
planned work can be found on the Tianocore Memory Protections project

(https://github.com/orgs/tianocore/projects/3). I'll add an item there 
to add fw_cfg parsing support for PEI ArmVirt and assign myself.

Any more task suggestions are welcome :)


In this series, I'll add a FixedAtBuild PCD to ArmVirtPkg which will 
dictate the protection profile used for the boot. The default will be

the release profile. I'll also make the other updates mentioned in this 
thread.


-Taylor


On 10/5/2023 5:57 AM, Laszlo Ersek wrote:
> On 10/5/23 12:23, Gerd Hoffmann wrote:
>>    Hi,
>>
>>>>> An Arm compatible PEIM instance of QemuFwCfgLib will need to be created.
>>>>> I'm happy to look into it, but I don't want to hang up this patch series on
>>>>> that addition. Instead, I'll set the protection policy for ArmVirtPkg to
>>>>> the equivalent of the new GrubCompat profile in this series.
>>>> Can you base the default policy (i.e., the one that takes effect in the
>>>> absence of fw_cfg) on a PCD?
>>> That would be nice indeed.
>> While being at it:  Does it make sense to have *two* defaults, one for
>> secureboot=on (strict) and one for secureboot=off (compat) ?
> I'm not sure, for now we can't enforce truly secure secure boot anyway.
>
> Laszlo
>


-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#109403): https://edk2.groups.io/g/devel/message/109403
Mute This Topic: https://groups.io/mt/101469960/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 38+ messages in thread

end of thread, other threads:[~2023-10-08 20:26 UTC | newest]

Thread overview: 38+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2023-09-20  0:57 [edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 01/28] MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 02/28] MdeModulePkg: Define SetMemoryProtectionsLib and GetMemoryProtectionsLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 03/28] MdeModulePkg: Add NULL Instances for Get/SetMemoryProtectionsLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 04/28] MdeModulePkg: Implement SetMemoryProtectionsLib and GetMemoryProtectionsLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 05/28] MdeModulePkg: Copy PEI PCD Database Into New Buffer Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 06/28] MdeModulePkg: Apply Protections to the HOB List Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 07/28] MdeModulePkg: Check Print Level Before Dumping GCD Memory Map Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 08/28] UefiCpuPkg: Always Set Stack Guard in MpPei Init Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 09/28] ArmVirtPkg: Add Memory Protection Library Definitions to Platforms Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 10/28] OvmfPkg: " Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 11/28] OvmfPkg: Apply Memory Protections via SetMemoryProtectionsLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 12/28] OvmfPkg: Update PeilessStartupLib to use SetMemoryProtectionsLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 13/28] UefiPayloadPkg: Update DXE Handoff " Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 14/28] MdeModulePkg: " Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 15/28] ArmPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 16/28] EmulatorPkg: " Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 17/28] OvmfPkg: " Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 18/28] UefiCpuPkg: " Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 19/28] MdeModulePkg: " Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 20/28] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib Taylor Beebe
2023-09-27  8:19   ` Gerd Hoffmann
2023-09-29 19:52     ` Taylor Beebe
2023-10-04  8:46       ` Gerd Hoffmann
2023-10-04 16:31         ` Taylor Beebe
2023-10-05  8:20           ` Laszlo Ersek
2023-10-05  9:29             ` Gerd Hoffmann
2023-10-05 10:23               ` Gerd Hoffmann
2023-10-05 12:57                 ` Laszlo Ersek
2023-10-08 20:26                   ` Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 21/28] OvmfPkg: Add QemuFwCfgParseString to QemuFwCfgSimpleParserLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 22/28] OvmfPkg: Add MemoryProtectionConfigLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 23/28] OvmfPkg: Enable Choosing Memory Protection Profile via QemuCfg Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 24/28] ArmVirtPkg: Apply Memory Protections via SetMemoryProtectionsLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 25/28] MdeModulePkg: Delete PCD Profile from SetMemoryProtectionsLib Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 26/28] OvmfPkg: Delete Memory Protection PCDs Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 27/28] ArmVirtPkg: " Taylor Beebe
2023-09-20  0:57 ` [edk2-devel] [PATCH v4 28/28] MdeModulePkg: " Taylor Beebe

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox