[edk2-devel] [PATCH v2 0/2] Update BaseTools NULL Include and Library Matching

2024-03-22 Thread Taylor Beebe
v1:
  - Initial patch series
v2:
  - Simplified the check for if the currently evaluated inf is a module or 
library.
  - Added a commit to use stronger matching of NULL includes (check for pattern 
"NULL")

Cc: Rebecca Cran 
Cc: Liming Gao 
Cc: Bob Feng 
Cc: Yuwei Chen 

Taylor Beebe (2):
  BaseTools: Don't Recurse NULL Includes Not Linked to Module
  BaseTools: Use Stronger Matching for NULL Linked Libraries

 BaseTools/Source/Python/GenFds/FfsInfStatement.py| 4 ++--
 BaseTools/Source/Python/Workspace/WorkspaceCommon.py | 8 +---
 2 files changed, 7 insertions(+), 5 deletions(-)

-- 
2.40.1.vfs.0.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117061): https://edk2.groups.io/g/devel/message/117061
Mute This Topic: https://groups.io/mt/105092033/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 1/2] BaseTools: Don't Recurse NULL Includes Not Linked to Module

2024-03-22 Thread Taylor Beebe
When collecting the required library instances for modules and
libraries, included libraries will be recursed to ensure the module is
built with all the libraries directly linked to it and indirectly
linked to it via included libraries.

Using the following scenario as an example:

[LibraryClasses.common.DXE_CORE]
NULL|Path/To/Library1.inf // Includes DebugLib

[LibraryClasses.common.DXE_DRIVER]
NULL|Path/To/Library2.inf // Includes DebugLib

[LibraryClasses.common.DXE_CORE, LibraryClasses.common.DXE_DRIVER]
DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf

[Components]
MdeModulePkg/Core/Dxe/DxeMain.inf // Includes DebugLib

The DXE_CORE NULL library will be assigned a fake library class like
NULL1 and the DXE_DRIVER will be assigned NULL2. The recursion logic
will see NULL1 as a directly linked and will add an instance of it to
the list of libraries which need to be included in the module. When
DebugLib is evaluated, the recursion logic will add the libraries
DebugLib depends on to the queue which includes both NULL1 and NULL2.
When NULL2 is unqueued, an instance of it will also be added to the
list of libraries needed to build DxeMain which now means that both
NULL1 and NULL2 have been linked.

NULL includes outside of module overrides are not supported according
to the spec, but we do it anyways so this seems like a case which
should be fixed. This change updates the recursion logic to skip
evaluating NULL libraries unless they are linked directly to the
module/library being evaluated.

Signed-off-by: Taylor Beebe 
Cc: Rebecca Cran 
Cc: Liming Gao 
Cc: Bob Feng 
Cc: Yuwei Chen 
---
 BaseTools/Source/Python/Workspace/WorkspaceCommon.py | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py 
b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
index 9e506fc646..8bb6553c6f 100644
--- a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
+++ b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
@@ -123,6 +123,8 @@ def GetModuleLibInstances(Module, Platform, BuildDatabase, 
Arch, Target, Toolcha
 while len(LibraryConsumerList) > 0:
 M = LibraryConsumerList.pop()
 for LibraryClassName in M.LibraryClasses:
+if LibraryClassName.startswith("NULL") and bool(M.LibraryClass):
+continue
 if LibraryClassName not in LibraryInstance:
 # override library instance for this module
 LibraryPath = 
Platform.Modules[str(Module)].LibraryClasses.get(LibraryClassName,Platform.LibraryClasses[LibraryClassName,
 ModuleType])
-- 
2.40.1.vfs.0.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117062): https://edk2.groups.io/g/devel/message/117062
Mute This Topic: https://groups.io/mt/105092034/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 2/2] BaseTools: Use Stronger Matching for NULL Linked Libraries

2024-03-22 Thread Taylor Beebe
To prevent the possibility that a library with a name like
NULLTestLib is interpreted as a NULL linked library, use
more explicit pattern matching to ensure that the library
name follows the pattern NULL%d.

Signed-off-by: Taylor Beebe 
Cc: Rebecca Cran 
Cc: Liming Gao 
Cc: Bob Feng 
Cc: Yuwei Chen 
---
 BaseTools/Source/Python/GenFds/FfsInfStatement.py| 4 ++--
 BaseTools/Source/Python/Workspace/WorkspaceCommon.py | 8 
 2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/BaseTools/Source/Python/GenFds/FfsInfStatement.py 
b/BaseTools/Source/Python/GenFds/FfsInfStatement.py
index 6550d939d4..ec9713484e 100644
--- a/BaseTools/Source/Python/GenFds/FfsInfStatement.py
+++ b/BaseTools/Source/Python/GenFds/FfsInfStatement.py
@@ -93,7 +93,7 @@ class FfsInfStatement(FfsInfStatementClassObject):
 
 if ModuleType != SUP_MODULE_USER_DEFINED and ModuleType != 
SUP_MODULE_HOST_APPLICATION:
 for LibraryClass in 
PlatformDataBase.LibraryClasses.GetKeys():
-if LibraryClass.startswith("NULL") and 
PlatformDataBase.LibraryClasses[LibraryClass, ModuleType]:
+if LibraryClass.startswith("NULL") and 
LibraryClass[4:].isdigit() and PlatformDataBase.LibraryClasses[LibraryClass, 
ModuleType]:
 self.InfModule.LibraryClasses[LibraryClass] = 
PlatformDataBase.LibraryClasses[LibraryClass, ModuleType]
 
 StrModule = str(self.InfModule)
@@ -101,7 +101,7 @@ class FfsInfStatement(FfsInfStatementClassObject):
 if StrModule in PlatformDataBase.Modules:
 PlatformModule = PlatformDataBase.Modules[StrModule]
 for LibraryClass in PlatformModule.LibraryClasses:
-if LibraryClass.startswith("NULL"):
+if LibraryClass.startswith("NULL") and 
LibraryClass[4:].isdigit():
 self.InfModule.LibraryClasses[LibraryClass] = 
PlatformModule.LibraryClasses[LibraryClass]
 
 DependencyList = [self.InfModule]
diff --git a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py 
b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
index 8bb6553c6f..c3b26b370a 100644
--- a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
+++ b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
@@ -102,12 +102,12 @@ def GetModuleLibInstances(Module, Platform, 
BuildDatabase, Arch, Target, Toolcha
 #
 if Module.ModuleType != SUP_MODULE_USER_DEFINED:
 for LibraryClass in Platform.LibraryClasses.GetKeys():
-if LibraryClass.startswith("NULL") and 
Platform.LibraryClasses[LibraryClass, Module.ModuleType]:
+if LibraryClass.startswith("NULL") and LibraryClass[4:].isdigit() 
and Platform.LibraryClasses[LibraryClass, Module.ModuleType]:
 Module.LibraryClasses[LibraryClass] = 
Platform.LibraryClasses[LibraryClass, Module.ModuleType]
 
 # add forced library instances (specified in module overrides)
 for LibraryClass in Platform.Modules[str(Module)].LibraryClasses:
-if LibraryClass.startswith("NULL"):
+if LibraryClass.startswith("NULL") and LibraryClass[4:].isdigit():
 Module.LibraryClasses[LibraryClass] = 
Platform.Modules[str(Module)].LibraryClasses[LibraryClass]
 
 # EdkII module
@@ -123,7 +123,7 @@ def GetModuleLibInstances(Module, Platform, BuildDatabase, 
Arch, Target, Toolcha
 while len(LibraryConsumerList) > 0:
 M = LibraryConsumerList.pop()
 for LibraryClassName in M.LibraryClasses:
-if LibraryClassName.startswith("NULL") and bool(M.LibraryClass):
+if LibraryClassName.startswith("NULL") and 
LibraryClass[4:].isdigit() and bool(M.LibraryClass):
 continue
 if LibraryClassName not in LibraryInstance:
 # override library instance for this module
@@ -141,7 +141,7 @@ def GetModuleLibInstances(Module, Platform, BuildDatabase, 
Arch, Target, Toolcha
 
 LibraryModule = BuildDatabase[LibraryPath, Arch, Target, 
Toolchain]
 # for those forced library instance (NULL library), add a fake 
library class
-if LibraryClassName.startswith("NULL"):
+if LibraryClassName.startswith("NULL") and 
LibraryClass[4:].isdigit():
 
LibraryModule.LibraryClass.append(LibraryClassObject(LibraryClassName, 
[ModuleType]))
 elif LibraryModule.LibraryClass is None \
  or len(LibraryModule.LibraryClass) == 0 \
-- 
2.40.1.vfs.0.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117063): https://edk2.groups.io/g/devel/message/117063
Mute This Topic: https://groups.io/mt/105092035/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: 回复: [edk2-devel] [PATCH v2 0/2] Update BaseTools NULL Include and Library Matching

2024-03-28 Thread Taylor Beebe

Hi Liming,

Each patch describes the issue being fixed with an example.

I created a bugzilla and assigned it to me for Patch 1: 
https://bugzilla.tianocore.org/show_bug.cgi?id=4744


GitHub PR: https://github.com/tianocore/edk2/pull/5365

Thanks :)

-Taylor

On 3/27/24 6:00 PM, gaoliming wrote:

Can you submit a Bugzilla for this problem?

Can you give one example to explain the incorrect usage?

Thanks
Liming

-邮件原件-
发件人: devel@edk2.groups.io  代表 Taylor Beebe
发送时间: 2024年3月23日 3:19
收件人: devel@edk2.groups.io
抄送: Rebecca Cran ; Liming Gao
; Bob Feng ; Yuwei Chen

主题: [edk2-devel] [PATCH v2 0/2] Update BaseTools NULL Include and
Library Matching

v1:
   - Initial patch series
v2:
   - Simplified the check for if the currently evaluated inf is a module or
library.
   - Added a commit to use stronger matching of NULL includes (check for
pattern "NULL")

Cc: Rebecca Cran 
Cc: Liming Gao 
Cc: Bob Feng 
Cc: Yuwei Chen 

Taylor Beebe (2):
   BaseTools: Don't Recurse NULL Includes Not Linked to Module
   BaseTools: Use Stronger Matching for NULL Linked Libraries

  BaseTools/Source/Python/GenFds/FfsInfStatement.py| 4 ++--
  BaseTools/Source/Python/Workspace/WorkspaceCommon.py | 8 +---
  2 files changed, 7 insertions(+), 5 deletions(-)

--
2.40.1.vfs.0.0











-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117218): https://edk2.groups.io/g/devel/message/117218
Mute This Topic: https://groups.io/mt/105189358/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 0/2] Update BaseTools NULL Include and Library Matching

2024-04-09 Thread Taylor Beebe
v1:
  - Initial patch series
v2:
  - Simplified the check for if the currently evaluated inf is a module or 
library.
  - Added a commit to use stronger matching of NULL includes (check for pattern 
"NULL")
v3:
  - In the WorkspaceCommon.py lines 126 and 144 should check 
LibraryClassName[4:].isdigit()
instead of LibraryClass[4:].isdigit().

Taylor Beebe (2):
  BaseTools: Don't Recurse NULL Includes Not Linked to Module
  BaseTools: Use Stronger Matching for NULL Linked Libraries

 BaseTools/Source/Python/GenFds/FfsInfStatement.py| 4 ++--
 BaseTools/Source/Python/Workspace/WorkspaceCommon.py | 8 +---
 2 files changed, 7 insertions(+), 5 deletions(-)

-- 
2.40.1.vfs.0.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117555): https://edk2.groups.io/g/devel/message/117555
Mute This Topic: https://groups.io/mt/105428854/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 1/2] BaseTools: Don't Recurse NULL Includes Not Linked to Module

2024-04-09 Thread Taylor Beebe
When collecting the required library instances for modules and
libraries, included libraries will be recursed to ensure the module is
built with all the libraries directly linked to it and indirectly
linked to it via included libraries.

Using the following scenario as an example:

[LibraryClasses.common.DXE_CORE]
NULL|Path/To/Library1.inf // Includes DebugLib

[LibraryClasses.common.DXE_DRIVER]
NULL|Path/To/Library2.inf // Includes DebugLib

[LibraryClasses.common.DXE_CORE, LibraryClasses.common.DXE_DRIVER]
DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf

[Components]
MdeModulePkg/Core/Dxe/DxeMain.inf // Includes DebugLib

The DXE_CORE NULL library will be assigned a fake library class like
NULL1 and the DXE_DRIVER will be assigned NULL2. The recursion logic
will see NULL1 as a directly linked and will add an instance of it to
the list of libraries which need to be included in the module. When
DebugLib is evaluated, the recursion logic will add the libraries
DebugLib depends on to the queue which includes both NULL1 and NULL2.
When NULL2 is unqueued, an instance of it will also be added to the
list of libraries needed to build DxeMain which now means that both
NULL1 and NULL2 have been linked.

NULL includes outside of module overrides are not supported according
to the spec, but we do it anyways so this seems like a case which
should be fixed. This change updates the recursion logic to skip
evaluating NULL libraries unless they are linked directly to the
module/library being evaluated.

Cc: Rebecca Cran 
Cc: Liming Gao 
Cc: Bob Feng 
Cc: Yuwei Chen 

Signed-off-by: Taylor Beebe 
Reviewed-by: Liming Gao 
---
 BaseTools/Source/Python/Workspace/WorkspaceCommon.py | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py 
b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
index 9e506fc646..8bb6553c6f 100644
--- a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
+++ b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
@@ -123,6 +123,8 @@ def GetModuleLibInstances(Module, Platform, BuildDatabase, 
Arch, Target, Toolcha
 while len(LibraryConsumerList) > 0:
 M = LibraryConsumerList.pop()
 for LibraryClassName in M.LibraryClasses:
+if LibraryClassName.startswith("NULL") and bool(M.LibraryClass):
+continue
 if LibraryClassName not in LibraryInstance:
 # override library instance for this module
 LibraryPath = 
Platform.Modules[str(Module)].LibraryClasses.get(LibraryClassName,Platform.LibraryClasses[LibraryClassName,
 ModuleType])
-- 
2.40.1.vfs.0.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117556): https://edk2.groups.io/g/devel/message/117556
Mute This Topic: https://groups.io/mt/105428855/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 2/2] BaseTools: Use Stronger Matching for NULL Linked Libraries

2024-04-09 Thread Taylor Beebe
To prevent the possibility that a library with a name like
NULLTestLib is interpreted as a NULL linked library, use
more explicit pattern matching to ensure that the library
name follows the pattern NULL%d.

Cc: Rebecca Cran 
Cc: Liming Gao 
Cc: Bob Feng 
Cc: Yuwei Chen 

Signed-off-by: Taylor Beebe 
---
 BaseTools/Source/Python/GenFds/FfsInfStatement.py| 4 ++--
 BaseTools/Source/Python/Workspace/WorkspaceCommon.py | 8 
 2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/BaseTools/Source/Python/GenFds/FfsInfStatement.py 
b/BaseTools/Source/Python/GenFds/FfsInfStatement.py
index 6550d939d4..ec9713484e 100644
--- a/BaseTools/Source/Python/GenFds/FfsInfStatement.py
+++ b/BaseTools/Source/Python/GenFds/FfsInfStatement.py
@@ -93,7 +93,7 @@ class FfsInfStatement(FfsInfStatementClassObject):
 
 if ModuleType != SUP_MODULE_USER_DEFINED and ModuleType != 
SUP_MODULE_HOST_APPLICATION:
 for LibraryClass in 
PlatformDataBase.LibraryClasses.GetKeys():
-if LibraryClass.startswith("NULL") and 
PlatformDataBase.LibraryClasses[LibraryClass, ModuleType]:
+if LibraryClass.startswith("NULL") and 
LibraryClass[4:].isdigit() and PlatformDataBase.LibraryClasses[LibraryClass, 
ModuleType]:
 self.InfModule.LibraryClasses[LibraryClass] = 
PlatformDataBase.LibraryClasses[LibraryClass, ModuleType]
 
 StrModule = str(self.InfModule)
@@ -101,7 +101,7 @@ class FfsInfStatement(FfsInfStatementClassObject):
 if StrModule in PlatformDataBase.Modules:
 PlatformModule = PlatformDataBase.Modules[StrModule]
 for LibraryClass in PlatformModule.LibraryClasses:
-if LibraryClass.startswith("NULL"):
+if LibraryClass.startswith("NULL") and 
LibraryClass[4:].isdigit():
 self.InfModule.LibraryClasses[LibraryClass] = 
PlatformModule.LibraryClasses[LibraryClass]
 
 DependencyList = [self.InfModule]
diff --git a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py 
b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
index 8bb6553c6f..6ad7a3b940 100644
--- a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
+++ b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py
@@ -102,12 +102,12 @@ def GetModuleLibInstances(Module, Platform, 
BuildDatabase, Arch, Target, Toolcha
 #
 if Module.ModuleType != SUP_MODULE_USER_DEFINED:
 for LibraryClass in Platform.LibraryClasses.GetKeys():
-if LibraryClass.startswith("NULL") and 
Platform.LibraryClasses[LibraryClass, Module.ModuleType]:
+if LibraryClass.startswith("NULL") and LibraryClass[4:].isdigit() 
and Platform.LibraryClasses[LibraryClass, Module.ModuleType]:
 Module.LibraryClasses[LibraryClass] = 
Platform.LibraryClasses[LibraryClass, Module.ModuleType]
 
 # add forced library instances (specified in module overrides)
 for LibraryClass in Platform.Modules[str(Module)].LibraryClasses:
-if LibraryClass.startswith("NULL"):
+if LibraryClass.startswith("NULL") and LibraryClass[4:].isdigit():
 Module.LibraryClasses[LibraryClass] = 
Platform.Modules[str(Module)].LibraryClasses[LibraryClass]
 
 # EdkII module
@@ -123,7 +123,7 @@ def GetModuleLibInstances(Module, Platform, BuildDatabase, 
Arch, Target, Toolcha
 while len(LibraryConsumerList) > 0:
 M = LibraryConsumerList.pop()
 for LibraryClassName in M.LibraryClasses:
-if LibraryClassName.startswith("NULL") and bool(M.LibraryClass):
+if LibraryClassName.startswith("NULL") and 
LibraryClassName[4:].isdigit() and bool(M.LibraryClass):
 continue
 if LibraryClassName not in LibraryInstance:
 # override library instance for this module
@@ -141,7 +141,7 @@ def GetModuleLibInstances(Module, Platform, BuildDatabase, 
Arch, Target, Toolcha
 
 LibraryModule = BuildDatabase[LibraryPath, Arch, Target, 
Toolchain]
 # for those forced library instance (NULL library), add a fake 
library class
-if LibraryClassName.startswith("NULL"):
+if LibraryClassName.startswith("NULL") and 
LibraryClassName[4:].isdigit():
 
LibraryModule.LibraryClass.append(LibraryClassObject(LibraryClassName, 
[ModuleType]))
 elif LibraryModule.LibraryClass is None \
  or len(LibraryModule.LibraryClass) == 0 \
-- 
2.40.1.vfs.0.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117557): https://edk2.groups.io/g/devel/message/117557
Mute This Topic: https://groups.io/mt/105428856/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: 回复: 回复: [edk2-devel] [PATCH v2 0/2] Update BaseTools NULL Include and Library Matching

2024-04-09 Thread Taylor Beebe

Hi Liming,

I made a mistake in patch 2 of the v2 series. In v3, lines 126 and 144 
of WorkspaceCommon.py update the check to:


`LibraryClassName[4:].isdigit()`

instead of

`LibraryClass[4:].isdigit()`

Can you re-review with this change?

-Taylor

On 4/1/2024 6:37 PM, gaoliming via groups.io wrote:

Taylor:
   Thanks for you detail information. I understand this problem. I agree your fix. 
Reviewed-by: Liming Gao 

Thanks
Liming




-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117558): https://edk2.groups.io/g/devel/message/117558
Mute This Topic: https://groups.io/mt/105280288/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] MdeModulePkg: Fix MAT SplitRecord() Logic introduce one bug and will cause SUT reset when boot to windows

2024-04-12 Thread Taylor Beebe

Hi Yanbo,

Can you help me understand the memory layout which causes this issue?

If a single EfiRuntimeServicesCode descriptor needs to be split because 
an image is within the memory range. I think that descriptor is split 
like so in the case you're encountering:


---  ---   ---
|   DATA  | |    |
--- |    |
|   CODE  | | Image  |
--- | Memory | EfiRuntimeServicesCode
|   DATA  | |    |
---  --- |
|   Extra Pages   |  |
---    ---

In this case, because the memory type of the buffer is 
EfiRuntimeServicesCode, shouldn't the final pages be EFI_MEMORY_RO?


Thanks!
-Taylor
On 4/11/2024 10:14 PM, Huang, Yanbo wrote:

Hi Beebe,

Recently we found this commit " MdeModulePkg: Fix MAT SplitRecord() Logic " 
will cause SUT reset after enable some knobs.
I filed one Bugzilla for it: https://bugzilla.tianocore.org/show_bug.cgi?id=4751

After debug, we found in SplitRecord API, many entries attribute are set to 0, 
not align with the UEFI spec:
"Memory Attributes Table (MAT):
EFI_MEMORY_ATTRIBUTES_TABLE. The entire UEFI runtime must be described by this 
table.
All entries must include attributes EFI_MEMORY_RO, EFI_MEMORY_XP, or both. Memory 
MUST be either readable and executable OR writeable and non-executable."
This should be the root cause of this issue.
When we update "NewRecord->Attribute = TempRecord.Attribute;" to 
"NewRecord->Attribute = TempRecord.Attribute | EFI_MEMORY_XP;", SUT can boot to windows.

@taylor.d.be...@gmail.com Could you please help to send one formal fix patch 
for this issue?
Thanks!

Best Regards,
Yanbo Huang

-Original Message-----
From: devel@edk2.groups.io  On Behalf Of Taylor Beebe
Sent: Tuesday, November 28, 2023 2:18 AM
To: devel@edk2.groups.io
Cc: Wang, Jian J ; Gao, Liming ; Bi, 
Dandan 
Subject: [edk2-devel] [PATCH v5 10/16] MdeModulePkg: Fix MAT SplitRecord() Logic

SplitRecord() does not handle the case where a memory descriptor describes an 
image region plus extra pages before or after the image region. This patch 
fixes this case by carving off the unrelated regions into their own descriptors.

Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
Signed-off-by: Taylor Beebe 
Reviewed-by: Liming Gao 
---
  MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c | 56 
++--
  1 file changed, 27 insertions(+), 29 deletions(-)

diff --git 
a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c 
b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
index 7c0ecd07c1bb..9d4082280bf5 100644
--- a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
+++ b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecor
+++ dLib.c
@@ -323,7 +323,6 @@ SplitRecord (
UINT64   PhysicalEnd;
UINTNNewRecordCount;
UINTNTotalNewRecordCount;
-  BOOLEAN  IsLastRecordData;
  
if (MaxSplitRecordCount == 0) {

  CopyMem (NewRecord, OldRecord, DescriptorSize); @@ -344,35 +343,16 @@ 
SplitRecord (
  NewImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - 
PhysicalStart, ImageRecordList);
  if (NewImageRecord == NULL) {
//
-  // No more image covered by this range, stop
+  // No more images cover this range, check if we've reached the end of 
the old descriptor. If not,
+  // add the remaining range to the new descriptor list.
//
-  if ((PhysicalEnd > PhysicalStart) && (ImageRecord != NULL)) {
-//
-// If this is still address in this record, need record.
-//
-NewRecord= PREVIOUS_MEMORY_DESCRIPTOR (NewRecord, 
DescriptorSize);
-IsLastRecordData = FALSE;
-if ((NewRecord->Attribute & EFI_MEMORY_XP) != 0) {
-  IsLastRecordData = TRUE;
-}
-
-if (IsLastRecordData) {
-  //
-  // Last record is DATA, just merge it.
-  //
-  NewRecord->NumberOfPages = EfiSizeToPages (PhysicalEnd - 
NewRecord->PhysicalStart);
-} else {
-  //
-  // Last record is CODE, create a new DATA entry.
-  //
-  NewRecord= NEXT_MEMORY_DESCRIPTOR (NewRecord, 
DescriptorSize);
-  NewRecord->Type  = TempRecord.Type;
-  NewRecord->PhysicalStart = TempRecord.PhysicalStart;
-  NewRecord->VirtualStart  = 0;
-  NewRecord->NumberOfPages = TempRecord.NumberOfPages;
-  NewRecord->Attribute = TempRecord.Attribute | EFI_MEMORY_XP;
-  TotalNewRecordCount++;
-}
+  if (PhysicalEnd > PhysicalStart) {
+NewRecord->Type  = TempRecord.Type;
+NewRecord->PhysicalStart = Physical

Re: [edk2-devel] MdeModulePkg: Fix MAT SplitRecord() Logic introduce one bug and will cause SUT reset when boot to windows

2024-04-15 Thread Taylor Beebe


On 4/15/2024 3:57 AM, Bi, Dandan wrote:

Hi Taylor,

With this patch, MAT contains some entries with Attribute - 0x8000, 
doesn't have EFI_MEMORY_RO or EFI_MEMORY_XP.
After revert this patch, don't see such entries in MAT.

a. MAT with this patch:
Entry (0x609E4268)
   Type  - 0x5
   PhysicalStart - 0x769CF000
   VirtualStart  - 0x
   NumberOfPages - 0x0016
   Attribute - 0x8000
Entry (0x609E4298)
   Type  - 0x5
   PhysicalStart - 0x769E5000
   VirtualStart  - 0x
   NumberOfPages - 0x0001
   Attribute - 0x80004000
Entry (0x609E42C8)
   Type  - 0x5
   PhysicalStart - 0x769E6000
   VirtualStart  - 0x
   NumberOfPages - 0x0002
   Attribute - 0x8002

b. MAT without this patch:
Entry (0x609E4268)
   Type  - 0x5
   PhysicalStart - 0x769CF000
   VirtualStart  - 0x
   NumberOfPages - 0x0017
   Attribute - 0x80004000
Entry (0x609E4298)
   Type  - 0x5
   PhysicalStart - 0x769E6000
   VirtualStart  - 0x
   NumberOfPages - 0x0002
   Attribute - 0x8002

1. For example, when OldRecord in old memory map with:
 Type - 0x0005
 Attribute - 0x800F
 PhysicalStart - 0x769CF000
 PhysicalStart is smaller than ImageBase 0x769E5000, with this patch, it 
will create a new memory descriptor entry for range 0x769CF000~0x769E5000 and 
without EFI_MEMORY_RO or EFI_MEMORY_XP Attribute.
 Then it will only contain EFI_MEMORY_RUNTIME Attribute in MAT as doing  
MemoryAttributesEntry->Attribute &= 
(EFI_MEMORY_RO|EFI_MEMORY_XP|EFI_MEMORY_RUNTIME); when install MAT.
 It seems not aligned with UEFI Spec " The only valid bits for Attribute field 
currently are EFI_MEMORY_RO ,EFI_MEMORY_XP , plus EFI_MEMORY_RUNTIME "?
 Could you please help double check? Thanks.
Agreed that this is currently the behaviour and that the range should 
have a restrictive access attribute. More below.

2. In function SetNewRecord, it semes already cover the DATA entry before the 
CODE and the DATA entry after the CODE.
 And old SplitRecord function without this patch, also has the entry to 
cover the reaming range of this record if no more image covered by this range.
 Why do we still need this patch? Could you please help explain? Thanks.


GetMemoryMap() will merge adjacent descriptors which have the same type 
and attributes. This means that a single EfiRuntimeServicesCode 
descriptor within the memory map returned by CoreGetMemoryMap() could 
describe memory with the following layout (NOTE: this layout is odd but 
needs to be handled to fulfill the SplitTable() contract):


-
Some EfiRuntimeServicesCode memory
-
Runtime Image DATA Section
-
Runtime Image CODE Section
-
Runtime Image DATA Section
-
Some EfiRuntimeServicesCode memory
-

In this possible layout, the pre-patch logic would assume that the 
regions before and after the image were part of the image's data 
sections and would mark them as EFI_MEMORY_XP. The post-patch logic does 
not mark them with any access attributes which is fine but the DXE MAT 
logic needs to walk the memory map returned by SplitTable() to add 
access attributes to runtime regions which don't have any.


In your example, because PhysicalStart < ImageBase and 
0769CF000-0x769E5000 is EfiRuntimeServicesCode, the access attribute 
should technically be EFI_MEMORY_RO. It's likely that 
0769CF000-0x769E5000is just the unused memory bucket and so it might be 
best to mark it both EFI_MEMORY_RO and EFI_MEMORY_XP.


*An open question to the community:* Are there cases where runtime 
executable code is in a buffer separate from a loaded runtime image? Can 
the EfiRuntimeServicesCode memory regions not part of an image be 
specified in the MAT as both EFI_MEMORY_RO and EFI_MEMORY_XP, or even 
dropped entirely?


Thanks :)
-Taylor


-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117813): https://edk2.groups.io/g/devel/message/117813
Mute This Topic: https://groups.io/mt/105477564/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v1] MdeModulePkg: Fixup MAT Attributes After Splitting EFI Memory Map

2024-04-16 Thread Taylor Beebe
The Memory Attributes Table is generated by fetching the EFI
memory map and splitting entries which contain loaded
images so DATA and CODE sections have separate descriptors.
The splitting is done via a call to SplitTable() which
marks image DATA sections with the EFI_MEMORY_XP attribute
and CODE sections with the EFI_MEMORY_RO attribute when
splitting. After this process, there may still be
EfiRuntimeServicesCode regions which did not have their
attributes set because they are not part of loaded images.

This patch updates the MAT EnforceMemoryMapAttribute logic
to set the access attributes of runtime memory regions
which are not part of loaded images (have not had their
access attributes set).

Cc: Liming Gao 
Signed-off-by: Taylor Beebe 
---
 MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c | 29 ++--
 1 file changed, 15 insertions(+), 14 deletions(-)

diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c 
b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
index e9343a2c4e..1d9f935db0 100644
--- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
+++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
@@ -425,8 +425,8 @@ MergeMemoryMap (
 }
 
 /**
-  Enforce memory map attributes.
-  This function will set 
EfiRuntimeServicesData/EfiMemoryMappedIO/EfiMemoryMappedIOPortSpace to be 
EFI_MEMORY_XP.
+  Walk the memory map and set 
EfiRuntimeServicesData/EfiMemoryMappedIO/EfiMemoryMappedIOPortSpace
+  to EFI_MEMORY_XP and EfiRuntimeServicesCode to EFI_MEMORY_RO.
 
   @param  MemoryMap  A pointer to the buffer in which firmware 
places
  the current memory map.
@@ -447,18 +447,19 @@ EnforceMemoryMapAttribute (
   MemoryMapEntry = MemoryMap;
   MemoryMapEnd   = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + 
MemoryMapSize);
   while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd) {
-switch (MemoryMapEntry->Type) {
-  case EfiRuntimeServicesCode:
-// do nothing
-break;
-  case EfiRuntimeServicesData:
-  case EfiMemoryMappedIO:
-  case EfiMemoryMappedIOPortSpace:
-MemoryMapEntry->Attribute |= EFI_MEMORY_XP;
-break;
-  case EfiReservedMemoryType:
-  case EfiACPIMemoryNVS:
-break;
+if ((MemoryMapEntry->Attribute & EFI_MEMORY_ACCESS_MASK) == 0) {
+  switch (MemoryMapEntry->Type) {
+case EfiRuntimeServicesCode:
+  MemoryMapEntry->Attribute |= EFI_MEMORY_RO;
+  break;
+case EfiRuntimeServicesData:
+case EfiMemoryMappedIO:
+case EfiMemoryMappedIOPortSpace:
+  MemoryMapEntry->Attribute |= EFI_MEMORY_XP;
+  break;
+default:
+  break;
+  }
 }
 
 MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
-- 
2.40.1.vfs.0.0



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117889): https://edk2.groups.io/g/devel/message/117889
Mute This Topic: https://groups.io/mt/105570114/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] MdeModulePkg: Fix MAT SplitRecord() Logic introduce one bug and will cause SUT reset when boot to windows

2024-04-16 Thread Taylor Beebe

Hi Yanbo,

Can you confirm that the following resolves the issue you're seeing?

[PATCH v1] MdeModulePkg: Fixup MAT Attributes After Splitting EFI Memory 
Map (groups.io) <https://edk2.groups.io/g/devel/message/117889>


-Taylor

On 4/15/2024 6:17 PM, Taylor Beebe wrote:

On 4/15/2024 3:57 AM, Bi, Dandan wrote:

Hi Taylor,

With this patch, MAT contains some entries with Attribute - 0x8000, 
doesn't have EFI_MEMORY_RO or EFI_MEMORY_XP.
After revert this patch, don't see such entries in MAT.

a. MAT with this patch:
Entry (0x609E4268)
   Type  - 0x5
   PhysicalStart - 0x769CF000
   VirtualStart  - 0x
   NumberOfPages - 0x0016
   Attribute - 0x8000
Entry (0x609E4298)
   Type  - 0x5
   PhysicalStart - 0x769E5000
   VirtualStart  - 0x
   NumberOfPages - 0x0001
   Attribute - 0x80004000
Entry (0x609E42C8)
   Type  - 0x5
   PhysicalStart - 0x769E6000
   VirtualStart  - 0x
   NumberOfPages - 0x0002
   Attribute - 0x8002

b. MAT without this patch:
Entry (0x609E4268)
   Type  - 0x5
   PhysicalStart - 0x769CF000
   VirtualStart  - 0x
   NumberOfPages - 0x0017
   Attribute - 0x80004000
Entry (0x609E4298)
   Type  - 0x5
   PhysicalStart - 0x769E6000
   VirtualStart  - 0x
   NumberOfPages - 0x0002
   Attribute - 0x8002

1. For example, when OldRecord in old memory map with:
 Type - 0x0005
 Attribute - 0x800F
 PhysicalStart - 0x769CF000
 PhysicalStart is smaller than ImageBase 0x769E5000, with this patch, it 
will create a new memory descriptor entry for range 0x769CF000~0x769E5000 and 
without EFI_MEMORY_RO or EFI_MEMORY_XP Attribute.
 Then it will only contain EFI_MEMORY_RUNTIME Attribute in MAT as doing  
MemoryAttributesEntry->Attribute &= 
(EFI_MEMORY_RO|EFI_MEMORY_XP|EFI_MEMORY_RUNTIME); when install MAT.
 It seems not aligned with UEFI Spec " The only valid bits for Attribute field 
currently are EFI_MEMORY_RO ,EFI_MEMORY_XP , plus EFI_MEMORY_RUNTIME "?
 Could you please help double check? Thanks.
Agreed that this is currently the behaviour and that the range should 
have a restrictive access attribute. More below.

2. In function SetNewRecord, it semes already cover the DATA entry before the 
CODE and the DATA entry after the CODE.
 And old SplitRecord function without this patch, also has the entry to 
cover the reaming range of this record if no more image covered by this range.
 Why do we still need this patch? Could you please help explain? Thanks.


GetMemoryMap() will merge adjacent descriptors which have the same 
type and attributes. This means that a single EfiRuntimeServicesCode 
descriptor within the memory map returned by CoreGetMemoryMap() could 
describe memory with the following layout (NOTE: this layout is odd 
but needs to be handled to fulfill the SplitTable() contract):


-
Some EfiRuntimeServicesCode memory
-
Runtime Image DATA Section
-
Runtime Image CODE Section
-
Runtime Image DATA Section
-
Some EfiRuntimeServicesCode memory
-

In this possible layout, the pre-patch logic would assume that the 
regions before and after the image were part of the image's data 
sections and would mark them as EFI_MEMORY_XP. The post-patch logic 
does not mark them with any access attributes which is fine but the 
DXE MAT logic needs to walk the memory map returned by SplitTable() to 
add access attributes to runtime regions which don't have any.


In your example, because PhysicalStart < ImageBase and 
0769CF000-0x769E5000 is EfiRuntimeServicesCode, the access attribute 
should technically be EFI_MEMORY_RO. It's likely that 
0769CF000-0x769E5000is just the unused memory bucket and so it might 
be best to mark it both EFI_MEMORY_RO and EFI_MEMORY_XP.


*An open question to the community:* Are there cases where runtime 
executable code is in a buffer separate from a loaded runtime image? 
Can the EfiRuntimeServicesCode memory regions not part of an image be 
specified in the MAT as both EFI_MEMORY_RO and EFI_MEMORY_XP, or even 
dropped entirely?


Thanks :)
-Taylor



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117890): https://edk2.groups.io/g/devel/message/117890
Mute This Topic: https://groups.io/mt/105477564/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] [PATCH v1] MdeModulePkg: Fixup MAT Attributes After Splitting EFI Memory Map

2024-04-17 Thread Taylor Beebe



On 4/17/2024 6:40 AM, Oliver Smith-Denny wrote:

Hi Ard,

On 4/16/2024 11:38 PM, Ard Biesheuvel wrote:


For entries where we lack such additional metadata, I don't think we
can make assumptions based on the type beyond mapping data and MMIO
regions XP. We have no idea how those EfiRuntimeServicesCode regions
may be used, and currently, the spec permits RWX semantics for those
if no restrictions are specified.


The logic before the ImagePropertiesRecordLib addition was applying
XP to these EfiRuntimeServicesCode regions which are not part of loaded
images. I agree with you that we cannot make assumptions on how these
regions are used, but it seems the logic was this way long enough for
expectations to be built around the incorrect behaviour. Something to
consider.

The spec suggests that omitting an entry from the MAT is the same as
listing it with RO|XP cleared. How RO|XP from the original entry
should be interpreted wrt to the MAT is unspecified. So I think the
only thing we can do at this point is preserve the entry if it has
RO|XP set, or just drop it otherwise.


I do agree that it is probably safer to exclude the sub-region from
the MAT entirely. However, from my reading of the spec, it is
unclear to me whether it envisions that. From section 4.6.4 of
UEFI spec 2.10:

"The Memory Attributes Table may define multiple entries to describe
sub-regions that comprise a single entry returned by GetMemoryMap()
however the sub-regions must total to completely describe the larger
region and may not cross boundaries between entries reported by
GetMemoryMap() . If a run-time region returned in GetMemoryMap() entry
is not described within the Memory Attributes Table, this region is
assumed to not be compatible with any memory protections."

The unclear part to me here is "the sub-regions must total to completely
describe the larger region." To me that says that in Taylor's case,
where we have a memory map descriptor with attributes set for part of
the region but not the whole region, that the spec envisions the MAT
having either the whole region split into sub-regions or not
including the MAT entry for this region. In this reading the final
sentence would say that if an entire memory map entry is not
described in the MAT, then it is assumed to be incompatible.

A different reading would say what you are saying, that a sub-region
can be dropped from the MAT (although it is hard to justify that with
the language that says the sub-regions must total to completely
describe the larger region). What are your thoughts here?

Aside from this, I wonder if we can be more aspirational here. These
EfiRuntimeServicesCode regions without attributes set are, if I am
understanding correctly, from loaded images. 

These EfiRuntimeServicesCode regions without attributes set are
not part of loaded image memory. I think that's what you meant but
wanted to clarify.

The spec does call out
that EfiRuntimeServicesCode is explicitly for code sections of loaded
images. Can we just say outright that any memory of this type should
be RO? I understand that existing drivers may attempt to break this,
but from the core, I think this is reasonable to say, but would love
to hear thoughts.


Note that the spec also mentions that the MAT must only contain
EfiRuntimeServicesCode or EfiRuntimeServicesData entries, and it looks
like this is not being enforced either.


Agreed, this should be amended.
The InstallMemoryAttributesTable() logic will only add the 
EfiRuntimeServicesCode

and EfiRuntimeServicesData regions to the final MAT. I'm not sure why
EnforceMemoryMapAttribute() is setting XP on EfiMemoryMappedIO and
EfiMemoryMappedIOPortSpace here when those entries are not included in the
MAT anyways.


Thanks,
Oliver



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117922): https://edk2.groups.io/g/devel/message/117922
Mute This Topic: https://groups.io/mt/105570114/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] [PATCH v1] MdeModulePkg: Fixup MAT Attributes After Splitting EFI Memory Map

2024-04-17 Thread Taylor Beebe



On 4/17/2024 7:09 AM, Oliver Smith-Denny wrote:

On 4/17/2024 7:05 AM, Taylor Beebe wrote:


On 4/17/2024 6:40 AM, Oliver Smith-Denny wrote:

Aside from this, I wonder if we can be more aspirational here. These
EfiRuntimeServicesCode regions without attributes set are, if I am
understanding correctly, from loaded images. 

These EfiRuntimeServicesCode regions without attributes set are
not part of loaded image memory. I think that's what you meant but
wanted to clarify.


Are these regions without attributes from image sections that have
been padded to RUNTIME_PAGE_ALLOCATION_GRANULARITY, i.e. they are
the pads? Or are we saying we don't know what these regions are
at this point? It is true in theory someone could just allocate
an EfiRuntimeServicesCode section.

Good question -- I had not considered the extra padding applied
to these allocations. It could be either. The memory map returned
via GetMemoryMap() will merge descriptors together based on type
so it's possible to mistake an unrelated EfiRuntimeServicesCode
allocation with padding applied to a runtime image memory
allocation if they are contiguous.

When the IMAGE_PROPERTIES_RECORD entry is created, perhaps
it would be best to set the ImageSize field to the padded allocation
size instead of the file size. Is this the difference between virtual size
and raw data size? I recall you recently did this in 
ImagePropertiesRecordLib

for the code size of a new entry.

-Taylor



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117924): https://edk2.groups.io/g/devel/message/117924
Mute This Topic: https://groups.io/mt/105570114/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] MdeModulePkg: Fix MAT SplitRecord() Logic introduce one bug and will cause SUT reset when boot to windows

2024-04-17 Thread Taylor Beebe

Hi Yanbo,

I didn't do it in the way you suggest for the same reason that the 
SplitTable() logic doesn't set attributes
on descriptors of type EfiRuntimeServicesData or other memory types. The 
purpose of the SplitTable() function
is to use the input image records to split descriptors so each image 
section has it's own descriptor. I think
it's reasonable to set the attributes on descriptors associated with 
images because those new descriptors are the
intended side effect of the function, but I don't think setting 
attributes on other descriptors is a good design pattern.
This pattern matches what's done in PiSmmCore/MemoryAttributesTable.c. 
Also, even if we did
it the way you suggest, we would still need call 
EnforceMemoryMapAttribute() later to set XP on the

EfiRuntimeServicesData descriptors.

Can you or Dandan explain the origin of the extra EfiRuntimeServicesCode 
regions which aren't
part of loaded runtime images? It would be a good datapoint for our 
discussion on the proposed fix.


-Taylor
On 4/17/2024 7:04 AM, Huang, Yanbo wrote:


Hi Taylor,

Thanks for your update.

After test, issue can be fixed by your patch.

But why we not set the EFI_MEMORY_XP or EFI_MEMORY_RO attribute in 
SplitRecord API?


If we set the attribute in the beginning of the NewRecord created, it 
seems we don’t need to EnforceMemoryMapAttribute later?


Best Regards,

Yanbo Huang




-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117937): https://edk2.groups.io/g/devel/message/117937
Mute This Topic: https://groups.io/mt/105477564/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] [PATCH] ArmVirtPkg: Allow EFI memory attributes protocol to be disabled

2023-12-06 Thread Taylor Beebe

But what we might do is invent a way to avoid setting the XP attribute
on the entire region based on some heuristic. Given that the main
purpose of the EFI memory attribute protocol is to provide the ability
to remove XP (and set RO instead), perhaps we can avoid the set
entirely? Just brainstorming here.

Can the fault handler deal with this?  Set a flag somewhere, print a
big'n'fat error message, wait 5 secs, reset machine?  After reset the
firmware will see the flag and come up in 'compat' instead of 'strict'
mode.

Not sure what a good place for such a flag would be.  Do we have other
options than a non-volatile efi variable?  When using a efi variable we
probably should add an 'expires' timestamp, so the machine doesn't stay
in 'compat' mode forever.


This is what we do in Project Mu currently and is what we would like to 
push into


EDK2. For x86 platforms, we use CMOS to communicate to the next boot 
that the


system needs to enter compatibility mode. Of course this doesn't work on ARM

platforms, so we'll have to come up with a more permanent mechanism to 
support


this functionality.


(cc'ing Taylor and Oliver given that this is related to the memory
policy work as well) Perhaps we can use the fact that the active image
is non-NX compat to make some tweaks?

Memory policies would be another candidate which could possibly use a
less strict profile in 'compat' mode.  I'd love to see memory policies
land for the February stable tag.


I don't think the policy can change how the SHIM sets attributes using the

protocol, but you can hook the installation of the Memory Attribute

Protocol into the policy system so it's not installed in compat mode.

I have not revisited the memory protection policy interface update

since Lazlo's feedback in October, but I'd be happy to return to it if 
there's


motivation to get it in over the finish line. Note that there are more 
changes


that will need to be made to add testing, compat mode

switching, support for the nx_compat flag, etc. The patch series that's

currently in flight is just meant to be a lateral move to a runtime 
configurable


interface.


What I really want to avoid is derail our effort to tighten things
down and comply with the NX compat related policies, by adding some
build time control that the distros will enable now and never disable
again, citing backward compat concerns.

Sure, I want that too.  Having an runtime switch is already an
improvement over having a compile time switch.  Having this working
fully automatic would be even better of course.


If a fix for this issue is needed immediately, I'm fine with Ard's 
solution as a stop-gap.


Assuming we can make progress on committing the memory protection updates,

I can update the CpuDxe drivers to check the memory protection policy

before installing the Memory Attribute Protocol. When adding this policy 
config,


I would revert the change made here to uninstall the protocol.


Thanks :)

-Taylor


-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#112138): https://edk2.groups.io/g/devel/message/112138
Mute This Topic: https://groups.io/mt/102967690/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] [PATCH v1 1/1] ArmPkg: CpuDxe: Sync GCD Capabilities With Page Table Attributes

2023-05-10 Thread Taylor Beebe
Can we schedule the meeting for Wednesday 5/17? I will be out the 
following week and would like to attend.


Thanks :)

On 5/9/2023 7:59 AM, Oliver Smith-Denny wrote:

On 5/8/2023 11:59 PM, Ard Biesheuvel wrote:

On Tue, 9 May 2023 at 04:04, Kinney, Michael D
 wrote:


I would prefer next week as well.

Mike



Next week, i can only do Wednesday. The week after (22-26), the time
slot works for me on any day of the week.



Weds works from our side, the week after also works perfectly well
any day. Thanks for the flexibility and willingness to meet.

For reference for this specific patch, this bz may help cache in
some info: https://bugzilla.tianocore.org/show_bug.cgi?id=753. The
mail links are largely dead, of course, but can be found on other
mailing list retention sites (maybe in the future we will have PRs
and discussions to reference :).

Thanks,
Oliver









-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#104585): https://edk2.groups.io/g/devel/message/104585
Mute This Topic: https://groups.io/mt/98505340/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] Now: UEFI Memory Map, GCD, Page Table discussion - ARM/X86 - Wednesday, May 17, 2023 #cal-notice

2023-05-19 Thread Taylor Beebe
A summary email containing the presentation, supplementary files, and 
next steps will go out on Monday to avoid the thread getting buried over 
the weekend.


Thanks for your patience :)

On 5/19/2023 1:10 PM, Sheng Lean Tan wrote:

This was a good sharing! May I know where can I get the presentation slides?
Thanks.



--
Taylor Beebe
Software Engineer @ Microsoft


-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#105086): https://edk2.groups.io/g/devel/message/105086
Mute This Topic: https://groups.io/mt/98948349/21656
Mute #cal-notice:https://edk2.groups.io/g/devel/mutehashtag/cal-notice
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v4 00/14] Add ImagePropertiesRecordLib and Fix MAT Bugs

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

v4:
- Expose additional functions in the Library API
- Add NULL checks to library functions and return a
  status where applicable.

v3:
- Refactor patch series so the transition of logic from the DXE
  MAT logic to the new library is more clear.
- Update function headers to improve clarity and follow EDK2
  standards.
- Add Create and Delete functions for Image Properties Records
  and redirect some of the SMM and DXE MAT code to use these
  functions.
- Update/Add DumpImageRecords() to print the image name and code
  sections of each runtime image which will be put in the MAT.
  The DXE and SMM MAT logic will now invoke the DumpImageRecords()
  on DEBUG builds at the EndOfDxe event to install the MAT.

v2:
- A one-line change in patch 3 was moved to patch 9 for correctness.

Reference: https://github.com/tianocore/edk2/pull/4590
Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4492

The UEFI and SMM MAT logic contains duplicate logic for manipulating image
properties records which is used to track runtime images.
This patch series adds a new library, ImagePropertiesRecordLib,
which consolidates this logic and fixes the bugs which currently exist in
the MAT logic.

The first patch adds the ImagePropertiesRecordLib implementation which
is a copy of the UEFI MAT logic with minor modifications to remove the
reliance on globabl variables and make the code unit testable.

The second patch adds a unit test for the ImagePropertiesRecordLib. The
logic tests various potential layouts of the EFI memory map and runtime
images. 3/4 of these tests will fail which demonstrates the MAT logic
bugs.

The third patch fixes the logic in the ImagePropertiesRecordLib so
that all of the unit tests pass and the MAT logic can be fixed by
using the library.

The remaining patches add library instances to DSC files and remove
the image properties record logic from the SMM and UEFI MAT logic.

Cc: Andrew Fish 
Cc: Ard Biesheuvel 
Cc: Dandan Bi 
Cc: Eric Dong 
Cc: Gerd Hoffmann 
Cc: Guo Dong 
Cc: Gua Guo 
Cc: James Lu 
Cc: Jian J Wang 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Leif Lindholm 
Cc: Liming Gao 
Cc: Rahul Kumar 
Cc: Ray Ni 
Cc: Sami Mujawar 
Cc: Sean Rhodes 

Taylor Beebe (14):
  MdeModulePkg: Add ImagePropertiesRecordLib
  ArmVirtPkg: Add ImagePropertiesRecordLib Instance
  EmulatorPkg: Add ImagePropertiesRecordLib Instance
  OvmfPkg: Add ImagePropertiesRecordLib Instance
  UefiPayloadPkg: Add ImagePropertiesRecordLib Instance
  MdeModulePkg: Update MemoryAttributesTable.c to Reduce Global Variable
Use
  MdeModulePkg: Move Some DXE MAT Logic to ImagePropertiesRecordLib
  MdeModulePkg: Add ImagePropertiesRecordLib Host-Based Unit Test
  MdeModulePkg: Fix Bugs in MAT Logic
  MdeModulePkg: Add NULL checks and Return Status to
ImagePropertiesRecordLib
  UefiCpuPkg: Use Attribute From SMM MemoryAttributesTable if Nonzero
  MdeModulePkg: Transition SMM MAT Logic to Use ImagePropertiesRecordLib
  MdeModulePkg: Add Logic to Create/Delete Image Properties Records
  MdeModulePkg: Update DumpImageRecord() in ImagePropertiesRecordLib

 MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c 
 |  967 +
 MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c  
 |   24 +-
 MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c
 |  958 +---
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c   
 | 1144 
 
MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.c
   |  938 
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c 
 |   19 +-
 ArmVirtPkg/ArmVirt.dsc.inc 
 |1 +
 EmulatorPkg/EmulatorPkg.dsc
 |1 +
 MdeModulePkg/Core/Dxe/DxeMain.h
 |   20 -
 MdeModulePkg/Core/Dxe/DxeMain.inf  
 |1 +
 MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf  
 |1 +
 MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h
 |  234 
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf 
 |   31 +
 
MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.inf
 |   35 +
 MdeModulePkg/MdeModulePkg.dec  
 |5 +
 MdeModulePkg/MdeModulePkg.dsc  
 |2 +
 MdeModulePkg/Test/MdeModulePkgHostTest.dsc 
 |6 +
 OvmfPkg

[edk2-devel] [PATCH v4 01/14] MdeModulePkg: Add ImagePropertiesRecordLib

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Create a library for manipulating image properties records. The
library is currently blank and will be filled in a future patch
to help with reviewer readability.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c   |  
9 +++
 MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h| 
14 +++
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf | 
25 
 MdeModulePkg/MdeModulePkg.dec  |  
5 
 MdeModulePkg/MdeModulePkg.dsc  |  
2 ++
 5 files changed, 55 insertions(+)

diff --git 
a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c 
b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
new file mode 100644
index ..df7c54ebb793
--- /dev/null
+++ b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
@@ -0,0 +1,9 @@
+/** @file
+
+  Provides definitions and functionality for manipulating 
IMAGE_PROPERTIES_RECORD.
+
+  Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
+  Copyright (c) Microsoft Corporation.
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
diff --git a/MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h 
b/MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h
new file mode 100644
index ..728008a2e5bb
--- /dev/null
+++ b/MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h
@@ -0,0 +1,14 @@
+/** @file
+
+  Provides definitions and functionality for manipulating 
IMAGE_PROPERTIES_RECORD.
+
+  Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
+  Copyright (c) Microsoft Corporation.
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef IMAGE_PROPERTIES_RECORD_SUPPORT_LIB_H_
+#define IMAGE_PROPERTIES_RECORD_SUPPORT_LIB_H_
+
+#endif
diff --git 
a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf 
b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
new file mode 100644
index ..b7e493056889
--- /dev/null
+++ b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
@@ -0,0 +1,25 @@
+## @file
+#  Provides definitions and functionality for manipulating
+#  IMAGE_PROPERTIES_RECORD.
+#
+#  Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
+#  Copyright (c) Microsoft Corporation.
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION= 0x00010005
+  BASE_NAME  = ImagePropertiesRecordLib
+  FILE_GUID  = 5CCA36C1-C430-4A90-8BF7-23D2719D5928
+  MODULE_TYPE= BASE
+  VERSION_STRING = 1.0
+  LIBRARY_CLASS  = ImagePropertiesRecordLib
+
+[Sources.common]
+  ImagePropertiesRecordLib.c
+
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index 0ff058b0a9da..80df553b2a5f 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -164,6 +164,11 @@ [LibraryClasses]
   #
   VariableFlashInfoLib|Include/Library/VariableFlashInfoLib.h
 
+  ##  @libraryclass   Memory Attribute Table support logic for tracking and 
reporting
+  #   runtime images
+  #
+  ImagePropertiesRecordLib|Include/Library/ImagePropertiesRecordLib.h
+
 [Guids]
   ## MdeModule package token space guid
   # Include/Guid/MdeModulePkgTokenSpace.h
diff --git a/MdeModulePkg/MdeModulePkg.dsc b/MdeModulePkg/MdeModulePkg.dsc
index db3b5af53795..6444111b9214 100644
--- a/MdeModulePkg/MdeModulePkg.dsc
+++ b/MdeModulePkg/MdeModulePkg.dsc
@@ -96,6 +96,7 @@ [LibraryClasses]
   VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
   FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf
   
NonDiscoverableDeviceRegistrationLib|MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 
   
FmpAuthenticationLib|MdeModulePkg/Library/FmpAuthenticationLibNull/FmpAuthenticationLibNull.inf
   CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
@@ -237,6 +238,7 @@ [Components]
   MdeModulePkg/Library/BaseHobLibNull/BaseHobLibNull.inf
   
MdeModulePkg/Library/BaseMemoryAllocationLibNull/BaseMemoryAllocationLibNull.inf
   MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf
+  MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 
   MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf
   MdeModulePkg/Bus/Pci/PciSioSerialDxe/PciSioSerialDxe.inf
-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group

[edk2-devel] [PATCH v4 02/14] ArmVirtPkg: Add ImagePropertiesRecordLib Instance

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Add an instance of ImagePropertiesRecordLib which will be used by the
DXE Core.

Signed-off-by: Taylor Beebe 
Cc: Ard Biesheuvel 
Cc: Leif Lindholm 
Cc: Sami Mujawar 
Cc: Gerd Hoffmann 
---
 ArmVirtPkg/ArmVirt.dsc.inc | 1 +
 1 file changed, 1 insertion(+)

diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc
index 2443e8351c99..b299028b9f51 100644
--- a/ArmVirtPkg/ArmVirt.dsc.inc
+++ b/ArmVirtPkg/ArmVirt.dsc.inc
@@ -52,6 +52,7 @@ [LibraryClasses.common]
   IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicArmVirt.inf
   
UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
   CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 
   UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
   HobLib|ArmVirtPkg/Library/ArmVirtDxeHobLib/ArmVirtDxeHobLib.inf
-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107588): https://edk2.groups.io/g/devel/message/107588
Mute This Topic: https://groups.io/mt/100553432/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v4 04/14] OvmfPkg: Add ImagePropertiesRecordLib Instance

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Add an instance of ImagePropertiesRecordLib which will be used by the
DXE Core.

Signed-off-by: Taylor Beebe 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
---
 OvmfPkg/AmdSev/AmdSevX64.dsc| 1 +
 OvmfPkg/Bhyve/BhyveX64.dsc  | 1 +
 OvmfPkg/CloudHv/CloudHvX64.dsc  | 1 +
 OvmfPkg/IntelTdx/IntelTdxX64.dsc| 1 +
 OvmfPkg/Microvm/MicrovmX64.dsc  | 1 +
 OvmfPkg/OvmfPkgIa32.dsc | 1 +
 OvmfPkg/OvmfPkgIa32X64.dsc  | 1 +
 OvmfPkg/OvmfPkgX64.dsc  | 1 +
 OvmfPkg/OvmfXen.dsc | 1 +
 OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc | 1 +
 10 files changed, 10 insertions(+)

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index 2c6ed7c9745f..e8c954a97956 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -171,6 +171,7 @@ [LibraryClasses]
   
MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
   
PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc
index 82c60ace1bbd..ee349e105787 100644
--- a/OvmfPkg/Bhyve/BhyveX64.dsc
+++ b/OvmfPkg/Bhyve/BhyveX64.dsc
@@ -173,6 +173,7 @@ [LibraryClasses]
   
MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 
   
CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   
FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc
index e000deed9e4d..91816a10996f 100644
--- a/OvmfPkg/CloudHv/CloudHvX64.dsc
+++ b/OvmfPkg/CloudHv/CloudHvX64.dsc
@@ -182,6 +182,7 @@ [LibraryClasses]
   MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLib.inf
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 !if $(SMM_REQUIRE) == FALSE
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
 !endif
diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
index 193657ff2d61..bee98e798717 100644
--- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
@@ -171,6 +171,7 @@ [LibraryClasses]
   
MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
   
CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index 2f7585639374..38e0af6ae101 100644
--- a/OvmfPkg/Microvm/MicrovmX64.dsc
+++ b/OvmfPkg/Microvm/MicrovmX64.dsc
@@ -185,6 +185,7 @@ [LibraryClasses]
   
MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
   
PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index ed36935770f3..84807b3ffee9 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -187,6 +187,7 @@ [LibraryClasses]
   
MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLibNull.inf
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 !if $(SMM_REQUIRE) == FALSE
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
 !endif
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 919315e4cb33..dc80edca1671 100644
--- a/OvmfPkg

[edk2-devel] [PATCH v4 03/14] EmulatorPkg: Add ImagePropertiesRecordLib Instance

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Add an instance of ImagePropertiesRecordLib which will be used by the
DXE Core.

Signed-off-by: Taylor Beebe 
Cc: Andrew Fish 
Cc: Ray Ni 
---
 EmulatorPkg/EmulatorPkg.dsc | 1 +
 1 file changed, 1 insertion(+)

diff --git a/EmulatorPkg/EmulatorPkg.dsc b/EmulatorPkg/EmulatorPkg.dsc
index b44435d7e6ee..e18eeca884a5 100644
--- a/EmulatorPkg/EmulatorPkg.dsc
+++ b/EmulatorPkg/EmulatorPkg.dsc
@@ -126,6 +126,7 @@ [LibraryClasses]
   SortLib|MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf
   ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf
   FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 
 !if $(SECURE_BOOT_ENABLE) == TRUE
   RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107589): https://edk2.groups.io/g/devel/message/107589
Mute This Topic: https://groups.io/mt/100553433/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v4 05/14] UefiPayloadPkg: Add ImagePropertiesRecordLib Instance

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Add an instance of ImagePropertiesRecordLib which will be used by the
DXE Core.

Signed-off-by: Taylor Beebe 
Cc: Guo Dong 
Cc: Sean Rhodes 
Cc: James Lu 
Cc: Gua Guo 
---
 UefiPayloadPkg/UefiPayloadPkg.dsc | 1 +
 1 file changed, 1 insertion(+)

diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc 
b/UefiPayloadPkg/UefiPayloadPkg.dsc
index 47812048ddcf..8d237b23339a 100644
--- a/UefiPayloadPkg/UefiPayloadPkg.dsc
+++ b/UefiPayloadPkg/UefiPayloadPkg.dsc
@@ -277,6 +277,7 @@ [LibraryClasses]
   #
   
DebugPrintErrorLevelLib|UefiPayloadPkg/Library/DebugPrintErrorLevelLibHob/DebugPrintErrorLevelLibHob.inf
   
PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
+  
ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
   
PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
   
DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107591): https://edk2.groups.io/g/devel/message/107591
Mute This Topic: https://groups.io/mt/100553435/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v4 06/14] MdeModulePkg: Update MemoryAttributesTable.c to Reduce Global Variable Use

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

This patch updates MemoryAttributesTable.c to reduce reliance on global
variables and allow some logic to move to a library.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c | 102 +++-
 1 file changed, 54 insertions(+), 48 deletions(-)

diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c 
b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
index fd127ee167e1..64b0aa1ff5e5 100644
--- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
+++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
@@ -541,8 +541,9 @@ EnforceMemoryMapAttribute (
 /**
   Return the first image record, whose [ImageBase, ImageSize] covered by 
[Buffer, Length].
 
-  @param Buffer  Start Address
-  @param Length  Address length
+  @param Buffer   Start Address
+  @param Length   Address length
+  @param ImageRecordList  Image record list
 
   @return first image record covered by [buffer, length]
 **/
@@ -550,14 +551,12 @@ STATIC
 IMAGE_PROPERTIES_RECORD *
 GetImageRecordByAddress (
   IN EFI_PHYSICAL_ADDRESS  Buffer,
-  IN UINT64Length
+  IN UINT64Length,
+  IN LIST_ENTRY*ImageRecordList
   )
 {
   IMAGE_PROPERTIES_RECORD  *ImageRecord;
   LIST_ENTRY   *ImageRecordLink;
-  LIST_ENTRY   *ImageRecordList;
-
-  ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList;
 
   for (ImageRecordLink = ImageRecordList->ForwardLink;
ImageRecordLink != ImageRecordList;
@@ -692,7 +691,8 @@ SetNewRecord (
 STATIC
 UINTN
 GetMaxSplitRecordCount (
-  IN EFI_MEMORY_DESCRIPTOR  *OldRecord
+  IN EFI_MEMORY_DESCRIPTOR  *OldRecord,
+  IN LIST_ENTRY *ImageRecordList
   )
 {
   IMAGE_PROPERTIES_RECORD  *ImageRecord;
@@ -705,7 +705,7 @@ GetMaxSplitRecordCount (
   PhysicalEnd  = OldRecord->PhysicalStart + EfiPagesToSize 
(OldRecord->NumberOfPages);
 
   do {
-ImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - 
PhysicalStart);
+ImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - 
PhysicalStart, ImageRecordList);
 if (ImageRecord == NULL) {
   break;
 }
@@ -725,13 +725,16 @@ GetMaxSplitRecordCount (
   Split the memory map to new entries, according to one old entry,
   based upon PE code section and data section.
 
-  @param  OldRecord  A pointer to one old memory map entry.
-  @param  NewRecord  A pointer to several new memory map entries.
- The caller gurantee the buffer size be 1 +
- (SplitRecordCount * DescriptorSize) calculated
- below.
-  @param  MaxSplitRecordCountThe max number of splitted entries
-  @param  DescriptorSize Size, in bytes, of an individual 
EFI_MEMORY_DESCRIPTOR.
+  @paramOldRecord A pointer to one old memory map entry.
+  @paramNewRecord A pointer to several new memory map 
entries.
+  The caller gurantee the buffer size be 1 
+
+  (SplitRecordCount * DescriptorSize) 
calculated
+  below.
+  @paramMaxSplitRecordCount   The max number of splitted entries
+  @paramDescriptorSizeSize, in bytes, of an individual 
EFI_MEMORY_DESCRIPTOR.
+  @paramImageRecordList   A list of IMAGE_PROPERTIES_RECORD 
entries used when searching
+  for an image record contained by the 
memory range described in
+  the existing EFI memory map descriptor 
OldRecord
 
   @retval  0 no entry is splitted.
   @return  the real number of splitted record.
@@ -742,7 +745,8 @@ SplitRecord (
   IN EFI_MEMORY_DESCRIPTOR  *OldRecord,
   IN OUT EFI_MEMORY_DESCRIPTOR  *NewRecord,
   IN UINTN  MaxSplitRecordCount,
-  IN UINTN  DescriptorSize
+  IN UINTN  DescriptorSize,
+  IN LIST_ENTRY *ImageRecordList
   )
 {
   EFI_MEMORY_DESCRIPTORTempRecord;
@@ -770,7 +774,7 @@ SplitRecord (
 
   ImageRecord = NULL;
   do {
-NewImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - 
PhysicalStart);
+NewImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - 
PhysicalStart, ImageRecordList);
 if (NewImageRecord == NULL) {
   //
   // No more image covered by this range, stop
@@ -867,23 +871,29 @@ SplitRecord (
| Record Y  |
+---+
 
-  @param  MemoryMapSize  A pointer to the size, in bytes, of the
- MemoryMap buffer. On input, this is the size 
of
- old MemoryMap before split. The actual buffer
- size of MemoryMap is 

[edk2-devel] [PATCH v4 07/14] MdeModulePkg: Move Some DXE MAT Logic to ImagePropertiesRecordLib

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Move some DXE MAT logic to ImagePropertiesRecordLib to consolidate
code and enable unit testability.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c | 
774 +---
 MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c  |  
24 +-
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c   | 
770 +++
 MdeModulePkg/Core/Dxe/DxeMain.h|  
20 -
 MdeModulePkg/Core/Dxe/DxeMain.inf  |   
1 +
 MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h| 
159 
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf |   
4 +
 7 files changed, 947 insertions(+), 805 deletions(-)

diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c 
b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
index 64b0aa1ff5e5..51630f504ea1 100644
--- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
+++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
@@ -14,6 +14,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include 
 #include 
 #include 
+#include 
 
 #include 
 
@@ -333,45 +334,6 @@ CoreInitializeMemoryAttributesTable (
 // Below functions are for MemoryMap
 //
 
-/**
-  Converts a number of EFI_PAGEs to a size in bytes.
-
-  NOTE: Do not use EFI_PAGES_TO_SIZE because it handles UINTN only.
-
-  @param  Pages The number of EFI_PAGES.
-
-  @return  The number of bytes associated with the number of EFI_PAGEs 
specified
-   by Pages.
-**/
-STATIC
-UINT64
-EfiPagesToSize (
-  IN UINT64  Pages
-  )
-{
-  return LShiftU64 (Pages, EFI_PAGE_SHIFT);
-}
-
-/**
-  Converts a size, in bytes, to a number of EFI_PAGESs.
-
-  NOTE: Do not use EFI_SIZE_TO_PAGES because it handles UINTN only.
-
-  @param  Size  A size in bytes.
-
-  @return  The number of EFI_PAGESs associated with the number of bytes 
specified
-   by Size.
-
-**/
-STATIC
-UINT64
-EfiSizeToPages (
-  IN UINT64  Size
-  )
-{
-  return RShiftU64 (Size, EFI_PAGE_SHIFT) + UINTN)Size) & EFI_PAGE_MASK) ? 
1 : 0);
-}
-
 /**
   Acquire memory lock on mMemoryAttributesTableLock.
 **/
@@ -396,48 +358,6 @@ CoreReleasemMemoryAttributesTableLock (
   CoreReleaseLock (&mMemoryAttributesTableLock);
 }
 
-/**
-  Sort memory map entries based upon PhysicalStart, from low to high.
-
-  @param  MemoryMap  A pointer to the buffer in which firmware 
places
- the current memory map.
-  @param  MemoryMapSize  Size, in bytes, of the MemoryMap buffer.
-  @param  DescriptorSize Size, in bytes, of an individual 
EFI_MEMORY_DESCRIPTOR.
-**/
-STATIC
-VOID
-SortMemoryMap (
-  IN OUT EFI_MEMORY_DESCRIPTOR  *MemoryMap,
-  IN UINTN  MemoryMapSize,
-  IN UINTN  DescriptorSize
-  )
-{
-  EFI_MEMORY_DESCRIPTOR  *MemoryMapEntry;
-  EFI_MEMORY_DESCRIPTOR  *NextMemoryMapEntry;
-  EFI_MEMORY_DESCRIPTOR  *MemoryMapEnd;
-  EFI_MEMORY_DESCRIPTOR  TempMemoryMap;
-
-  MemoryMapEntry = MemoryMap;
-  NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
-  MemoryMapEnd   = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + 
MemoryMapSize);
-  while (MemoryMapEntry < MemoryMapEnd) {
-while (NextMemoryMapEntry < MemoryMapEnd) {
-  if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart) {
-CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof 
(EFI_MEMORY_DESCRIPTOR));
-CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof 
(EFI_MEMORY_DESCRIPTOR));
-CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof 
(EFI_MEMORY_DESCRIPTOR));
-  }
-
-  NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, 
DescriptorSize);
-}
-
-MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, 
DescriptorSize);
-NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, 
DescriptorSize);
-  }
-
-  return;
-}
-
 /**
   Merge continous memory map entries whose have same attributes.
 
@@ -471,7 +391,7 @@ MergeMemoryMap (
 
 do {
   MergeGuardPages (NewMemoryMapEntry, NextMemoryMapEntry->PhysicalStart);
-  MemoryBlockLength = (UINT64)(EfiPagesToSize 
(NewMemoryMapEntry->NumberOfPages));
+  MemoryBlockLength = LShiftU64 (NewMemoryMapEntry->NumberOfPages, 
EFI_PAGE_SHIFT);
   if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) &&
   (NewMemoryMapEntry->Type == NextMemoryMapEntry->Type) &&
   (NewMemoryMapEntry->Attribute == NextMemoryMapEntry->Attribute) &&
@@ -538,434 +458,6 @@ EnforceMemoryMapAttribute (
   return;
 }
 
-/**
-  Return the first image record, whose [ImageBase, ImageSize] covered by 
[Buffer, Length].
-
-  @param Buffer   Start Address
-  @param Length

[edk2-devel] [PATCH v4 08/14] MdeModulePkg: Add ImagePropertiesRecordLib Host-Based Unit Test

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Create a host-based unit test for the ImagePropertiesRecordLib
SplitTable() logic. This test has 4 cases which tests different
potential image and memory map layouts. 3/4 of these tests fail
with the logic in its current state to provide proof of the bugs
in the current MAT logic.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 
MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.c
   | 938 
 
MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.inf
 |  35 +
 MdeModulePkg/Test/MdeModulePkgHostTest.dsc 
 |   5 +
 3 files changed, 978 insertions(+)

diff --git 
a/MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.c
 
b/MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.c
new file mode 100644
index ..8b0a55685ce3
--- /dev/null
+++ 
b/MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.c
@@ -0,0 +1,938 @@
+/** @file
+  Unit tests the SplitTable() ImagePropertiesRecordLib Logic
+
+  Copyright (C) Microsoft Corporation.
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#define UNIT_TEST_APP_NAME "Image Properties Record Lib Unit Test"
+#define UNIT_TEST_APP_VERSION  "1.0"
+
+#define NEXT_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \
+  ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) + (Size)))
+
+// The starting memory map will contain 6 entries
+#define NUMBER_OF_MEMORY_MAP_DESCRIPTORS  6
+
+// Each memory map descriptor will be the sizeof(EFI_MEMORY_DESCRIPTOR) 
instead of a nonstandard size
+// to catch pointer math issues
+#define DESCRIPTOR_SIZE  sizeof(EFI_MEMORY_DESCRIPTOR)
+
+// Each memory map descriptor will describe 12 pages
+#define BASE_DESCRIPTOR_NUMBER_OF_PAGES  0x0C
+
+// The size, in bytes, of each memory map descriptor range
+#define BASE_DESCRIPTOR_ENTRY_SIZE  
(EFI_PAGES_TO_SIZE(BASE_DESCRIPTOR_NUMBER_OF_PAGES))
+
+// MACRO to get the starting address of a descriptor's described range based 
on the index of that descriptor
+#define BASE_DESCRIPTOR_START_ADDRESS(DescriptorNumber)  (DescriptorNumber * 
BASE_DESCRIPTOR_ENTRY_SIZE)
+
+// Virtual start must be zero
+#define BASE_DESCRIPTOR_VIRTUAL_START  0x0
+
+// Size of the default memory map
+#define BASE_MEMORY_MAP_SIZE  (NUMBER_OF_MEMORY_MAP_DESCRIPTORS * 
DESCRIPTOR_SIZE)
+
+// Number of images in each test case
+#define NUMBER_OF_IMAGES_TO_SPLIT  3
+
+// Maximum number of descriptors required for each image 
(None->Data->Code->Data->Code->Data->None)
+#define MAX_DESCRIPTORS_PER_IMAGE  7
+
+// Number of unused additional descriptors in the starting memory map buffer 
which is used by the
+// SplitTable() logic
+#define NUMBER_OF_ADDITIONAL_DESCRIPTORS  (NUMBER_OF_IMAGES_TO_SPLIT * 
MAX_DESCRIPTORS_PER_IMAGE)
+
+// Size of the memory map with enough space for the starting descriptors and 
the split descriptors
+#define SPLIT_MEMORY_MAP_SIZE  (BASE_MEMORY_MAP_SIZE + 
(NUMBER_OF_ADDITIONAL_DESCRIPTORS * DESCRIPTOR_SIZE))
+
+typedef enum {
+  SectionTypeCode,
+  SectionTypeData,
+  SectionTypeNotFound
+} SECTION_TYPE;
+
+typedef struct {
+  EFI_MEMORY_DESCRIPTOR*MemoryMap;
+  LIST_ENTRY   ImageList;
+} IMAGE_PROPERTIES_RECORD_HOST_TEST_CONTEXT;
+
+EFI_MEMORY_DESCRIPTOR  BaseMemoryMap[] = {
+  {
+EfiConventionalMemory, // Type
+BASE_DESCRIPTOR_START_ADDRESS (0), // PhysicalStart
+BASE_DESCRIPTOR_VIRTUAL_START, // VirtualStart
+BASE_DESCRIPTOR_NUMBER_OF_PAGES,   // Number of Pages
+0  // Attribute
+  },
+  {
+EfiConventionalMemory, // Type
+BASE_DESCRIPTOR_START_ADDRESS (1), // PhysicalStart
+BASE_DESCRIPTOR_VIRTUAL_START, // VirtualStart
+BASE_DESCRIPTOR_NUMBER_OF_PAGES,   // Number of Pages
+0  // Attribute
+  },
+  {
+EfiConventionalMemory, // Type
+BASE_DESCRIPTOR_START_ADDRESS (2), // PhysicalStart
+BASE_DESCRIPTOR_VIRTUAL_START, // VirtualStart
+BASE_DESCRIPTOR_NUMBER_OF_PAGES,   // Number of Pages
+0  // Attribute
+  },
+  {
+EfiConventionalMemory, // Type
+BASE_DESCRIPTOR_START_ADDRESS (3), // PhysicalStart
+BASE_DESCRIPTOR_VIRTUAL_START, // VirtualStart
+BASE_DESCRIPTOR_NUMBER_OF_PAGES,   // Number of Pages
+0  // Attribute
+  },
+  {
+EfiConventionalMemory, // Type
+BASE_DESCRIPTOR_START_ADDRESS (4), // PhysicalStart
+BASE_DESCRIPTOR_VIRTUAL_START, // VirtualStart
+BASE_DESCRIPTOR_N

[edk2-devel] [PATCH v4 09/14] MdeModulePkg: Fix Bugs in MAT Logic

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Fix the bugs in the MAT logic before switching the
UEFI and SMM MAT logic to use the new library.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c   |  2 
+-
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c | 98 
++--
 2 files changed, 49 insertions(+), 51 deletions(-)

diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c 
b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
index 51630f504ea1..af6c26244cc0 100644
--- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
+++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
@@ -517,7 +517,7 @@ CoreGetMemoryMapWithSeparatedImageSection (
 
   CoreAcquiremMemoryAttributesTableLock ();
 
-  AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax 
+ 1) * mImagePropertiesPrivateData.ImageRecordCount;
+  AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax 
+ 3) * mImagePropertiesPrivateData.ImageRecordCount;
 
   OldMemoryMapSize = *MemoryMapSize;
   Status   = CoreGetMemoryMap (MemoryMapSize, MemoryMap, MapKey, 
DescriptorSize, DescriptorVersion);
diff --git 
a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c 
b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
index 9fb3b922038f..379eb0c6cccd 100644
--- a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
+++ b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
@@ -277,7 +277,7 @@ GetMaxSplitRecordCount (
   break;
 }
 
-SplitRecordCount += (2 * ImageRecord->CodeSegmentCount + 1);
+SplitRecordCount += (2 * ImageRecord->CodeSegmentCount + 3);
 PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize;
   } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd));
 
@@ -323,7 +323,6 @@ SplitRecord (
   UINT64   PhysicalEnd;
   UINTNNewRecordCount;
   UINTNTotalNewRecordCount;
-  BOOLEAN  IsLastRecordData;
 
   if (MaxSplitRecordCount == 0) {
 CopyMem (NewRecord, OldRecord, DescriptorSize);
@@ -344,35 +343,16 @@ SplitRecord (
 NewImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - 
PhysicalStart, ImageRecordList);
 if (NewImageRecord == NULL) {
   //
-  // No more image covered by this range, stop
+  // No more images cover this range, check if we've reached the end of 
the old descriptor. If not,
+  // add the remaining range to the new descriptor list.
   //
-  if ((PhysicalEnd > PhysicalStart) && (ImageRecord != NULL)) {
-//
-// If this is still address in this record, need record.
-//
-NewRecord= PREVIOUS_MEMORY_DESCRIPTOR (NewRecord, 
DescriptorSize);
-IsLastRecordData = FALSE;
-if ((NewRecord->Attribute & EFI_MEMORY_XP) != 0) {
-  IsLastRecordData = TRUE;
-}
-
-if (IsLastRecordData) {
-  //
-  // Last record is DATA, just merge it.
-  //
-  NewRecord->NumberOfPages = EfiSizeToPages (PhysicalEnd - 
NewRecord->PhysicalStart);
-} else {
-  //
-  // Last record is CODE, create a new DATA entry.
-  //
-  NewRecord= NEXT_MEMORY_DESCRIPTOR (NewRecord, 
DescriptorSize);
-  NewRecord->Type  = TempRecord.Type;
-  NewRecord->PhysicalStart = TempRecord.PhysicalStart;
-  NewRecord->VirtualStart  = 0;
-  NewRecord->NumberOfPages = TempRecord.NumberOfPages;
-  NewRecord->Attribute = TempRecord.Attribute | EFI_MEMORY_XP;
-  TotalNewRecordCount++;
-}
+  if (PhysicalEnd > PhysicalStart) {
+NewRecord->Type  = TempRecord.Type;
+NewRecord->PhysicalStart = PhysicalStart;
+NewRecord->VirtualStart  = 0;
+NewRecord->NumberOfPages = EfiSizeToPages (PhysicalEnd - 
PhysicalStart);
+NewRecord->Attribute = TempRecord.Attribute;
+TotalNewRecordCount++;
   }
 
   break;
@@ -380,6 +360,24 @@ SplitRecord (
 
 ImageRecord = NewImageRecord;
 
+//
+// Update PhysicalStart to exclude the portion before the image buffer
+//
+if (TempRecord.PhysicalStart < ImageRecord->ImageBase) {
+  NewRecord->Type  = TempRecord.Type;
+  NewRecord->PhysicalStart = TempRecord.PhysicalStart;
+  NewRecord->VirtualStart  = 0;
+  NewRecord->NumberOfPages = EfiSizeToPages (ImageRecord->ImageBase - 
TempRecord.PhysicalStart);
+  NewRecord->Attribute = TempRecord.Attribute;
+  TotalNewRecordCount++;
+
+  PhysicalStart= ImageRecord->ImageBase;
+  TempRecord.PhysicalStart = PhysicalStart;
+  Temp

[edk2-devel] [PATCH v4 11/14] UefiCpuPkg: Use Attribute From SMM MemoryAttributesTable if Nonzero

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

The function EnforceMemoryMapAttribute() in the SMM MAT logic will
ensure that the CODE and DATA memory types have the desired attributes.
The consumer of the SMM MAT should only override the Attributes field
in the MAT if it is nonzero. This also allows the UEFI and SMM MAT
logic to use ImagePropertiesRecordLib instead of carrying two copies
of the image properties record manipulation.

Signed-off-by: Taylor Beebe 
Cc: Eric Dong 
Cc: Ray Ni 
Cc: Rahul Kumar 
Cc: Gerd Hoffmann 
---
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c | 19 +++
 1 file changed, 11 insertions(+), 8 deletions(-)

diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c 
b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c
index 6f498666157e..d302a9b0cbcf 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c
@@ -1062,14 +1062,17 @@ SetMemMapAttributes (
   MemoryMap = MemoryMapStart;
   for (Index = 0; Index < MemoryMapEntryCount; Index++) {
 DEBUG ((DEBUG_VERBOSE, "SetAttribute: Memory Entry - 0x%lx, 0x%x\n", 
MemoryMap->PhysicalStart, MemoryMap->NumberOfPages));
-if (MemoryMap->Type == EfiRuntimeServicesCode) {
-  MemoryAttribute = EFI_MEMORY_RO;
-} else {
-  ASSERT ((MemoryMap->Type == EfiRuntimeServicesData) || (MemoryMap->Type 
== EfiConventionalMemory));
-  //
-  // Set other type memory as NX.
-  //
-  MemoryAttribute = EFI_MEMORY_XP;
+MemoryAttribute = MemoryMap->Attribute & EFI_MEMORY_ACCESS_MASK;
+if (MemoryAttribute == 0) {
+  if (MemoryMap->Type == EfiRuntimeServicesCode) {
+MemoryAttribute = EFI_MEMORY_RO;
+  } else {
+ASSERT ((MemoryMap->Type == EfiRuntimeServicesData) || 
(MemoryMap->Type == EfiConventionalMemory));
+//
+// Set other type memory as NX.
+//
+MemoryAttribute = EFI_MEMORY_XP;
+  }
 }
 
 //
-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107597): https://edk2.groups.io/g/devel/message/107597
Mute This Topic: https://groups.io/mt/100553443/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v4 10/14] MdeModulePkg: Add NULL checks and Return Status to ImagePropertiesRecordLib

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Update function headers to clarify the contract of each function and
improve readability. Add NULL checks to all functions that take a
pointer as an argument. Add return status to functions that
may need to return early due to invalid input.

Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c | 290 

 MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h  | 137 
-
 2 files changed, 246 insertions(+), 181 deletions(-)

diff --git 
a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c 
b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
index 379eb0c6cccd..c9378679e7bb 100644
--- a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
+++ b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
@@ -22,14 +22,13 @@
   ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) + (Size)))
 
 /**
-  Converts a number of EFI_PAGEs to a size in bytes.
+  Converts a number of pages to a size in bytes.
 
   NOTE: Do not use EFI_PAGES_TO_SIZE because it handles UINTN only.
 
-  @param  Pages The number of EFI_PAGES.
+  @param[in]  Pages The number of EFI_PAGES.
 
-  @return  The number of bytes associated with the number of EFI_PAGEs 
specified
-   by Pages.
+  @retval  The number of bytes associated with the input number of pages.
 **/
 STATIC
 UINT64
@@ -45,10 +44,9 @@ EfiPagesToSize (
 
   NOTE: Do not use EFI_SIZE_TO_PAGES because it handles UINTN only.
 
-  @param  Size  A size in bytes.
+  @param[in]  Size  A size in bytes.
 
-  @return  The number of EFI_PAGESs associated with the number of bytes 
specified
-   by Size.
+  @retval  The number of pages associated with the input number of bytes.
 
 **/
 STATIC
@@ -61,12 +59,12 @@ EfiSizeToPages (
 }
 
 /**
-  Sort memory map entries based upon PhysicalStart, from low to high.
+  Sort memory map entries based upon PhysicalStart from low to high.
 
-  @param  MemoryMap  A pointer to the buffer in which firmware 
places
- the current memory map.
-  @param  MemoryMapSize  Size, in bytes, of the MemoryMap buffer.
-  @param  DescriptorSize Size, in bytes, of an individual 
EFI_MEMORY_DESCRIPTOR.
+  @param[in, out] MemoryMap   A pointer to the buffer in which firmware 
places
+  the current memory map.
+  @param[in]  MemoryMapSize   Size, in bytes, of the MemoryMap buffer.
+  @param[in]  DescriptorSize  Size, in bytes, of an individual 
EFI_MEMORY_DESCRIPTOR.
 **/
 STATIC
 VOID
@@ -105,11 +103,12 @@ SortMemoryMap (
 /**
   Return the first image record, whose [ImageBase, ImageSize] covered by 
[Buffer, Length].
 
-  @param Buffer   Start Address
-  @param Length   Address length
-  @param ImageRecordList  Image record list
+  @param[in] Buffer   Starting Address
+  @param[in] Length   Length to check
+  @param[in] ImageRecordList  A list of IMAGE_PROPERTIES_RECORD entries to 
check against
+  the memory range Buffer -> Buffer + Length
 
-  @return first image record covered by [buffer, length]
+  @retval The first image record covered by [Buffer, Length]
 **/
 STATIC
 IMAGE_PROPERTIES_RECORD *
@@ -144,17 +143,19 @@ GetImageRecordByAddress (
 }
 
 /**
-  Set the memory map to new entries, according to one old entry,
-  based upon PE code section and data section in image record
+  Break up the input OldRecord into multiple new records based on the code
+  and data sections in the input ImageRecord.
 
-  @param  ImageRecordAn image record whose [ImageBase, ImageSize] 
covered
- by old memory map entry.
-  @param  NewRecord  A pointer to several new memory map entries.
- The caller gurantee the buffer size be 1 +
- (SplitRecordCount * DescriptorSize) calculated
- below.
-  @param  OldRecord  A pointer to one old memory map entry.
-  @param  DescriptorSize Size, in bytes, of an individual 
EFI_MEMORY_DESCRIPTOR.
+  @param[in]ImageRecord   An IMAGE_PROPERTIES_RECORD whose 
ImageBase and
+  ImageSize is covered by by OldRecord.
+  @param[in, out]   NewRecord A pointer to several new memory map 
entries.
+  The caller gurantee the buffer size be 1 
+
+  (SplitRecordCount * DescriptorSize) 
calculated
+  below.
+  @param[in]OldRecord A pointer to one old memory map entry.
+  @param[in]DescriptorSizeThe size, in bytes, of an individual 
EFI_MEMORY_DESCRIPTOR.
+
+  @retval The number of new descriptors crea

[edk2-devel] [PATCH v4 12/14] MdeModulePkg: Transition SMM MAT Logic to Use ImagePropertiesRecordLib

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Now that the bugs are fixed in the MAT logic, we can remove the
duplicate logic from PiSmmCore/MemoryAttributesTable.c and use
ImagePropertiesRecordLib instead.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
Cc: Jiaxin Wu 
Cc: Ray Ni 
---
 MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c  | 785 
+---
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c |  29 
+
 MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf|   1 
+
 MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h  |  11 
+
 4 files changed, 58 insertions(+), 768 deletions(-)

diff --git a/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c 
b/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c
index 394fdae50741..2e4aaddef4e5 100644
--- a/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c
+++ b/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c
@@ -14,6 +14,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -25,26 +26,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \
   ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size)))
 
-#define IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE  SIGNATURE_32 
('I','P','R','C')
-
-typedef struct {
-  UINT32  Signature;
-  LIST_ENTRY  Link;
-  EFI_PHYSICAL_ADDRESSCodeSegmentBase;
-  UINT64  CodeSegmentSize;
-} IMAGE_PROPERTIES_RECORD_CODE_SECTION;
-
-#define IMAGE_PROPERTIES_RECORD_SIGNATURE  SIGNATURE_32 ('I','P','R','D')
-
-typedef struct {
-  UINT32  Signature;
-  LIST_ENTRY  Link;
-  EFI_PHYSICAL_ADDRESSImageBase;
-  UINT64  ImageSize;
-  UINTN   CodeSegmentCount;
-  LIST_ENTRY  CodeSegmentList;
-} IMAGE_PROPERTIES_RECORD;
-
 #define IMAGE_PROPERTIES_PRIVATE_DATA_SIGNATURE  SIGNATURE_32 ('I','P','P','D')
 
 typedef struct {
@@ -69,87 +50,6 @@ UINT64  mMemoryProtectionAttribute = 
EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTEC
 // Below functions are for MemoryMap
 //
 
-/**
-  Converts a number of EFI_PAGEs to a size in bytes.
-
-  NOTE: Do not use EFI_PAGES_TO_SIZE because it handles UINTN only.
-
-  @param[in]  Pages The number of EFI_PAGES.
-
-  @return  The number of bytes associated with the number of EFI_PAGEs 
specified
-   by Pages.
-**/
-STATIC
-UINT64
-EfiPagesToSize (
-  IN UINT64  Pages
-  )
-{
-  return LShiftU64 (Pages, EFI_PAGE_SHIFT);
-}
-
-/**
-  Converts a size, in bytes, to a number of EFI_PAGESs.
-
-  NOTE: Do not use EFI_SIZE_TO_PAGES because it handles UINTN only.
-
-  @param[in]  Size  A size in bytes.
-
-  @return  The number of EFI_PAGESs associated with the number of bytes 
specified
-   by Size.
-
-**/
-STATIC
-UINT64
-EfiSizeToPages (
-  IN UINT64  Size
-  )
-{
-  return RShiftU64 (Size, EFI_PAGE_SHIFT) + UINTN)Size) & EFI_PAGE_MASK) ? 
1 : 0);
-}
-
-/**
-  Sort memory map entries based upon PhysicalStart, from low to high.
-
-  @param[in,out]  MemoryMap A pointer to the buffer in which firmware 
places
-the current memory map.
-  @param[in]  MemoryMapSize Size, in bytes, of the MemoryMap buffer.
-  @param[in]  DescriptorSizeSize, in bytes, of an individual 
EFI_MEMORY_DESCRIPTOR.
-**/
-STATIC
-VOID
-SortMemoryMap (
-  IN OUT EFI_MEMORY_DESCRIPTOR  *MemoryMap,
-  IN UINTN  MemoryMapSize,
-  IN UINTN  DescriptorSize
-  )
-{
-  EFI_MEMORY_DESCRIPTOR  *MemoryMapEntry;
-  EFI_MEMORY_DESCRIPTOR  *NextMemoryMapEntry;
-  EFI_MEMORY_DESCRIPTOR  *MemoryMapEnd;
-  EFI_MEMORY_DESCRIPTOR  TempMemoryMap;
-
-  MemoryMapEntry = MemoryMap;
-  NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
-  MemoryMapEnd   = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + 
MemoryMapSize);
-  while (MemoryMapEntry < MemoryMapEnd) {
-while (NextMemoryMapEntry < MemoryMapEnd) {
-  if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart) {
-CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof 
(EFI_MEMORY_DESCRIPTOR));
-CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof 
(EFI_MEMORY_DESCRIPTOR));
-CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof 
(EFI_MEMORY_DESCRIPTOR));
-  }
-
-  NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, 
DescriptorSize);
-}
-
-MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, 
DescriptorSize);
-NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, 
DescriptorSize);
-  }
-
-  return;
-}
-
 /**
   Merge continuous memory map entries whose have same attributes.
 
@@ -183,7

[edk2-devel] [PATCH v4 13/14] MdeModulePkg: Add Logic to Create/Delete Image Properties Records

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Add logic to create and delete image properties records. Where
applicable, redirect existing code to use the new library.

Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
Cc: Jiaxin Wu 
Cc: Ray Ni 
---
 MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c | 
184 +++
 MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c| 
166 +++--
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c   | 
186 
 MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h|  
39 
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf |   
1 +
 5 files changed, 281 insertions(+), 295 deletions(-)

diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c 
b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
index af6c26244cc0..993db281062a 100644
--- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
+++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
@@ -557,25 +557,6 @@ CoreGetMemoryMapWithSeparatedImageSection (
 // Below functions are for ImageRecord
 //
 
-/**
-  Set MemoryAttributesTable according to PE/COFF image section alignment.
-
-  @param  SectionAlignmentPE/COFF section alignment
-**/
-STATIC
-VOID
-SetMemoryAttributesTableSectionAlignment (
-  IN UINT32  SectionAlignment
-  )
-{
-  if (((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) &&
-  mMemoryAttributesTableEnable)
-  {
-DEBUG ((DEBUG_VERBOSE, "SetMemoryAttributesTableSectionAlignment - 
Clear\n"));
-mMemoryAttributesTableEnable = FALSE;
-  }
-}
-
 /**
   Insert image record.
 
@@ -586,20 +567,12 @@ InsertImageRecord (
   IN EFI_RUNTIME_IMAGE_ENTRY  *RuntimeImage
   )
 {
-  VOID  *ImageAddress;
-  EFI_IMAGE_DOS_HEADER  *DosHdr;
-  UINT32PeCoffHeaderOffset;
-  UINT32SectionAlignment;
-  EFI_IMAGE_SECTION_HEADER  *Section;
-  EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION   Hdr;
-  UINT8 *Name;
-  UINTN Index;
-  IMAGE_PROPERTIES_RECORD   *ImageRecord;
-  CHAR8 *PdbPointer;
-  IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
+  EFI_STATUS   Status;
+  IMAGE_PROPERTIES_RECORD  *ImageRecord;
+  CHAR8*PdbPointer;
+  UINT32   RequiredAlignment;
 
   DEBUG ((DEBUG_VERBOSE, "InsertImageRecord - 0x%x\n", RuntimeImage));
-  DEBUG ((DEBUG_VERBOSE, "InsertImageRecord - 0x%016lx - 0x%016lx\n", 
(EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase, RuntimeImage->ImageSize));
 
   if (mMemoryAttributesTableEndOfDxe) {
 DEBUG ((DEBUG_INFO, "Do not insert runtime image record after 
EndOfDxe\n"));
@@ -611,139 +584,48 @@ InsertImageRecord (
 return;
   }
 
-  ImageRecord->Signature = IMAGE_PROPERTIES_RECORD_SIGNATURE;
+  InitializeListHead (&ImageRecord->Link);
+  InitializeListHead (&ImageRecord->CodeSegmentList);
 
-  DEBUG ((DEBUG_VERBOSE, "ImageRecordCount - 0x%x\n", 
mImagePropertiesPrivateData.ImageRecordCount));
-
-  //
-  // Step 1: record whole region
-  //
-  ImageRecord->ImageBase = 
(EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase;
-  ImageRecord->ImageSize = RuntimeImage->ImageSize;
-
-  ImageAddress = RuntimeImage->ImageBase;
-
-  PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
+  PdbPointer = PeCoffLoaderGetPdbPointer ((VOID 
*)(UINTN)RuntimeImage->ImageBase);
   if (PdbPointer != NULL) {
 DEBUG ((DEBUG_VERBOSE, "  Image - %a\n", PdbPointer));
   }
 
-  //
-  // Check PE/COFF image
-  //
-  DosHdr = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress;
-  PeCoffHeaderOffset = 0;
-  if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
-PeCoffHeaderOffset = DosHdr->e_lfanew;
-  }
-
-  Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + 
PeCoffHeaderOffset);
-  if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
-DEBUG ((DEBUG_VERBOSE, "Hdr.Pe32->Signature invalid - 0x%x\n", 
Hdr.Pe32->Signature));
-// It might be image in SMM.
-goto Finish;
-  }
-
-  //
-  // Get SectionAlignment
-  //
-  if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
-SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment;
-  } else {
-SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment;
-  }
-
-  SetMemoryAttributesTableSectionAlignment (SectionAlignment);
-  if ((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) {
-DEBUG ((
-  DEBUG_WARN,
-  "  InsertImageRecord - Section Alignment(0x%x) is not %dK  
\n",
-  SectionAlignment,
-  RUNTIME_PAGE_ALLOCATION

[edk2-devel] [PATCH v4 14/14] MdeModulePkg: Update DumpImageRecord() in ImagePropertiesRecordLib

2023-08-04 Thread Taylor Beebe
From: Taylor Beebe 

Update DumpImageRecord() to be DumpImageRecords(), and improve
the debug output. The function will output at DEBUG_INFO instead,
and the function will be run in DXE and SMM
MAT logic when the MAT is installed at EndOfDxe on DEBUG builds.

Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
Cc: Jiaxin Wu 
Cc: Ray Ni 
---
 MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c |   
9 ++
 MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c|  
11 +-
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c   | 
134 +---
 MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h|   
6 +-
 MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf |   
1 +
 MdeModulePkg/Test/MdeModulePkgHostTest.dsc |   
1 +
 6 files changed, 138 insertions(+), 24 deletions(-)

diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c 
b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
index 993db281062a..e9343a2c4ef1 100644
--- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
+++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
@@ -284,6 +284,15 @@ InstallMemoryAttributesTableOnEndOfDxe (
 {
   mMemoryAttributesTableEndOfDxe = TRUE;
   InstallMemoryAttributesTable ();
+
+  DEBUG_CODE_BEGIN ();
+  if ( mImagePropertiesPrivateData.ImageRecordCount > 0) {
+DEBUG ((DEBUG_INFO, "DXE - Total Runtime Image Count: 0x%x\n", 
mImagePropertiesPrivateData.ImageRecordCount));
+DEBUG ((DEBUG_INFO, "DXE - Dump Runtime Image Records:\n"));
+DumpImageRecords (&mImagePropertiesPrivateData.ImageRecordList);
+  }
+
+  DEBUG_CODE_END ();
 }
 
 /**
diff --git a/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c 
b/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c
index 03de9b2c5fff..28fe74ecc421 100644
--- a/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c
+++ b/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c
@@ -496,9 +496,14 @@ SmmInstallMemoryAttributesTable (
 return EFI_SUCCESS;
   }
 
-  DEBUG ((DEBUG_VERBOSE, "SMM Total Image Count - 0x%x\n", 
mImagePropertiesPrivateData.ImageRecordCount));
-  DEBUG ((DEBUG_VERBOSE, "SMM Dump ImageRecord:\n"));
-  DumpImageRecord (&mImagePropertiesPrivateData.ImageRecordList);
+  DEBUG_CODE_BEGIN ();
+  if ( mImagePropertiesPrivateData.ImageRecordCount > 0) {
+DEBUG ((DEBUG_INFO, "SMM - Total Runtime Image Count - 0x%x\n", 
mImagePropertiesPrivateData.ImageRecordCount));
+DEBUG ((DEBUG_INFO, "SMM - Dump Runtime Image Records:\n"));
+DumpImageRecords (&mImagePropertiesPrivateData.ImageRecordList);
+  }
+
+  DEBUG_CODE_END ();
 
   PublishMemoryAttributesTable ();
 
diff --git 
a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c 
b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
index 6c5eb1dc3185..e53ce086c54c 100644
--- a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
+++ b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c
@@ -14,6 +14,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 
 #define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \
@@ -785,31 +786,128 @@ SortImageRecord (
 }
 
 /**
-  Dump image record.
+  Extract the .efi filename out of the input PDB.
 
-  @param[in]  ImageRecordList  A list of IMAGE_PROPERTIES_RECORD entries
+  @param[in]  PdbPointer  Pointer to the PDB file path.
+  @param[out] EfiFileName Pointer to the .efi filename.
+  @param[in]  EfiFileNameSize Size of the .efi filename buffer.
+**/
+STATIC
+VOID
+GetFilename (
+  IN CHAR8   *PdbPointer,
+  OUT CHAR8  *EfiFileName,
+  IN UINTN   EfiFileNameSize
+  )
+{
+  UINTN  Index;
+  UINTN  StartIndex;
+
+  if ((PdbPointer == NULL) || (EfiFileNameSize < 5)) {
+return;
+  }
+
+  // Print Module Name by Pdb file path.
+  StartIndex = 0;
+  for (Index = 0; PdbPointer[Index] != 0; Index++) {
+if ((PdbPointer[Index] == '\\') || (PdbPointer[Index] == '/')) {
+  StartIndex = Index + 1;
+}
+  }
+
+  // Copy the PDB file name to EfiFileName and replace .pdb with .efi
+  for (Index = 0; Index < EfiFileNameSize - 4; Index++) {
+EfiFileName[Index] = PdbPointer[Index + StartIndex];
+if (EfiFileName[Index] == 0) {
+  EfiFileName[Index] = '.';
+}
+
+if (EfiFileName[Index] == '.') {
+  EfiFileName[Index + 1] = 'e';
+  EfiFileName[Index + 2] = 'f';
+  EfiFileName[Index + 3] = 'i';
+  EfiFileName[Index + 4] = 0;
+  break;
+}
+  }
+
+  if (Index == sizeof (EfiFileName) - 4) {
+EfiFileName[Index] = 0;
+  }
+}
+
+/**
+  Debug dumps the input list of IMAGE_PROPERTIES_RECORD structs.
+
+  @param[in]  ImageRecordList   Head of the IMAGE_PROPERTIES_RECORD list
 **/
 VOID
 EFIAPI
-DumpImageRecord (
+Dump

[edk2-devel] [PATCH v1 0/1] Fix Memory Bin Range Calculation to Account for Guard Page

2023-08-10 Thread Taylor Beebe
From: Taylor Beebe 

The following flow will produce an issue:

If page guards are active for EfiReservedMemoryType and SMM NULL pointer
protection is active with nonstop mode enabled, then a large (600 page)
allocation of EfiReservedMemoryType will be made for profiling.

0. InitSmmProfile() will be called to allocate a large range of memory for
   profiling.
1. gBS->AllocatePages() will be called with Type = EfiReservedMemoryType and
   Pages = 600.
2. gBS->AllocatePages() will call FindFreePages() to find a range of 600 pages
   in the memory map.
3. FindFreePages() will find a range and the binned address range will need to
   be updated.
4. The binned address range start will be updated to include the start of the
   range found by FindFreePages() but will NOT include the guard page.
5. CoreConvertPagesWithGuard() will be called to change the range type to
   EfiReservedMemoryType. The function will increase the conversion range
   to include the guard pages.
6. After converting the range, the CoreConvertRangeEx() logic will check
   if the range is in the binned address bounds to see if it should updated
   the memory type statistics.
7. The range will be outside of the binned address bounds by one page because
   the guard page was not included in the binned address range causing the
   large allocation to be unnacounted for in the of memory type statistics.
8. When the original bins are compared with the current bins to see if the
   system should reset with a larger original bin size, the large allocation
   will not be accounted for and the system will not reset with a larger bin
   size which is incorrect behavior.

Cc: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 

Taylor Beebe (1):
  MdeModulePkg: Memory Bin Range Update Accounts for Guard Page

 MdeModulePkg/Core/Dxe/Mem/Page.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107697): https://edk2.groups.io/g/devel/message/107697
Mute This Topic: https://groups.io/mt/100668861/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v1 1/1] MdeModulePkg: Memory Bin Range Update Accounts for Guard Page

2023-08-10 Thread Taylor Beebe
From: Taylor Beebe 

When finding a free page range for allocation, if the found range
starts below the tracked memory bin address range, the lowest
memory bin address is updated which will not include the guard page if
present. When CoreConvertPagesWithGuard() is called on the range
being allocated, the memory range is adjusted to include guard
pages which can push it out of the memory bin address range and
cause the memory type statistics to be unaltered.

This patch updates the lowest memory bin address range to account for
the guard page if NeedGuard is TRUE so the memory type statistics
are updated correctly.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 MdeModulePkg/Core/Dxe/Mem/Page.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/MdeModulePkg/Core/Dxe/Mem/Page.c b/MdeModulePkg/Core/Dxe/Mem/Page.c
index 41af50b3d5ab..6497af573353 100644
--- a/MdeModulePkg/Core/Dxe/Mem/Page.c
+++ b/MdeModulePkg/Core/Dxe/Mem/Page.c
@@ -1210,7 +1210,7 @@ FindFreePages (
   );
 if (Start != 0) {
   if (Start < mDefaultBaseAddress) {
-mDefaultBaseAddress = Start;
+mDefaultBaseAddress = NeedGuard ? Start - EFI_PAGE_SIZE : Start;
   }
 
   return Start;
-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107698): https://edk2.groups.io/g/devel/message/107698
Mute This Topic: https://groups.io/mt/100668862/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] [PATCH v4 00/14] Add ImagePropertiesRecordLib and Fix MAT Bugs

2023-08-16 Thread Taylor Beebe

Can I please get reviews/feedback on this patch series?

On 8/4/2023 12:46 PM, Taylor Beebe via groups.io wrote:

From: Taylor Beebe 

v4:
- Expose additional functions in the Library API
- Add NULL checks to library functions and return a
   status where applicable.

v3:
- Refactor patch series so the transition of logic from the DXE
   MAT logic to the new library is more clear.
- Update function headers to improve clarity and follow EDK2
   standards.
- Add Create and Delete functions for Image Properties Records
   and redirect some of the SMM and DXE MAT code to use these
   functions.
- Update/Add DumpImageRecords() to print the image name and code
   sections of each runtime image which will be put in the MAT.
   The DXE and SMM MAT logic will now invoke the DumpImageRecords()
   on DEBUG builds at the EndOfDxe event to install the MAT.

v2:
- A one-line change in patch 3 was moved to patch 9 for correctness.

Reference: https://github.com/tianocore/edk2/pull/4590
Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4492

The UEFI and SMM MAT logic contains duplicate logic for manipulating image
properties records which is used to track runtime images.
This patch series adds a new library, ImagePropertiesRecordLib,
which consolidates this logic and fixes the bugs which currently exist in
the MAT logic.

The first patch adds the ImagePropertiesRecordLib implementation which
is a copy of the UEFI MAT logic with minor modifications to remove the
reliance on globabl variables and make the code unit testable.

The second patch adds a unit test for the ImagePropertiesRecordLib. The
logic tests various potential layouts of the EFI memory map and runtime
images. 3/4 of these tests will fail which demonstrates the MAT logic
bugs.

The third patch fixes the logic in the ImagePropertiesRecordLib so
that all of the unit tests pass and the MAT logic can be fixed by
using the library.

The remaining patches add library instances to DSC files and remove
the image properties record logic from the SMM and UEFI MAT logic.

Cc: Andrew Fish 
Cc: Ard Biesheuvel 
Cc: Dandan Bi 
Cc: Eric Dong 
Cc: Gerd Hoffmann 
Cc: Guo Dong 
Cc: Gua Guo 
Cc: James Lu 
Cc: Jian J Wang 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Leif Lindholm 
Cc: Liming Gao 
Cc: Rahul Kumar 
Cc: Ray Ni 
Cc: Sami Mujawar 
Cc: Sean Rhodes 

Taylor Beebe (14):
   MdeModulePkg: Add ImagePropertiesRecordLib
   ArmVirtPkg: Add ImagePropertiesRecordLib Instance
   EmulatorPkg: Add ImagePropertiesRecordLib Instance
   OvmfPkg: Add ImagePropertiesRecordLib Instance
   UefiPayloadPkg: Add ImagePropertiesRecordLib Instance
   MdeModulePkg: Update MemoryAttributesTable.c to Reduce Global Variable
 Use
   MdeModulePkg: Move Some DXE MAT Logic to ImagePropertiesRecordLib
   MdeModulePkg: Add ImagePropertiesRecordLib Host-Based Unit Test
   MdeModulePkg: Fix Bugs in MAT Logic
   MdeModulePkg: Add NULL checks and Return Status to
 ImagePropertiesRecordLib
   UefiCpuPkg: Use Attribute From SMM MemoryAttributesTable if Nonzero
   MdeModulePkg: Transition SMM MAT Logic to Use ImagePropertiesRecordLib
   MdeModulePkg: Add Logic to Create/Delete Image Properties Records
   MdeModulePkg: Update DumpImageRecord() in ImagePropertiesRecordLib

  MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c
  |  967 +
  MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c 
  |   24 +-
  MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c   
  |  958 +---
  MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c  
  | 1144 
  
MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.c
   |  938 
  UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c
  |   19 +-
  ArmVirtPkg/ArmVirt.dsc.inc
  |1 +
  EmulatorPkg/EmulatorPkg.dsc   
  |1 +
  MdeModulePkg/Core/Dxe/DxeMain.h   
  |   20 -
  MdeModulePkg/Core/Dxe/DxeMain.inf 
  |1 +
  MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf 
  |1 +
  MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h   
  |  234 
  MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
  |   31 +
  
MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.inf
 |   35 +
  MdeModulePkg/MdeModulePkg.dec 
  |5 +
  MdeModulePkg/MdeModulePkg.dsc

[edk2-devel] [PATCH v2 01/25] MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 {
+  BOOLEANEnabled: 1;
+  BOOLEANDisableEndOfDxe: 1;
+  BOOLEANNonstopModeEnabled : 1;
+} DXE_NULL_DETECTION_POLICY;
+
+typedef struct {
+  BOOLEANProtectImageFromUnknown : 1;
+  BOOLEANProtectImageFromFv  : 1;
+} DXE_IMAGE_PROTECTION_POLICY;
+
+typedef struct {
+  BOOLEANPageGuardEnabled: 1;
+  BOOLEANPoolGuardEnabled: 1;
+  BOOLEANFreedMemoryGuardEnabled : 1;
+  BOOLEANNonstopModeEnabled  : 1;
+  BOOLEANGuardAlignedToTail  : 1;
+} DXE_HEAP_GUARD_POLICY;
+
+typedef struct {
+  BOOLEANEnabled: 1;
+  BOOLEANNonstopModeEnabled : 1;
+} MM_NULL_DETECTION_POLICY;
+
+typedef struct {
+  BOOLEANPageGuardEnabled   : 1;
+  BOOLEANPoolGuardEnabled   : 1;
+  BOOLEANNonstopModeEnabled : 1;
+  BOOLEANGuardAlignedToTail : 1;
+} MM_HEAP_GUARD_POLICY;
+
+typedef struct {
+  BOOLEANEnabledForType[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_SIGNATURESignature;
+
+  // 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_POLICYNullPointerDetection;
+
+  // 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 no

[edk2-devel] [PATCH v2 00/25] Implement Dynamic Memory Protections

2023-08-18 Thread Taylor Beebe
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.

This patch series adds two libraries:
SetMemoryProtectionsLib: A PEIM that allows for setting/fetching memory
protections and "locking" to prevent further updates via the library interface.
The backing for the settings are a GUIDed HOB that is created by the library
whenever its API is invoked.

GetMemoryProtectionsLib: A DXE library that allows for getting the memory
protection settings for the current boot. This library populates a global
with the settings from the HOB entry (if present) for access in the module.
Previous references to the PCDs are replaced with references to the global.

OvmfPkg has been updated to allow the setting of the memory protection profile
via QemuCfg instead of just the NxForStack setting. If no profile is passed,
the platform will default to the Debug profile for DXE and Off profile for MM.

ArmVirtPkg will use the Release profile.

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

Cc: Abner Chang 
Cc: Andrei Warkentin 
Cc: Anatol Belski 
Cc: Andrew Fish 
Cc: Anthony Perard 
Cc: Ard Biesheuvel 
Cc: Corvin Köhne 
Cc: Dandan Bi 
Cc: Eric Dong 
Cc: Erdem Aktas 
Cc: Gerd Hoffmann 
Cc: Guo Dong 
Cc: Gua Guo 
Cc: James Bottomley 
Cc: James Lu 
Cc: Jian J Wang 
Cc: Jianyong Wu 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Julien Grall 
Cc: Leif Lindholm 
Cc: Liming Gao 
Cc: Michael Roth 
Cc: Min Xu 
Cc: Peter Grehan 
Cc: Rahul Kumar  
Cc: Ray Ni 
Cc: Rebecca Cran 
Cc: Sami Mujawar 
Cc: Sean Rhodes 
Cc: Sunil V L 
Cc: Tom Lendacky 

Taylor Beebe (25):
  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: 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: 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/Virtu

[edk2-devel] [PATCH v2 04/25] MdeModulePkg: Implement SetMemoryProtectionsLib and GetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+
+#include 
+#include 
+#include 
+
+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

[edk2-devel] [PATCH v2 02/25] MdeModulePkg: Define SetMemoryProtectionsLib and GetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+#include 
+
+#pragma pack(1)
+
+typedef union {
+  DXE_MEMORY_PROTECTION_SETTINGSDxe;
+  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   
 ||  \
+   

[edk2-devel] [PATCH v2 05/25] MdeModulePkg: Apply Protections to the HOB List

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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..6c1c17a5c205 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.
 
@@ -995,6 +1021,9 @@ MemoryProtectionCpuArchProtocolNotify (
 goto Done;
   }
 
+  // Mark the HOB list XP and RO.
+  ProtectHobList ();
+
   //
   // Apply the memory protection policy on non-BScode/RTcode regions.
   //
-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107860): https://edk2.groups.io/g/devel/message/107860
Mute This Topic: https://groups.io/mt/100830903/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 06/25] MdeModulePkg: Check Print Level Before Dumping GCD Memory Map

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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;
   UINTNIndex;
 
+  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.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107861): https://edk2.groups.io/g/devel/message/107861
Mute This Topic: https://groups.io/mt/100830904/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 03/25] MdeModulePkg: Add NULL Instances for Get/SetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
The NULL instances for GetMemoryProtectionsLib and
SetMemoryProtectionsLib just zero out the memory protections
structure effectively disabling memory protections.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+#include 
+
+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 ..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 
+#include 
+
+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] DxeMpsPointer 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

[edk2-devel] [PATCH v2 07/25] UefiCpuPkg: Always Set Stack Guard in MpPei Init

2023-08-18 Thread Taylor Beebe
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 
Cc: Eric Dong 
Cc: Ray Ni 
Cc: Rahul Kumar  
Cc: Gerd Hoffmann 
---
 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..0ab8c8a6 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_POINTERSHob;
   IA32_CR0Cr0;
@@ -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 
 
 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 

[edk2-devel] [PATCH v2 08/25] ArmVirtPkg: Add Memory Protection Library Definitions to Platforms

2023-08-18 Thread Taylor Beebe
Add library classes for SetMemoryProtectionsLib and
GetMemoryProtectionsLib to ArmVirtPkg.

Signed-off-by: Taylor Beebe 
Cc: Ard Biesheuvel 
Cc: Leif Lindholm 
Cc: Sami Mujawar 
Cc: Gerd Hoffmann 
Cc: Julien Grall 
---
 ArmVirtPkg/ArmVirt.dsc.inc | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc
index 2443e8351c99..6de28d0e0d4e 100644
--- a/ArmVirtPkg/ArmVirt.dsc.inc
+++ b/ArmVirtPkg/ArmVirt.dsc.inc
@@ -156,6 +156,12 @@ [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   RngLib|MdePkg/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.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107863): https://edk2.groups.io/g/devel/message/107863
Mute This Topic: https://groups.io/mt/100830906/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 09/25] OvmfPkg: Add Memory Protection Library Definitions to Platforms

2023-08-18 Thread Taylor Beebe
Add library classes for SetMemoryProtectionsLib and
GetMemoryProtectionsLib to OvmfPkg platfomrs.

Signed-off-by: Taylor Beebe 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
Cc: Rebecca Cran 
Cc: Peter Grehan 
Cc: Corvin Köhne 
Cc: Jianyong Wu 
Cc: Anatol Belski 
Cc: Anthony Perard 
Cc: Julien Grall 
---
 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 2c6ed7c9745f..0913aa734114 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -202,6 +202,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/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc
index 82c60ace1bbd..c2a3b9bf3960 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 e000deed9e4d..20d609156e7d 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 ..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 193657ff2d61..fadfff3f5202 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 2f7585639374..c1374e8f3000 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

[edk2-devel] [PATCH v2 16/25] OvmfPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-18 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
Cc: Leif Lindholm 
Cc: Abner Chang 
---
 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 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -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 
 #include 
 #include 
+#include 
 #include 
 
 #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.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107871): https://edk2.groups.io/g/devel/message/107871
Mute This Topic: https://groups.io/mt/100830915/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 11/25] OvmfPkg: Update PeilessStartupLib to use SetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
---
 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 
 #include "X64/PageTables.h"
 #include 
+#include 
 
 #define STACK_SIZE  0x2
-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 
 #include 
 #include 
+#include 
 #include 
 #include 
 #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.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107866): https://edk2.groups.io/g/devel/message/107866
Mute This Topic: https://groups.io/mt/100830909/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 15/25] EmulatorPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-18 Thread Taylor Beebe
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 
Cc: Andrew Fish 
Cc: Ray Ni 
---
 EmulatorPkg/EmulatorPkg.dsc | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/EmulatorPkg/EmulatorPkg.dsc b/EmulatorPkg/EmulatorPkg.dsc
index b44435d7e6ee..1e2c903f5c30 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|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
@@ -216,7 +218,6 @@ [PcdsFeatureFlag]
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplBuildPageTables|FALSE
 
 [PcdsFixedAtBuild]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy|0x
   gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE
   gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8040
   gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x0f
-- 
2.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107870): https://edk2.groups.io/g/devel/message/107870
Mute This Topic: https://groups.io/mt/100830914/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 14/25] ArmPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-18 Thread Taylor Beebe
Replace references to the memory protection PCDs to instead
check the platform protections via GetMemoryProtectionsLib.

Signed-off-by: Taylor Beebe 
Cc: Leif Lindholm 
Cc: Ard Biesheuvel 
Cc: Sami Mujawar 
---
 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 
 
 #include 
+#include 
 
 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 4939b3d59b7f..354535eb3718 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.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107869): https://edk2.groups.io/g/devel/message/107869
Mute This Topic: https://groups.io/mt/100830913/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 13/25] MdeModulePkg: Update DXE Handoff to use SetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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;
   UINTNGhcbSize;
 
+  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

[edk2-devel] [PATCH v2 12/25] UefiPayloadPkg: Update DXE Handoff to use SetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Guo Dong 
Cc: Sean Rhodes 
Cc: James Lu 
Cc: Gua Guo 
---
 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  0x2
 
+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 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
 #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

[edk2-devel] [PATCH v2 19/25] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c | 413 

 MdeModulePkg/Include/Library/SetMemoryProtectionsLib.h |   7 +
 2 files changed, 420 insertions(+)

diff --git 
a/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c 
b/MdeModulePkg/Library/SetMemoryProtectionsLib/SetMemoryProtectionsLib.c
index cef9a5680c75..312a5da63bf5 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 = FALSE   \
+  },  \
+  { /* 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

[edk2-devel] [PATCH v2 17/25] UefiCpuPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-18 Thread Taylor Beebe
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 
Cc: Eric Dong 
Cc: Ray Ni 
Cc: Rahul Kumar 
Cc: Gerd Hoffmann 
---
 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 Servic

[edk2-devel] [PATCH v2 18/25] MdeModulePkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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 9377f620c5a5..ee03906a009d 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
 //
@@ -1045,7 +1055,7 @@ AdjustPoolHeadF (

[edk2-devel] [PATCH v2 10/25] OvmfPkg: Apply Memory Protections via SetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
---
 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 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 #include 
 #include 
@@ -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 
 #include 
 #include 
+#include 
 
 #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
   gUefiOvmfPkgTokenSp

[edk2-devel] [PATCH v2 21/25] ArmVirtPkg: Apply Memory Protections via SetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Leif Lindholm 
Cc: Sami Mujawar 
Cc: Gerd Hoffmann 
---
 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 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -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.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107876): https://edk2.groups.io/g/devel/message/107876
Mute This Topic: https://groups.io/mt/100830925/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 20/25] OvmfPkg: Enable Choosing Memory Protection Profile via QemuCfg

2023-08-18 Thread Taylor Beebe
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. Other presets are "debug" and "off":
-fw_cfg name=opt/org.tianocore/DxeMemoryProtectionProfile,string=release

The following will set the DXE memory protection to
the RELEASE preset. Other presets are "debug" and "off":
-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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
Cc: Rebecca Cran 
Cc: Peter Grehan 
Cc: Corvin Köhne 
---
 OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c   | 56 
++--
 OvmfPkg/Library/PeilessStartupLib/X64/VirtualMemory.c| 13 +---
 OvmfPkg/Library/PlatformInitLib/Platform.c   | 15 -
 OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParser.c | 11 +++
 OvmfPkg/PlatformPei/IntelTdx.c   |  2 -
 OvmfPkg/PlatformPei/Platform.c   | 70 
++--
 OvmfPkg/TdxDxe/TdxDxe.c  |  7 +-
 OvmfPkg/Bhyve/PlatformPei/PlatformPei.inf|  1 -
 OvmfPkg/Include/Library/PlatformInitLib.h| 13 
 OvmfPkg/Include/Library/QemuFwCfgSimpleParserLib.h   |  8 +++
 OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf  |  1 -
 OvmfPkg/PlatformCI/PlatformBuildLib.py   | 31 -
 OvmfPkg/PlatformPei/PlatformPei.inf  |  1 -
 OvmfPkg/TdxDxe/TdxDxe.inf|  1 -
 14 files changed, 148 insertions(+), 82 deletions(-)

diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c 
b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
index cf645aad3246..a6ac6a8a15cc 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
@@ -28,6 +28,12 @@
 
 #define GET_GPAW_INIT_STATE(INFO)  ((UINT8) ((INFO) & 0x3f))
 
+#define DXE_MEMORY_PROTECTION_PROFILE_FWCFG_FILE \
+  "opt/org.tianocore/DxeMemoryProtectionProfile"
+
+#define MM_MEMORY_PROTECTION_PROFILE_FWCFG_FILE \
+  "opt/org.tianocore/MmMemoryProtectionProfile"
+
 EFI_MEMORY_TYPE_INFORMATION  mDefaultMemoryTypeInformation[] = {
   { EfiACPIMemoryNVS,   0x004 },
   { EfiACPIReclaimMemory,   0x008 },
@@ -48,6 +54,9 @@ InitializePlatform (
   VOID*VariableStore;
   DXE_MEMORY_PROTECTION_SETTINGS  DxeSettings;
   MM_MEMORY_PROTECTION_SETTINGS   MmSettings;
+  CHAR8   String[100];
+  UINTN   StringSize;
+  EFI_STATUS  Status;
 
   DEBUG ((DEBUG_INFO, "InitializePlatform in Pei-less boot\n"));
   PlatformDebugDumpCmos ();
@@ -109,18 +118,51 @@ InitializePlatform (
 
   PlatformMemMapInitialization (PlatformInfoHob);
 
-  DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsPcd].Settings;
-  MmSettings  = 
MmMemoryProtectionProfiles[MmMemoryProtectionSettingsPcd].Settings;
-  DxeSettings.StackExecutionProtectionEnabled = PcdGetBool (PcdSetNxForStack);
-  QemuFwCfgParseBool ("opt/ovmf/PcdSetNxForStack", 
&DxeSettings.StackExecutionProtectionEnabled);
+  StringSize = sizeof (String);
 
-  SetDxeMemoryProtectionSettings (&DxeSettings, 
DxeMemoryProtectionSettingsPcd);
-  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsPcd);
+  Status = QemuFwCfgParseString (DXE_MEMORY_PROTECTION_PROFILE_FWCFG_FILE, 
&StringSize, String);
+  if (!EFI_ERROR (Status)) {
+DEBUG ((DEBUG_INFO, "Setting DXE Memory Protection Profile: %a\n", 
String));
+if (AsciiStriCmp (String, "debug") == 0) {
+  DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsDebug].Settings;
+} else if (AsciiStriCmp (String, "release") == 0) {
+  DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsRelease].Settings;
+} else if (AsciiStriCmp (String, "off") == 0) {
+  DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsOff].Settings;
+} else {
+  DEBUG ((DEBUG_ERROR, "Invalid DXE memory protection profile: %a\n", 
String));
+  ASSERT (FALSE);
+}
+  } else {
+DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsDebug].Settings;
+  }
+
+  Status = QemuFwCfgParseString (MM_MEMORY_PROTECTION_PROFILE_FWCFG_FILE, 
&

[edk2-devel] [PATCH v2 23/25] OvmfPkg: Delete Memory Protection PCDs

2023-08-18 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
Cc: Rebecca Cran 
Cc: Peter Grehan 
Cc: Corvin Köhne 
Cc: Jianyong Wu 
Cc: Anatol Belski 
Cc: Anthony Perard 
Cc: Julien Grall 
Cc: Erdem Aktas 
Cc: James Bottomley 
Cc: Min Xu 
Cc: Tom Lendacky 
Cc: Michael Roth 
Cc: Sunil V L 
Cc: Andrei Warkentin 
---
 OvmfPkg/AmdSev/AmdSevX64.dsc|  3 ---
 OvmfPkg/Bhyve/BhyveX64.dsc  |  3 ---
 OvmfPkg/CloudHv/CloudHvX64.dsc  |  3 ---
 OvmfPkg/IntelTdx/IntelTdxX64.dsc|  3 ---
 OvmfPkg/Microvm/MicrovmX64.dsc  |  3 ---
 OvmfPkg/OvmfPkgIa32.dsc |  3 ---
 OvmfPkg/OvmfPkgIa32X64.dsc  |  3 ---
 OvmfPkg/OvmfPkgX64.dsc  |  3 ---
 OvmfPkg/OvmfXen.dsc |  3 ---
 OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc | 13 -
 10 files changed, 40 deletions(-)

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index 0913aa734114..2e2e320c61fb 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -507,9 +507,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 c2a3b9bf3960..30f0e27ea840 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|5
diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc
index 20d609156e7d..ecf723b20439 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 fadfff3f5202..60b3a9bad237 100644
--- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
@@ -503,9 +503,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/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index c1374e8f3000..560f8139f803 100644
--- a/OvmfPkg/Microvm/MicrovmX64.dsc
+++ b/OvmfPkg/Microvm/MicrovmX64.dsc
@@ -615,9 +615,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 8267cf20e4a9..ced2fd724954 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

[edk2-devel] [PATCH v2 22/25] MdeModulePkg: Delete PCD Profile from SetMemoryProtectionsLib

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 312a5da63bf5..7d965c190105 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 
 #include 
 #include 
-#include 
 #include 
 
 #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),\
- 

[edk2-devel] [PATCH v2 24/25] ArmVirtPkg: Delete Memory Protection PCDs

2023-08-18 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Leif Lindholm 
Cc: Sami Mujawar 
Cc: Gerd Hoffmann 
---
 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 6de28d0e0d4e..2df479331ae6 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|0xC0007FD5
-
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard|TRUE
-
 [Components.common]
   #
   # Ramdisk support
diff --git a/ArmVirtPkg/ArmVirtCloudHv.dsc b/ArmVirtPkg/ArmVirtCloudHv.dsc
index c975e139a216..c4c3e0da4491 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 1e0225951aef..214e08b789eb 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.41.0.windows.3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#107879): https://edk2.groups.io/g/devel/message/107879
Mute This Topic: https://groups.io/mt/100830928/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v2 25/25] MdeModulePkg: Delete Memory Protection PCDs

2023-08-18 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 MdeModulePkg/MdeModulePkg.dec | 169 
 MdeModulePkg/MdeModulePkg.uni | 153 --
 2 files changed, 322 deletions(-)

diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index 50c26fedaf6f..c701173b9803 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -1004,119 +1004,12 @@ [PcdsFixedAtBuild]
   # @ValidList  0x8006 | 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.
-  #BIT0- Enable NULL pointer detection for UEFI.
-  #BIT1- Enable NULL pointer detection for SMM.
-  #BIT2..5 - Reserved for future uses.
-  #BIT6- Enable non-stop mode.
-  #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.
-  # @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)
-  #  EfiReservedMemoryType 0x0001
-  #  EfiLoaderCode 0x0002
-  #  EfiLoaderData 0x0004
-  #  EfiBootServicesCode   0x0008
-  #  EfiBootServicesData   0x0010
-  #  EfiRuntimeServicesCode0x0020
-  #  EfiRuntimeServicesData0x0040
-  #  EfiConventionalMemory 0x0080
-  #  EfiUnusableMemory 0x0100
-  #  EfiACPIReclaimMemory  0x0200
-  #  EfiACPIMemoryNVS  0x0400
-  #  EfiMemoryMappedIO 0x0800
-  #  EfiMemoryMappedIOPortSpace0x1000
-  #  EfiPalCode0x2000
-  #  EfiPersistentMemory   0x4000
-  #  OEM Reserved  0x4000
-  #  OS Reserved   0x8000
-  # e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 
0x1E should be used.
-  # @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)
-  #  EfiReservedMemoryType 0x0001
-  #  EfiLoaderCode 0x0002
-  #  EfiLoaderData 0x0004
-  #  EfiBootServicesCode   0x0008
-  #  EfiBootServicesData   0x0010
-  #  EfiRuntimeServicesCode0x0020
-  #  EfiRuntimeServicesData0x0040
-  #  EfiConventionalMemory 0x0080
-  #  EfiUnusableMemory 0x0100
-  #  EfiACPIReclaimMemory  0x0200
-  #  EfiACPIMemoryNVS  0x0400
-  #  EfiMemo

Re: [edk2-devel] [PATCH v2 00/25] Implement Dynamic Memory Protections

2023-08-21 Thread Taylor Beebe

Here's a summmary of the v2 changes :)

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.

On 8/18/23 3:31 PM, Taylor Beebe wrote:

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.

This patch series adds two libraries:
SetMemoryProtectionsLib: A PEIM that allows for setting/fetching memory
protections and "locking" to prevent further updates via the library interface.
The backing for the settings are a GUIDed HOB that is created by the library
whenever its API is invoked.

GetMemoryProtectionsLib: A DXE library that allows for getting the memory
protection settings for the current boot. This library populates a global
with the settings from the HOB entry (if present) for access in the module.
Previous references to the PCDs are replaced with references to the global.

OvmfPkg has been updated to allow the setting of the memory protection profile
via QemuCfg instead of just the NxForStack setting. If no profile is passed,
the platform will default to the Debug profile for DXE and Off profile for MM.

ArmVirtPkg will use the Release profile.

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

Cc: Abner Chang 
Cc: Andrei Warkentin 
Cc: Anatol Belski 
Cc: Andrew Fish 
Cc: Anthony Perard 
Cc: Ard Biesheuvel 
Cc: Corvin Köhne 
Cc: Dandan Bi 
Cc: Eric Dong 
Cc: Erdem Aktas 
Cc: Gerd Hoffmann 
Cc: Guo Dong 
Cc: Gua Guo 
Cc: James Bottomley 
Cc: James Lu 
Cc: Jian J Wang 
Cc: Jianyong Wu 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Julien Grall 
Cc: Leif Lindholm 
Cc: Liming Gao 
Cc: Michael Roth 
Cc: Min Xu 
Cc: Peter Grehan 
Cc: Rahul Kumar 
Cc: Ray Ni 
Cc: Rebecca Cran 
Cc: Sami Mujawar 
Cc: Sean Rhodes 
Cc: Sunil V L 
Cc: Tom Lendacky 

Taylor Beebe (25):
   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: 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 GetMemor

Re: [edk2-devel] [PATCH v4 00/14] Add ImagePropertiesRecordLib and Fix MAT Bugs

2023-08-28 Thread Taylor Beebe

Can I please get reviews/feedback on this patch series?

On 8/16/23 11:14 AM, Taylor Beebe via groups.io wrote:

Can I please get reviews/feedback on this patch series?

On 8/4/2023 12:46 PM, Taylor Beebe via groups.io wrote:

From: Taylor Beebe 

v4:
- Expose additional functions in the Library API
- Add NULL checks to library functions and return a
   status where applicable.

v3:
- Refactor patch series so the transition of logic from the DXE
   MAT logic to the new library is more clear.
- Update function headers to improve clarity and follow EDK2
   standards.
- Add Create and Delete functions for Image Properties Records
   and redirect some of the SMM and DXE MAT code to use these
   functions.
- Update/Add DumpImageRecords() to print the image name and code
   sections of each runtime image which will be put in the MAT.
   The DXE and SMM MAT logic will now invoke the DumpImageRecords()
   on DEBUG builds at the EndOfDxe event to install the MAT.

v2:
- A one-line change in patch 3 was moved to patch 9 for correctness.

Reference: https://github.com/tianocore/edk2/pull/4590
Bugzilla: https://bugzilla.tianocore.org/show_bug.cgi?id=4492

The UEFI and SMM MAT logic contains duplicate logic for manipulating 
image

properties records which is used to track runtime images.
This patch series adds a new library, ImagePropertiesRecordLib,
which consolidates this logic and fixes the bugs which currently 
exist in

the MAT logic.

The first patch adds the ImagePropertiesRecordLib implementation which
is a copy of the UEFI MAT logic with minor modifications to remove the
reliance on globabl variables and make the code unit testable.

The second patch adds a unit test for the ImagePropertiesRecordLib. The
logic tests various potential layouts of the EFI memory map and runtime
images. 3/4 of these tests will fail which demonstrates the MAT logic
bugs.

The third patch fixes the logic in the ImagePropertiesRecordLib so
that all of the unit tests pass and the MAT logic can be fixed by
using the library.

The remaining patches add library instances to DSC files and remove
the image properties record logic from the SMM and UEFI MAT logic.

Cc: Andrew Fish 
Cc: Ard Biesheuvel 
Cc: Dandan Bi 
Cc: Eric Dong 
Cc: Gerd Hoffmann 
Cc: Guo Dong 
Cc: Gua Guo 
Cc: James Lu 
Cc: Jian J Wang 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Leif Lindholm 
Cc: Liming Gao 
Cc: Rahul Kumar 
Cc: Ray Ni 
Cc: Sami Mujawar 
Cc: Sean Rhodes 

Taylor Beebe (14):
   MdeModulePkg: Add ImagePropertiesRecordLib
   ArmVirtPkg: Add ImagePropertiesRecordLib Instance
   EmulatorPkg: Add ImagePropertiesRecordLib Instance
   OvmfPkg: Add ImagePropertiesRecordLib Instance
   UefiPayloadPkg: Add ImagePropertiesRecordLib Instance
   MdeModulePkg: Update MemoryAttributesTable.c to Reduce Global 
Variable

 Use
   MdeModulePkg: Move Some DXE MAT Logic to ImagePropertiesRecordLib
   MdeModulePkg: Add ImagePropertiesRecordLib Host-Based Unit Test
   MdeModulePkg: Fix Bugs in MAT Logic
   MdeModulePkg: Add NULL checks and Return Status to
 ImagePropertiesRecordLib
   UefiCpuPkg: Use Attribute From SMM MemoryAttributesTable if Nonzero
   MdeModulePkg: Transition SMM MAT Logic to Use 
ImagePropertiesRecordLib

   MdeModulePkg: Add Logic to Create/Delete Image Properties Records
   MdeModulePkg: Update DumpImageRecord() in ImagePropertiesRecordLib

MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c |  967 
+

MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c |   24 +-
MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c |  958 
+---
MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c 
| 1144 
MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.c 
|  938 

UefiCpuPkg/PiSmmCpuDxeSmm/SmmCpuMemoryManagement.c |   19 +-
ArmVirtPkg/ArmVirt.dsc.inc |    1 +
EmulatorPkg/EmulatorPkg.dsc |    1 +
MdeModulePkg/Core/Dxe/DxeMain.h |   20 -
MdeModulePkg/Core/Dxe/DxeMain.inf |    1 +
MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf |    1 +
MdeModulePkg/Include/Library/ImagePropertiesRecordLib.h |  234 
MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf 
|   31 +
MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.inf 
|   35 +

MdeModulePkg/MdeModulePkg.dec |    5 +
MdeModulePkg/MdeModulePkg.dsc |    2 +
MdeModulePkg/Test/MdeModulePkgHostTest.dsc |    6 +
OvmfPkg/AmdSev/AmdSevX64.dsc |    1 +
OvmfPkg/Bhyve/BhyveX64.dsc |    1 +
OvmfPkg/CloudHv/CloudHvX64.dsc |    1 +
OvmfPkg/IntelTdx/IntelTdxX64.dsc |    1 +
OvmfPkg/Microvm/MicrovmX64.dsc |    1 +
OvmfPkg/OvmfPkgIa32.dsc |    1 +
OvmfPkg/OvmfPkgIa32X64.dsc |    1 +
OvmfPkg/OvmfPkgX64.dsc |    1 +
OvmfPkg/OvmfXen.dsc |    1 +
OvmfPkg/RiscVVirt/RiscVVirtQemu.dsc |    1 +
UefiPayloadPkg/UefiPayloadPkg.dsc |    1 +
  28 files changed, 2524 insertions(+), 1874 deletions(-)
  create mode 100644 
MdeModulePkg/Library/ImagePropertiesRecordLib

Re: [edk2-devel] another PR rejected by CI

2023-08-28 Thread Taylor Beebe

Here's a git-patch so you can easily fix it:

---
 OvmfPkg/IoMmuDxe/IoMmuBuffer.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/OvmfPkg/IoMmuDxe/IoMmuBuffer.c b/OvmfPkg/IoMmuDxe/IoMmuBuffer.c
index 2764c35044ac..d66763263784 100644
--- a/OvmfPkg/IoMmuDxe/IoMmuBuffer.c
+++ b/OvmfPkg/IoMmuDxe/IoMmuBuffer.c
@@ -434,7 +434,7 @@ IoMmuFreeBounceBuffer (
       mReservedMemBitmap,
       mReservedMemBitmap & ((UINT32)(~MapInfo->ReservedMemBitmap))
       ));
-    MapInfo->PlainTextAddress  = 0;
+    MapInfo->PlainTextAddress = 0;
     ClearReservedMemBit (MapInfo->ReservedMemBitmap);
     MapInfo->ReservedMemBitmap = 0;
   }
--
On 8/28/2023 11:16 AM, Mike Maslenkin wrote:

Hello!

https://dev.azure.com/tianocore/edk2-ci/_build/results?buildId=100301&view=ms.vss-test-web.build-test-results-tab&runId=877528&resultId=16&paneView=attachments

Uncrustify found formatting errors in IoMmuDxe/IoMmuBuffer.c
See Standard_Error_Output.log in "attachments"

It doesn't like two spaces at assignment
MapInfo->PlainTextAddress_ _= 0;

Best Regards,
Mike


On Mon, Aug 28, 2023 at 8:58 PM Ard Biesheuvel  wrote:

Could someone please explain to me how I can figure out why this PR
was rejected by the CI?

https://github.com/tianocore/edk2/pull/4763













-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108062): https://edk2.groups.io/g/devel/message/108062
Mute This Topic: https://groups.io/mt/101015386/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] [PATCH v2 19/25] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib

2023-08-29 Thread Taylor Beebe



On 8/29/23 3:46 AM, Gerd Hoffmann wrote:



--- 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;

Ordering mismatch for "pcd" and "off".

I'd suggest to use C99 initializers, i.e.

DxeMemoryProtectionProfiles[] = {
[ DxeMemoryProtectionSettingsDebug ] = {
.Name = "Debug",

to avoid that.

take care,
   Gerd



Thanks! Will fix in v3



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108097): https://edk2.groups.io/g/devel/message/108097
Mute This Topic: https://groups.io/mt/100830918/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




Re: [edk2-devel] [PATCH v2 20/25] OvmfPkg: Enable Choosing Memory Protection Profile via QemuCfg

2023-08-29 Thread Taylor Beebe



On 8/29/23 4:17 AM, Gerd Hoffmann wrote:

   Hi,


-  SetDxeMemoryProtectionSettings (&DxeSettings, 
DxeMemoryProtectionSettingsPcd);
-  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsPcd);
+  Status = QemuFwCfgParseString (DXE_MEMORY_PROTECTION_PROFILE_FWCFG_FILE, 
&StringSize, String);
+  if (!EFI_ERROR (Status)) {
+DEBUG ((DEBUG_INFO, "Setting DXE Memory Protection Profile: %a\n", 
String));
+if (AsciiStriCmp (String, "debug") == 0) {
+  DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsDebug].Settings;

I'd suggest to just loop over DxeMemoryProtectionProfiles and compare
String with .Name, so we don't have to touch this in case we add or
remove profiles.


Sounds good -- will update in v3


+DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsDebug].Settings;

I'd prefer to use DxeMemoryProtectionSettingsPcd by default.


The PCDs are still removed in this patch series. The PCD profile is 
included in the earlier patches of this series to ensure the memory 
protections are consistent as each patch transitions the references to 
use the library interface. I opted to to remove the PCDs for a couple of 
reasons:
1. The PCDs are the legacy interface, and keeping legacy interfaces 
around is sometimes necessary for compatibility but not in this case. 
Keeping the PCDs would disrupt maintainability, clarity, and 
extensibility of memory protections. I am also not confident the legacy 
interface would ever be removed in the future.


2. Removing the PCDs will cause a build failure for platforms which 
reference them. This outcome is desirable in this case because action 
needs to be taken to ensure the platform protection meets expectations 
with this new system. If the PCDs were kept, platform creators may try 
updating the PCDs and be confused when the changes are not reflected in 
the state of the system because the PCD profile is not in use. This 
nuance helps identify a confusing interface.




-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108098): https://edk2.groups.io/g/devel/message/108098
Mute This Topic: https://groups.io/mt/100830924/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 00/26] Implement Dynamic Memory Protections

2023-08-30 Thread Taylor Beebe
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 
Cc: Andrei Warkentin 
Cc: Anatol Belski 
Cc: Andrew Fish 
Cc: Anthony Perard 
Cc: Ard Biesheuvel 
Cc: Corvin Köhne 
Cc: Dandan Bi 
Cc: Eric Dong 
Cc: Erdem Aktas 
Cc: Gerd Hoffmann 
Cc: Guo Dong 
Cc: Gua Guo 
Cc: James Bottomley 
Cc: James Lu 
Cc: Jian J Wang 
Cc: Jianyong Wu 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Julien Grall 
Cc: Leif Lindholm 
Cc: Liming Gao 
Cc: Michael Roth 
Cc: Min Xu 
Cc: Peter Grehan 
Cc: Rahul Kumar  
Cc: Ray Ni 
Cc: Rebecca Cran 
Cc: Sami Mujawar 
Cc: Sean Rhodes 
Cc: Sunil V L 
Cc: Tom Lendacky 

Taylor Beebe (26):
  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

[edk2-devel] [PATCH v3 01/26] MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 {
+  BOOLEANEnabled: 1;
+  BOOLEANDisableEndOfDxe: 1;
+  BOOLEANNonstopModeEnabled : 1;
+} DXE_NULL_DETECTION_POLICY;
+
+typedef struct {
+  BOOLEANProtectImageFromUnknown : 1;
+  BOOLEANProtectImageFromFv  : 1;
+} DXE_IMAGE_PROTECTION_POLICY;
+
+typedef struct {
+  BOOLEANPageGuardEnabled: 1;
+  BOOLEANPoolGuardEnabled: 1;
+  BOOLEANFreedMemoryGuardEnabled : 1;
+  BOOLEANNonstopModeEnabled  : 1;
+  BOOLEANGuardAlignedToTail  : 1;
+} DXE_HEAP_GUARD_POLICY;
+
+typedef struct {
+  BOOLEANEnabled: 1;
+  BOOLEANNonstopModeEnabled : 1;
+} MM_NULL_DETECTION_POLICY;
+
+typedef struct {
+  BOOLEANPageGuardEnabled   : 1;
+  BOOLEANPoolGuardEnabled   : 1;
+  BOOLEANNonstopModeEnabled : 1;
+  BOOLEANGuardAlignedToTail : 1;
+} MM_HEAP_GUARD_POLICY;
+
+typedef struct {
+  BOOLEANEnabledForType[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_SIGNATURESignature;
+
+  // 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_POLICYNullPointerDetection;
+
+  // 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 no

[edk2-devel] [PATCH v3 03/26] MdeModulePkg: Add NULL Instances for Get/SetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
The NULL instances for GetMemoryProtectionsLib and
SetMemoryProtectionsLib just zero out the memory protections
structure effectively disabling memory protections.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+#include 
+
+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 ..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 
+#include 
+
+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] DxeMpsPointer 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

[edk2-devel] [PATCH v3 05/26] MdeModulePkg: Copy PEI PCD Database Into New Buffer

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108159): https://edk2.groups.io/g/devel/message/108159
Mute This Topic: https://groups.io/mt/101064077/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 04/26] MdeModulePkg: Implement SetMemoryProtectionsLib and GetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+
+#include 
+#include 
+#include 
+
+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

[edk2-devel] [PATCH v3 06/26] MdeModulePkg: Apply Protections to the HOB List

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108160): https://edk2.groups.io/g/devel/message/108160
Mute This Topic: https://groups.io/mt/101064078/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 07/26] MdeModulePkg: Check Print Level Before Dumping GCD Memory Map

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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;
   UINTNIndex;
 
+  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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108161): https://edk2.groups.io/g/devel/message/108161
Mute This Topic: https://groups.io/mt/101064079/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 08/26] UefiCpuPkg: Always Set Stack Guard in MpPei Init

2023-08-30 Thread Taylor Beebe
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 
Cc: Eric Dong 
Cc: Ray Ni 
Cc: Rahul Kumar  
Cc: Gerd Hoffmann 
---
 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..0ab8c8a6 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_POINTERSHob;
   IA32_CR0Cr0;
@@ -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 
 
 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 

[edk2-devel] [PATCH v3 09/26] ArmVirtPkg: Add Memory Protection Library Definitions to Platforms

2023-08-30 Thread Taylor Beebe
Add library classes for SetMemoryProtectionsLib and
GetMemoryProtectionsLib to ArmVirtPkg.

Signed-off-by: Taylor Beebe 
Cc: Ard Biesheuvel 
Cc: Leif Lindholm 
Cc: Sami Mujawar 
Cc: Gerd Hoffmann 
Cc: Julien Grall 
---
 ArmVirtPkg/ArmVirt.dsc.inc | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/ArmVirtPkg/ArmVirt.dsc.inc b/ArmVirtPkg/ArmVirt.dsc.inc
index 2443e8351c99..6de28d0e0d4e 100644
--- a/ArmVirtPkg/ArmVirt.dsc.inc
+++ b/ArmVirtPkg/ArmVirt.dsc.inc
@@ -156,6 +156,12 @@ [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   RngLib|MdePkg/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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108163): https://edk2.groups.io/g/devel/message/108163
Mute This Topic: https://groups.io/mt/101064081/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 02/26] MdeModulePkg: Define SetMemoryProtectionsLib and GetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+#include 
+
+#pragma pack(1)
+
+typedef union {
+  DXE_MEMORY_PROTECTION_SETTINGSDxe;
+  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   
 ||  \
+   

[edk2-devel] [PATCH v3 10/26] OvmfPkg: Add Memory Protection Library Definitions to Platforms

2023-08-30 Thread Taylor Beebe
Add library classes for SetMemoryProtectionsLib and
GetMemoryProtectionsLib to OvmfPkg platfomrs.

Signed-off-by: Taylor Beebe 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
Cc: Rebecca Cran 
Cc: Peter Grehan 
Cc: Corvin Köhne 
Cc: Jianyong Wu 
Cc: Anatol Belski 
Cc: Anthony Perard 
Cc: Julien Grall 
---
 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 2c6ed7c9745f..0913aa734114 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -202,6 +202,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/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc
index 82c60ace1bbd..c2a3b9bf3960 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 e000deed9e4d..20d609156e7d 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 ..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 80b0558c3f77..7d589d887732 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 d2ef1e00a5c2..1c9b0532599c 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

[edk2-devel] [PATCH v3 11/26] OvmfPkg: Apply Memory Protections via SetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
---
 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 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 #include 
 #include 
@@ -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 
 #include 
 #include 
+#include 
 
 #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
   gUefiOvmfPkgTokenSp

[edk2-devel] [PATCH v3 12/26] OvmfPkg: Update PeilessStartupLib to use SetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
---
 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 
 #include "X64/PageTables.h"
 #include 
+#include 
 
 #define STACK_SIZE  0x2
-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 
 #include 
 #include 
+#include 
 #include 
 #include 
 #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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108166): https://edk2.groups.io/g/devel/message/108166
Mute This Topic: https://groups.io/mt/101064084/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 13/26] UefiPayloadPkg: Update DXE Handoff to use SetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Guo Dong 
Cc: Sean Rhodes 
Cc: James Lu 
Cc: Gua Guo 
---
 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  0x2
 
+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 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
 #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

[edk2-devel] [PATCH v3 14/26] MdeModulePkg: Update DXE Handoff to use SetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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;
   UINTNGhcbSize;
 
+  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

[edk2-devel] [PATCH v3 15/26] ArmPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-30 Thread Taylor Beebe
Replace references to the memory protection PCDs to instead
check the platform protections via GetMemoryProtectionsLib.

Signed-off-by: Taylor Beebe 
Cc: Leif Lindholm 
Cc: Ard Biesheuvel 
Cc: Sami Mujawar 
---
 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 
 
 #include 
+#include 
 
 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 4939b3d59b7f..354535eb3718 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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108169): https://edk2.groups.io/g/devel/message/108169
Mute This Topic: https://groups.io/mt/101064089/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 16/26] EmulatorPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-30 Thread Taylor Beebe
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 
Cc: Andrew Fish 
Cc: Ray Ni 
---
 EmulatorPkg/EmulatorPkg.dsc | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/EmulatorPkg/EmulatorPkg.dsc b/EmulatorPkg/EmulatorPkg.dsc
index b44435d7e6ee..1e2c903f5c30 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|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
@@ -216,7 +218,6 @@ [PcdsFeatureFlag]
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplBuildPageTables|FALSE
 
 [PcdsFixedAtBuild]
-  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy|0x
   gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE
   gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8040
   gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x0f
-- 
2.42.0.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108170): https://edk2.groups.io/g/devel/message/108170
Mute This Topic: https://groups.io/mt/101064090/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 17/26] OvmfPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-30 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
Cc: Leif Lindholm 
Cc: Abner Chang 
---
 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 
 #include 
 #include 
+#include 
 
 #include 
 #include 
@@ -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 
 #include 
 #include 
+#include 
 #include 
 
 #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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108171): https://edk2.groups.io/g/devel/message/108171
Mute This Topic: https://groups.io/mt/101064091/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 18/26] UefiCpuPkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-30 Thread Taylor Beebe
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 
Cc: Eric Dong 
Cc: Ray Ni 
Cc: Rahul Kumar 
Cc: Gerd Hoffmann 
---
 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 Servic

[edk2-devel] [PATCH v3 19/26] MdeModulePkg: Use GetMemoryProtectionsLib instead of Memory Protection PCDs

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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

[edk2-devel] [PATCH v3 20/26] MdeModulePkg: Add Additional Profiles to SetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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..40d4f3081133 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 = FALSE   \
+  },  \
+  { /* 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

[edk2-devel] [PATCH v3 21/26] OvmfPkg: Enable Choosing Memory Protection Profile via QemuCfg

2023-08-30 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
Cc: Rebecca Cran 
Cc: Peter Grehan 
Cc: Corvin Köhne 
---
 .../PeilessStartupLib/PeilessStartup.c| 60 +--
 .../PeilessStartupLib/X64/VirtualMemory.c | 13 +---
 OvmfPkg/Library/PlatformInitLib/Platform.c| 15 
 .../QemuFwCfgSimpleParser.c   | 11 +++
 OvmfPkg/PlatformPei/IntelTdx.c|  2 -
 OvmfPkg/PlatformPei/Platform.c| 74 +--
 OvmfPkg/TdxDxe/TdxDxe.c   |  7 +-
 OvmfPkg/Bhyve/PlatformPei/PlatformPei.inf |  1 -
 OvmfPkg/Include/Library/PlatformInitLib.h | 13 
 .../Library/QemuFwCfgSimpleParserLib.h|  8 ++
 .../PeilessStartupLib/PeilessStartupLib.inf   |  1 -
 OvmfPkg/PlatformCI/PlatformBuildLib.py|  8 ++
 OvmfPkg/PlatformPei/PlatformPei.inf   |  1 -
 OvmfPkg/TdxDxe/TdxDxe.inf |  1 -
 14 files changed, 135 insertions(+), 80 deletions(-)

diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c 
b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
index cf645aad3246..8626b00da964 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
@@ -28,6 +28,12 @@
 
 #define GET_GPAW_INIT_STATE(INFO)  ((UINT8) ((INFO) & 0x3f))
 
+#define DXE_MEMORY_PROTECTION_PROFILE_FWCFG_FILE \
+  "opt/org.tianocore/DxeMemoryProtectionProfile"
+
+#define MM_MEMORY_PROTECTION_PROFILE_FWCFG_FILE \
+  "opt/org.tianocore/MmMemoryProtectionProfile"
+
 EFI_MEMORY_TYPE_INFORMATION  mDefaultMemoryTypeInformation[] = {
   { EfiACPIMemoryNVS,   0x004 },
   { EfiACPIReclaimMemory,   0x008 },
@@ -48,6 +54,10 @@ InitializePlatform (
   VOID*VariableStore;
   DXE_MEMORY_PROTECTION_SETTINGS  DxeSettings;
   MM_MEMORY_PROTECTION_SETTINGS   MmSettings;
+  CHAR8   String[100];
+  UINTN   StringSize;
+  EFI_STATUS  Status;
+  UINTN   Index;
 
   DEBUG ((DEBUG_INFO, "InitializePlatform in Pei-less boot\n"));
   PlatformDebugDumpCmos ();
@@ -109,18 +119,54 @@ InitializePlatform (
 
   PlatformMemMapInitialization (PlatformInfoHob);
 
-  DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsPcd].Settings;
-  MmSettings  = 
MmMemoryProtectionProfiles[MmMemoryProtectionSettingsPcd].Settings;
-  DxeSettings.StackExecutionProtectionEnabled = PcdGetBool (PcdSetNxForStack);
-  QemuFwCfgParseBool ("opt/ovmf/PcdSetNxForStack", 
&DxeSettings.StackExecutionProtectionEnabled);
+  StringSize = sizeof (String);
+  Status = QemuFwCfgParseString (DXE_MEMORY_PROTECTION_PROFILE_FWCFG_FILE, 
&StringSize, String);
+  if (!EFI_ERROR (Status)) {
+Index = 0;
+do {
+  if (AsciiStriCmp (DxeMemoryProtectionProfiles[Index].Name, String) == 0) 
{
+DEBUG ((DEBUG_INFO, "Setting DXE Memory Protection Profile: %a\n", 
String));
+DxeSettings = DxeMemoryProtectionProfiles[Index].Settings;
+break;
+  }
+} while (++Index < DxeMemoryProtectionSettingsMax);
 
-  SetDxeMemoryProtectionSettings (&DxeSettings, 
DxeMemoryProtectionSettingsPcd);
-  SetMmMemoryProtectionSettings (&MmSettings, MmMemoryProtectionSettingsPcd);
+if (Index >= DxeMemoryProtectionSettingsMax) {
+  DEBUG ((DEBUG_ERROR, "Invalid DXE memory protection profile: %a\n", 
String));
+  ASSERT (Index < DxeMemoryProtectionSettingsMax);
+}
+  } else {
+DxeSettings = 
DxeMemoryProtectionProfiles[DxeMemoryProtectionSettingsRelease].Settings;
+  }
+
+  Status = QemuFwCfgParseString (MM_MEMORY_PROTECTION_PROFILE_FWCFG_FILE, 
&StringSize, String);
+  if (!EFI_ERROR (Status)) {
+Index = 0;
+do {
+  if (AsciiStriCmp (MmMemoryProtectionProfiles[Index].Name, String) == 0) {
+DEBUG ((DEBUG_INFO, "Setting MM Memory Protection Profile: %a\n", 
String));
+MmSettings = MmMemoryProtectionProfiles[Index].Settings;
+break;
+  }
+} while (++Index < MmMemoryProtectionSettingsMax);
+
+if (Index >= MmMemoryProtectionSettingsMax

[edk2-devel] [PATCH v3 22/26] ArmVirtPkg: Apply Memory Protections via SetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Leif Lindholm 
Cc: Sami Mujawar 
Cc: Gerd Hoffmann 
---
 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 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108176): https://edk2.groups.io/g/devel/message/108176
Mute This Topic: https://groups.io/mt/101064097/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 23/26] MdeModulePkg: Delete PCD Profile from SetMemoryProtectionsLib

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 40d4f3081133..dffc7f0eea5d 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 
 #include 
 #include 
-#include 
 #include 
 
 #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),\
- 

[edk2-devel] [PATCH v3 24/26] OvmfPkg: Delete Memory Protection PCDs

2023-08-30 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Gerd Hoffmann 
Cc: Rebecca Cran 
Cc: Peter Grehan 
Cc: Corvin Köhne 
Cc: Jianyong Wu 
Cc: Anatol Belski 
Cc: Anthony Perard 
Cc: Julien Grall 
Cc: Erdem Aktas 
Cc: James Bottomley 
Cc: Min Xu 
Cc: Tom Lendacky 
Cc: Michael Roth 
Cc: Sunil V L 
Cc: Andrei Warkentin 
---
 OvmfPkg/AmdSev/AmdSevX64.dsc|  3 ---
 OvmfPkg/Bhyve/BhyveX64.dsc  |  3 ---
 OvmfPkg/CloudHv/CloudHvX64.dsc  |  3 ---
 OvmfPkg/IntelTdx/IntelTdxX64.dsc|  3 ---
 OvmfPkg/Microvm/MicrovmX64.dsc  |  3 ---
 OvmfPkg/OvmfPkgIa32.dsc |  3 ---
 OvmfPkg/OvmfPkgIa32X64.dsc  |  3 ---
 OvmfPkg/OvmfPkgX64.dsc  |  3 ---
 OvmfPkg/OvmfXen.dsc |  3 ---
 OvmfPkg/RiscVVirt/RiscVVirt.dsc.inc | 13 -
 10 files changed, 40 deletions(-)

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index 0913aa734114..2e2e320c61fb 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -507,9 +507,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 c2a3b9bf3960..30f0e27ea840 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|5
diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc
index 20d609156e7d..ecf723b20439 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 7d589d887732..7406eefbc156 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/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index 1c9b0532599c..f0573fcc12ca 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 8267cf20e4a9..ced2fd724954 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

[edk2-devel] [PATCH v3 25/26] ArmVirtPkg: Delete Memory Protection PCDs

2023-08-30 Thread Taylor Beebe
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 
Cc: Ard Biesheuvel 
Cc: Leif Lindholm 
Cc: Sami Mujawar 
Cc: Gerd Hoffmann 
---
 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 6de28d0e0d4e..2df479331ae6 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|0xC0007FD5
-
-  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard|TRUE
-
 [Components.common]
   #
   # Ramdisk support
diff --git a/ArmVirtPkg/ArmVirtCloudHv.dsc b/ArmVirtPkg/ArmVirtCloudHv.dsc
index c975e139a216..c4c3e0da4491 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 1e0225951aef..214e08b789eb 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.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#108179): https://edk2.groups.io/g/devel/message/108179
Mute This Topic: https://groups.io/mt/101064100/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v3 26/26] MdeModulePkg: Delete Memory Protection PCDs

2023-08-30 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 MdeModulePkg/MdeModulePkg.dec | 169 
 MdeModulePkg/MdeModulePkg.uni | 153 --
 2 files changed, 322 deletions(-)

diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index 50c26fedaf6f..c701173b9803 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -1004,119 +1004,12 @@ [PcdsFixedAtBuild]
   # @ValidList  0x8006 | 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.
-  #BIT0- Enable NULL pointer detection for UEFI.
-  #BIT1- Enable NULL pointer detection for SMM.
-  #BIT2..5 - Reserved for future uses.
-  #BIT6- Enable non-stop mode.
-  #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.
-  # @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)
-  #  EfiReservedMemoryType 0x0001
-  #  EfiLoaderCode 0x0002
-  #  EfiLoaderData 0x0004
-  #  EfiBootServicesCode   0x0008
-  #  EfiBootServicesData   0x0010
-  #  EfiRuntimeServicesCode0x0020
-  #  EfiRuntimeServicesData0x0040
-  #  EfiConventionalMemory 0x0080
-  #  EfiUnusableMemory 0x0100
-  #  EfiACPIReclaimMemory  0x0200
-  #  EfiACPIMemoryNVS  0x0400
-  #  EfiMemoryMappedIO 0x0800
-  #  EfiMemoryMappedIOPortSpace0x1000
-  #  EfiPalCode0x2000
-  #  EfiPersistentMemory   0x4000
-  #  OEM Reserved  0x4000
-  #  OS Reserved   0x8000
-  # e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 
0x1E should be used.
-  # @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)
-  #  EfiReservedMemoryType 0x0001
-  #  EfiLoaderCode 0x0002
-  #  EfiLoaderData 0x0004
-  #  EfiBootServicesCode   0x0008
-  #  EfiBootServicesData   0x0010
-  #  EfiRuntimeServicesCode0x0020
-  #  EfiRuntimeServicesData0x0040
-  #  EfiConventionalMemory 0x0080
-  #  EfiUnusableMemory 0x0100
-  #  EfiACPIReclaimMemory  0x0200
-  #  EfiACPIMemoryNVS  0x0400
-  #  EfiMemo

[edk2-devel] [PATCH v4 00/28] Implement Dynamic Memory Protection Settings

2023-09-19 Thread Taylor Beebe
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 
Cc: Andrei Warkentin 
Cc: Anatol Belski 
Cc: Andrew Fish 
Cc: Anthony Perard 
Cc: Ard Biesheuvel 
Cc: Corvin Köhne 
Cc: Dandan Bi 
Cc: Eric Dong 
Cc: Erdem Aktas 
Cc: Gerd Hoffmann 
Cc: Guo Dong 
Cc: Gua Guo 
Cc: James Bottomley 
Cc: James Lu 
Cc: Jian J Wang 
Cc: Jianyong Wu 
Cc: Jiewen Yao 
Cc: Jordan Justen 
Cc: Julien Grall 
Cc: Leif Lindholm 
Cc: Liming Gao 
Cc: Michael Roth 
Cc: Min Xu 
Cc: Peter Grehan 
Cc: Rahul Kumar  
Cc: Ray Ni 
Cc: Rebecca Cran 
Cc: Sami Mujawar 
Cc: Sean Rhodes 
Cc: Sunil V L 
Cc: Tom Lendacky 

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

[edk2-devel] [PATCH v4 01/28] MdeModulePkg: Add DXE and MM Memory Protection Settings Definitions

2023-09-19 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 {
+  BOOLEANEnabled: 1;
+  BOOLEANDisableEndOfDxe: 1;
+  BOOLEANNonstopModeEnabled : 1;
+} DXE_NULL_DETECTION_POLICY;
+
+typedef struct {
+  BOOLEANProtectImageFromUnknown : 1;
+  BOOLEANProtectImageFromFv  : 1;
+} DXE_IMAGE_PROTECTION_POLICY;
+
+typedef struct {
+  BOOLEANPageGuardEnabled: 1;
+  BOOLEANPoolGuardEnabled: 1;
+  BOOLEANFreedMemoryGuardEnabled : 1;
+  BOOLEANNonstopModeEnabled  : 1;
+  BOOLEANGuardAlignedToTail  : 1;
+} DXE_HEAP_GUARD_POLICY;
+
+typedef struct {
+  BOOLEANEnabled: 1;
+  BOOLEANNonstopModeEnabled : 1;
+} MM_NULL_DETECTION_POLICY;
+
+typedef struct {
+  BOOLEANPageGuardEnabled   : 1;
+  BOOLEANPoolGuardEnabled   : 1;
+  BOOLEANNonstopModeEnabled : 1;
+  BOOLEANGuardAlignedToTail : 1;
+} MM_HEAP_GUARD_POLICY;
+
+typedef struct {
+  BOOLEANEnabledForType[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_SIGNATURESignature;
+
+  // 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_POLICYNullPointerDetection;
+
+  // 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 no

[edk2-devel] [PATCH v4 02/28] MdeModulePkg: Define SetMemoryProtectionsLib and GetMemoryProtectionsLib

2023-09-19 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+#include 
+
+#pragma pack(1)
+
+typedef union {
+  DXE_MEMORY_PROTECTION_SETTINGSDxe;
+  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   
 ||  \
+   

[edk2-devel] [PATCH v4 03/28] MdeModulePkg: Add NULL Instances for Get/SetMemoryProtectionsLib

2023-09-19 Thread Taylor Beebe
The NULL instances for GetMemoryProtectionsLib and
SetMemoryProtectionsLib just zero out the memory protections
structure effectively disabling memory protections.

Signed-off-by: Taylor Beebe 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+#include 
+
+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 ..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 
+#include 
+
+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] DxeMpsPointer 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

[edk2-devel] [PATCH v4 05/28] MdeModulePkg: Copy PEI PCD Database Into New Buffer

2023-09-19 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
Cc: Dandan Bi 
---
 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/21656
Group Owner: devel+ow...@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [arch...@mail-archive.com]
-=-=-=-=-=-=-=-=-=-=-=-




[edk2-devel] [PATCH v4 04/28] MdeModulePkg: Implement SetMemoryProtectionsLib and GetMemoryProtectionsLib

2023-09-19 Thread Taylor Beebe
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 
Cc: Jian J Wang 
Cc: Liming Gao 
---
 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 ..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 
+
+#include 
+#include 
+#include 
+
+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

  1   2   3   >