Date   

[edk2-platforms][PATCH v3 13/41] SimicsOpenBoardPkg: Use IntelSiliconPkg BIOS area and ucode PCDs

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Updates PCDs to use the IntelSiliconPkg PCD tokenspace now that the
PCDs are declared in IntelSiliconPkg.dec.

Cc: Agyeman Prince <prince.agyeman@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Platform/Intel/SimicsOpenBoardPkg/BoardX58Ich10/OpenBoardPkg.fdf.inc | 8=
++++----
1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/Platform/Intel/SimicsOpenBoardPkg/BoardX58Ich10/OpenBoardPkg=
.fdf.inc b/Platform/Intel/SimicsOpenBoardPkg/BoardX58Ich10/OpenBoardPkg.f=
df.inc
index 9c2436c3ad38..69a566307551 100644
--- a/Platform/Intel/SimicsOpenBoardPkg/BoardX58Ich10/OpenBoardPkg.fdf.in=
c
+++ b/Platform/Intel/SimicsOpenBoardPkg/BoardX58Ich10/OpenBoardPkg.fdf.in=
c
@@ -45,10 +45,10 @@
SET gSimicsOpenBoardPkgTokenSpaceGuid.PcdSimicsFlashNvStorageFtwSpareBas=
e =3D gSimicsOpenBoardPkgTokenSpaceGuid.PcdSimicsFlashNvStorageFtwWorking=
Base + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
SET gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize =3D 0x1=
0000
=20
-SET gEfiPchTokenSpaceGuid.PcdFlashAreaBaseAddress =3D 0xFFE00000
-SET gEfiPchTokenSpaceGuid.PcdFlashAreaSize =3D 0x00200000
+SET gIntelSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress =3D $(FW_BASE_=
ADDRESS)
+SET gIntelSiliconPkgTokenSpaceGuid.PcdBiosSize =3D $(FW_SIZE)
=20
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaBaseAddress =3D gEfiPchTok=
enSpaceGuid.PcdFlashAreaBaseAddress
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaSize =3D gEfiPchTokenSpace=
Guid.PcdFlashAreaSize
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaBaseAddress =3D gIntelSili=
conPkgTokenSpaceGuid.PcdBiosAreaBaseAddress
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaSize =3D gIntelSiliconPkgT=
okenSpaceGuid.PcdBiosSize
=20
DEFINE MEMFD_BASE_ADDRESS =3D 0x800000
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 12/41] KabylakeOpenBoardPkg: Use IntelSiliconPkg BIOS area and ucode PCDs

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Updates PCDs to use the IntelSiliconPkg PCD tokenspace now that the
PCDs are declared in IntelSiliconPkg.dec.

Cc: Chasel Chiu <chasel.chiu@intel.com>
Cc: Nate DeSimone <nathaniel.l.desimone@intel.com>
Cc: Jeremy Soller <jeremy@system76.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Platform/Intel/KabylakeOpenBoardPkg/BiosInfo/BiosInfo.inf =
| 4 +--
Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/Include/Fdf/FlashMapInclu=
de.fdf | 4 +--
Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/OpenBoardPkg.fdf =
| 38 ++++++++++----------
Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Include/Fdf/FlashMapInc=
lude.fdf | 4 +--
Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/OpenBoardPkg.fdf =
| 38 ++++++++++----------
Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Policy/Library/PeiSilic=
onPolicyUpdateLib/PeiSiliconPolicyUpdateLib.inf | 4 +--
6 files changed, 46 insertions(+), 46 deletions(-)

diff --git a/Platform/Intel/KabylakeOpenBoardPkg/BiosInfo/BiosInfo.inf b/=
Platform/Intel/KabylakeOpenBoardPkg/BiosInfo/BiosInfo.inf
index e5e40144a68a..6607ea6edfc3 100644
--- a/Platform/Intel/KabylakeOpenBoardPkg/BiosInfo/BiosInfo.inf
+++ b/Platform/Intel/KabylakeOpenBoardPkg/BiosInfo/BiosInfo.inf
@@ -36,8 +36,8 @@ [Packages]
MinPlatformPkg/MinPlatformPkg.dec
=20
[Pcd]
- gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase ## CON=
SUMES
- gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize ## CON=
SUMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =
## CONSUMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =
## CONSUMES
=20
[Sources]
BiosInfo.c
diff --git a/Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/Include/Fdf/F=
lashMapInclude.fdf b/Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/Inclu=
de/Fdf/FlashMapInclude.fdf
index 6cb6d54f558f..ce809a277b6e 100644
--- a/Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/Include/Fdf/FlashMap=
Include.fdf
+++ b/Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/Include/Fdf/FlashMap=
Include.fdf
@@ -36,8 +36,8 @@
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvUefiBootSize =3D =
0x00140000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemoryOffset =3D =
0x002E0000 # Flash addr (0xFFD00000)
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemorySize =3D =
0x000B0000 #
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset =3D =
0x00390000 # Flash addr (0xFFDB0000)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D =
0x000A0000 #
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset =3D =
0x00390000 # Flash addr (0xFFDB0000)
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D =
0x000A0000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspSOffset =3D =
0x00430000 # Flash addr (0xFFE50000)
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspSSize =3D =
0x00060000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspMOffset =3D =
0x00490000 # Flash addr (0xFFEB0000)
diff --git a/Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/OpenBoardPkg.=
fdf b/Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/OpenBoardPkg.fdf
index bcd1ade72ba5..39432d21b8b5 100644
--- a/Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/OpenBoardPkg.fdf
+++ b/Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/OpenBoardPkg.fdf
@@ -29,8 +29,8 @@ [FD.GalagoPro3]
# assigned with PCD values. Instead, it uses the definitions for its var=
iety, which
# are FLASH_BASE, FLASH_SIZE, FLASH_BLOCK_SIZE and FLASH_NUM_BLOCKS.
#
-BaseAddress =3D $(FLASH_BASE) | gSiPkgTokenSpaceGuid.PcdFlashAreaBaseA=
ddress #The base address of the FLASH Device.
-Size =3D $(FLASH_SIZE) | gSiPkgTokenSpaceGuid.PcdFlashAreaSize =
#The size in bytes of the FLASH Device
+BaseAddress =3D $(FLASH_BASE) | gIntelSiliconPkgTokenSpaceGuid.PcdBios=
AreaBaseAddress #The base address of the FLASH Device.
+Size =3D $(FLASH_SIZE) | gIntelSiliconPkgTokenSpaceGuid.PcdBios=
Size #The size in bytes of the FLASH Device
ErasePolarity =3D 1
BlockSize =3D $(FLASH_BLOCK_SIZE)
NumBlocks =3D $(FLASH_NUM_BLOCKS)
@@ -39,23 +39,23 @@ [FD.GalagoPro3]
DEFINE SIPKG_PEI_BIN =3D INF
=20
# Set FLASH_REGION_FV_RECOVERY_OFFSET to PcdNemCodeCacheBase, because ma=
cro expression is not supported.
-# So, PlatformSecLib uses PcdFlashAreaBaseAddress + PcdNemCodeCacheBase =
to get the real CodeCache base address.
+# So, PlatformSecLib uses PcdBiosAreaBaseAddress + PcdNemCodeCacheBase t=
o get the real CodeCache base address.
SET gSiPkgTokenSpaceGuid.PcdNemCodeCacheBase =3D $(gMinPlatformPkgTokenS=
paceGuid.PcdFlashFvPreMemoryOffset)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =3D $(gSiPkgTokenSpaceG=
uid.PcdFlashAreaBaseAddress) + $(gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFv=
Offset)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D $(gSiPkgTokenSpaceG=
uid.PcdFlashMicrocodeFvSize)
-SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress =3D $(gSiPkgTo=
kenSpaceGuid.PcdFlashMicrocodeFvBase) + 0x60
-SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashMicrocodeFvSize) - 0x60
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =3D $(gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gIntelSiliconPkgToken=
SpaceGuid.PcdFlashMicrocodeFvOffset)
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D $(gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize)
+SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress =3D $(gIntelSi=
liconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase) + 0x60
+SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize) - 0x60
SET gMinPlatformPkgTokenSpaceGuid.PcdMicrocodeOffsetInFv =3D 0x60
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeBase =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvBase
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeSize =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvSize
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeOffset =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvOffset
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheAddress =3D gSiPkgT=
okenSpaceGuid.PcdFlashAreaBaseAddress
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheSize =3D gSiPkgT=
okenSpaceGuid.PcdFlashAreaSize
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFsptBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGui=
d.PcdFlashFvFspTOffset)
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspmBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGui=
d.PcdFlashFvFspMOffset)
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspsBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGui=
d.PcdFlashFvFspSOffset)
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaBaseAddress =3D gSiPkgT=
okenSpaceGuid.PcdFlashAreaBaseAddress
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaSize =3D gSiPkgT=
okenSpaceGuid.PcdFlashAreaSize
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeBase =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeOffset =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheAddress =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosSize
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFsptBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspTOffset)
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspmBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspMOffset)
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspsBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspSOffset)
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaBaseAddress =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosSize
########################################################################=
########
#
# Following are lists of FD Region layout which correspond to the locati=
ons of different
@@ -155,8 +155,8 @@ [FD.GalagoPro3]
gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemoryBase|gMinPlatformPkgTo=
kenSpaceGuid.PcdFlashFvPostMemorySize
FV =3D FvPostMemory
=20
-gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset|gSiPkgTokenSpaceGuid.PcdF=
lashMicrocodeFvSize
-gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase|gSiPkgTokenSpaceGuid.PcdFla=
shMicrocodeFvSize
+gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset|gIntelSiliconPk=
gTokenSpaceGuid.PcdFlashMicrocodeFvSize
+gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase|gIntelSiliconPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvSize
#Microcode
FV =3D FvMicrocode
=20
diff --git a/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Include/Fdf=
/FlashMapInclude.fdf b/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/I=
nclude/Fdf/FlashMapInclude.fdf
index b5e3f66ceafc..67649e867616 100644
--- a/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Include/Fdf/FlashM=
apInclude.fdf
+++ b/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Include/Fdf/FlashM=
apInclude.fdf
@@ -34,8 +34,8 @@
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvUefiBootSize =3D =
0x001E0000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemoryOffset =3D =
0x00370000 # Flash addr (0xFFB70000)
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemorySize =3D =
0x00180000 #
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset =3D =
0x004F0000 # Flash addr (0xFFCF0000)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D =
0x000A0000 #
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset =3D =
0x004F0000 # Flash addr (0xFFCF0000)
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D =
0x000A0000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspSOffset =3D =
0x00590000 # Flash addr (0xFFD90000)
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspSSize =3D =
0x00060000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspMOffset =3D =
0x005F0000 # Flash addr (0xFFDF0000)
diff --git a/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/OpenBoardPk=
g.fdf b/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/OpenBoardPkg.fdf
index 6cdf4e2f9f1f..f003dda0ddfc 100644
--- a/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/OpenBoardPkg.fdf
+++ b/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/OpenBoardPkg.fdf
@@ -29,8 +29,8 @@ [FD.KabylakeRvp3]
# assigned with PCD values. Instead, it uses the definitions for its var=
iety, which
# are FLASH_BASE, FLASH_SIZE, FLASH_BLOCK_SIZE and FLASH_NUM_BLOCKS.
#
-BaseAddress =3D $(FLASH_BASE) | gSiPkgTokenSpaceGuid.PcdFlashAreaBaseA=
ddress #The base address of the FLASH Device.
-Size =3D $(FLASH_SIZE) | gSiPkgTokenSpaceGuid.PcdFlashAreaSize =
#The size in bytes of the FLASH Device
+BaseAddress =3D $(FLASH_BASE) | gIntelSiliconPkgTokenSpaceGuid.PcdBios=
AreaBaseAddress #The base address of the FLASH Device.
+Size =3D $(FLASH_SIZE) | gIntelSiliconPkgTokenSpaceGuid.PcdBios=
Size #The size in bytes of the FLASH Device
ErasePolarity =3D 1
BlockSize =3D $(FLASH_BLOCK_SIZE)
NumBlocks =3D $(FLASH_NUM_BLOCKS)
@@ -39,23 +39,23 @@ [FD.KabylakeRvp3]
DEFINE SIPKG_PEI_BIN =3D INF
=20
# Set FLASH_REGION_FV_RECOVERY_OFFSET to PcdNemCodeCacheBase, because ma=
cro expression is not supported.
-# So, PlatformSecLib uses PcdFlashAreaBaseAddress + PcdNemCodeCacheBase =
to get the real CodeCache base address.
+# So, PlatformSecLib uses PcdBiosAreaBaseAddress + PcdNemCodeCacheBase t=
o get the real CodeCache base address.
SET gSiPkgTokenSpaceGuid.PcdNemCodeCacheBase =3D $(gMinPlatformPkgTokenS=
paceGuid.PcdFlashFvPreMemoryOffset)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =3D $(gSiPkgTokenSpaceG=
uid.PcdFlashAreaBaseAddress) + $(gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFv=
Offset)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D $(gSiPkgTokenSpaceG=
uid.PcdFlashMicrocodeFvSize)
-SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress =3D $(gSiPkgTo=
kenSpaceGuid.PcdFlashMicrocodeFvBase) + 0x60
-SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashMicrocodeFvSize) - 0x60
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =3D $(gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gIntelSiliconPkgToken=
SpaceGuid.PcdFlashMicrocodeFvOffset)
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D $(gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize)
+SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress =3D $(gIntelSi=
liconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase) + 0x60
+SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize) - 0x60
SET gMinPlatformPkgTokenSpaceGuid.PcdMicrocodeOffsetInFv =3D 0x60
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeBase =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvBase
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeSize =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvSize
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeOffset =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvOffset
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheAddress =3D gSiPkgT=
okenSpaceGuid.PcdFlashAreaBaseAddress
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheSize =3D gSiPkgT=
okenSpaceGuid.PcdFlashAreaSize
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFsptBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGui=
d.PcdFlashFvFspTOffset)
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspmBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGui=
d.PcdFlashFvFspMOffset)
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspsBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGui=
d.PcdFlashFvFspSOffset)
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaBaseAddress =3D gSiPkgT=
okenSpaceGuid.PcdFlashAreaBaseAddress
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaSize =3D gSiPkgT=
okenSpaceGuid.PcdFlashAreaSize
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeBase =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeOffset =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheAddress =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosSize
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFsptBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspTOffset)
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspmBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspMOffset)
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspsBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspSOffset)
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaBaseAddress =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosSize
########################################################################=
########
#
# Following are lists of FD Region layout which correspond to the locati=
ons of different
@@ -151,8 +151,8 @@ [FD.KabylakeRvp3]
gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemoryBase|gMinPlatformPkgTo=
kenSpaceGuid.PcdFlashFvPostMemorySize
FV =3D FvPostMemory
=20
-gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset|gSiPkgTokenSpaceGuid.PcdF=
lashMicrocodeFvSize
-gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase|gSiPkgTokenSpaceGuid.PcdFla=
shMicrocodeFvSize
+gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset|gIntelSiliconPk=
gTokenSpaceGuid.PcdFlashMicrocodeFvSize
+gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase|gIntelSiliconPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvSize
#Microcode
FV =3D FvMicrocode
=20
diff --git a/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Policy/Libr=
ary/PeiSiliconPolicyUpdateLib/PeiSiliconPolicyUpdateLib.inf b/Platform/In=
tel/KabylakeOpenBoardPkg/KabylakeRvp3/Policy/Library/PeiSiliconPolicyUpda=
teLib/PeiSiliconPolicyUpdateLib.inf
index 97ec70f611b1..8a99f7c59a49 100644
--- a/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Policy/Library/Pei=
SiliconPolicyUpdateLib/PeiSiliconPolicyUpdateLib.inf
+++ b/Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Policy/Library/Pei=
SiliconPolicyUpdateLib/PeiSiliconPolicyUpdateLib.inf
@@ -52,8 +52,8 @@ [Guids]
=20
[Pcd]
gSiPkgTokenSpaceGuid.PcdPeiMinMemorySize
- gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase
- gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize
gKabylakeOpenBoardPkgTokenSpaceGuid.PcdGraphicsVbtGuid
gKabylakeOpenBoardPkgTokenSpaceGuid.PcdMrcRcompResistor ## CONSU=
MES
gKabylakeOpenBoardPkgTokenSpaceGuid.PcdMrcRcompTarget ## CONSU=
MES
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 11/41] CometlakeOpenBoardPkg: Use IntelSiliconPkg BIOS area and ucode PCDs

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Updates PCDs to use the IntelSiliconPkg PCD tokenspace now that the
PCDs are declared in IntelSiliconPkg.dec.

Cc: Chasel Chiu <chasel.chiu@intel.com>
Cc: Nate DeSimone <nathaniel.l.desimone@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Cc: Deepika Kethi Reddy <deepika.kethi.reddy@intel.com>
Cc: Kathappan Esakkithevar <kathappan.esakkithevar@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Platform/Intel/CometlakeOpenBoardPkg/BiosInfo/BiosInfo.inf =
| 4 +--
Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/Include/Fdf/FlashMapI=
nclude.fdf | 4 +--
Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/OpenBoardPkg.fdf =
| 36 ++++++++++----------
Platform/Intel/CometlakeOpenBoardPkg/Policy/PolicyInitDxe/PolicyInitDxe.=
inf | 4 +--
4 files changed, 24 insertions(+), 24 deletions(-)

diff --git a/Platform/Intel/CometlakeOpenBoardPkg/BiosInfo/BiosInfo.inf b=
/Platform/Intel/CometlakeOpenBoardPkg/BiosInfo/BiosInfo.inf
index 9208aeda5d2a..6ca0ada751f6 100644
--- a/Platform/Intel/CometlakeOpenBoardPkg/BiosInfo/BiosInfo.inf
+++ b/Platform/Intel/CometlakeOpenBoardPkg/BiosInfo/BiosInfo.inf
@@ -36,8 +36,8 @@ [Packages]
MinPlatformPkg/MinPlatformPkg.dec
=20
[Pcd]
- gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase ## CON=
SUMES
- gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize ## CON=
SUMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase ## CON=
SUMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize ## CON=
SUMES
=20
[Sources]
BiosInfo.c
diff --git a/Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/Include/F=
df/FlashMapInclude.fdf b/Platform/Intel/CometlakeOpenBoardPkg/CometlakeUR=
vp/Include/Fdf/FlashMapInclude.fdf
index d9959a79d0bb..7d2f4b2c0cb2 100644
--- a/Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/Include/Fdf/Flas=
hMapInclude.fdf
+++ b/Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/Include/Fdf/Flas=
hMapInclude.fdf
@@ -34,8 +34,8 @@
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvUefiBootSize =3D =
0x00190000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemoryOffset =3D =
0x00320000 # Flash addr (0xFFB20000)
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemorySize =3D =
0x00170000 #
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset =3D =
0x00490000 # Flash addr (0xFFC90000)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D =
0x000B0000 #
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset =3D =
0x00490000 # Flash addr (0xFFC90000)
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D =
0x000B0000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspSOffset =3D =
0x00540000 # Flash addr (0xFFD40000)
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspSSize =3D =
0x00070000 #
SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvFspMOffset =3D =
0x005B0000 # Flash addr (0xFFDB0000)
diff --git a/Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/OpenBoard=
Pkg.fdf b/Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/OpenBoardPkg=
.fdf
index 795cc0da75d8..6397d80d3895 100644
--- a/Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/OpenBoardPkg.fdf
+++ b/Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/OpenBoardPkg.fdf
@@ -31,8 +31,8 @@ [FD.CometlakeURvp]
# assigned with PCD values. Instead, it uses the definitions for its var=
iety, which
# are FLASH_BASE, FLASH_SIZE, FLASH_BLOCK_SIZE and FLASH_NUM_BLOCKS.
#
-BaseAddress =3D $(FLASH_BASE) | gSiPkgTokenSpaceGuid.PcdBiosAreaBaseAd=
dress #The base address of the FLASH Device.
-Size =3D $(FLASH_SIZE) | gSiPkgTokenSpaceGuid.PcdBiosSize =
#The size in bytes of the FLASH Device
+BaseAddress =3D $(FLASH_BASE) | gIntelSiliconPkgTokenSpaceGuid.PcdBios=
AreaBaseAddress #The base address of the FLASH Device.
+Size =3D $(FLASH_SIZE) | gIntelSiliconPkgTokenSpaceGuid.PcdBios=
Size #The size in bytes of the FLASH Device
ErasePolarity =3D 1
BlockSize =3D $(FLASH_BLOCK_SIZE)
NumBlocks =3D $(FLASH_NUM_BLOCKS)
@@ -43,21 +43,21 @@ [FD.CometlakeURvp]
# Set FLASH_REGION_FV_RECOVERY_OFFSET to PcdNemCodeCacheBase, because ma=
cro expression is not supported.
# So, PlatformSecLib uses PcdBiosAreaBaseAddress + PcdNemCodeCacheBase t=
o get the real CodeCache base address.
SET gSiPkgTokenSpaceGuid.PcdNemCodeCacheBase =3D $(gMinPlatformPkgTokenS=
paceGuid.PcdFlashFvPreMemoryOffset)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =3D $(gSiPkgTokenSpaceG=
uid.PcdBiosAreaBaseAddress) + $(gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvO=
ffset)
-SET gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D $(gSiPkgTokenSpaceG=
uid.PcdFlashMicrocodeFvSize)
-SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress =3D $(gSiPkgTo=
kenSpaceGuid.PcdFlashMicrocodeFvBase) + 0x60
-SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize =3D $(gSiPk=
gTokenSpaceGuid.PcdFlashMicrocodeFvSize) - 0x60
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =3D $(gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gIntelSiliconPkgToken=
SpaceGuid.PcdFlashMicrocodeFvOffset)
+SET gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =3D $(gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize)
+SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress =3D $(gIntelSi=
liconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase) + 0x60
+SET gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize) - 0x60
SET gMinPlatformPkgTokenSpaceGuid.PcdMicrocodeOffsetInFv =3D 0x60
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeBase =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvBase
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeSize =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvSize
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeOffset =3D gSiPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvOffset
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheAddress =3D gSiPkgT=
okenSpaceGuid.PcdBiosAreaBaseAddress
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheSize =3D gSiPkgT=
okenSpaceGuid.PcdBiosSize
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFsptBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGuid=
.PcdFlashFvFspTOffset)
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspmBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGuid=
.PcdFlashFvFspMOffset)
-SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspsBaseAddress =3D $(gSiPk=
gTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgTokenSpaceGuid=
.PcdFlashFvFspSOffset)
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaBaseAddress =3D gSiPkgT=
okenSpaceGuid.PcdBiosAreaBaseAddress
-SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaSize =3D gSiPkgT=
okenSpaceGuid.PcdBiosSize
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeBase =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashFvMicrocodeOffset =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheAddress =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFlashCodeCacheSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosSize
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFsptBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspTOffset)
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspmBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspMOffset)
+SET gIntelFsp2WrapperTokenSpaceGuid.PcdFspsBaseAddress =3D $(gInte=
lSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress) + $(gMinPlatformPkgToke=
nSpaceGuid.PcdFlashFvFspSOffset)
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaBaseAddress =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress
+SET gMinPlatformPkgTokenSpaceGuid.PcdFlashAreaSize =3D gIntelS=
iliconPkgTokenSpaceGuid.PcdBiosSize
########################################################################=
########
#
# Following are lists of FD Region layout which correspond to the locati=
ons of different
@@ -153,8 +153,8 @@ [FD.CometlakeURvp]
gMinPlatformPkgTokenSpaceGuid.PcdFlashFvPostMemoryBase|gMinPlatformPkgTo=
kenSpaceGuid.PcdFlashFvPostMemorySize
FV =3D FvPostMemory
=20
-gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset|gSiPkgTokenSpaceGuid.PcdF=
lashMicrocodeFvSize
-gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase|gSiPkgTokenSpaceGuid.PcdFla=
shMicrocodeFvSize
+gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset|gIntelSiliconPk=
gTokenSpaceGuid.PcdFlashMicrocodeFvSize
+gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase|gIntelSiliconPkgT=
okenSpaceGuid.PcdFlashMicrocodeFvSize
#Microcode
FV =3D FvMicrocode
=20
diff --git a/Platform/Intel/CometlakeOpenBoardPkg/Policy/PolicyInitDxe/Po=
licyInitDxe.inf b/Platform/Intel/CometlakeOpenBoardPkg/Policy/PolicyInitD=
xe/PolicyInitDxe.inf
index 1d09b990b163..abb79c111e0b 100644
--- a/Platform/Intel/CometlakeOpenBoardPkg/Policy/PolicyInitDxe/PolicyIni=
tDxe.inf
+++ b/Platform/Intel/CometlakeOpenBoardPkg/Policy/PolicyInitDxe/PolicyIni=
tDxe.inf
@@ -47,8 +47,8 @@ [Packages]
=20
[Pcd]
gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress =
## CONSUMES
- gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =
## CONSUMES
- gSiPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =
## CONSUMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase =
## CONSUMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize =
## CONSUMES
gCometlakeOpenBoardPkgTokenSpaceGuid.PcdIntelGopEnable
gCometlakeOpenBoardPkgTokenSpaceGuid.PcdPlatformFlavor
gCometlakeOpenBoardPkgTokenSpaceGuid.PcdPlatformType
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 10/41] IntelSiliconPkg: Add MM SPI FVB services

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Adds a Traditional MM and Standalone MM SPI FVB Service driver to
IntelSiliconPkg. These drivers produce the firmware volume block
protocol for SPI flash devices compliant with the Intel Serial
Flash Interface Compatibility Specification.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/FvbInfo.c =
| 94 ++
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceC=
ommon.c | 903 ++++++++++++++++++++
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceM=
m.c | 271 ++++++
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceS=
tandaloneMm.c | 32 +
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceT=
raditionalMm.c | 32 +
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceC=
ommon.h | 158 ++++
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceM=
m.h | 22 +
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceS=
mm.inf | 68 ++
Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceS=
tandaloneMm.inf | 67 ++
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc =
| 11 +
10 files changed, 1658 insertions(+)

diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Fv=
bInfo.c b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/FvbIn=
fo.c
new file mode 100644
index 000000000000..7f2678fa9e5a
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/FvbInfo.c
@@ -0,0 +1,94 @@
+/**@file
+ Defines data structure that is the volume header found.
+ These data is intent to decouple FVB driver with FV header.
+
+Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "SpiFvbServiceCommon.h"
+
+#define FIRMWARE_BLOCK_SIZE 0x10000
+#define FVB_MEDIA_BLOCK_SIZE FIRMWARE_BLOCK_SIZE
+
+#define NV_STORAGE_BASE_ADDRESS FixedPcdGet32(PcdFlashNvStorageVaria=
bleBase)
+#define SYSTEM_NV_BLOCK_NUM ((FixedPcdGet32(PcdFlashNvStorageVar=
iableSize)+ FixedPcdGet32(PcdFlashNvStorageFtwWorkingSize) + FixedPcdGet3=
2(PcdFlashNvStorageFtwSpareSize))/ FVB_MEDIA_BLOCK_SIZE)
+
+typedef struct {
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+ EFI_FIRMWARE_VOLUME_HEADER FvbInfo;
+ EFI_FV_BLOCK_MAP_ENTRY End[1];
+} EFI_FVB2_MEDIA_INFO;
+
+//
+// This data structure contains a template of all correct FV headers, wh=
ich is used to restore
+// Fv header if it's corrupted.
+//
+EFI_FVB2_MEDIA_INFO mPlatformFvbMediaInfo[] =3D {
+ //
+ // Systen NvStorage FVB
+ //
+ {
+ NV_STORAGE_BASE_ADDRESS,
+ {
+ {0,}, //ZeroVector[16]
+ EFI_SYSTEM_NV_DATA_FV_GUID,
+ FVB_MEDIA_BLOCK_SIZE * SYSTEM_NV_BLOCK_NUM,
+ EFI_FVH_SIGNATURE,
+ 0x0004feff, // check MdePkg/Include/Pi/PiFirmwareVolume.h for deta=
ils on EFI_FVB_ATTRIBUTES_2
+ sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENT=
RY),
+ 0, //CheckSum which will be calucated dynamically.
+ 0, //ExtHeaderOffset
+ {0,}, //Reserved[1]
+ 2, //Revision
+ {
+ {
+ SYSTEM_NV_BLOCK_NUM,
+ FVB_MEDIA_BLOCK_SIZE,
+ }
+ }
+ },
+ {
+ {
+ 0,
+ 0
+ }
+ }
+ }
+};
+
+EFI_STATUS
+GetFvbInfo (
+ IN EFI_PHYSICAL_ADDRESS FvBaseAddress,
+ OUT EFI_FIRMWARE_VOLUME_HEADER **FvbInfo
+ )
+{
+ UINTN Index;
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
+
+ for (Index =3D 0; Index < sizeof (mPlatformFvbMediaInfo) / sizeof (EFI=
_FVB2_MEDIA_INFO); Index++) {
+ if (mPlatformFvbMediaInfo[Index].BaseAddress =3D=3D FvBaseAddress) {
+ FvHeader =3D &mPlatformFvbMediaInfo[Index].FvbInfo;
+
+ //
+ // Update the checksum value of FV header.
+ //
+ FvHeader->Checksum =3D CalculateCheckSum16 ( (UINT16 *) FvHeader, =
FvHeader->HeaderLength);
+
+ *FvbInfo =3D FvHeader;
+
+ DEBUG ((DEBUG_INFO, "BaseAddr: 0x%lx \n", FvBaseAddress));
+ DEBUG ((DEBUG_INFO, "FvLength: 0x%lx \n", (*FvbInfo)->FvLength));
+ DEBUG ((DEBUG_INFO, "HeaderLength: 0x%x \n", (*FvbInfo)->HeaderLen=
gth));
+ DEBUG ((DEBUG_INFO, "Header Checksum: 0x%X\n", (*FvbInfo)->Checksu=
m));
+ DEBUG ((DEBUG_INFO, "FvBlockMap[0].NumBlocks: 0x%x \n", (*FvbInfo)=
->BlockMap[0].NumBlocks));
+ DEBUG ((DEBUG_INFO, "FvBlockMap[0].BlockLength: 0x%x \n", (*FvbInf=
o)->BlockMap[0].Length));
+ DEBUG ((DEBUG_INFO, "FvBlockMap[1].NumBlocks: 0x%x \n", (*FvbInfo)=
->BlockMap[1].NumBlocks));
+ DEBUG ((DEBUG_INFO, "FvBlockMap[1].BlockLength: 0x%x \n\n", (*FvbI=
nfo)->BlockMap[1].Length));
+
+ return EFI_SUCCESS;
+ }
+ }
+ return EFI_NOT_FOUND;
+}
diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Sp=
iFvbServiceCommon.c b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbS=
ervice/SpiFvbServiceCommon.c
new file mode 100644
index 000000000000..dab818e98087
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbSer=
viceCommon.c
@@ -0,0 +1,903 @@
+/** @file
+ Common driver source for several Serial Flash devices
+ which are compliant with the Intel(R) Serial Flash Interface Compatibi=
lity Specification.
+
+Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "SpiFvbServiceCommon.h"
+
+//
+// Global variable for this FVB driver which contains
+// the private data of all firmware volume block instances
+//
+FVB_GLOBAL mFvbModuleGlobal;
+
+//
+// This platform driver knows there are multiple FVs on FD.
+// Now we only provide FVs on Variable region and MicorCode region for p=
erformance issue.
+//
+FV_INFO mPlatformFvBaseAddress[] =3D {
+ {0, 0}, // {FixedPcdGet32(PcdFlashNvStorageVariableBase), FixedPcdGet3=
2(PcdFlashNvStorageVariableSize)},
+ {0, 0}, // {FixedPcdGet32(PcdFlashMicrocodeFvBase), FixedPcdGet32(PcdF=
lashMicrocodeFvSize)},
+ {0, 0}
+};
+
+FV_INFO mPlatformDefaultBaseAddress[] =3D {
+ {0, 0}, // {FixedPcdGet32(PcdFlashNvStorageVariableBase), FixedPcdGet3=
2(PcdFlashNvStorageVariableSize)},
+ {0, 0}, // {FixedPcdGet32(PcdFlashMicrocodeFvBase), FixedPcdGet32(PcdF=
lashMicrocodeFvSize)},
+ {0, 0}
+};
+
+FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate =3D {
+ {
+ {
+ HARDWARE_DEVICE_PATH,
+ HW_MEMMAP_DP,
+ {
+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH)),
+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH) >> 8)
+ }
+ },
+ EfiMemoryMappedIO,
+ (EFI_PHYSICAL_ADDRESS) 0,
+ (EFI_PHYSICAL_ADDRESS) 0,
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ END_DEVICE_PATH_LENGTH,
+ 0
+ }
+ }
+};
+
+FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate =3D {
+ {
+ {
+ MEDIA_DEVICE_PATH,
+ MEDIA_PIWG_FW_VOL_DP,
+ {
+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH)),
+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH) >> 8)
+ }
+ },
+ { 0 }
+ },
+ {
+ END_DEVICE_PATH_TYPE,
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,
+ {
+ END_DEVICE_PATH_LENGTH,
+ 0
+ }
+ }
+};
+
+//
+// Template structure used when installing FVB protocol
+//
+EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL mFvbProtocolTemplate =3D {
+ FvbProtocolGetAttributes,
+ FvbProtocolSetAttributes,
+ FvbProtocolGetPhysicalAddress,
+ FvbProtocolGetBlockSize,
+ FvbProtocolRead,
+ FvbProtocolWrite,
+ FvbProtocolEraseBlocks,
+ NULL
+};
+
+/**
+ Get the EFI_FVB_ATTRIBUTES_2 of a FV.
+
+ @param[in] FvbInstance The pointer to the EFI_FVB_INSTANCE.
+
+ @return Attributes of the FV identified by FvbInstance.
+
+**/
+EFI_FVB_ATTRIBUTES_2
+FvbGetVolumeAttributes (
+ IN EFI_FVB_INSTANCE *FvbInstance
+ )
+{
+ return FvbInstance->FvHeader.Attributes;
+}
+
+/**
+ Retrieves the starting address of an LBA in an FV. It also
+ return a few other attribut of the FV.
+
+ @param[in] FvbInstance The pointer to the EFI_FVB_INSTANCE.
+ @param[in] Lba The logical block address
+ @param[out] LbaAddress On output, contains the physical starting =
address
+ of the Lba
+ @param[out] LbaLength On output, contains the length of the bloc=
k
+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in w=
hich the
+ number of consecutive blocks starting with=
Lba is
+ returned. All blocks in this range have a =
size of
+ BlockSize
+
+ @retval EFI_SUCCESS Successfully returns
+ @retval EFI_INVALID_PARAMETER Instance not found
+
+**/
+EFI_STATUS
+FvbGetLbaAddress (
+ IN EFI_FVB_INSTANCE *FvbInstance,
+ IN EFI_LBA Lba,
+ OUT UINTN *LbaAddress,
+ OUT UINTN *LbaLength,
+ OUT UINTN *NumOfBlocks
+ )
+{
+ UINT32 NumBlocks;
+ UINT32 BlockLength;
+ UINTN Offset;
+ EFI_LBA StartLba;
+ EFI_LBA NextLba;
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;
+
+ StartLba =3D 0;
+ Offset =3D 0;
+ BlockMap =3D &(FvbInstance->FvHeader.BlockMap[0]);
+
+ //
+ // Parse the blockmap of the FV to find which map entry the Lba belong=
s to
+ //
+ while (TRUE) {
+ NumBlocks =3D BlockMap->NumBlocks;
+ BlockLength =3D BlockMap->Length;
+
+ if ( NumBlocks =3D=3D 0 || BlockLength =3D=3D 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ NextLba =3D StartLba + NumBlocks;
+
+ //
+ // The map entry found
+ //
+ if (Lba >=3D StartLba && Lba < NextLba) {
+ Offset =3D Offset + (UINTN)MultU64x32((Lba - StartLba), BlockLengt=
h);
+ if (LbaAddress ) {
+ *LbaAddress =3D FvbInstance->FvBase + Offset;
+ }
+
+ if (LbaLength ) {
+ *LbaLength =3D BlockLength;
+ }
+
+ if (NumOfBlocks ) {
+ *NumOfBlocks =3D (UINTN)(NextLba - Lba);
+ }
+ return EFI_SUCCESS;
+ }
+
+ StartLba =3D NextLba;
+ Offset =3D Offset + NumBlocks * BlockLength;
+ BlockMap++;
+ }
+}
+
+/**
+ Reads specified number of bytes into a buffer from the specified block=
.
+
+ @param[in] FvbInstance The pointer to the EFI_FVB_INSTA=
NCE
+ @param[in] Lba The logical block address to be =
read from
+ @param[in] BlockOffset Offset into the block at which t=
o begin reading
+ @param[in] NumBytes Pointer that on input contains t=
he total size of
+ the buffer. On output, it contai=
ns the total number
+ of bytes read
+ @param[in] Buffer Pointer to a caller allocated bu=
ffer that will be
+ used to hold the data read
+
+
+ @retval EFI_SUCCESS The firmware volume was read suc=
cessfully and
+ contents are in Buffer
+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boun=
dary. On output,
+ NumBytes contains the total numb=
er of bytes returned
+ in Buffer
+ @retval EFI_ACCESS_DENIED The firmware volume is in the Re=
adDisabled state
+ @retval EFI_DEVICE_ERROR The block device is not function=
ing correctly and
+ could not be read
+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes,=
Buffer are NULL
+
+**/
+EFI_STATUS
+FvbReadBlock (
+ IN EFI_FVB_INSTANCE *FvbInstance,
+ IN EFI_LBA Lba,
+ IN UINTN BlockOffset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_FVB_ATTRIBUTES_2 Attributes;
+ UINTN LbaAddress;
+ UINTN LbaLength;
+ EFI_STATUS Status;
+ BOOLEAN BadBufferSize =3D FALSE;
+
+ if ((NumBytes =3D=3D NULL) || (Buffer =3D=3D NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+ if (*NumBytes =3D=3D 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Status =3D FvbGetLbaAddress (FvbInstance, Lba, &LbaAddress, &LbaLength=
, NULL);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Attributes =3D FvbGetVolumeAttributes (FvbInstance);
+
+ if ((Attributes & EFI_FVB2_READ_STATUS) =3D=3D 0) {
+ return EFI_ACCESS_DENIED;
+ }
+
+ if (BlockOffset > LbaLength) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (LbaLength < (*NumBytes + BlockOffset)) {
+ DEBUG ((DEBUG_INFO,
+ "FvReadBlock: Reducing Numbytes from 0x%x to 0x%x\n",
+ *NumBytes,
+ (UINT32)(LbaLength - BlockOffset))
+ );
+ *NumBytes =3D (UINT32) (LbaLength - BlockOffset);
+ BadBufferSize =3D TRUE;
+ }
+
+ Status =3D SpiFlashRead (LbaAddress + BlockOffset, (UINT32 *)NumBytes,=
Buffer);
+
+ if (!EFI_ERROR (Status) && BadBufferSize) {
+ return EFI_BAD_BUFFER_SIZE;
+ } else {
+ return Status;
+ }
+}
+
+/**
+ Writes specified number of bytes from the input buffer to the block.
+
+ @param[in] FvbInstance The pointer to the EFI_FVB_INSTANCE
+ @param[in] Lba The starting logical block index to =
write to
+ @param[in] BlockOffset Offset into the block at which to be=
gin writing
+ @param[in] NumBytes Pointer that on input contains the t=
otal size of
+ the buffer. On output, it contains t=
he total number
+ of bytes actually written
+ @param[in] Buffer Pointer to a caller allocated buffer=
that contains
+ the source for the write
+ @retval EFI_SUCCESS The firmware volume was written succ=
essfully
+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundar=
y. On output,
+ NumBytes contains the total number o=
f bytes
+ actually written
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteD=
isabled state
+ @retval EFI_DEVICE_ERROR The block device is not functioning =
correctly and
+ could not be written
+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buf=
fer are NULL
+
+**/
+EFI_STATUS
+FvbWriteBlock (
+ IN EFI_FVB_INSTANCE *FvbInstance,
+ IN EFI_LBA Lba,
+ IN UINTN BlockOffset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_FVB_ATTRIBUTES_2 Attributes;
+ UINTN LbaAddress;
+ UINTN LbaLength;
+ EFI_STATUS Status;
+ BOOLEAN BadBufferSize =3D FALSE;
+
+ if ((NumBytes =3D=3D NULL) || (Buffer =3D=3D NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+ if (*NumBytes =3D=3D 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Status =3D FvbGetLbaAddress (FvbInstance, Lba, &LbaAddress, &LbaLength=
, NULL);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ //
+ // Check if the FV is write enabled
+ //
+ Attributes =3D FvbGetVolumeAttributes (FvbInstance);
+ if ((Attributes & EFI_FVB2_WRITE_STATUS) =3D=3D 0) {
+ return EFI_ACCESS_DENIED;
+ }
+
+ //
+ // Perform boundary checks and adjust NumBytes
+ //
+ if (BlockOffset > LbaLength) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (LbaLength < (*NumBytes + BlockOffset)) {
+ DEBUG ((DEBUG_INFO,
+ "FvWriteBlock: Reducing Numbytes from 0x%x to 0x%x\n",
+ *NumBytes,
+ (UINT32)(LbaLength - BlockOffset))
+ );
+ *NumBytes =3D (UINT32) (LbaLength - BlockOffset);
+ BadBufferSize =3D TRUE;
+ }
+
+ Status =3D SpiFlashWrite (LbaAddress + BlockOffset, (UINT32 *)NumBytes=
, Buffer);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Status =3D SpiFlashLock ();
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ WriteBackInvalidateDataCacheRange ((VOID *) (LbaAddress + BlockOffset)=
, *NumBytes);
+
+ if (!EFI_ERROR (Status) && BadBufferSize) {
+ return EFI_BAD_BUFFER_SIZE;
+ } else {
+ return Status;
+ }
+}
+
+
+
+/**
+ Erases and initializes a firmware volume block.
+
+ @param[in] FvbInstance The pointer to the EFI_FVB_INSTANCE
+ @param[in] Lba The logical block index to be erased
+
+ @retval EFI_SUCCESS The erase request was successfully com=
pleted
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDis=
abled state
+ @retval EFI_DEVICE_ERROR The block device is not functioning co=
rrectly and
+ could not be written. Firmware device =
may have been
+ partially erased
+ @retval EFI_INVALID_PARAMETER Instance not found
+
+**/
+EFI_STATUS
+FvbEraseBlock (
+ IN EFI_FVB_INSTANCE *FvbInstance,
+ IN EFI_LBA Lba
+ )
+{
+
+ EFI_FVB_ATTRIBUTES_2 Attributes;
+ UINTN LbaAddress;
+ UINTN LbaLength;
+ EFI_STATUS Status;
+
+ //
+ // Check if the FV is write enabled
+ //
+ Attributes =3D FvbGetVolumeAttributes (FvbInstance);
+
+ if( (Attributes & EFI_FVB2_WRITE_STATUS) =3D=3D 0) {
+ return EFI_ACCESS_DENIED;
+ }
+
+ //
+ // Get the starting address of the block for erase.
+ //
+ Status =3D FvbGetLbaAddress (FvbInstance, Lba, &LbaAddress, &LbaLength=
, NULL);
+ if (EFI_ERROR(Status)) {
+ return Status;
+ }
+
+ Status =3D SpiFlashBlockErase (LbaAddress, &LbaLength);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Status =3D SpiFlashLock ();
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ WriteBackInvalidateDataCacheRange ((VOID *) LbaAddress, LbaLength);
+
+ return Status;
+}
+
+/**
+ Modifies the current settings of the firmware volume according to the
+ input parameter, and returns the new setting of the volume
+
+ @param[in] FvbInstance The pointer to the EFI_FVB_INSTANCE.
+ @param[in] Attributes On input, it is a pointer to EFI_FVB=
_ATTRIBUTES_2
+ containing the desired firmware volu=
me settings.
+ On successful return, it contains th=
e new settings
+ of the firmware volume
+
+ @retval EFI_SUCCESS Successfully returns
+ @retval EFI_ACCESS_DENIED The volume setting is locked and can=
not be modified
+ @retval EFI_INVALID_PARAMETER Instance not found, or The attribute=
s requested are
+ in conflict with the capabilities as=
declared in the
+ firmware volume header
+
+**/
+EFI_STATUS
+FvbSetVolumeAttributes (
+ IN EFI_FVB_INSTANCE *FvbInstance,
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ )
+{
+ EFI_FVB_ATTRIBUTES_2 OldAttributes;
+ EFI_FVB_ATTRIBUTES_2 *AttribPtr;
+ EFI_FVB_ATTRIBUTES_2 UnchangedAttributes;
+ UINT32 Capabilities;
+ UINT32 OldStatus, NewStatus;
+
+ AttribPtr =3D (EFI_FVB_ATTRIBUTES_2 *) &(FvbInstance->FvHeader.Att=
ributes);
+ OldAttributes =3D *AttribPtr;
+ Capabilities =3D OldAttributes & EFI_FVB2_CAPABILITIES;
+ OldStatus =3D OldAttributes & EFI_FVB2_STATUS;
+ NewStatus =3D *Attributes & EFI_FVB2_STATUS;
+
+ UnchangedAttributes =3D EFI_FVB2_READ_DISABLED_CAP | \
+ EFI_FVB2_READ_ENABLED_CAP | \
+ EFI_FVB2_WRITE_DISABLED_CAP | \
+ EFI_FVB2_WRITE_ENABLED_CAP | \
+ EFI_FVB2_LOCK_CAP | \
+ EFI_FVB2_STICKY_WRITE | \
+ EFI_FVB2_MEMORY_MAPPED | \
+ EFI_FVB2_ERASE_POLARITY | \
+ EFI_FVB2_READ_LOCK_CAP | \
+ EFI_FVB2_WRITE_LOCK_CAP | \
+ EFI_FVB2_ALIGNMENT;
+
+ //
+ // Some attributes of FV is read only can *not* be set
+ //
+ if ((OldAttributes & UnchangedAttributes) ^ (*Attributes & UnchangedAt=
tributes)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // If firmware volume is locked, no status bit can be updated
+ //
+ if ( OldAttributes & EFI_FVB2_LOCK_STATUS ) {
+ if ( OldStatus ^ NewStatus ) {
+ return EFI_ACCESS_DENIED;
+ }
+ }
+
+ //
+ // Test read disable
+ //
+ if ((Capabilities & EFI_FVB2_READ_DISABLED_CAP) =3D=3D 0) {
+ if ((NewStatus & EFI_FVB2_READ_STATUS) =3D=3D 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+
+ //
+ // Test read enable
+ //
+ if ((Capabilities & EFI_FVB2_READ_ENABLED_CAP) =3D=3D 0) {
+ if (NewStatus & EFI_FVB2_READ_STATUS) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+
+ //
+ // Test write disable
+ //
+ if ((Capabilities & EFI_FVB2_WRITE_DISABLED_CAP) =3D=3D 0) {
+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) =3D=3D 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+
+ //
+ // Test write enable
+ //
+ if ((Capabilities & EFI_FVB2_WRITE_ENABLED_CAP) =3D=3D 0) {
+ if (NewStatus & EFI_FVB2_WRITE_STATUS) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+
+ //
+ // Test lock
+ //
+ if ((Capabilities & EFI_FVB2_LOCK_CAP) =3D=3D 0) {
+ if (NewStatus & EFI_FVB2_LOCK_STATUS) {
+ return EFI_INVALID_PARAMETER;
+ }
+ }
+
+ *AttribPtr =3D (*AttribPtr) & (0xFFFFFFFF & (~EFI_FVB2_STATUS));
+ *AttribPtr =3D (*AttribPtr) | NewStatus;
+ *Attributes =3D *AttribPtr;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Check the integrity of firmware volume header
+
+ @param[in] FvHeader A pointer to a firmware volume header
+
+ @retval TRUE The firmware volume is consistent
+ @retval FALSE The firmware volume has corrupted.
+
+**/
+BOOLEAN
+IsFvHeaderValid (
+ IN EFI_PHYSICAL_ADDRESS FvBase,
+ IN CONST EFI_FIRMWARE_VOLUME_HEADER *FvHeader
+ )
+{
+ if (FvBase =3D=3D PcdGet32(PcdFlashNvStorageVariableBase)) {
+ if (CompareMem (&FvHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid, =
sizeof(EFI_GUID)) !=3D 0 ) {
+ return FALSE;
+ }
+ } else {
+ if (CompareMem (&FvHeader->FileSystemGuid, &gEfiFirmwareFileSystem2G=
uid, sizeof(EFI_GUID)) !=3D 0 ) {
+ return FALSE;
+ }
+ }
+ if ( (FvHeader->Revision !=3D EFI_FVH_REVISION) ||
+ (FvHeader->Signature !=3D EFI_FVH_SIGNATURE) ||
+ (FvHeader->FvLength =3D=3D ((UINTN) -1)) ||
+ ((FvHeader->HeaderLength & 0x01 ) !=3D0) ) {
+ return FALSE;
+ }
+
+ if (CalculateCheckSum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength) =
!=3D 0) {
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+//
+// FVB protocol APIs
+//
+
+/**
+ Retrieves the physical address of the device.
+
+ @param[in] This A pointer to EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL.
+ @param[out] Address Output buffer containing the address.
+
+ retval EFI_SUCCESS The function always return successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+FvbProtocolGetPhysicalAddress (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ OUT EFI_PHYSICAL_ADDRESS *Address
+ )
+{
+ EFI_FVB_INSTANCE *FvbInstance;
+
+ FvbInstance =3D FVB_INSTANCE_FROM_THIS (This);
+
+ *Address =3D FvbInstance->FvBase;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Retrieve the size of a logical block
+
+ @param[in] This Calling context
+ @param[in] Lba Indicates which block to return the size for.
+ @param[out] BlockSize A pointer to a caller allocated UINTN in which
+ the size of the block is returned
+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which=
the
+ number of consecutive blocks starting with Lba=
is
+ returned. All blocks in this range have a size=
of
+ BlockSize
+
+ @retval EFI_SUCCESS The function always return successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+FvbProtocolGetBlockSize (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ OUT UINTN *BlockSize,
+ OUT UINTN *NumOfBlocks
+ )
+{
+ EFI_FVB_INSTANCE *FvbInstance;
+
+ FvbInstance =3D FVB_INSTANCE_FROM_THIS (This);
+
+ DEBUG((DEBUG_INFO,
+ "FvbProtocolGetBlockSize: Lba: 0x%lx BlockSize: 0x%x NumOfBlocks: 0x=
%x\n",
+ Lba,
+ BlockSize,
+ NumOfBlocks)
+ );
+
+ return FvbGetLbaAddress (
+ FvbInstance,
+ Lba,
+ NULL,
+ BlockSize,
+ NumOfBlocks
+ );
+}
+
+/**
+ Retrieves Volume attributes. No polarity translations are done.
+
+ @param[in] This Calling context
+ @param[out] Attributes Output buffer which contains attributes
+
+ @retval EFI_SUCCESS The function always return successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+FvbProtocolGetAttributes (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ )
+{
+ EFI_FVB_INSTANCE *FvbInstance;
+
+ FvbInstance =3D FVB_INSTANCE_FROM_THIS (This);
+
+ *Attributes =3D FvbGetVolumeAttributes (FvbInstance);
+
+ DEBUG ((DEBUG_INFO,
+ "FvbProtocolGetAttributes: This: 0x%x Attributes: 0x%x\n",
+ This,
+ *Attributes)
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Sets Volume attributes. No polarity translations are done.
+
+ @param[in] This Calling context
+ @param[out] Attributes Output buffer which contains attributes
+
+ @retval EFI_SUCCESS The function always return successfully.
+
+**/
+EFI_STATUS
+EFIAPI
+FvbProtocolSetAttributes (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ )
+{
+ EFI_STATUS Status;
+ EFI_FVB_INSTANCE *FvbInstance;
+
+ DEBUG((DEBUG_INFO,
+ "FvbProtocolSetAttributes: Before SET - This: 0x%x Attributes: 0x%x=
\n",
+ This,
+ *Attributes)
+ );
+
+ FvbInstance =3D FVB_INSTANCE_FROM_THIS (This);
+
+ Status =3D FvbSetVolumeAttributes (FvbInstance, Attributes);
+
+ DEBUG((DEBUG_INFO,
+ "FvbProtocolSetAttributes: After SET - This: 0x%x Attributes: 0x%x\=
n",
+ This,
+ *Attributes)
+ );
+
+ return Status;
+}
+
+/**
+ The EraseBlock() function erases one or more blocks as denoted by the
+ variable argument list. The entire parameter list of blocks must be ve=
rified
+ prior to erasing any blocks. If a block is requested that does not ex=
ist
+ within the associated firmware volume (it has a larger index than the =
last
+ block of the firmware volume), the EraseBlock() function must return
+ EFI_INVALID_PARAMETER without modifying the contents of the firmware v=
olume.
+
+ @param[in] This Calling context
+ @param[in] ... Starting LBA followed by Number of Lba to eras=
e.
+ a -1 to terminate the list.
+
+ @retval EFI_SUCCESS The erase request was successfully completed
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled =
state
+ @retval EFI_DEVICE_ERROR The block device is not functioning correctl=
y and
+ could not be written. Firmware device may ha=
ve been
+ partially erased
+
+**/
+EFI_STATUS
+EFIAPI
+FvbProtocolEraseBlocks (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ ...
+ )
+{
+ EFI_FVB_INSTANCE *FvbInstance;
+ UINTN NumOfBlocks;
+ VA_LIST Args;
+ EFI_LBA StartingLba;
+ UINTN NumOfLba;
+ EFI_STATUS Status;
+
+ DEBUG((DEBUG_INFO, "FvbProtocolEraseBlocks: \n"));
+
+ FvbInstance =3D FVB_INSTANCE_FROM_THIS (This);
+
+ NumOfBlocks =3D FvbInstance->NumOfBlocks;
+
+ VA_START (Args, This);
+
+ do {
+ StartingLba =3D VA_ARG (Args, EFI_LBA);
+ if ( StartingLba =3D=3D EFI_LBA_LIST_TERMINATOR ) {
+ break;
+ }
+
+ NumOfLba =3D VA_ARG (Args, UINT32);
+
+ //
+ // Check input parameters
+ //
+ if (NumOfLba =3D=3D 0) {
+ VA_END (Args);
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if ( ( StartingLba + NumOfLba ) > NumOfBlocks ) {
+ return EFI_INVALID_PARAMETER;
+ }
+ } while ( 1 );
+
+ VA_END (Args);
+
+ VA_START (Args, This);
+ do {
+ StartingLba =3D VA_ARG (Args, EFI_LBA);
+ if (StartingLba =3D=3D EFI_LBA_LIST_TERMINATOR) {
+ break;
+ }
+
+ NumOfLba =3D VA_ARG (Args, UINT32);
+
+ while ( NumOfLba > 0 ) {
+ Status =3D FvbEraseBlock (FvbInstance, StartingLba);
+ if ( EFI_ERROR(Status)) {
+ VA_END (Args);
+ return Status;
+ }
+ StartingLba ++;
+ NumOfLba --;
+ }
+
+ } while ( 1 );
+
+ VA_END (Args);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Writes data beginning at Lba:Offset from FV. The write terminates eith=
er
+ when *NumBytes of data have been written, or when a block boundary is
+ reached. *NumBytes is updated to reflect the actual number of bytes
+ written. The write opertion does not include erase. This routine will
+ attempt to write only the specified bytes. If the writes do not stick,
+ it will return an error.
+
+ @param[in] This Calling context
+ @param[in] Lba Block in which to begin write
+ @param[in] Offset Offset in the block at which to begin write
+ @param[in,out] NumBytes On input, indicates the requested write size=
. On
+ output, indicates the actual number of bytes=
written
+ @param[in] Buffer Buffer containing source data for the write.
+
+ @retval EFI_SUCCESS The firmware volume was written successf=
ully
+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. O=
n output,
+ NumBytes contains the total number of by=
tes
+ actually written
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisab=
led state
+ @retval EFI_DEVICE_ERROR The block device is not functioning corr=
ectly and
+ could not be written
+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL
+
+**/
+EFI_STATUS
+EFIAPI
+FvbProtocolWrite (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_FVB_INSTANCE *FvbInstance;
+
+ FvbInstance =3D FVB_INSTANCE_FROM_THIS (This);
+
+ DEBUG((DEBUG_INFO,
+ "FvbProtocolWrite: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0=
x%x\n",
+ Lba,
+ Offset,
+ *NumBytes,
+ Buffer)
+ );
+
+ return FvbWriteBlock (FvbInstance, Lba, Offset, NumBytes, Buffer);
+}
+
+/**
+ Reads data beginning at Lba:Offset from FV. The Read terminates either
+ when *NumBytes of data have been read, or when a block boundary is
+ reached. *NumBytes is updated to reflect the actual number of bytes
+ written. The write opertion does not include erase. This routine will
+ attempt to write only the specified bytes. If the writes do not stick,
+ it will return an error.
+
+ @param[in] This Calling context
+ @param[in] Lba Block in which to begin write
+ @param[in] Offset Offset in the block at which to begin write
+ @param[in,out] NumBytes On input, indicates the requested write size=
. On
+ output, indicates the actual number of bytes=
written
+ @param[in] Buffer Buffer containing source data for the write.
+
+ @retval EFI_SUCCESS The firmware volume was read successfull=
y and
+ contents are in Buffer
+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On=
output,
+ NumBytes contains the total number of by=
tes returned
+ in Buffer
+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabl=
ed state
+ @retval EFI_DEVICE_ERROR The block device is not functioning corr=
ectly and
+ could not be read
+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL
+
+**/
+EFI_STATUS
+EFIAPI
+FvbProtocolRead (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ OUT UINT8 *Buffer
+ )
+{
+ EFI_FVB_INSTANCE *FvbInstance;
+ EFI_STATUS Status;
+
+ FvbInstance =3D FVB_INSTANCE_FROM_THIS (This);
+ Status =3D FvbReadBlock (FvbInstance, Lba, Offset, NumBytes, Buffer);
+ DEBUG((DEBUG_INFO,
+ "FvbProtocolRead: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x=
%x\n",
+ Lba,
+ Offset,
+ *NumBytes,
+ Buffer)
+ );
+
+ return Status;
+}
diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Sp=
iFvbServiceMm.c b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbServi=
ce/SpiFvbServiceMm.c
new file mode 100644
index 000000000000..42a0828c6fae
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbSer=
viceMm.c
@@ -0,0 +1,271 @@
+/** @file
+ MM driver source for several Serial Flash devices
+ which are compliant with the Intel(R) Serial Flash Interface Compatibi=
lity Specification.
+
+ Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) Microsoft Corporation.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "SpiFvbServiceCommon.h"
+#include <Library/MmServicesTableLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Protocol/SmmFirmwareVolumeBlock.h>
+
+/**
+ The function installs EFI_FIRMWARE_VOLUME_BLOCK protocol
+ for each FV in the system.
+
+ @param[in] FvbInstance The pointer to a FW volume instance structur=
e,
+ which contains the information about one FV.
+
+ @retval VOID
+
+**/
+VOID
+InstallFvbProtocol (
+ IN EFI_FVB_INSTANCE *FvbInstance
+ )
+{
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
+ EFI_STATUS Status;
+ EFI_HANDLE FvbHandle;
+
+ ASSERT (FvbInstance !=3D NULL);
+ if (FvbInstance =3D=3D NULL) {
+ return;
+ }
+
+ CopyMem (&FvbInstance->FvbProtocol, &mFvbProtocolTemplate, sizeof (EFI=
_FIRMWARE_VOLUME_BLOCK_PROTOCOL));
+
+ FvHeader =3D &FvbInstance->FvHeader;
+ if (FvHeader =3D=3D NULL) {
+ return;
+ }
+
+ //
+ // Set up the devicepath
+ //
+ DEBUG ((DEBUG_INFO, "FwBlockService.c: Setting up DevicePath for 0x%lx=
:\n", FvbInstance->FvBase));
+ if (FvHeader->ExtHeaderOffset =3D=3D 0) {
+ //
+ // FV does not contains extension header, then produce MEMMAP_DEVICE=
_PATH
+ //
+ FvbInstance->DevicePath =3D (EFI_DEVICE_PATH_PROTOCOL *) AllocateRun=
timeCopyPool (sizeof (FV_MEMMAP_DEVICE_PATH), &mFvMemmapDevicePathTemplat=
e);
+ if (FvbInstance->DevicePath =3D=3D NULL) {
+ DEBUG ((DEBUG_INFO, "SpiFvbServiceSmm.c: Memory allocation for MEM=
MAP_DEVICE_PATH failed\n"));
+ return;
+ }
+ ((FV_MEMMAP_DEVICE_PATH *) FvbInstance->DevicePath)->MemMapDevPath.S=
tartingAddress =3D FvbInstance->FvBase;
+ ((FV_MEMMAP_DEVICE_PATH *) FvbInstance->DevicePath)->MemMapDevPath.E=
ndingAddress =3D FvbInstance->FvBase + FvHeader->FvLength - 1;
+ } else {
+ FvbInstance->DevicePath =3D (EFI_DEVICE_PATH_PROTOCOL *) AllocateRun=
timeCopyPool (sizeof (FV_PIWG_DEVICE_PATH), &mFvPIWGDevicePathTemplate);
+ if (FvbInstance->DevicePath =3D=3D NULL) {
+ DEBUG ((DEBUG_INFO, "SpiFvbServiceSmm.c: Memory allocation for FV_=
PIWG_DEVICE_PATH failed\n"));
+ return;
+ }
+ CopyGuid (
+ &((FV_PIWG_DEVICE_PATH *)FvbInstance->DevicePath)->FvDevPath.FvNam=
e,
+ (GUID *)(UINTN)(FvbInstance->FvBase + FvHeader->ExtHeaderOffset)
+ );
+ }
+
+ //
+ // LocateDevicePath fails so install a new interface and device path
+ //
+ FvbHandle =3D NULL;
+
+ Status =3D gMmst->MmInstallProtocolInterface (
+ &FvbHandle,
+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,
+ EFI_NATIVE_INTERFACE,
+ &(FvbInstance->FvbProtocol)
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ Status =3D gMmst->MmInstallProtocolInterface (
+ &FvbHandle,
+ &gEfiDevicePathProtocolGuid,
+ EFI_NATIVE_INTERFACE,
+ &(FvbInstance->DevicePath)
+ );
+ ASSERT_EFI_ERROR (Status);
+}
+
+/**
+ The function does the necessary initialization work for
+ Firmware Volume Block Driver.
+
+**/
+VOID
+FvbInitialize (
+ VOID
+ )
+{
+ EFI_FVB_INSTANCE *FvbInstance;
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
+ EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry;
+ EFI_PHYSICAL_ADDRESS BaseAddress;
+ EFI_STATUS Status;
+ UINTN BufferSize;
+ UINTN Idx;
+ UINT32 MaxLbaSize;
+ UINT32 BytesWritten;
+ UINTN BytesErased;
+
+ mPlatformFvBaseAddress[0].FvBase =3D PcdGet32(PcdFlashNvStorageVariabl=
eBase);
+ mPlatformFvBaseAddress[0].FvSize =3D PcdGet32(PcdFlashNvStorageVariabl=
eSize);
+ mPlatformFvBaseAddress[1].FvBase =3D PcdGet32(PcdFlashMicrocodeFvBase)=
;
+ mPlatformFvBaseAddress[1].FvSize =3D PcdGet32(PcdFlashMicrocodeFvSize)=
;
+ mPlatformDefaultBaseAddress[0].FvBase =3D PcdGet32(PcdFlashNvStorageVa=
riableBase);
+ mPlatformDefaultBaseAddress[0].FvSize =3D PcdGet32(PcdFlashNvStorageVa=
riableSize);
+ mPlatformDefaultBaseAddress[1].FvBase =3D PcdGet32(PcdFlashMicrocodeFv=
Base);
+ mPlatformDefaultBaseAddress[1].FvSize =3D PcdGet32(PcdFlashMicrocodeFv=
Size);
+
+ //
+ // We will only continue with FVB installation if the
+ // SPI is the active BIOS state
+ //
+ {
+ //
+ // Make sure all FVB are valid and/or fix if possible
+ //
+ for (Idx =3D 0;; Idx++) {
+ if (mPlatformFvBaseAddress[Idx].FvSize =3D=3D 0 && mPlatformFvBase=
Address[Idx].FvBase =3D=3D 0) {
+ break;
+ }
+
+ BaseAddress =3D mPlatformFvBaseAddress[Idx].FvBase;
+ FvHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) BaseAddress;
+
+ if (!IsFvHeaderValid (BaseAddress, FvHeader)) {
+ BytesWritten =3D 0;
+ BytesErased =3D 0;
+ DEBUG ((DEBUG_ERROR, "ERROR - The FV in 0x%x is invalid!\n", FvH=
eader));
+ Status =3D GetFvbInfo (BaseAddress, &FvHeader);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_WARN, "ERROR - Can't recovery FV header at 0x%x.=
GetFvbInfo Status %r\n", BaseAddress, Status));
+ continue;
+ }
+ DEBUG ((DEBUG_INFO, "Rewriting FV header at 0x%X with static dat=
a\n", BaseAddress));
+ //
+ // Spi erase
+ //
+ BytesErased =3D (UINTN) FvHeader->BlockMap->Length;
+ Status =3D SpiFlashBlockErase( (UINTN) BaseAddress, &BytesErased=
);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_WARN, "ERROR - SpiFlashBlockErase Error %r\n", =
Status));
+ continue;
+ }
+ if (BytesErased !=3D FvHeader->BlockMap->Length) {
+ DEBUG ((DEBUG_WARN, "ERROR - BytesErased !=3D FvHeader->BlockM=
ap->Length\n"));
+ DEBUG ((DEBUG_INFO, " BytesErased =3D 0x%X\n Length =3D 0x%X\n=
", BytesErased, FvHeader->BlockMap->Length));
+ continue;
+ }
+ BytesWritten =3D FvHeader->HeaderLength;
+ Status =3D SpiFlashWrite ((UINTN)BaseAddress, &BytesWritten, (UI=
NT8*)FvHeader);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_WARN, "ERROR - SpiFlashWrite Error %r\n", Statu=
s));
+ continue;
+ }
+ if (BytesWritten !=3D FvHeader->HeaderLength) {
+ DEBUG ((DEBUG_WARN, "ERROR - BytesWritten !=3D HeaderLength\n"=
));
+ DEBUG ((DEBUG_INFO, " BytesWritten =3D 0x%X\n HeaderLength =3D=
0x%X\n", BytesWritten, FvHeader->HeaderLength));
+ continue;
+ }
+ Status =3D SpiFlashLock ();
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_WARN, "ERROR - SpiFlashLock Error %r\n", Status=
));
+ continue;
+ }
+ DEBUG ((DEBUG_INFO, "FV Header @ 0x%X restored with static data\=
n", BaseAddress));
+ //
+ // Clear cache for this range.
+ //
+ WriteBackInvalidateDataCacheRange ( (VOID *) (UINTN) BaseAddress=
, FvHeader->BlockMap->Length);
+ }
+ }
+
+ //
+ // Calculate the total size for all firmware volume block instances
+ //
+ BufferSize =3D 0;
+ for (Idx =3D 0; ; Idx++) {
+ if (mPlatformFvBaseAddress[Idx].FvSize =3D=3D 0 && mPlatformFvBase=
Address[Idx].FvBase =3D=3D 0) {
+ break;
+ }
+ BaseAddress =3D mPlatformFvBaseAddress[Idx].FvBase;
+ FvHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) BaseAddress;
+
+ if (!IsFvHeaderValid (BaseAddress, FvHeader)) {
+ DEBUG ((DEBUG_WARN, "ERROR - The FV in 0x%x is invalid!\n", FvHe=
ader));
+ continue;
+ }
+
+ BufferSize +=3D (FvHeader->HeaderLength +
+ sizeof (EFI_FVB_INSTANCE) -
+ sizeof (EFI_FIRMWARE_VOLUME_HEADER)
+ );
+ }
+
+ mFvbModuleGlobal.FvbInstance =3D (EFI_FVB_INSTANCE *) AllocateRunti=
meZeroPool (BufferSize);
+ if (mFvbModuleGlobal.FvbInstance =3D=3D NULL) {
+ ASSERT (FALSE);
+ return;
+ }
+
+ MaxLbaSize =3D 0;
+ FvbInstance =3D mFvbModuleGlobal.FvbInstance;
+ mFvbModuleGlobal.NumFv =3D 0;
+
+ for (Idx =3D 0; ; Idx++) {
+ if (mPlatformFvBaseAddress[Idx].FvSize =3D=3D 0 && mPlatformFvBase=
Address[Idx].FvBase =3D=3D 0) {
+ break;
+ }
+ BaseAddress =3D mPlatformFvBaseAddress[Idx].FvBase;
+ FvHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) BaseAddress;
+
+ if (!IsFvHeaderValid (BaseAddress, FvHeader)) {
+ DEBUG ((DEBUG_WARN, "ERROR - The FV in 0x%x is invalid!\n", FvHe=
ader));
+ continue;
+ }
+
+ FvbInstance->Signature =3D FVB_INSTANCE_SIGNATURE;
+ CopyMem (&(FvbInstance->FvHeader), FvHeader, FvHeader->HeaderLengt=
h);
+
+ FvHeader =3D &(FvbInstance->FvHeader);
+ FvbInstance->FvBase =3D (UINTN)BaseAddress;
+
+ //
+ // Process the block map for each FV
+ //
+ FvbInstance->NumOfBlocks =3D 0;
+ for (PtrBlockMapEntry =3D FvHeader->BlockMap;
+ PtrBlockMapEntry->NumBlocks !=3D 0;
+ PtrBlockMapEntry++) {
+ //
+ // Get the maximum size of a block.
+ //
+ if (MaxLbaSize < PtrBlockMapEntry->Length) {
+ MaxLbaSize =3D PtrBlockMapEntry->Length;
+ }
+ FvbInstance->NumOfBlocks +=3D PtrBlockMapEntry->NumBlocks;
+ }
+
+ //
+ // Add a FVB Protocol Instance
+ //
+ InstallFvbProtocol (FvbInstance);
+ mFvbModuleGlobal.NumFv++;
+
+ //
+ // Move on to the next FvbInstance
+ //
+ FvbInstance =3D (EFI_FVB_INSTANCE *) ((UINTN)((UINT8 *)FvbInstance=
) +
+ FvHeader->HeaderLength +
+ (sizeof (EFI_FVB_INSTANCE) -=
sizeof (EFI_FIRMWARE_VOLUME_HEADER)));
+
+ }
+ }
+}
diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Sp=
iFvbServiceStandaloneMm.c b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/S=
piFvbService/SpiFvbServiceStandaloneMm.c
new file mode 100644
index 000000000000..252c818d6551
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbSer=
viceStandaloneMm.c
@@ -0,0 +1,32 @@
+/** @file
+ MM driver source for several Serial Flash devices
+ which are compliant with the Intel(R) Serial Flash Interface Compatibi=
lity Specification.
+
+ Copyright (c) Microsoft Corporation.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "SpiFvbServiceCommon.h"
+#include "SpiFvbServiceMm.h"
+
+/**
+ The driver Standalone MM entry point.
+
+ @param[in] ImageHandle Image handle of this driver.
+ @param[in] MmSystemTable A pointer to the MM system table.
+
+ @retval EFI_SUCCESS This function always returns EFI_SUCCE=
SS.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFvbStandaloneMmInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_MM_SYSTEM_TABLE *MmSystemTable
+ )
+{
+ FvbInitialize ();
+
+ return EFI_SUCCESS;
+}
diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Sp=
iFvbServiceTraditionalMm.c b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/=
SpiFvbService/SpiFvbServiceTraditionalMm.c
new file mode 100644
index 000000000000..1c2dac70e3c6
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbSer=
viceTraditionalMm.c
@@ -0,0 +1,32 @@
+/** @file
+ MM driver source for several Serial Flash devices
+ which are compliant with the Intel(R) Serial Flash Interface Compatibi=
lity Specification.
+
+ Copyright (c) Microsoft Corporation.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "SpiFvbServiceCommon.h"
+#include "SpiFvbServiceMm.h"
+
+/**
+ The driver Traditional MM entry point.
+
+ @param[in] ImageHandle Image handle of this driver.
+ @param[in] SystemTable A pointer to the EFI system table.
+
+ @retval EFI_SUCCESS This function always returns EFI_SUCCE=
SS.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFvbTraditionalMmInitialize (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ FvbInitialize ();
+
+ return EFI_SUCCESS;
+}
diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Sp=
iFvbServiceCommon.h b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbS=
ervice/SpiFvbServiceCommon.h
new file mode 100644
index 000000000000..e9d69e985814
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbSer=
viceCommon.h
@@ -0,0 +1,158 @@
+/** @file
+ Common source definitions used in serial flash drivers
+
+Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef _SPI_FVB_SERVICE_COMMON_H
+#define _SPI_FVB_SERVICE_COMMON_H
+
+#include <Guid/EventGroup.h>
+#include <Guid/FirmwareFileSystem2.h>
+#include <Guid/SystemNvDataGuid.h>
+#include <Protocol/DevicePath.h>
+#include <Protocol/FirmwareVolumeBlock.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/IoLib.h>
+#include <Library/CacheMaintenanceLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/HobLib.h>
+
+#include <Library/SpiFlashCommonLib.h>
+
+//
+// Define two helper macro to extract the Capability field or Status fie=
ld in FVB
+// bit fields
+//
+#define EFI_FVB2_CAPABILITIES (EFI_FVB2_READ_DISABLED_CAP | \
+ EFI_FVB2_READ_ENABLED_CAP | \
+ EFI_FVB2_WRITE_DISABLED_CAP | \
+ EFI_FVB2_WRITE_ENABLED_CAP | \
+ EFI_FVB2_LOCK_CAP \
+ )
+
+#define EFI_FVB2_STATUS (EFI_FVB2_READ_STATUS | EFI_FVB2_WRITE_STATUS | =
EFI_FVB2_LOCK_STATUS)
+
+#define FVB_INSTANCE_SIGNATURE SIGNATURE_32('F','V','B','I')
+
+typedef struct {
+ UINT32 Signature;
+ UINTN FvBase;
+ UINTN NumOfBlocks;
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL FvbProtocol;
+ EFI_FIRMWARE_VOLUME_HEADER FvHeader;
+} EFI_FVB_INSTANCE;
+
+typedef struct {
+ EFI_FVB_INSTANCE *FvbInstance;
+ UINT32 NumFv;
+} FVB_GLOBAL;
+
+//
+// Fvb Protocol instance data
+//
+#define FVB_INSTANCE_FROM_THIS(a) CR(a, EFI_FVB_INSTANCE, FvbProtocol, F=
VB_INSTANCE_SIGNATURE)
+
+typedef struct {
+ MEDIA_FW_VOL_DEVICE_PATH FvDevPath;
+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;
+} FV_PIWG_DEVICE_PATH;
+
+typedef struct {
+ MEMMAP_DEVICE_PATH MemMapDevPath;
+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;
+} FV_MEMMAP_DEVICE_PATH;
+
+typedef struct {
+ UINT32 FvBase;
+ UINT32 FvSize;
+} FV_INFO;
+
+//
+// Protocol APIs
+//
+EFI_STATUS
+EFIAPI
+FvbProtocolGetAttributes (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ );
+
+EFI_STATUS
+EFIAPI
+FvbProtocolSetAttributes (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
+ );
+
+EFI_STATUS
+EFIAPI
+FvbProtocolGetPhysicalAddress (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ OUT EFI_PHYSICAL_ADDRESS *Address
+ );
+
+EFI_STATUS
+EFIAPI
+FvbProtocolGetBlockSize (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ OUT UINTN *BlockSize,
+ OUT UINTN *NumOfBlocks
+ );
+
+EFI_STATUS
+EFIAPI
+FvbProtocolRead (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ OUT UINT8 *Buffer
+ );
+
+EFI_STATUS
+EFIAPI
+FvbProtocolWrite (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ );
+
+EFI_STATUS
+EFIAPI
+FvbProtocolEraseBlocks (
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
+ ...
+ );
+
+BOOLEAN
+IsFvHeaderValid (
+ IN EFI_PHYSICAL_ADDRESS FvBase,
+ IN CONST EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader
+ );
+
+EFI_STATUS
+GetFvbInfo (
+ IN EFI_PHYSICAL_ADDRESS FvBaseAddress,
+ OUT EFI_FIRMWARE_VOLUME_HEADER **FvbInfo
+ );
+
+extern FVB_GLOBAL mFvbModuleGlobal;
+extern FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate;
+extern FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate;
+extern EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL mFvbProtocolTemplate;
+extern FV_INFO mPlatformFvBaseAddress[];
+extern FV_INFO mPlatformDefaultBaseAddress[];
+
+#endif
diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Sp=
iFvbServiceMm.h b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbServi=
ce/SpiFvbServiceMm.h
new file mode 100644
index 000000000000..36af1130c8ee
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbSer=
viceMm.h
@@ -0,0 +1,22 @@
+/** @file
+ Definitions common to MM implementation in this driver.
+
+ Copyright (c) Microsoft Corporation.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef _SPI_FVB_SERVICE_MM_H_
+#define _SPI_FVB_SERVICE_MM_H_
+
+/**
+ The function does the necessary initialization work for
+ Firmware Volume Block Driver.
+
+**/
+VOID
+FvbInitialize (
+ VOID
+ );
+
+#endif
diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Sp=
iFvbServiceSmm.inf b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbSe=
rvice/SpiFvbServiceSmm.inf
new file mode 100644
index 000000000000..bf1306f00201
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbSer=
viceSmm.inf
@@ -0,0 +1,68 @@
+### @file
+# Component description file for the Serial Flash device Runtime driver.
+#
+# Copyright (c) 2017-2019, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) Microsoft Corporation.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+###
+
+[Defines]
+ INF_VERSION =3D 0x00010017
+ BASE_NAME =3D SpiFvbServiceSmm
+ FILE_GUID =3D 68A10D85-6858-4402-B070-028B3EA2174=
7
+ VERSION_STRING =3D 1.0
+ MODULE_TYPE =3D DXE_SMM_DRIVER
+ PI_SPECIFICATION_VERSION =3D 1.10
+ ENTRY_POINT =3D SpiFvbTraditionalMmInitialize
+
+#
+# The following information is for reference only and not required by th=
e build tools.
+#
+# VALID_ARCHITECTURES =3D IA32 X64
+#
+
+[LibraryClasses]
+ PcdLib
+ MemoryAllocationLib
+ CacheMaintenanceLib
+ BaseMemoryLib
+ DebugLib
+ BaseLib
+ UefiBootServicesTableLib
+ UefiDriverEntryPoint
+ SpiFlashCommonLib
+ MmServicesTableLib
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelSiliconPkg/IntelSiliconPkg.dec
+
+[Pcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase ## CONS=
UMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize ## CONS=
UMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize ## CONS=
UMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize ## CONS=
UMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase ## CONS=
UMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize ## CONS=
UMES
+
+[Sources]
+ FvbInfo.c
+ SpiFvbServiceCommon.h
+ SpiFvbServiceCommon.c
+ SpiFvbServiceMm.h
+ SpiFvbServiceMm.c
+ SpiFvbServiceTraditionalMm.c
+
+[Protocols]
+ gEfiDevicePathProtocolGuid ## PRODUCES
+ gEfiSmmFirmwareVolumeBlockProtocolGuid ## PRODUCES
+
+[Guids]
+ gEfiFirmwareFileSystem2Guid ## CONSUMES
+ gEfiSystemNvDataFvGuid ## CONSUMES
+
+[Depex]
+ TRUE
diff --git a/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/Sp=
iFvbServiceStandaloneMm.inf b/Silicon/Intel/IntelSiliconPkg/Feature/Flash=
/SpiFvbService/SpiFvbServiceStandaloneMm.inf
new file mode 100644
index 000000000000..b66233968247
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbSer=
viceStandaloneMm.inf
@@ -0,0 +1,67 @@
+### @file
+# Component description file for the Serial Flash device Standalone MM d=
river.
+#
+# Copyright (c) 2017-2019, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) Microsoft Corporation.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+###
+
+[Defines]
+ INF_VERSION =3D 0x0001001B
+ BASE_NAME =3D SpiFvbServiceStandaloneMm
+ FILE_GUID =3D E6313655-8BD0-4EAB-B319-AD5E212CE6A=
B
+ VERSION_STRING =3D 1.0
+ MODULE_TYPE =3D MM_STANDALONE
+ PI_SPECIFICATION_VERSION =3D 0x00010032
+ ENTRY_POINT =3D SpiFvbStandaloneMmInitialize
+
+#
+# The following information is for reference only and not required by th=
e build tools.
+#
+# VALID_ARCHITECTURES =3D IA32 X64
+#
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ CacheMaintenanceLib
+ DebugLib
+ MemoryAllocationLib
+ PcdLib
+ MmServicesTableLib
+ SpiFlashCommonLib
+ StandaloneMmDriverEntryPoint
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ IntelSiliconPkg/IntelSiliconPkg.dec
+
+[Pcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase ## CONS=
UMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize ## CONS=
UMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize ## CONS=
UMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize ## CONS=
UMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase ## CONS=
UMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize ## CONS=
UMES
+
+[Sources]
+ FvbInfo.c
+ SpiFvbServiceCommon.h
+ SpiFvbServiceCommon.c
+ SpiFvbServiceMm.h
+ SpiFvbServiceMm.c
+ SpiFvbServiceStandaloneMm.c
+
+[Protocols]
+ gEfiDevicePathProtocolGuid ## PRODUCES
+ gEfiSmmFirmwareVolumeBlockProtocolGuid ## PRODUCES
+
+[Guids]
+ gEfiFirmwareFileSystem2Guid ## CONSUMES
+ gEfiSystemNvDataFvGuid ## CONSUMES
+
+[Depex]
+ TRUE
diff --git a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc b/Silicon/=
Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
index d4e15100bfde..1e826a080f28 100644
--- a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
+++ b/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
@@ -40,6 +40,9 @@ [LibraryClasses]
PeiGetVtdPmrAlignmentLib|IntelSiliconPkg/Library/PeiGetVtdPmrAlignment=
Lib/PeiGetVtdPmrAlignmentLib.inf
TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasur=
ementLibNull.inf
MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf
+ SpiFlashCommonLib|IntelSiliconPkg/Library/SpiFlashCommonLibNull/SpiFla=
shCommonLibNull.inf
+ UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiB=
ootServicesTableLib.inf
+ UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEnt=
ryPoint.inf
=20
[LibraryClasses.common.PEIM]
PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf
@@ -61,8 +64,14 @@ [LibraryClasses.common.DXE_DRIVER]
=20
[LibraryClasses.common.DXE_SMM_DRIVER]
MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAll=
ocationLib.inf
+ MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLi=
b.inf
SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTabl=
eLib.inf
=20
+[LibraryClasses.common.MM_STANDALONE]
+ MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmMemoryAllocati=
onLib/StandaloneMmMemoryAllocationLib.inf
+ MmServicesTableLib|MdePkg/Library/StandaloneMmServicesTableLib/Standal=
oneMmServicesTableLib.inf
+ StandaloneMmDriverEntryPoint|MdePkg/Library/StandaloneMmDriverEntryPoi=
nt/StandaloneMmDriverEntryPoint.inf
+
########################################################################=
###########################
#
# Components Section - list of the modules and components that will be p=
rocessed by compilation
@@ -86,6 +95,8 @@ [Components]
IntelSiliconPkg/Library/DxeSmbiosDataHobLib/DxeSmbiosDataHobLib.inf
IntelSiliconPkg/Feature/PcieSecurity/IntelPciDeviceSecurityDxe/IntelPc=
iDeviceSecurityDxe.inf
IntelSiliconPkg/Feature/PcieSecurity/SamplePlatformDevicePolicyDxe/Sam=
plePlatformDevicePolicyDxe.inf
+ IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceSmm.inf
+ IntelSiliconPkg/Feature/Flash/SpiFvbService/SpiFvbServiceStandaloneMm.=
inf
IntelSiliconPkg/Feature/VTd/IntelVTdDxe/IntelVTdDxe.inf
IntelSiliconPkg/Feature/VTd/IntelVTdDmarPei/IntelVTdDmarPei.inf
IntelSiliconPkg/Feature/VTd/IntelVTdPmrPei/IntelVTdPmrPei.inf
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 09/41] IntelSiliconPkg: Add SmmSpiFlashCommonLib

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Adds the SMM instance of SpiFlashCommonLib. The code is based on
refactoring existing library instances into a consolidated version
with no functional impact.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/SmmSpiFlashCo=
mmonLib.c | 58 ++++++
Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/SpiFlashCommo=
n.c | 209 ++++++++++++++++++++
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc =
| 5 +
Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/SmmSpiFlashCo=
mmonLib.inf | 48 +++++
4 files changed, 320 insertions(+)

diff --git a/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/S=
mmSpiFlashCommonLib.c b/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlash=
CommonLib/SmmSpiFlashCommonLib.c
new file mode 100644
index 000000000000..7941b8f8720c
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/SmmSpiFl=
ashCommonLib.c
@@ -0,0 +1,58 @@
+/** @file
+ SMM Library instance of SPI Flash Common Library Class
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Library/SmmServicesTableLib.h>
+#include <Protocol/Spi.h>
+#include <Library/DebugLib.h>
+
+extern PCH_SPI_PROTOCOL *mSpiProtocol;
+
+extern UINTN mBiosAreaBaseAddress;
+extern UINTN mBiosSize;
+extern UINTN mBiosOffset;
+
+/**
+ The library constructuor.
+
+ The function does the necessary initialization work for this library
+ instance.
+
+ @param[in] ImageHandle The firmware allocated handle for the UE=
FI image.
+ @param[in] SystemTable A pointer to the EFI system table.
+
+ @retval EFI_SUCCESS The function always return EFI_SUCCESS f=
or now.
+ It will ASSERT on error for debug versio=
n.
+ @retval EFI_ERROR Please reference LocateProtocol for erro=
r code details.
+**/
+EFI_STATUS
+EFIAPI
+SmmSpiFlashCommonLibConstructor (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ UINT32 BaseAddr;
+ UINT32 RegionSize;
+
+ mBiosAreaBaseAddress =3D (UINTN)PcdGet32 (PcdBiosAreaBaseAddress);
+ mBiosSize =3D (UINTN)PcdGet32 (PcdBiosSize);
+
+ //
+ // Locate the SMM SPI protocol.
+ //
+ Status =3D gSmst->SmmLocateProtocol (
+ &gPchSmmSpiProtocolGuid,
+ NULL,
+ (VOID **) &mSpiProtocol
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ mSpiProtocol->GetRegionAddress (mSpiProtocol, FlashRegionBios, &BaseAd=
dr, &RegionSize);
+ mBiosOffset =3D BaseAddr;
+ return Status;
+}
diff --git a/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/S=
piFlashCommon.c b/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommon=
Lib/SpiFlashCommon.c
new file mode 100644
index 000000000000..daebaf8e5e33
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/SpiFlash=
Common.c
@@ -0,0 +1,209 @@
+/** @file
+ Wrap PCH_SPI_PROTOCOL to provide some library level interfaces
+ for module use.
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Library/SpiFlashCommonLib.h>
+#include <Library/IoLib.h>
+#include <Protocol/Spi.h>
+
+PCH_SPI_PROTOCOL *mSpiProtocol;
+
+//
+// Variables for boottime and runtime usage.
+//
+UINTN mBiosAreaBaseAddress =3D 0;
+UINTN mBiosSize =3D 0;
+UINTN mBiosOffset =3D 0;
+
+/**
+ Enable block protection on the Serial Flash device.
+
+ @retval EFI_SUCCESS Opertion is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashLock (
+ VOID
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Read NumBytes bytes of data from the address specified by
+ PAddress into Buffer.
+
+ @param[in] Address The starting physical address of the rea=
d.
+ @param[in,out] NumBytes On input, the number of bytes to read. O=
n output, the number
+ of bytes actually read.
+ @param[out] Buffer The destination data buffer for the read=
.
+
+ @retval EFI_SUCCESS Operation is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashRead (
+ IN UINTN Address,
+ IN OUT UINT32 *NumBytes,
+ OUT UINT8 *Buffer
+ )
+{
+ ASSERT ((NumBytes !=3D NULL) && (Buffer !=3D NULL));
+ if ((NumBytes =3D=3D NULL) || (Buffer =3D=3D NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // This function is implemented specifically for those platforms
+ // at which the SPI device is memory mapped for read. So this
+ // function just do a memory copy for Spi Flash Read.
+ //
+ CopyMem (Buffer, (VOID *) Address, *NumBytes);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write NumBytes bytes of data from Buffer to the address specified by
+ PAddresss.
+
+ @param[in] Address The starting physical address of the w=
rite.
+ @param[in,out] NumBytes On input, the number of bytes to write=
. On output,
+ the actual number of bytes written.
+ @param[in] Buffer The source data buffer for the write.
+
+ @retval EFI_SUCCESS Operation is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+ @retval EFI_INVALID_PARAMETER Invalid parameter.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashWrite (
+ IN UINTN Address,
+ IN OUT UINT32 *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINTN Offset;
+ UINT32 Length;
+ UINT32 RemainingBytes;
+
+ ASSERT ((NumBytes !=3D NULL) && (Buffer !=3D NULL));
+ if ((NumBytes =3D=3D NULL) || (Buffer =3D=3D NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ASSERT (Address >=3D mBiosAreaBaseAddress);
+ if (Address < mBiosAreaBaseAddress) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Offset =3D Address - mBiosAreaBaseAddress;
+
+ ASSERT ((*NumBytes + Offset) <=3D mBiosSize);
+ if ((*NumBytes + Offset) > mBiosSize) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Status =3D EFI_SUCCESS;
+ RemainingBytes =3D *NumBytes;
+
+
+ while (RemainingBytes > 0) {
+ if (RemainingBytes > SECTOR_SIZE_4KB) {
+ Length =3D SECTOR_SIZE_4KB;
+ } else {
+ Length =3D RemainingBytes;
+ }
+ Status =3D mSpiProtocol->FlashWrite (
+ mSpiProtocol,
+ FlashRegionBios,
+ (UINT32) Offset,
+ Length,
+ Buffer
+ );
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ RemainingBytes -=3D Length;
+ Offset +=3D Length;
+ Buffer +=3D Length;
+ }
+
+ //
+ // Actual number of bytes written
+ //
+ *NumBytes -=3D RemainingBytes;
+
+ return Status;
+}
+
+/**
+ Erase the block starting at Address.
+
+ @param[in] Address The starting physical address of the block=
to be erased.
+ This library assume that caller garantee t=
hat the PAddress
+ is at the starting address of this block.
+ @param[in] NumBytes On input, the number of bytes of the logic=
al block to be erased.
+ On output, the actual number of bytes eras=
ed.
+
+ @retval EFI_SUCCESS. Operation is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+ @retval EFI_INVALID_PARAMETER Invalid parameter.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashBlockErase (
+ IN UINTN Address,
+ IN UINTN *NumBytes
+ )
+{
+ EFI_STATUS Status;
+ UINTN Offset;
+ UINTN RemainingBytes;
+
+ ASSERT (NumBytes !=3D NULL);
+ if (NumBytes =3D=3D NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ASSERT (Address >=3D mBiosAreaBaseAddress);
+ if (Address < mBiosAreaBaseAddress) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Offset =3D Address - mBiosAreaBaseAddress;
+
+ ASSERT ((*NumBytes % SECTOR_SIZE_4KB) =3D=3D 0);
+ if ((*NumBytes % SECTOR_SIZE_4KB) !=3D 0) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ASSERT ((*NumBytes + Offset) <=3D mBiosSize);
+ if ((*NumBytes + Offset) > mBiosSize) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Status =3D EFI_SUCCESS;
+ RemainingBytes =3D *NumBytes;
+
+
+ Status =3D mSpiProtocol->FlashErase (
+ mSpiProtocol,
+ FlashRegionBios,
+ (UINT32) Offset,
+ (UINT32) RemainingBytes
+ );
+ return Status;
+}
diff --git a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc b/Silicon/=
Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
index aeed452ed521..d4e15100bfde 100644
--- a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
+++ b/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
@@ -59,6 +59,10 @@ [LibraryClasses.common.DXE_DRIVER]
HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryA=
llocationLib.inf
=20
+[LibraryClasses.common.DXE_SMM_DRIVER]
+ MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAll=
ocationLib.inf
+ SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTabl=
eLib.inf
+
########################################################################=
###########################
#
# Components Section - list of the modules and components that will be p=
rocessed by compilation
@@ -95,6 +99,7 @@ [Components]
IntelSiliconPkg/Library/DxeAslUpdateLib/DxeAslUpdateLib.inf
IntelSiliconPkg/Library/ReportCpuHobLib/ReportCpuHobLib.inf
IntelSiliconPkg/Library/SpiFlashCommonLibNull/SpiFlashCommonLibNull.in=
f
+ IntelSiliconPkg/Library/SmmSpiFlashCommonLib/SmmSpiFlashCommonLib.inf
=20
[BuildOptions]
*_*_*_CC_FLAGS =3D -D DISABLE_NEW_DEPRECATED_INTERFACES
diff --git a/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/S=
mmSpiFlashCommonLib.inf b/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFla=
shCommonLib/SmmSpiFlashCommonLib.inf
new file mode 100644
index 000000000000..f6a06351ace5
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCommonLib/SmmSpiFl=
ashCommonLib.inf
@@ -0,0 +1,48 @@
+## @file
+# SMM Library instance of Spi Flash Common Library Class
+#
+# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION =3D 0x00010017
+ BASE_NAME =3D SmmSpiFlashCommonLib
+ FILE_GUID =3D 99721728-C39D-4600-BD38-71E8238FEEF=
2
+ VERSION_STRING =3D 1.0
+ MODULE_TYPE =3D DXE_SMM_DRIVER
+ LIBRARY_CLASS =3D SpiFlashCommonLib|DXE_SMM_DRIVER
+ CONSTRUCTOR =3D SmmSpiFlashCommonLibConstructor
+#
+# The following information is for reference only and not required by th=
e build tools.
+#
+# VALID_ARCHITECTURES =3D IA32 X64
+#
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
+ IoLib
+ MemoryAllocationLib
+ SmmServicesTableLib
+ UefiLib
+
+[Packages]
+ MdePkg/MdePkg.dec
+ IntelSiliconPkg/IntelSiliconPkg.dec
+
+[Pcd]
+ gIntelSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress ## CONSUMES
+ gIntelSiliconPkgTokenSpaceGuid.PcdBiosSize ## CONSUMES
+
+[Sources]
+ SmmSpiFlashCommonLib.c
+ SpiFlashCommon.c
+
+[Protocols]
+ gPchSmmSpiProtocolGuid ## CONSUMES
+
+[Depex.X64.DXE_SMM_DRIVER]
+ gPchSmmSpiProtocolGuid
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 08/41] IntelSiliconPkg: Add SpiFlashCommonLib

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Adds the SpiFlashCommonLib interface to IntelSiliconPkg. The initial
library instance added in this change is the NULL instance.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Silicon/Intel/IntelSiliconPkg/Library/SpiFlashCommonLibNull/SpiFlashComm=
onLibNull.c | 101 ++++++++++++++++++++
Silicon/Intel/IntelSiliconPkg/Include/Library/SpiFlashCommonLib.h =
| 98 +++++++++++++++++++
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec =
| 4 +
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc =
| 1 +
Silicon/Intel/IntelSiliconPkg/Library/SpiFlashCommonLibNull/SpiFlashComm=
onLibNull.inf | 28 ++++++
5 files changed, 232 insertions(+)

diff --git a/Silicon/Intel/IntelSiliconPkg/Library/SpiFlashCommonLibNull/=
SpiFlashCommonLibNull.c b/Silicon/Intel/IntelSiliconPkg/Library/SpiFlashC=
ommonLibNull/SpiFlashCommonLibNull.c
new file mode 100644
index 000000000000..c5f46829869c
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Library/SpiFlashCommonLibNull/SpiFlas=
hCommonLibNull.c
@@ -0,0 +1,101 @@
+/** @file
+ Null Library instance of SPI Flash Common Library Class
+
+Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Uefi.h>
+#include <Library/DebugLib.h>
+#include <Library/SpiFlashCommonLib.h>
+
+/**
+ Enable block protection on the Serial Flash device.
+
+ @retval EFI_SUCCESS Operation is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashLock (
+ VOID
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Read NumBytes bytes of data from the address specified by
+ PAddress into Buffer.
+
+ @param[in] Address The starting physical address of the rea=
d.
+ @param[in,out] NumBytes On input, the number of bytes to read. O=
n output, the number
+ of bytes actually read.
+ @param[out] Buffer The destination data buffer for the read=
.
+
+ @retval EFI_SUCCESS Operation is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashRead (
+ IN UINTN Address,
+ IN OUT UINT32 *NumBytes,
+ OUT UINT8 *Buffer
+ )
+{
+ ASSERT(FALSE);
+ return EFI_SUCCESS;
+}
+
+/**
+ Write NumBytes bytes of data from Buffer to the address specified by
+ PAddresss.
+
+ @param[in] Address The starting physical address of the w=
rite.
+ @param[in,out] NumBytes On input, the number of bytes to write=
. On output,
+ the actual number of bytes written.
+ @param[in] Buffer The source data buffer for the write.
+
+ @retval EFI_SUCCESS Operation is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashWrite (
+ IN UINTN Address,
+ IN OUT UINT32 *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ ASSERT(FALSE);
+ return EFI_SUCCESS;
+}
+
+/**
+ Erase the block starting at Address.
+
+ @param[in] Address The starting physical address of the block=
to be erased.
+ This library assume that caller guarantee =
that the PAddress
+ is at the starting address of this block.
+ @param[in] NumBytes On input, the number of bytes of the logic=
al block to be erased.
+ On output, the actual number of bytes eras=
ed.
+
+ @retval EFI_SUCCESS. Operation is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashBlockErase (
+ IN UINTN Address,
+ IN UINTN *NumBytes
+ )
+{
+ ASSERT(FALSE);
+ return EFI_SUCCESS;
+}
diff --git a/Silicon/Intel/IntelSiliconPkg/Include/Library/SpiFlashCommon=
Lib.h b/Silicon/Intel/IntelSiliconPkg/Include/Library/SpiFlashCommonLib.h
new file mode 100644
index 000000000000..ef62ba238d71
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Include/Library/SpiFlashCommonLib.h
@@ -0,0 +1,98 @@
+/** @file
+ The header file includes the common header files, defines
+ internal structure and functions used by SpiFlashCommonLib.
+
+ Copyright (c) 2019 Intel Corporation. All rights reserved. <BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef __SPI_FLASH_COMMON_LIB_H__
+#define __SPI_FLASH_COMMON_LIB_H__
+
+#include <Uefi.h>
+#include <Library/BaseLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#define SECTOR_SIZE_4KB 0x1000 // Common 4kBytes sector size
+/**
+ Enable block protection on the Serial Flash device.
+
+ @retval EFI_SUCCESS Opertion is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashLock (
+ VOID
+ );
+
+/**
+ Read NumBytes bytes of data from the address specified by
+ PAddress into Buffer.
+
+ @param[in] Address The starting physical address of the rea=
d.
+ @param[in,out] NumBytes On input, the number of bytes to read. O=
n output, the number
+ of bytes actually read.
+ @param[out] Buffer The destination data buffer for the read=
.
+
+ @retval EFI_SUCCESS Opertion is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashRead (
+ IN UINTN Address,
+ IN OUT UINT32 *NumBytes,
+ OUT UINT8 *Buffer
+ );
+
+/**
+ Write NumBytes bytes of data from Buffer to the address specified by
+ PAddresss.
+
+ @param[in] Address The starting physical address of the w=
rite.
+ @param[in,out] NumBytes On input, the number of bytes to write=
. On output,
+ the actual number of bytes written.
+ @param[in] Buffer The source data buffer for the write.
+
+ @retval EFI_SUCCESS Opertion is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashWrite (
+ IN UINTN Address,
+ IN OUT UINT32 *NumBytes,
+ IN UINT8 *Buffer
+ );
+
+/**
+ Erase the block starting at Address.
+
+ @param[in] Address The starting physical address of the block=
to be erased.
+ This library assume that caller garantee t=
hat the PAddress
+ is at the starting address of this block.
+ @param[in] NumBytes On input, the number of bytes of the logic=
al block to be erased.
+ On output, the actual number of bytes eras=
ed.
+
+ @retval EFI_SUCCESS. Opertion is successful.
+ @retval EFI_DEVICE_ERROR If there is any device errors.
+
+**/
+EFI_STATUS
+EFIAPI
+SpiFlashBlockErase (
+ IN UINTN Address,
+ IN UINTN *NumBytes
+ );
+
+#endif
diff --git a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec b/Silicon/=
Intel/IntelSiliconPkg/IntelSiliconPkg.dec
index 5c2c9cfbcaab..1a8290113fc9 100644
--- a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
+++ b/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
@@ -46,6 +46,10 @@ [LibraryClasses.IA32, LibraryClasses.X64]
#
ReportCpuHobLib|Include/Library/ReportCpuHobLib.h
=20
+ ## @libraryclass Provides services to perform SPI flash actions
+ #
+ SpiFlashCommonLib|Include/Library/SpiFlashCommonLib.h
+
[Guids]
## GUID for Package token space
# {A9F8D54E-1107-4F0A-ADD0-4587E7A4A735}
diff --git a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc b/Silicon/=
Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
index 1092371d848e..aeed452ed521 100644
--- a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
+++ b/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc
@@ -94,6 +94,7 @@ [Components]
IntelSiliconPkg/Library/PeiDxeSmmBootMediaLib/DxeSmmFirmwareBootMediaL=
ib.inf
IntelSiliconPkg/Library/DxeAslUpdateLib/DxeAslUpdateLib.inf
IntelSiliconPkg/Library/ReportCpuHobLib/ReportCpuHobLib.inf
+ IntelSiliconPkg/Library/SpiFlashCommonLibNull/SpiFlashCommonLibNull.in=
f
=20
[BuildOptions]
*_*_*_CC_FLAGS =3D -D DISABLE_NEW_DEPRECATED_INTERFACES
diff --git a/Silicon/Intel/IntelSiliconPkg/Library/SpiFlashCommonLibNull/=
SpiFlashCommonLibNull.inf b/Silicon/Intel/IntelSiliconPkg/Library/SpiFlas=
hCommonLibNull/SpiFlashCommonLibNull.inf
new file mode 100644
index 000000000000..f2d9e4f21d4b
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Library/SpiFlashCommonLibNull/SpiFlas=
hCommonLibNull.inf
@@ -0,0 +1,28 @@
+### @file
+# NULL instance of Spi Flash Common Library Class
+#
+# Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+###
+
+[Defines]
+ INF_VERSION =3D 0x00010017
+ BASE_NAME =3D SpiFlashCommonLibNull
+ FILE_GUID =3D F35BBEE7-A681-443E-BB15-07AF9FABBDE=
D
+ VERSION_STRING =3D 1.0
+ MODULE_TYPE =3D BASE
+ LIBRARY_CLASS =3D SpiFlashCommonLib
+#
+# The following information is for reference only and not required by th=
e build tools.
+#
+# VALID_ARCHITECTURES =3D IA32 X64
+#
+
+[Packages]
+ MdePkg/MdePkg.dec
+ IntelSiliconPkg/IntelSiliconPkg.dec
+
+[Sources]
+ SpiFlashCommonLibNull.c
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 07/41] IntelSiliconPkg: Add PCH SPI Protocol

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

These SPI Protocol definitions are intended to serve as the single
definitions for Intel platform and silicon packages.

1. gPchSpiProtocolGuid
2. gPchSmmSpiProtocolGuid

Cc: Ray Ni <ray.ni@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Silicon/Intel/IntelSiliconPkg/Include/Protocol/Spi.h | 301 +++++++++++++=
+++++++
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec | 5 +
2 files changed, 306 insertions(+)

diff --git a/Silicon/Intel/IntelSiliconPkg/Include/Protocol/Spi.h b/Silic=
on/Intel/IntelSiliconPkg/Include/Protocol/Spi.h
new file mode 100644
index 000000000000..c13dc5a5f5f5
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Include/Protocol/Spi.h
@@ -0,0 +1,301 @@
+/** @file
+ This file defines the PCH SPI Protocol which implements the
+ Intel(R) PCH SPI Host Controller Compatibility Interface.
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+#ifndef _PCH_SPI_PROTOCOL_H_
+#define _PCH_SPI_PROTOCOL_H_
+
+//
+// Extern the GUID for protocol users.
+//
+extern EFI_GUID gPchSpiProtocolGuid;
+extern EFI_GUID gPchSmmSpiProtocolGuid;
+
+//
+// Forward reference for ANSI C compatibility
+//
+typedef struct _PCH_SPI_PROTOCOL PCH_SPI_PROTOCOL;
+
+//
+// SPI protocol data structures and definitions
+//
+
+/**
+ Flash Region Type
+**/
+typedef enum {
+ FlashRegionDescriptor,
+ FlashRegionBios,
+ FlashRegionMe,
+ FlashRegionGbE,
+ FlashRegionPlatformData,
+ FlashRegionDer,
+ FlashRegionSecondaryBios,
+ FlashRegionuCodePatch,
+ FlashRegionEC,
+ FlashRegionDeviceExpansion2,
+ FlashRegionIE,
+ FlashRegion10Gbe_A,
+ FlashRegion10Gbe_B,
+ FlashRegion13,
+ FlashRegion14,
+ FlashRegion15,
+ FlashRegionAll,
+ FlashRegionMax
+} FLASH_REGION_TYPE;
+//
+// Protocol member functions
+//
+
+/**
+ Read data from the flash part.
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] FlashRegionType The Flash Region type for flash cycle =
which is listed in the Descriptor.
+ @param[in] Address The Flash Linear Address must fall wit=
hin a region for which BIOS has access permissions.
+ @param[in] ByteCount Number of bytes in the data portion of=
the SPI cycle.
+ @param[out] Buffer The Pointer to caller-allocated buffer=
containing the dada received.
+ It is the caller's responsibility to m=
ake sure Buffer is large enough for the total number of bytes read.
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_FLASH_READ) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN FLASH_REGION_TYPE FlashRegionType,
+ IN UINT32 Address,
+ IN UINT32 ByteCount,
+ OUT UINT8 *Buffer
+ );
+
+/**
+ Write data to the flash part. Remark: Erase may be needed before write=
to the flash part.
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] FlashRegionType The Flash Region type for flash cycle =
which is listed in the Descriptor.
+ @param[in] Address The Flash Linear Address must fall wit=
hin a region for which BIOS has access permissions.
+ @param[in] ByteCount Number of bytes in the data portion of=
the SPI cycle.
+ @param[in] Buffer Pointer to caller-allocated buffer con=
taining the data sent during the SPI cycle.
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_FLASH_WRITE) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN FLASH_REGION_TYPE FlashRegionType,
+ IN UINT32 Address,
+ IN UINT32 ByteCount,
+ IN UINT8 *Buffer
+ );
+
+/**
+ Erase some area on the flash part.
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] FlashRegionType The Flash Region type for flash cycle =
which is listed in the Descriptor.
+ @param[in] Address The Flash Linear Address must fall wit=
hin a region for which BIOS has access permissions.
+ @param[in] ByteCount Number of bytes in the data portion of=
the SPI cycle.
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_FLASH_ERASE) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN FLASH_REGION_TYPE FlashRegionType,
+ IN UINT32 Address,
+ IN UINT32 ByteCount
+ );
+
+/**
+ Read SFDP data from the flash part.
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] ComponentNumber The Componen Number for chip select
+ @param[in] Address The starting byte address for SFDP dat=
a read.
+ @param[in] ByteCount Number of bytes in SFDP data portion o=
f the SPI cycle
+ @param[out] SfdpData The Pointer to caller-allocated buffer=
containing the SFDP data received
+ It is the caller's responsibility to m=
ake sure Buffer is large enough for the total number of bytes read
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_FLASH_READ_SFDP) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN UINT8 ComponentNumber,
+ IN UINT32 Address,
+ IN UINT32 ByteCount,
+ OUT UINT8 *SfdpData
+ );
+
+/**
+ Read Jedec Id from the flash part.
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] ComponentNumber The Componen Number for chip select
+ @param[in] ByteCount Number of bytes in JedecId data portio=
n of the SPI cycle, the data size is 3 typically
+ @param[out] JedecId The Pointer to caller-allocated buffer=
containing JEDEC ID received
+ It is the caller's responsibility to m=
ake sure Buffer is large enough for the total number of bytes read.
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_FLASH_READ_JEDEC_ID) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN UINT8 ComponentNumber,
+ IN UINT32 ByteCount,
+ OUT UINT8 *JedecId
+ );
+
+/**
+ Write the status register in the flash part.
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] ByteCount Number of bytes in Status data portion=
of the SPI cycle, the data size is 1 typically
+ @param[in] StatusValue The Pointer to caller-allocated buffer=
containing the value of Status register writing
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_FLASH_WRITE_STATUS) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN UINT32 ByteCount,
+ IN UINT8 *StatusValue
+ );
+
+/**
+ Read status register in the flash part.
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] ByteCount Number of bytes in Status data portion=
of the SPI cycle, the data size is 1 typically
+ @param[out] StatusValue The Pointer to caller-allocated buffer=
containing the value of Status register received.
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_FLASH_READ_STATUS) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN UINT32 ByteCount,
+ OUT UINT8 *StatusValue
+ );
+
+/**
+ Get the SPI region base and size, based on the enum type
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] FlashRegionType The Flash Region type for for the base=
address which is listed in the Descriptor.
+ @param[out] BaseAddress The Flash Linear Address for the Regio=
n 'n' Base
+ @param[out] RegionSize The size for the Region 'n'
+
+ @retval EFI_SUCCESS Read success
+ @retval EFI_INVALID_PARAMETER Invalid region type given
+ @retval EFI_DEVICE_ERROR The region is not used
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_GET_REGION_ADDRESS) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN FLASH_REGION_TYPE FlashRegionType,
+ OUT UINT32 *BaseAddress,
+ OUT UINT32 *RegionSize
+ );
+
+/**
+ Read PCH Soft Strap Values
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] SoftStrapAddr PCH Soft Strap address offset from FPS=
BA.
+ @param[in] ByteCount Number of bytes in SoftStrap data port=
ion of the SPI cycle
+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer=
containing PCH Soft Strap Value.
+ If the value of ByteCount is 0, the da=
ta type of SoftStrapValue should be UINT16 and SoftStrapValue will be PCH=
Soft Strap Length
+ It is the caller's responsibility to m=
ake sure Buffer is large enough for the total number of bytes read.
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_READ_PCH_SOFTSTRAP) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN UINT32 SoftStrapAddr,
+ IN UINT32 ByteCount,
+ OUT VOID *SoftStrapValue
+ );
+
+/**
+ Read CPU Soft Strap Values
+
+ @param[in] This Pointer to the PCH_SPI_PROTOCOL instan=
ce.
+ @param[in] SoftStrapAddr CPU Soft Strap address offset from FCP=
USBA.
+ @param[in] ByteCount Number of bytes in SoftStrap data port=
ion of the SPI cycle.
+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer=
containing CPU Soft Strap Value.
+ If the value of ByteCount is 0, the da=
ta type of SoftStrapValue should be UINT16 and SoftStrapValue will be PCH=
Soft Strap Length
+ It is the caller's responsibility to m=
ake sure Buffer is large enough for the total number of bytes read.
+
+ @retval EFI_SUCCESS Command succeed.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid=
.
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormall=
y.
+**/
+typedef
+EFI_STATUS
+(EFIAPI *PCH_SPI_READ_CPU_SOFTSTRAP) (
+ IN PCH_SPI_PROTOCOL *This,
+ IN UINT32 SoftStrapAddr,
+ IN UINT32 ByteCount,
+ OUT VOID *SoftStrapValue
+ );
+
+/**
+ These protocols/PPI allows a platform module to perform SPI operations=
through the
+ Intel PCH SPI Host Controller Interface.
+**/
+struct _PCH_SPI_PROTOCOL {
+ /**
+ This member specifies the revision of this structure. This field is =
used to
+ indicate backwards compatible changes to the protocol.
+ **/
+ UINT8 Revision;
+ PCH_SPI_FLASH_READ FlashRead; ///< Read data f=
rom the flash part.
+ PCH_SPI_FLASH_WRITE FlashWrite; ///< Write data =
to the flash part. Remark: Erase may be needed before write to the flash =
part.
+ PCH_SPI_FLASH_ERASE FlashErase; ///< Erase some =
area on the flash part.
+ PCH_SPI_FLASH_READ_SFDP FlashReadSfdp; ///< Read SFDP d=
ata from the flash part.
+ PCH_SPI_FLASH_READ_JEDEC_ID FlashReadJedecId; ///< Read Jedec =
Id from the flash part.
+ PCH_SPI_FLASH_WRITE_STATUS FlashWriteStatus; ///< Write the s=
tatus register in the flash part.
+ PCH_SPI_FLASH_READ_STATUS FlashReadStatus; ///< Read status=
register in the flash part.
+ PCH_SPI_GET_REGION_ADDRESS GetRegionAddress; ///< Get the SPI=
region base and size
+ PCH_SPI_READ_PCH_SOFTSTRAP ReadPchSoftStrap; ///< Read PCH So=
ft Strap Values
+ PCH_SPI_READ_CPU_SOFTSTRAP ReadCpuSoftStrap; ///< Read CPU So=
ft Strap Values
+};
+
+/**
+ PCH SPI PPI/PROTOCOL revision number
+
+ Revision 1: Initial version
+**/
+#define PCH_SPI_SERVICES_REVISION 1
+
+#endif
diff --git a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec b/Silicon/=
Intel/IntelSiliconPkg/IntelSiliconPkg.dec
index 70f030e3a295..5c2c9cfbcaab 100644
--- a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
+++ b/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
@@ -78,6 +78,11 @@ [Ppis]
gEdkiiVTdNullRootEntryTableGuid =3D { 0x3de0593f, 0x6e3e, 0x4542, { 0x=
a1, 0xcb, 0xcb, 0xb2, 0xdb, 0xeb, 0xd8, 0xff } }
=20
[Protocols]
+ ## Protocols that provide services for the Intel(R) PCH SPI Host Contr=
oller Compatibility Interface
+ # Include/Protocol/Spi.h
+ gPchSpiProtocolGuid =3D {0xc7d289, 0x1347, 0x4de0, {0xbf, 0x42, 0xe,=
0x26, 0x9d, 0xe, 0xf3, 0x4a}}
+ gPchSmmSpiProtocolGuid =3D {0x56521f06, 0xa62, 0x4822, {0x99, 0x63, 0x=
df, 0x1, 0x9d, 0x72, 0xc7, 0xe1}}
+
gEdkiiPlatformVTdPolicyProtocolGuid =3D { 0x3d17e448, 0x466, 0x4e20, {=
0x99, 0x9f, 0xb2, 0xe1, 0x34, 0x88, 0xee, 0x22 }}
=20
## Protocol for device security policy.
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 06/41] IntelSiliconPkg: Add PCH SPI PPI

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

This SPI PPI definition is intended to serve as the single
definition for Intel platform and silicon packages.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Silicon/Intel/IntelSiliconPkg/Include/Ppi/Spi.h | 25 +++++++++++++++++=
+++
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec | 3 +++
2 files changed, 28 insertions(+)

diff --git a/Silicon/Intel/IntelSiliconPkg/Include/Ppi/Spi.h b/Silicon/In=
tel/IntelSiliconPkg/Include/Ppi/Spi.h
new file mode 100644
index 000000000000..b2410bd17300
--- /dev/null
+++ b/Silicon/Intel/IntelSiliconPkg/Include/Ppi/Spi.h
@@ -0,0 +1,25 @@
+/** @file
+ This file defines the PCH SPI PPI which implements the
+ Intel(R) PCH SPI Host Controller Compatibility Interface.
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+#ifndef _PCH_SPI_PPI_H_
+#define _PCH_SPI_PPI_H_
+
+#include <Protocol/Spi.h>
+
+//
+// Extern the GUID for PPI users.
+//
+extern EFI_GUID gPchSpiPpiGuid;
+
+/**
+ Reuse the PCH_SPI_PROTOCOL definitions
+ This is possible becaues the PPI implementation does not rely on a Pei=
Service pointer,
+ as it uses EDKII Glue Lib to do IO accesses
+**/
+typedef PCH_SPI_PROTOCOL PCH_SPI_PPI;
+
+#endif
diff --git a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec b/Silicon/=
Intel/IntelSiliconPkg/IntelSiliconPkg.dec
index fb8391000347..70f030e3a295 100644
--- a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
+++ b/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
@@ -71,6 +71,9 @@ [Guids]
gEdkiiMicrocodeStorageTypeFlashGuid =3D { 0x2cba01b3, 0xd391, 0x4598, =
{ 0x8d, 0x89, 0xb7, 0xfc, 0x39, 0x22, 0xfd, 0x71 } }
=20
[Ppis]
+ ## Include/Ppi/Spi.h
+ gPchSpiPpiGuid =3D {0xdade7ce3, 0x6971, 0x4b75, {0x82, 0x5e, 0xe, 0xe0=
, 0xeb, 0x17, 0x72, 0x2d}}
+
gEdkiiVTdInfoPpiGuid =3D { 0x8a59fcb3, 0xf191, 0x400c, { 0x97, 0x67, 0=
x67, 0xaf, 0x2b, 0x25, 0x68, 0x4a } }
gEdkiiVTdNullRootEntryTableGuid =3D { 0x3de0593f, 0x6e3e, 0x4542, { 0x=
a1, 0xcb, 0xcb, 0xb2, 0xdb, 0xeb, 0xd8, 0xff } }
=20
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 05/41] IntelSiliconPkg: Add microcode FV PCDs

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Adds the following PCDs to IntelSiliconPkg.dec to consolidate the
PCD to a single silicon declaration file. This allows libraries
modules in IntelSiliconPkg to be able to use this PCD.

gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase
gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize
gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset

Cc: Ray Ni <ray.ni@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec | 3 +++
1 file changed, 3 insertions(+)

diff --git a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec b/Silicon/=
Intel/IntelSiliconPkg/IntelSiliconPkg.dec
index 097c4ca4d795..fb8391000347 100644
--- a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
+++ b/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
@@ -91,6 +91,9 @@ [PcdsFeatureFlag]
[PcdsFixedAtBuild]
gIntelSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress|0xFF800000|UINT3=
2|0x00000007
gIntelSiliconPkgTokenSpaceGuid.PcdBiosSize|0x00800000|UINT32|0x0000000=
8
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvBase|0xFFE60000|UINT=
32|0x00000009
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvSize|0x000A0000|UINT=
32|0x0000000A
+ gIntelSiliconPkgTokenSpaceGuid.PcdFlashMicrocodeFvOffset|0x00660000|UI=
NT32|0x0000000B
=20
[PcdsFixedAtBuild, PcdsPatchableInModule]
## Error code for VTd error.<BR><BR>
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 04/41] IntelSiliconPkg: Add BIOS area base address and size PCDs

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Adds the following PCDs to IntelSiliconPkg.dec to consolidate the
PCD to a single silicon declaration file. This allows libraries
and modules in IntelSiliconPkg to be able to use this PCD.

gIntelSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress
gIntelSiliconPkgTokenSpaceGuid.PcdBiosSize

Cc: Ray Ni <ray.ni@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec | 4 ++++
1 file changed, 4 insertions(+)

diff --git a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec b/Silicon/=
Intel/IntelSiliconPkg/IntelSiliconPkg.dec
index 2461ab8e06e7..097c4ca4d795 100644
--- a/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
+++ b/Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec
@@ -88,6 +88,10 @@ [PcdsFeatureFlag]
# @Prompt Shadow all microcode update patches.
gIntelSiliconPkgTokenSpaceGuid.PcdShadowAllMicrocode|FALSE|BOOLEAN|0x0=
0000006
=20
+[PcdsFixedAtBuild]
+ gIntelSiliconPkgTokenSpaceGuid.PcdBiosAreaBaseAddress|0xFF800000|UINT3=
2|0x00000007
+ gIntelSiliconPkgTokenSpaceGuid.PcdBiosSize|0x00800000|UINT32|0x0000000=
8
+
[PcdsFixedAtBuild, PcdsPatchableInModule]
## Error code for VTd error.<BR><BR>
# EDKII_ERROR_CODE_VTD_ERROR =3D (EFI_IO_BUS_UNSPECIFIED | (EFI_OEM_S=
PECIFIC | 0x00000000)) =3D 0x02008000<BR>
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 03/41] CometlakeOpenBoardPkg/PeiPolicyUpdateLib: Add missing GUID to INF

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

gEfiMemoryTypeInformationGuid is used in PeiSaPolicyUpdatePreMem.c
but not in the [Guids] section in PeiPolicyUpdateLib.inf.

Cc: Chasel Chiu <chasel.chiu@intel.com>
Cc: Nate DeSimone <nathaniel.l.desimone@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Cc: Deepika Kethi Reddy <deepika.kethi.reddy@intel.com>
Cc: Kathappan Esakkithevar <kathappan.esakkithevar@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
Reviewed-by: Chasel Chiu <chasel.chiu@intel.com>
---
Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolicyUpdateLib/P=
eiPolicyUpdateLib.inf | 1 +
1 file changed, 1 insertion(+)

diff --git a/Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolic=
yUpdateLib/PeiPolicyUpdateLib.inf b/Platform/Intel/CometlakeOpenBoardPkg/=
Policy/Library/PeiPolicyUpdateLib/PeiPolicyUpdateLib.inf
index fd51e2b8c40b..5213253f7313 100644
--- a/Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolicyUpdate=
Lib/PeiPolicyUpdateLib.inf
+++ b/Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolicyUpdate=
Lib/PeiPolicyUpdateLib.inf
@@ -270,3 +270,4 @@ [Ppis]
[Guids]
gTianoLogoGuid ## CONSUMES
gSiConfigGuid ## CONSUMES
+ gEfiMemoryTypeInformationGuid ## PRODUCES
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 02/41] WhiskeylakeOpenBoardPkg: Remove redundant IntelSiliconPkg.dec entry

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Removes extra IntelSiliconPkg.dec entry in PeiPolicyUpdateLib.inf.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
---
Platform/Intel/WhiskeylakeOpenBoardPkg/Policy/Library/PeiPolicyUpdateLib=
/PeiPolicyUpdateLib.inf | 1 -
1 file changed, 1 deletion(-)

diff --git a/Platform/Intel/WhiskeylakeOpenBoardPkg/Policy/Library/PeiPol=
icyUpdateLib/PeiPolicyUpdateLib.inf b/Platform/Intel/WhiskeylakeOpenBoard=
Pkg/Policy/Library/PeiPolicyUpdateLib/PeiPolicyUpdateLib.inf
index 252f92f48736..b36dc2b4097c 100644
--- a/Platform/Intel/WhiskeylakeOpenBoardPkg/Policy/Library/PeiPolicyUpda=
teLib/PeiPolicyUpdateLib.inf
+++ b/Platform/Intel/WhiskeylakeOpenBoardPkg/Policy/Library/PeiPolicyUpda=
teLib/PeiPolicyUpdateLib.inf
@@ -52,7 +52,6 @@ [Packages]
SecurityPkg/SecurityPkg.dec
IntelSiliconPkg/IntelSiliconPkg.dec
MinPlatformPkg/MinPlatformPkg.dec
- IntelSiliconPkg/IntelSiliconPkg.dec
=20
[FixedPcd]
gSiPkgTokenSpaceGuid.PcdTsegSize ## CONSUM=
ES
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 01/41] CometlakeOpenBoardPkg: Remove redundant IntelSiliconPkg.dec entry

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

Removes extra IntelSiliconPkg.dec entry in PeiPolicyUpdateLib.inf.

Cc: Chasel Chiu <chasel.chiu@intel.com>
Cc: Nate DeSimone <nathaniel.l.desimone@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Cc: Deepika Kethi Reddy <deepika.kethi.reddy@intel.com>
Cc: Kathappan Esakkithevar <kathappan.esakkithevar@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
Reviewed-by: Nate DeSimone <nathaniel.l.desimone@intel.com>
Reviewed-by: Chasel Chiu <chasel.chiu@intel.com>
---
Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolicyUpdateLib/P=
eiPolicyUpdateLib.inf | 1 -
1 file changed, 1 deletion(-)

diff --git a/Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolic=
yUpdateLib/PeiPolicyUpdateLib.inf b/Platform/Intel/CometlakeOpenBoardPkg/=
Policy/Library/PeiPolicyUpdateLib/PeiPolicyUpdateLib.inf
index 014967c7f65a..fd51e2b8c40b 100644
--- a/Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolicyUpdate=
Lib/PeiPolicyUpdateLib.inf
+++ b/Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolicyUpdate=
Lib/PeiPolicyUpdateLib.inf
@@ -52,7 +52,6 @@ [Packages]
SecurityPkg/SecurityPkg.dec
IntelSiliconPkg/IntelSiliconPkg.dec
MinPlatformPkg/MinPlatformPkg.dec
- IntelSiliconPkg/IntelSiliconPkg.dec
=20
[FixedPcd]
gSiPkgTokenSpaceGuid.PcdTsegSize ## CONSUM=
ES
--=20
2.28.0.windows.1


[edk2-platforms][PATCH v3 00/41] Consolidate SpiFlashCommonLib instances

Michael Kubacki
 

From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3D3307

SpiFlashCommonLib is duplicated in multiple places across the MinPlatform
design in edk2-platforms. I'm planning to build some additional
functionality on top of SpiFlashCommonLib and, ideally, this duplication
will be consolidated into a single instance usable across all current lib=
rary
consumers.

This patch series focuses on consolidating the various SpiFlashCommonLib
instances as agreed upon in https://edk2.groups.io/g/devel/message/71701.

Read the BZ for more general background around this series.

I only have an UpXtreme board on hand so maintainers/reviewers of other
board packages should test these changes on those boards.

V3 changes:
- Added support to IntelSiliconPkg to identify flash regions by GUID as
requested in v2 review feedback.
V2 changes:
- Rebased patch series on current edk2-platforms master (32183bdaa91)

Note: Previous patch series only received a couple review comments after
being on the mailing list for over 2 months. Please be respectful of
contributors time and efforts and review in a timely manner.

Cc: Agyeman Prince <prince.agyeman@intel.com>
Cc: Chasel Chiu <chasel.chiu@intel.com>
Cc: Deepika Kethi Reddy <deepika.kethi.reddy@intel.com>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Heng Luo <heng.luo@intel.com>
Cc: Jeremy Soller <jeremy@system76.com>
Cc: Kathappan Esakkithevar <kathappan.esakkithevar@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Nate DeSimone <nathaniel.l.desimone@intel.com>
Cc: Rangasai V Chaganty <rangasai.v.chaganty@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>

Michael Kubacki (41):
CometlakeOpenBoardPkg: Remove redundant IntelSiliconPkg.dec entry
WhiskeylakeOpenBoardPkg: Remove redundant IntelSiliconPkg.dec entry
CometlakeOpenBoardPkg/PeiPolicyUpdateLib: Add missing GUID to INF
IntelSiliconPkg: Add BIOS area base address and size PCDs
IntelSiliconPkg: Add microcode FV PCDs
IntelSiliconPkg: Add PCH SPI PPI
IntelSiliconPkg: Add PCH SPI Protocol
IntelSiliconPkg: Add SpiFlashCommonLib
IntelSiliconPkg: Add SmmSpiFlashCommonLib
IntelSiliconPkg: Add MM SPI FVB services
CometlakeOpenBoardPkg: Use IntelSiliconPkg BIOS area and ucode PCDs
KabylakeOpenBoardPkg: Use IntelSiliconPkg BIOS area and ucode PCDs
SimicsOpenBoardPkg: Use IntelSiliconPkg BIOS area and ucode PCDs
TigerlakeOpenBoardPkg: Use IntelSiliconPkg BIOS area and ucode PCDs
WhiskeylakeOpenBoardPkg: Use IntelSiliconPkg BIOS area and ucode PCDs
CoffeelakeSiliconPkg: Use IntelSiliconPkg BIOS area and ucode PCDs
KabylakeSiliconPkg: Use IntelSiliconPkg BIOS area and ucode PCDs
SimicsIch10Pkg: Use IntelSiliconPkg BIOS area and ucode PCDs
TigerlakeSiliconPkg: Use IntelSiliconPkg BIOS area and ucode PCDs
CometlakeOpenBoardPkg: Update SpiFvbService & SpiFlashCommonLib
KabylakeOpenBoardPkg: Update SpiFvbService & SpiFlashCommonLib
SimicsOpenBoardPkg: Update SpiFvbService & SpiFlashCommonLib
TigerlakeOpenBoardPkg: Update SpiFvbService & SpiFlashCommonLib
WhiskeylakeOpenBoardPkg: Update SpiFvbService & SpiFlashCommonLib
MinPlatformPkg: Remove SpiFvbService modules
CoffeelakeSiliconPkg: Remove SmmSpiFlashCommonLib
KabylakeSiliconPkg: Remove SmmSpiFlashCommonLib
SimicsIch10Pkg: Remove SmmSpiFlashCommonLib
TigerlakeOpenBoardPkg: Remove SmmSpiFlashCommonLib
MinPlatformPkg: Remove SpiFlashCommonLibNull
KabylakeOpenBoardPkg/PeiSerialPortLibSpiFlash: Add IntelSiliconPkg.dec
CoffeelakeSiliconPkg: Remove PCH SPI PPI and Protocol from package
KabylakeSiliconPkg: Remove PCH SPI PPI and Protocol from package
SimicsIch10Pkg: Remove PCH SPI SMM Protocol from package
TigerlakeSiliconPkg: Remove PCH SPI PPI and Protocol from package
IntelSiliconPkg: Add flash region GUIDs
IntelSiliconPkg: Identify flash regions by GUID
CoffeelakeSiliconPkg/BasePchSpiCommonLib: Identify flash regions by
GUID
KabylakeSiliconPkg: Identify flash regions by GUID
SimicsIch10Pkg/BasePchSpiCommonLib: Identify flash regions by GUID
TigerlakeSiliconPkg/BasePchSpiCommonLib: Identify flash regions by
GUID

Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/Private/BasePchSpiCommonL=
ib/SpiCommon.c =
| 144 ++++++++--
Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/SmmSpiFlashCommonLib/SpiF=
lashCommon.c =
| 196 -------------
Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/SmmSpiFlashCommonLib/SpiF=
lashCommonSmmLib.c =
| 54 ----
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/FvbInfo.c =
| 0
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/SpiFvbServiceCommon.c =
| 4 +-
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/SpiFvbServiceMm.c =
| 8 +-
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/SpiFvbServiceStandaloneMm.c =
| 0
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/SpiFvbServiceTraditionalMm.c =
| 0
Platform/Intel/TigerlakeOpenBoardPkg/Library/SmmSpiFlashCommonLib/SpiFla=
shCommonSmmLib.c =3D> Silicon/Intel/IntelSiliconPkg/Library/SmmSpiFlashCo=
mmonLib/SmmSpiFlashCommonLib.c | 2 +-
{Platform/Intel/TigerlakeOpenBoardPkg =3D> Silicon/Intel/IntelSiliconPkg=
}/Library/SmmSpiFlashCommonLib/SpiFlashCommon.c =
| 7 +-
{Platform/Intel/MinPlatformPkg/Flash =3D> Silicon/Intel/IntelSiliconPkg}=
/Library/SpiFlashCommonLibNull/SpiFlashCommonLibNull.c =
| 12 +-
Silicon/Intel/KabylakeSiliconPkg/Hsti/Dxe/SecureMemoryMapConfiguration.c=
=
| 106 ++++++-
Silicon/Intel/KabylakeSiliconPkg/Pch/Library/SmmSpiFlashCommonLib/SpiFla=
shCommon.c =
| 196 -------------
Silicon/Intel/KabylakeSiliconPkg/Pch/Library/SmmSpiFlashCommonLib/SpiFla=
shCommonSmmLib.c =
| 54 ----
Silicon/Intel/KabylakeSiliconPkg/Pch/LibraryPrivate/BasePchSpiCommonLib/=
SpiCommon.c =
| 140 +++++++--
Silicon/Intel/SimicsIch10Pkg/Library/SmmSpiFlashCommonLib/SpiFlashCommon=
.c =
| 194 -------------
Silicon/Intel/SimicsIch10Pkg/Library/SmmSpiFlashCommonLib/SpiFlashCommon=
SmmLib.c =
| 54 ----
Silicon/Intel/SimicsIch10Pkg/LibraryPrivate/BasePchSpiCommonLib/SpiCommo=
n.c =
| 165 ++++++++---
Silicon/Intel/SimicsIch10Pkg/Spi/Smm/PchSpi.c =
=
| 4 +-
Silicon/Intel/TigerlakeSiliconPkg/IpBlock/Spi/LibraryPrivate/BaseSpiComm=
onLib/SpiCommon.c =
| 176 ++++++++++--
Platform/Intel/CometlakeOpenBoardPkg/BiosInfo/BiosInfo.inf =
=
| 4 +-
Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/Include/Fdf/FlashMapI=
nclude.fdf =
| 4 +-
Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/OpenBoardPkg.dsc =
=
| 7 +-
Platform/Intel/CometlakeOpenBoardPkg/CometlakeURvp/OpenBoardPkg.fdf =
=
| 38 +--
Platform/Intel/CometlakeOpenBoardPkg/Policy/Library/PeiPolicyUpdateLib/P=
eiPolicyUpdateLib.inf =
| 2 +-
Platform/Intel/CometlakeOpenBoardPkg/Policy/PolicyInitDxe/PolicyInitDxe.=
inf =
| 4 +-
Platform/Intel/KabylakeOpenBoardPkg/BiosInfo/BiosInfo.inf =
=
| 4 +-
Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/Include/Fdf/FlashMapInclu=
de.fdf =
| 4 +-
Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/OpenBoardPkg.dsc =
=
| 7 +-
Platform/Intel/KabylakeOpenBoardPkg/GalagoPro3/OpenBoardPkg.fdf =
=
| 40 +--
Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Include/Fdf/FlashMapInc=
lude.fdf =
| 4 +-
Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/OpenBoardPkg.dsc =
=
| 7 +-
Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/OpenBoardPkg.fdf =
=
| 40 +--
Platform/Intel/KabylakeOpenBoardPkg/KabylakeRvp3/Policy/Library/PeiSilic=
onPolicyUpdateLib/PeiSiliconPolicyUpdateLib.inf =
| 4 +-
Platform/Intel/KabylakeOpenBoardPkg/Library/PeiSerialPortLibSpiFlash/Pei=
SerialPortLibSpiFlash.inf =
| 1 +
Platform/Intel/MinPlatformPkg/Include/Library/SpiFlashCommonLib.h =
=
| 98 -------
Platform/Intel/MinPlatformPkg/MinPlatformPkg.dec =
=
| 2 -
Platform/Intel/MinPlatformPkg/MinPlatformPkg.dsc =
=
| 6 -
Platform/Intel/SimicsOpenBoardPkg/BoardX58Ich10/OpenBoardPkg.dsc =
=
| 6 +-
Platform/Intel/SimicsOpenBoardPkg/BoardX58Ich10/OpenBoardPkg.fdf =
=
| 2 +-
Platform/Intel/SimicsOpenBoardPkg/BoardX58Ich10/OpenBoardPkg.fdf.inc =
=
| 8 +-
Platform/Intel/TigerlakeOpenBoardPkg/BiosInfo/BiosInfo.inf =
=
| 8 +-
Platform/Intel/TigerlakeOpenBoardPkg/TigerlakeURvp/Include/Fdf/FlashMapI=
nclude.fdf =
| 4 +-
Platform/Intel/TigerlakeOpenBoardPkg/TigerlakeURvp/OpenBoardPkg.dsc =
=
| 7 +-
Platform/Intel/TigerlakeOpenBoardPkg/TigerlakeURvp/OpenBoardPkg.fdf =
=
| 40 +--
Platform/Intel/WhiskeylakeOpenBoardPkg/BiosInfo/BiosInfo.inf =
=
| 4 +-
Platform/Intel/WhiskeylakeOpenBoardPkg/Policy/Library/PeiPolicyUpdateLib=
/PeiPolicyUpdateLib.inf =
| 1 -
Platform/Intel/WhiskeylakeOpenBoardPkg/Policy/PolicyInitDxe/PolicyInitDx=
e.inf =
| 4 +-
Platform/Intel/WhiskeylakeOpenBoardPkg/UpXtreme/Include/Fdf/FlashMapIncl=
ude.fdf =
| 4 +-
Platform/Intel/WhiskeylakeOpenBoardPkg/UpXtreme/Library/BoardInitLib/Pei=
MultiBoardInitPreMemLib.inf =
| 2 +-
Platform/Intel/WhiskeylakeOpenBoardPkg/UpXtreme/OpenBoardPkg.dsc =
=
| 7 +-
Platform/Intel/WhiskeylakeOpenBoardPkg/UpXtreme/OpenBoardPkg.fdf =
=
| 38 +--
Platform/Intel/WhiskeylakeOpenBoardPkg/WhiskeylakeURvp/Include/Fdf/Flash=
MapInclude.fdf =
| 4 +-
Platform/Intel/WhiskeylakeOpenBoardPkg/WhiskeylakeURvp/OpenBoardPkg.dsc =
=
| 7 +-
Platform/Intel/WhiskeylakeOpenBoardPkg/WhiskeylakeURvp/OpenBoardPkg.fdf =
=
| 38 +--
Silicon/Intel/CoffeelakeSiliconPkg/Cpu/Library/PeiCpuPolicyLib/PeiCpuPol=
icyLib.inf =
| 4 +-
Silicon/Intel/CoffeelakeSiliconPkg/Pch/Include/Private/Library/PchSpiCom=
monLib.h =
| 16 +-
Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/PeiSpiLib/PeiSpiLib.inf =
=
| 1 +
Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/Private/BasePchSpiCommonL=
ib/BasePchSpiCommonLib.inf =
| 13 +
Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/SmmSpiFlashCommonLib/SmmS=
piFlashCommonLib.inf =
| 51 ----
Silicon/Intel/CoffeelakeSiliconPkg/Pch/Spi/Smm/PchSpiSmm.inf =
=
| 1 +
Silicon/Intel/CoffeelakeSiliconPkg/SiPkg.dec =
=
| 8 -
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/SpiFvbServiceCommon.h =
| 0
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/SpiFvbServiceMm.h =
| 0
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/SpiFvbServiceSmm.inf =
| 6 +-
{Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg/Featur=
e}/Flash/SpiFvbService/SpiFvbServiceStandaloneMm.inf =
| 6 +-
Silicon/Intel/IntelSiliconPkg/Include/Guid/FlashRegion.h =
=
| 45 +++
Silicon/Intel/{CoffeelakeSiliconPkg/Pch =3D> IntelSiliconPkg}/Include/Li=
brary/SpiFlashCommonLib.h =
| 2 +-
Silicon/Intel/{CoffeelakeSiliconPkg/Pch =3D> IntelSiliconPkg}/Include/Pp=
i/Spi.h =
| 4 +-
Silicon/Intel/{CoffeelakeSiliconPkg/Pch =3D> IntelSiliconPkg}/Include/Pr=
otocol/Spi.h =
| 39 +--
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dec =
=
| 37 +++
Silicon/Intel/IntelSiliconPkg/IntelSiliconPkg.dsc =
=
| 17 ++
{Platform/Intel/TigerlakeOpenBoardPkg =3D> Silicon/Intel/IntelSiliconPkg=
}/Library/SmmSpiFlashCommonLib/SmmSpiFlashCommonLib.inf =
| 24 +-
{Platform/Intel/MinPlatformPkg/Flash =3D> Silicon/Intel/IntelSiliconPkg}=
/Library/SpiFlashCommonLibNull/SpiFlashCommonLibNull.inf =
| 3 +-
Silicon/Intel/KabylakeSiliconPkg/Cpu/Library/PeiCpuPolicyLib/PeiCpuPolic=
yLib.inf =
| 4 +-
Silicon/Intel/KabylakeSiliconPkg/Hsti/Dxe/HstiSiliconDxe.inf =
=
| 12 +-
Silicon/Intel/KabylakeSiliconPkg/Pch/Include/Library/SpiFlashCommonLib.h=
=
| 98 -------
Silicon/Intel/KabylakeSiliconPkg/Pch/Include/Ppi/Spi.h =
=
| 26 --
Silicon/Intel/KabylakeSiliconPkg/Pch/Include/Protocol/Spi.h =
=
| 293 -------------------
Silicon/Intel/KabylakeSiliconPkg/Pch/IncludePrivate/Library/PchSpiCommon=
Lib.h =
| 20 +-
Silicon/Intel/KabylakeSiliconPkg/Pch/Library/PeiSpiLib/PeiSpiLib.inf =
=
| 1 +
Silicon/Intel/KabylakeSiliconPkg/Pch/Library/SmmSpiFlashCommonLib/SmmSpi=
FlashCommonLib.inf =
| 53 ----
Silicon/Intel/KabylakeSiliconPkg/Pch/LibraryPrivate/BasePchSpiCommonLib/=
BasePchSpiCommonLib.inf =
| 11 +
Silicon/Intel/KabylakeSiliconPkg/Pch/Spi/Smm/PchSpiSmm.inf =
=
| 1 +
Silicon/Intel/KabylakeSiliconPkg/SiPkg.dec =
=
| 13 +-
Silicon/Intel/SimicsIch10Pkg/Ich10Pkg.dec =
=
| 11 -
Silicon/Intel/SimicsIch10Pkg/Include/Library/SpiFlashCommonLib.h =
=
| 98 -------
Silicon/Intel/SimicsIch10Pkg/Include/Protocol/Spi.h =
=
| 295 -------------------
Silicon/Intel/SimicsIch10Pkg/IncludePrivate/Library/PchSpiCommonLib.h =
=
| 46 +--
Silicon/Intel/SimicsIch10Pkg/Library/SmmSpiFlashCommonLib/SmmSpiFlashCom=
monLib.inf =
| 50 ----
Silicon/Intel/SimicsIch10Pkg/LibraryPrivate/BasePchSpiCommonLib/BasePchS=
piCommonLib.inf =
| 16 +-
Silicon/Intel/SimicsIch10Pkg/Spi/Smm/PchSpiSmm.inf =
=
| 3 +-
Silicon/Intel/TigerlakeSiliconPkg/Include/Protocol/Spi.h =
=
| 301 --------------------
Silicon/Intel/TigerlakeSiliconPkg/IpBlock/Spi/IncludePrivate/Library/Spi=
CommonLib.h =
| 16 +-
Silicon/Intel/TigerlakeSiliconPkg/IpBlock/Spi/LibraryPrivate/BaseSpiComm=
onLib/BaseSpiCommonLib.inf =
| 19 +-
Silicon/Intel/TigerlakeSiliconPkg/IpBlock/Spi/Smm/SpiSmm.inf =
=
| 1 +
Silicon/Intel/TigerlakeSiliconPkg/Pch/PchInit/Dxe/PchInitDxeTgl.inf =
=
| 1 +
Silicon/Intel/TigerlakeSiliconPkg/SiPkg.dec =
=
| 8 -
98 files changed, 1083 insertions(+), 2567 deletions(-)
delete mode 100644 Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/SmmSpi=
FlashCommonLib/SpiFlashCommon.c
delete mode 100644 Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/SmmSpi=
FlashCommonLib/SpiFlashCommonSmmLib.c
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/FvbInfo.c (100%)
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/SpiFvbServiceCommon.c (96%)
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/SpiFvbServiceMm.c (94%)
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/SpiFvbServiceStandaloneMm.c (100%)
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/SpiFvbServiceTraditionalMm.c (100%)
rename Platform/Intel/TigerlakeOpenBoardPkg/Library/SmmSpiFlashCommonLib=
/SpiFlashCommonSmmLib.c =3D> Silicon/Intel/IntelSiliconPkg/Library/SmmSpi=
FlashCommonLib/SmmSpiFlashCommonLib.c (90%)
rename {Platform/Intel/TigerlakeOpenBoardPkg =3D> Silicon/Intel/IntelSil=
iconPkg}/Library/SmmSpiFlashCommonLib/SpiFlashCommon.c (93%)
rename {Platform/Intel/MinPlatformPkg/Flash =3D> Silicon/Intel/IntelSili=
conPkg}/Library/SpiFlashCommonLibNull/SpiFlashCommonLibNull.c (83%)
delete mode 100644 Silicon/Intel/KabylakeSiliconPkg/Pch/Library/SmmSpiFl=
ashCommonLib/SpiFlashCommon.c
delete mode 100644 Silicon/Intel/KabylakeSiliconPkg/Pch/Library/SmmSpiFl=
ashCommonLib/SpiFlashCommonSmmLib.c
delete mode 100644 Silicon/Intel/SimicsIch10Pkg/Library/SmmSpiFlashCommo=
nLib/SpiFlashCommon.c
delete mode 100644 Silicon/Intel/SimicsIch10Pkg/Library/SmmSpiFlashCommo=
nLib/SpiFlashCommonSmmLib.c
delete mode 100644 Platform/Intel/MinPlatformPkg/Include/Library/SpiFlas=
hCommonLib.h
delete mode 100644 Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/SmmSpi=
FlashCommonLib/SmmSpiFlashCommonLib.inf
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/SpiFvbServiceCommon.h (100%)
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/SpiFvbServiceMm.h (100%)
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/SpiFvbServiceSmm.inf (88%)
rename {Platform/Intel/MinPlatformPkg =3D> Silicon/Intel/IntelSiliconPkg=
/Feature}/Flash/SpiFvbService/SpiFvbServiceStandaloneMm.inf (88%)
create mode 100644 Silicon/Intel/IntelSiliconPkg/Include/Guid/FlashRegio=
n.h
rename Silicon/Intel/{CoffeelakeSiliconPkg/Pch =3D> IntelSiliconPkg}/Inc=
lude/Library/SpiFlashCommonLib.h (96%)
rename Silicon/Intel/{CoffeelakeSiliconPkg/Pch =3D> IntelSiliconPkg}/Inc=
lude/Ppi/Spi.h (85%)
rename Silicon/Intel/{CoffeelakeSiliconPkg/Pch =3D> IntelSiliconPkg}/Inc=
lude/Protocol/Spi.h (89%)
rename {Platform/Intel/TigerlakeOpenBoardPkg =3D> Silicon/Intel/IntelSil=
iconPkg}/Library/SmmSpiFlashCommonLib/SmmSpiFlashCommonLib.inf (67%)
rename {Platform/Intel/MinPlatformPkg/Flash =3D> Silicon/Intel/IntelSili=
conPkg}/Library/SpiFlashCommonLibNull/SpiFlashCommonLibNull.inf (91%)
delete mode 100644 Silicon/Intel/KabylakeSiliconPkg/Pch/Include/Library/=
SpiFlashCommonLib.h
delete mode 100644 Silicon/Intel/KabylakeSiliconPkg/Pch/Include/Ppi/Spi.=
h
delete mode 100644 Silicon/Intel/KabylakeSiliconPkg/Pch/Include/Protocol=
/Spi.h
delete mode 100644 Silicon/Intel/KabylakeSiliconPkg/Pch/Library/SmmSpiFl=
ashCommonLib/SmmSpiFlashCommonLib.inf
delete mode 100644 Silicon/Intel/SimicsIch10Pkg/Include/Library/SpiFlash=
CommonLib.h
delete mode 100644 Silicon/Intel/SimicsIch10Pkg/Include/Protocol/Spi.h
delete mode 100644 Silicon/Intel/SimicsIch10Pkg/Library/SmmSpiFlashCommo=
nLib/SmmSpiFlashCommonLib.inf
delete mode 100644 Silicon/Intel/TigerlakeSiliconPkg/Include/Protocol/Sp=
i.h

--=20
2.28.0.windows.1


[PATCH v6] IntelFsp2Pkg: Add Config Editor tool support

 

This is a GUI interface that can be used by users who
would like to change configuration settings directly
from the interface without having to modify the source.

This tool depends on Python GUI tool kit Tkinter.
It runs on both Windows and Linux.

The user needs to load the YAML file along with DLT file
for a specific board into the ConfigEditor, change the desired
configuration values. Finally, generate a new configuration delta
file or a config binary blob for the newly changed values to take
effect. These will be the inputs to the merge tool or the stitch
tool so that new config changes can be merged and stitched into
the final configuration blob.

This tool also supports binary update directly and display FSP
information. It is also backward compatible for BSF file format.

Running Configuration Editor:
python ConfigEditor.py

Co-authored-by: Maurice Ma <maurice.ma@intel.com>
Cc: Maurice Ma <maurice.ma@intel.com>
Cc: Nate DeSimone <nathaniel.l.desimone@intel.com>
Cc: Star Zeng <star.zeng@intel.com>
Cc: Chasel Chiu <chasel.chiu@intel.com>
Signed-off-by: Loo Tung Lun <tung.lun.loo@intel.com>
---
IntelFsp2Pkg/Tools/ConfigEditor/CommonUtility.py | 504 ++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++
IntelFsp2Pkg/Tools/ConfigEditor/ConfigEditor.py | 1499 ++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
IntelFsp2Pkg/Tools/ConfigEditor/GenYamlCfg.py | 2254 ++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++++++++++++++++++++++++++++++
IntelFsp2Pkg/Tools/ConfigEditor/SingleSign.py | 324 ++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++
IntelFsp2Pkg/Tools/FspDscBsf2Yaml.py | 370 ++++++++++++++++++=
++++++++++-----------------------------------------------------------------=
------------------------------------------
IntelFsp2Pkg/Tools/FspGenCfgData.py | 2593 ++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++++
6 files changed, 7249 insertions(+), 295 deletions(-)

diff --git a/IntelFsp2Pkg/Tools/ConfigEditor/CommonUtility.py b/IntelFsp2Pk=
g/Tools/ConfigEditor/CommonUtility.py
new file mode 100644
index 0000000000..757e63150f
--- /dev/null
+++ b/IntelFsp2Pkg/Tools/ConfigEditor/CommonUtility.py
@@ -0,0 +1,504 @@
+#!/usr/bin/env python=0D
+# @ CommonUtility.py=0D
+# Common utility script=0D
+#=0D
+# Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+import os=0D
+import sys=0D
+import shutil=0D
+import subprocess=0D
+import string=0D
+from ctypes import ARRAY, c_char, c_uint16, c_uint32, \=0D
+ c_uint8, Structure, sizeof=0D
+from importlib.machinery import SourceFileLoader=0D
+from SingleSign import single_sign_gen_pub_key=0D
+=0D
+=0D
+# Key types defined should match with cryptolib.h=0D
+PUB_KEY_TYPE =3D {=0D
+ "RSA": 1,=0D
+ "ECC": 2,=0D
+ "DSA": 3,=0D
+ }=0D
+=0D
+# Signing type schemes defined should match with cryptolib.h=0D
+SIGN_TYPE_SCHEME =3D {=0D
+ "RSA_PKCS1": 1,=0D
+ "RSA_PSS": 2,=0D
+ "ECC": 3,=0D
+ "DSA": 4,=0D
+ }=0D
+=0D
+# Hash values defined should match with cryptolib.h=0D
+HASH_TYPE_VALUE =3D {=0D
+ "SHA2_256": 1,=0D
+ "SHA2_384": 2,=0D
+ "SHA2_512": 3,=0D
+ "SM3_256": 4,=0D
+ }=0D
+=0D
+# Hash values defined should match with cryptolib.h=0D
+HASH_VAL_STRING =3D dict(map(reversed, HASH_TYPE_VALUE.items()))=0D
+=0D
+AUTH_TYPE_HASH_VALUE =3D {=0D
+ "SHA2_256": 1,=0D
+ "SHA2_384": 2,=0D
+ "SHA2_512": 3,=0D
+ "SM3_256": 4,=0D
+ "RSA2048SHA256": 1,=0D
+ "RSA3072SHA384": 2,=0D
+ }=0D
+=0D
+HASH_DIGEST_SIZE =3D {=0D
+ "SHA2_256": 32,=0D
+ "SHA2_384": 48,=0D
+ "SHA2_512": 64,=0D
+ "SM3_256": 32,=0D
+ }=0D
+=0D
+=0D
+class PUB_KEY_HDR (Structure):=0D
+ _pack_ =3D 1=0D
+ _fields_ =3D [=0D
+ ('Identifier', ARRAY(c_char, 4)), # signature ('P', 'U', 'B',=
'K')=0D
+ ('KeySize', c_uint16), # Length of Public Key=0D
+ ('KeyType', c_uint8), # RSA or ECC=0D
+ ('Reserved', ARRAY(c_uint8, 1)),=0D
+ ('KeyData', ARRAY(c_uint8, 0)),=0D
+ ]=0D
+=0D
+ def __init__(self):=0D
+ self.Identifier =3D b'PUBK'=0D
+=0D
+=0D
+class SIGNATURE_HDR (Structure):=0D
+ _pack_ =3D 1=0D
+ _fields_ =3D [=0D
+ ('Identifier', ARRAY(c_char, 4)),=0D
+ ('SigSize', c_uint16),=0D
+ ('SigType', c_uint8),=0D
+ ('HashAlg', c_uint8),=0D
+ ('Signature', ARRAY(c_uint8, 0)),=0D
+ ]=0D
+=0D
+ def __init__(self):=0D
+ self.Identifier =3D b'SIGN'=0D
+=0D
+=0D
+class LZ_HEADER(Structure):=0D
+ _pack_ =3D 1=0D
+ _fields_ =3D [=0D
+ ('signature', ARRAY(c_char, 4)),=0D
+ ('compressed_len', c_uint32),=0D
+ ('length', c_uint32),=0D
+ ('version', c_uint16),=0D
+ ('svn', c_uint8),=0D
+ ('attribute', c_uint8)=0D
+ ]=0D
+ _compress_alg =3D {=0D
+ b'LZDM': 'Dummy',=0D
+ b'LZ4 ': 'Lz4',=0D
+ b'LZMA': 'Lzma',=0D
+ }=0D
+=0D
+=0D
+def print_bytes(data, indent=3D0, offset=3D0, show_ascii=3DFalse):=0D
+ bytes_per_line =3D 16=0D
+ printable =3D ' ' + string.ascii_letters + string.digits + string.punc=
tuation=0D
+ str_fmt =3D '{:s}{:04x}: {:%ds} {:s}' % (bytes_per_line * 3)=0D
+ bytes_per_line=0D
+ data_array =3D bytearray(data)=0D
+ for idx in range(0, len(data_array), bytes_per_line):=0D
+ hex_str =3D ' '.join(=0D
+ '%02X' % val for val in data_array[idx:idx + bytes_per_line])=
=0D
+ asc_str =3D ''.join('%c' % (val if (chr(val) in printable) else '.=
')=0D
+ for val in data_array[idx:idx + bytes_per_line])=
=0D
+ print(str_fmt.format(=0D
+ indent * ' ',=0D
+ offset + idx, hex_str,=0D
+ ' ' + asc_str if show_ascii else ''))=0D
+=0D
+=0D
+def get_bits_from_bytes(bytes, start, length):=0D
+ if length =3D=3D 0:=0D
+ return 0=0D
+ byte_start =3D (start) // 8=0D
+ byte_end =3D (start + length - 1) // 8=0D
+ bit_start =3D start & 7=0D
+ mask =3D (1 << length) - 1=0D
+ val =3D bytes_to_value(bytes[byte_start:byte_end + 1])=0D
+ val =3D (val >> bit_start) & mask=0D
+ return val=0D
+=0D
+=0D
+def set_bits_to_bytes(bytes, start, length, bvalue):=0D
+ if length =3D=3D 0:=0D
+ return=0D
+ byte_start =3D (start) // 8=0D
+ byte_end =3D (start + length - 1) // 8=0D
+ bit_start =3D start & 7=0D
+ mask =3D (1 << length) - 1=0D
+ val =3D bytes_to_value(bytes[byte_start:byte_end + 1])=0D
+ val &=3D ~(mask << bit_start)=0D
+ val |=3D ((bvalue & mask) << bit_start)=0D
+ bytes[byte_start:byte_end+1] =3D value_to_bytearray(=0D
+ val,=0D
+ byte_end + 1 - byte_start)=0D
+=0D
+=0D
+def value_to_bytes(value, length):=0D
+ return value.to_bytes(length, 'little')=0D
+=0D
+=0D
+def bytes_to_value(bytes):=0D
+ return int.from_bytes(bytes, 'little')=0D
+=0D
+=0D
+def value_to_bytearray(value, length):=0D
+ return bytearray(value_to_bytes(value, length))=0D
+=0D
+# def value_to_bytearray (value, length):=0D
+ return bytearray(value_to_bytes(value, length))=0D
+=0D
+=0D
+def get_aligned_value(value, alignment=3D4):=0D
+ if alignment !=3D (1 << (alignment.bit_length() - 1)):=0D
+ raise Exception(=0D
+ 'Alignment (0x%x) should to be power of 2 !' % alignment)=0D
+ value =3D (value + (alignment - 1)) & ~(alignment - 1)=0D
+ return value=0D
+=0D
+=0D
+def get_padding_length(data_len, alignment=3D4):=0D
+ new_data_len =3D get_aligned_value(data_len, alignment)=0D
+ return new_data_len - data_len=0D
+=0D
+=0D
+def get_file_data(file, mode=3D'rb'):=0D
+ return open(file, mode).read()=0D
+=0D
+=0D
+def gen_file_from_object(file, object):=0D
+ open(file, 'wb').write(object)=0D
+=0D
+=0D
+def gen_file_with_size(file, size):=0D
+ open(file, 'wb').write(b'\xFF' * size)=0D
+=0D
+=0D
+def check_files_exist(base_name_list, dir=3D'', ext=3D''):=0D
+ for each in base_name_list:=0D
+ if not os.path.exists(os.path.join(dir, each + ext)):=0D
+ return False=0D
+ return True=0D
+=0D
+=0D
+def load_source(name, filepath):=0D
+ mod =3D SourceFileLoader(name, filepath).load_module()=0D
+ return mod=0D
+=0D
+=0D
+def get_openssl_path():=0D
+ if os.name =3D=3D 'nt':=0D
+ if 'OPENSSL_PATH' not in os.environ:=0D
+ openssl_dir =3D "C:\\Openssl\\bin\\"=0D
+ if os.path.exists(openssl_dir):=0D
+ os.environ['OPENSSL_PATH'] =3D openssl_dir=0D
+ else:=0D
+ os.environ['OPENSSL_PATH'] =3D "C:\\Openssl\\"=0D
+ if 'OPENSSL_CONF' not in os.environ:=0D
+ openssl_cfg =3D "C:\\Openssl\\openssl.cfg"=0D
+ if os.path.exists(openssl_cfg):=0D
+ os.environ['OPENSSL_CONF'] =3D openssl_cfg=0D
+ openssl =3D os.path.join(=0D
+ os.environ.get('OPENSSL_PATH', ''),=0D
+ 'openssl.exe')=0D
+ else:=0D
+ # Get openssl path for Linux cases=0D
+ openssl =3D shutil.which('openssl')=0D
+=0D
+ return openssl=0D
+=0D
+=0D
+def run_process(arg_list, print_cmd=3DFalse, capture_out=3DFalse):=0D
+ sys.stdout.flush()=0D
+ if os.name =3D=3D 'nt' and os.path.splitext(arg_list[0])[1] =3D=3D '' =
and \=0D
+ os.path.exists(arg_list[0] + '.exe'):=0D
+ arg_list[0] +=3D '.exe'=0D
+ if print_cmd:=0D
+ print(' '.join(arg_list))=0D
+=0D
+ exc =3D None=0D
+ result =3D 0=0D
+ output =3D ''=0D
+ try:=0D
+ if capture_out:=0D
+ output =3D subprocess.check_output(arg_list).decode()=0D
+ else:=0D
+ result =3D subprocess.call(arg_list)=0D
+ except Exception as ex:=0D
+ result =3D 1=0D
+ exc =3D ex=0D
+=0D
+ if result:=0D
+ if not print_cmd:=0D
+ print('Error in running process:\n %s' % ' '.join(arg_list))=
=0D
+ if exc is None:=0D
+ sys.exit(1)=0D
+ else:=0D
+ raise exc=0D
+=0D
+ return output=0D
+=0D
+=0D
+# Adjust hash type algorithm based on Public key file=0D
+def adjust_hash_type(pub_key_file):=0D
+ key_type =3D get_key_type(pub_key_file)=0D
+ if key_type =3D=3D 'RSA2048':=0D
+ hash_type =3D 'SHA2_256'=0D
+ elif key_type =3D=3D 'RSA3072':=0D
+ hash_type =3D 'SHA2_384'=0D
+ else:=0D
+ hash_type =3D None=0D
+=0D
+ return hash_type=0D
+=0D
+=0D
+def rsa_sign_file(=0D
+ priv_key, pub_key, hash_type, sign_scheme,=0D
+ in_file, out_file, inc_dat=3DFalse, inc_key=3DFalse):=0D
+=0D
+ bins =3D bytearray()=0D
+ if inc_dat:=0D
+ bins.extend(get_file_data(in_file))=0D
+=0D
+=0D
+# def single_sign_file(priv_key, hash_type, sign_scheme, in_file, out_file=
):=0D
+=0D
+ out_data =3D get_file_data(out_file)=0D
+=0D
+ sign =3D SIGNATURE_HDR()=0D
+ sign.SigSize =3D len(out_data)=0D
+ sign.SigType =3D SIGN_TYPE_SCHEME[sign_scheme]=0D
+ sign.HashAlg =3D HASH_TYPE_VALUE[hash_type]=0D
+=0D
+ bins.extend(bytearray(sign) + out_data)=0D
+ if inc_key:=0D
+ key =3D gen_pub_key(priv_key, pub_key)=0D
+ bins.extend(key)=0D
+=0D
+ if len(bins) !=3D len(out_data):=0D
+ gen_file_from_object(out_file, bins)=0D
+=0D
+=0D
+def get_key_type(in_key):=0D
+=0D
+ # Check in_key is file or key Id=0D
+ if not os.path.exists(in_key):=0D
+ key =3D bytearray(gen_pub_key(in_key))=0D
+ else:=0D
+ # Check for public key in binary format.=0D
+ key =3D bytearray(get_file_data(in_key))=0D
+=0D
+ pub_key_hdr =3D PUB_KEY_HDR.from_buffer(key)=0D
+ if pub_key_hdr.Identifier !=3D b'PUBK':=0D
+ pub_key =3D gen_pub_key(in_key)=0D
+ pub_key_hdr =3D PUB_KEY_HDR.from_buffer(pub_key)=0D
+=0D
+ key_type =3D next(=0D
+ (key for key,=0D
+ value in PUB_KEY_TYPE.items() if value =3D=3D pub_key_hdr.KeyT=
ype))=0D
+ return '%s%d' % (key_type, (pub_key_hdr.KeySize - 4) * 8)=0D
+=0D
+=0D
+def get_auth_hash_type(key_type, sign_scheme):=0D
+ if key_type =3D=3D "RSA2048" and sign_scheme =3D=3D "RSA_PKCS1":=0D
+ hash_type =3D 'SHA2_256'=0D
+ auth_type =3D 'RSA2048_PKCS1_SHA2_256'=0D
+ elif key_type =3D=3D "RSA3072" and sign_scheme =3D=3D "RSA_PKCS1":=0D
+ hash_type =3D 'SHA2_384'=0D
+ auth_type =3D 'RSA3072_PKCS1_SHA2_384'=0D
+ elif key_type =3D=3D "RSA2048" and sign_scheme =3D=3D "RSA_PSS":=0D
+ hash_type =3D 'SHA2_256'=0D
+ auth_type =3D 'RSA2048_PSS_SHA2_256'=0D
+ elif key_type =3D=3D "RSA3072" and sign_scheme =3D=3D "RSA_PSS":=0D
+ hash_type =3D 'SHA2_384'=0D
+ auth_type =3D 'RSA3072_PSS_SHA2_384'=0D
+ else:=0D
+ hash_type =3D ''=0D
+ auth_type =3D ''=0D
+ return auth_type, hash_type=0D
+=0D
+=0D
+# def single_sign_gen_pub_key(in_key, pub_key_file=3DNone):=0D
+=0D
+=0D
+def gen_pub_key(in_key, pub_key=3DNone):=0D
+=0D
+ keydata =3D single_sign_gen_pub_key(in_key, pub_key)=0D
+=0D
+ publickey =3D PUB_KEY_HDR()=0D
+ publickey.KeySize =3D len(keydata)=0D
+ publickey.KeyType =3D PUB_KEY_TYPE['RSA']=0D
+=0D
+ key =3D bytearray(publickey) + keydata=0D
+=0D
+ if pub_key:=0D
+ gen_file_from_object(pub_key, key)=0D
+=0D
+ return key=0D
+=0D
+=0D
+def decompress(in_file, out_file, tool_dir=3D''):=0D
+ if not os.path.isfile(in_file):=0D
+ raise Exception("Invalid input file '%s' !" % in_file)=0D
+=0D
+ # Remove the Lz Header=0D
+ fi =3D open(in_file, 'rb')=0D
+ di =3D bytearray(fi.read())=0D
+ fi.close()=0D
+=0D
+ lz_hdr =3D LZ_HEADER.from_buffer(di)=0D
+ offset =3D sizeof(lz_hdr)=0D
+ if lz_hdr.signature =3D=3D b"LZDM" or lz_hdr.compressed_len =3D=3D 0:=
=0D
+ fo =3D open(out_file, 'wb')=0D
+ fo.write(di[offset:offset + lz_hdr.compressed_len])=0D
+ fo.close()=0D
+ return=0D
+=0D
+ temp =3D os.path.splitext(out_file)[0] + '.tmp'=0D
+ if lz_hdr.signature =3D=3D b"LZMA":=0D
+ alg =3D "Lzma"=0D
+ elif lz_hdr.signature =3D=3D b"LZ4 ":=0D
+ alg =3D "Lz4"=0D
+ else:=0D
+ raise Exception("Unsupported compression '%s' !" % lz_hdr.signatur=
e)=0D
+=0D
+ fo =3D open(temp, 'wb')=0D
+ fo.write(di[offset:offset + lz_hdr.compressed_len])=0D
+ fo.close()=0D
+=0D
+ compress_tool =3D "%sCompress" % alg=0D
+ if alg =3D=3D "Lz4":=0D
+ try:=0D
+ cmdline =3D [=0D
+ os.path.join(tool_dir, compress_tool),=0D
+ "-d",=0D
+ "-o", out_file,=0D
+ temp]=0D
+ run_process(cmdline, False, True)=0D
+ except Exception:=0D
+ msg_string =3D "Could not find/use CompressLz4 tool, " \=0D
+ "trying with python lz4..."=0D
+ print(msg_string)=0D
+ try:=0D
+ import lz4.block=0D
+ if lz4.VERSION !=3D '3.1.1':=0D
+ msg_string =3D "Recommended lz4 module version " \=0D
+ "is '3.1.1'," + lz4.VERSION \=0D
+ + " is currently installed."=0D
+ print(msg_string)=0D
+ except ImportError:=0D
+ msg_string =3D "Could not import lz4, use " \=0D
+ "'python -m pip install lz4=3D=3D3.1.1' " \=0D
+ "to install it."=0D
+ print(msg_string)=0D
+ exit(1)=0D
+ decompress_data =3D lz4.block.decompress(get_file_data(temp))=
=0D
+ with open(out_file, "wb") as lz4bin:=0D
+ lz4bin.write(decompress_data)=0D
+ else:=0D
+ cmdline =3D [=0D
+ os.path.join(tool_dir, compress_tool),=0D
+ "-d",=0D
+ "-o", out_file,=0D
+ temp]=0D
+ run_process(cmdline, False, True)=0D
+ os.remove(temp)=0D
+=0D
+=0D
+def compress(in_file, alg, svn=3D0, out_path=3D'', tool_dir=3D''):=0D
+ if not os.path.isfile(in_file):=0D
+ raise Exception("Invalid input file '%s' !" % in_file)=0D
+=0D
+ basename, ext =3D os.path.splitext(os.path.basename(in_file))=0D
+ if out_path:=0D
+ if os.path.isdir(out_path):=0D
+ out_file =3D os.path.join(out_path, basename + '.lz')=0D
+ else:=0D
+ out_file =3D os.path.join(out_path)=0D
+ else:=0D
+ out_file =3D os.path.splitext(in_file)[0] + '.lz'=0D
+=0D
+ if alg =3D=3D "Lzma":=0D
+ sig =3D "LZMA"=0D
+ elif alg =3D=3D "Tiano":=0D
+ sig =3D "LZUF"=0D
+ elif alg =3D=3D "Lz4":=0D
+ sig =3D "LZ4 "=0D
+ elif alg =3D=3D "Dummy":=0D
+ sig =3D "LZDM"=0D
+ else:=0D
+ raise Exception("Unsupported compression '%s' !" % alg)=0D
+=0D
+ in_len =3D os.path.getsize(in_file)=0D
+ if in_len > 0:=0D
+ compress_tool =3D "%sCompress" % alg=0D
+ if sig =3D=3D "LZDM":=0D
+ shutil.copy(in_file, out_file)=0D
+ compress_data =3D get_file_data(out_file)=0D
+ elif sig =3D=3D "LZ4 ":=0D
+ try:=0D
+ cmdline =3D [=0D
+ os.path.join(tool_dir, compress_tool),=0D
+ "-e",=0D
+ "-o", out_file,=0D
+ in_file]=0D
+ run_process(cmdline, False, True)=0D
+ compress_data =3D get_file_data(out_file)=0D
+ except Exception:=0D
+ msg_string =3D "Could not find/use CompressLz4 tool, " \=0D
+ "trying with python lz4..."=0D
+ print(msg_string)=0D
+ try:=0D
+ import lz4.block=0D
+ if lz4.VERSION !=3D '3.1.1':=0D
+ msg_string =3D "Recommended lz4 module version " \=
=0D
+ "is '3.1.1', " + lz4.VERSION \=0D
+ + " is currently installed."=0D
+ print(msg_string)=0D
+ except ImportError:=0D
+ msg_string =3D "Could not import lz4, use " \=0D
+ "'python -m pip install lz4=3D=3D3.1.1' " =
\=0D
+ "to install it."=0D
+ print(msg_string)=0D
+ exit(1)=0D
+ compress_data =3D lz4.block.compress(=0D
+ get_file_data(in_file),=0D
+ mode=3D'high_compression')=0D
+ elif sig =3D=3D "LZMA":=0D
+ cmdline =3D [=0D
+ os.path.join(tool_dir, compress_tool),=0D
+ "-e",=0D
+ "-o", out_file,=0D
+ in_file]=0D
+ run_process(cmdline, False, True)=0D
+ compress_data =3D get_file_data(out_file)=0D
+ else:=0D
+ compress_data =3D bytearray()=0D
+=0D
+ lz_hdr =3D LZ_HEADER()=0D
+ lz_hdr.signature =3D sig.encode()=0D
+ lz_hdr.svn =3D svn=0D
+ lz_hdr.compressed_len =3D len(compress_data)=0D
+ lz_hdr.length =3D os.path.getsize(in_file)=0D
+ data =3D bytearray()=0D
+ data.extend(lz_hdr)=0D
+ data.extend(compress_data)=0D
+ gen_file_from_object(out_file, data)=0D
+=0D
+ return out_file=0D
diff --git a/IntelFsp2Pkg/Tools/ConfigEditor/ConfigEditor.py b/IntelFsp2Pkg=
/Tools/ConfigEditor/ConfigEditor.py
new file mode 100644
index 0000000000..a7f79bbc96
--- /dev/null
+++ b/IntelFsp2Pkg/Tools/ConfigEditor/ConfigEditor.py
@@ -0,0 +1,1499 @@
+# @ ConfigEditor.py=0D
+#=0D
+# Copyright(c) 2018 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+import os=0D
+import sys=0D
+import marshal=0D
+import tkinter=0D
+import tkinter.ttk as ttk=0D
+import tkinter.messagebox as messagebox=0D
+import tkinter.filedialog as filedialog=0D
+=0D
+from pathlib import Path=0D
+from GenYamlCfg import CGenYamlCfg, bytes_to_value, \=0D
+ bytes_to_bracket_str, value_to_bytes, array_str_to_value=0D
+from ctypes import sizeof, Structure, ARRAY, c_uint8, c_uint64, c_char, \=
=0D
+ c_uint32, c_uint16=0D
+from functools import reduce=0D
+=0D
+sys.path.insert(0, '..')=0D
+from FspDscBsf2Yaml import bsf_to_dsc, dsc_to_yaml # noqa=0D
+=0D
+=0D
+sys.dont_write_bytecode =3D True=0D
+=0D
+=0D
+class create_tool_tip(object):=0D
+ '''=0D
+ create a tooltip for a given widget=0D
+ '''=0D
+ in_progress =3D False=0D
+=0D
+ def __init__(self, widget, text=3D''):=0D
+ self.top_win =3D None=0D
+ self.widget =3D widget=0D
+ self.text =3D text=0D
+ self.widget.bind("<Enter>", self.enter)=0D
+ self.widget.bind("<Leave>", self.leave)=0D
+=0D
+ def enter(self, event=3DNone):=0D
+ if self.in_progress:=0D
+ return=0D
+ if self.widget.winfo_class() =3D=3D 'Treeview':=0D
+ # Only show help when cursor is on row header.=0D
+ rowid =3D self.widget.identify_row(event.y)=0D
+ if rowid !=3D '':=0D
+ return=0D
+ else:=0D
+ x, y, cx, cy =3D self.widget.bbox("insert")=0D
+=0D
+ cursor =3D self.widget.winfo_pointerxy()=0D
+ x =3D self.widget.winfo_rootx() + 35=0D
+ y =3D self.widget.winfo_rooty() + 20=0D
+ if cursor[1] > y and cursor[1] < y + 20:=0D
+ y +=3D 20=0D
+=0D
+ # creates a toplevel window=0D
+ self.top_win =3D tkinter.Toplevel(self.widget)=0D
+ # Leaves only the label and removes the app window=0D
+ self.top_win.wm_overrideredirect(True)=0D
+ self.top_win.wm_geometry("+%d+%d" % (x, y))=0D
+ label =3D tkinter.Message(self.top_win,=0D
+ text=3Dself.text,=0D
+ justify=3D'left',=0D
+ background=3D'bisque',=0D
+ relief=3D'solid',=0D
+ borderwidth=3D1,=0D
+ font=3D("times", "10", "normal"))=0D
+ label.pack(ipadx=3D1)=0D
+ self.in_progress =3D True=0D
+=0D
+ def leave(self, event=3DNone):=0D
+ if self.top_win:=0D
+ self.top_win.destroy()=0D
+ self.in_progress =3D False=0D
+=0D
+=0D
+class validating_entry(tkinter.Entry):=0D
+ def __init__(self, master, **kw):=0D
+ tkinter.Entry.__init__(*(self, master), **kw)=0D
+ self.parent =3D master=0D
+ self.old_value =3D ''=0D
+ self.last_value =3D ''=0D
+ self.variable =3D tkinter.StringVar()=0D
+ self.variable.trace("w", self.callback)=0D
+ self.config(textvariable=3Dself.variable)=0D
+ self.config({"background": "#c0c0c0"})=0D
+ self.bind("<Return>", self.move_next)=0D
+ self.bind("<Tab>", self.move_next)=0D
+ self.bind("<Escape>", self.cancel)=0D
+ for each in ['BackSpace', 'Delete']:=0D
+ self.bind("<%s>" % each, self.ignore)=0D
+ self.display(None)=0D
+=0D
+ def ignore(self, even):=0D
+ return "break"=0D
+=0D
+ def move_next(self, event):=0D
+ if self.row < 0:=0D
+ return=0D
+ row, col =3D self.row, self.col=0D
+ txt, row_id, col_id =3D self.parent.get_next_cell(row, col)=0D
+ self.display(txt, row_id, col_id)=0D
+ return "break"=0D
+=0D
+ def cancel(self, event):=0D
+ self.variable.set(self.old_value)=0D
+ self.display(None)=0D
+=0D
+ def display(self, txt, row_id=3D'', col_id=3D''):=0D
+ if txt is None:=0D
+ self.row =3D -1=0D
+ self.col =3D -1=0D
+ self.place_forget()=0D
+ else:=0D
+ row =3D int('0x' + row_id[1:], 0) - 1=0D
+ col =3D int(col_id[1:]) - 1=0D
+ self.row =3D row=0D
+ self.col =3D col=0D
+ self.old_value =3D txt=0D
+ self.last_value =3D txt=0D
+ x, y, width, height =3D self.parent.bbox(row_id, col)=0D
+ self.place(x=3Dx, y=3Dy, w=3Dwidth)=0D
+ self.variable.set(txt)=0D
+ self.focus_set()=0D
+ self.icursor(0)=0D
+=0D
+ def callback(self, *Args):=0D
+ cur_val =3D self.variable.get()=0D
+ new_val =3D self.validate(cur_val)=0D
+ if new_val is not None and self.row >=3D 0:=0D
+ self.last_value =3D new_val=0D
+ self.parent.set_cell(self.row, self.col, new_val)=0D
+ self.variable.set(self.last_value)=0D
+=0D
+ def validate(self, value):=0D
+ if len(value) > 0:=0D
+ try:=0D
+ int(value, 16)=0D
+ except Exception:=0D
+ return None=0D
+=0D
+ # Normalize the cell format=0D
+ self.update()=0D
+ cell_width =3D self.winfo_width()=0D
+ max_len =3D custom_table.to_byte_length(cell_width) * 2=0D
+ cur_pos =3D self.index("insert")=0D
+ if cur_pos =3D=3D max_len + 1:=0D
+ value =3D value[-max_len:]=0D
+ else:=0D
+ value =3D value[:max_len]=0D
+ if value =3D=3D '':=0D
+ value =3D '0'=0D
+ fmt =3D '%%0%dX' % max_len=0D
+ return fmt % int(value, 16)=0D
+=0D
+=0D
+class custom_table(ttk.Treeview):=0D
+ _Padding =3D 20=0D
+ _Char_width =3D 6=0D
+=0D
+ def __init__(self, parent, col_hdr, bins):=0D
+ cols =3D len(col_hdr)=0D
+=0D
+ col_byte_len =3D []=0D
+ for col in range(cols): # Columns=0D
+ col_byte_len.append(int(col_hdr[col].split(':')[1]))=0D
+=0D
+ byte_len =3D sum(col_byte_len)=0D
+ rows =3D (len(bins) + byte_len - 1) // byte_len=0D
+=0D
+ self.rows =3D rows=0D
+ self.cols =3D cols=0D
+ self.col_byte_len =3D col_byte_len=0D
+ self.col_hdr =3D col_hdr=0D
+=0D
+ self.size =3D len(bins)=0D
+ self.last_dir =3D ''=0D
+=0D
+ style =3D ttk.Style()=0D
+ style.configure("Custom.Treeview.Heading",=0D
+ font=3D('calibri', 10, 'bold'),=0D
+ foreground=3D"blue")=0D
+ ttk.Treeview.__init__(self, parent, height=3Drows,=0D
+ columns=3D[''] + col_hdr, show=3D'headings',=
=0D
+ style=3D"Custom.Treeview",=0D
+ selectmode=3D'none')=0D
+ self.bind("<Button-1>", self.click)=0D
+ self.bind("<FocusOut>", self.focus_out)=0D
+ self.entry =3D validating_entry(self, width=3D4, justify=3Dtkinte=
r.CENTER)=0D
+=0D
+ self.heading(0, text=3D'LOAD')=0D
+ self.column(0, width=3D60, stretch=3D0, anchor=3Dtkinter.CENTER)=0D
+=0D
+ for col in range(cols): # Columns=0D
+ text =3D col_hdr[col].split(':')[0]=0D
+ byte_len =3D int(col_hdr[col].split(':')[1])=0D
+ self.heading(col+1, text=3Dtext)=0D
+ self.column(col+1, width=3Dself.to_cell_width(byte_len),=0D
+ stretch=3D0, anchor=3Dtkinter.CENTER)=0D
+ idx =3D 0=0D
+ for row in range(rows): # Rows=0D
+ text =3D '%04X' % (row * len(col_hdr))=0D
+ vals =3D ['%04X:' % (cols * row)]=0D
+ for col in range(cols): # Columns=0D
+ if idx >=3D len(bins):=0D
+ break=0D
+ byte_len =3D int(col_hdr[col].split(':')[1])=0D
+ value =3D bytes_to_value(bins[idx:idx+byte_len])=0D
+ hex =3D ("%%0%dX" % (byte_len * 2)) % value=0D
+ vals.append(hex)=0D
+ idx +=3D byte_len=0D
+ self.insert('', 'end', values=3Dtuple(vals))=0D
+ if idx >=3D len(bins):=0D
+ break=0D
+=0D
+ @staticmethod=0D
+ def to_cell_width(byte_len):=0D
+ return byte_len * 2 * custom_table._Char_width + custom_table._Pad=
ding=0D
+=0D
+ @staticmethod=0D
+ def to_byte_length(cell_width):=0D
+ return(cell_width - custom_table._Padding) \=0D
+ // (2 * custom_table._Char_width)=0D
+=0D
+ def focus_out(self, event):=0D
+ self.entry.display(None)=0D
+=0D
+ def refresh_bin(self, bins):=0D
+ if not bins:=0D
+ return=0D
+=0D
+ # Reload binary into widget=0D
+ bin_len =3D len(bins)=0D
+ for row in range(self.rows):=0D
+ iid =3D self.get_children()[row]=0D
+ for col in range(self.cols):=0D
+ idx =3D row * sum(self.col_byte_len) + \=0D
+ sum(self.col_byte_len[:col])=0D
+ byte_len =3D self.col_byte_len[col]=0D
+ if idx + byte_len <=3D self.size:=0D
+ byte_len =3D int(self.col_hdr[col].split(':')[1])=0D
+ if idx + byte_len > bin_len:=0D
+ val =3D 0=0D
+ else:=0D
+ val =3D bytes_to_value(bins[idx:idx+byte_len])=0D
+ hex_val =3D ("%%0%dX" % (byte_len * 2)) % val=0D
+ self.set(iid, col + 1, hex_val)=0D
+=0D
+ def get_cell(self, row, col):=0D
+ iid =3D self.get_children()[row]=0D
+ txt =3D self.item(iid, 'values')[col]=0D
+ return txt=0D
+=0D
+ def get_next_cell(self, row, col):=0D
+ rows =3D self.get_children()=0D
+ col +=3D 1=0D
+ if col > self.cols:=0D
+ col =3D 1=0D
+ row +=3D 1=0D
+ cnt =3D row * sum(self.col_byte_len) + sum(self.col_byte_len[:col]=
)=0D
+ if cnt > self.size:=0D
+ # Reached the last cell, so roll back to beginning=0D
+ row =3D 0=0D
+ col =3D 1=0D
+=0D
+ txt =3D self.get_cell(row, col)=0D
+ row_id =3D rows[row]=0D
+ col_id =3D '#%d' % (col + 1)=0D
+ return(txt, row_id, col_id)=0D
+=0D
+ def set_cell(self, row, col, val):=0D
+ iid =3D self.get_children()[row]=0D
+ self.set(iid, col, val)=0D
+=0D
+ def load_bin(self):=0D
+ # Load binary from file=0D
+ path =3D filedialog.askopenfilename(=0D
+ initialdir=3Dself.last_dir,=0D
+ title=3D"Load binary file",=0D
+ filetypes=3D(("Binary files", "*.bin"), (=0D
+ "binary files", "*.bin")))=0D
+ if path:=0D
+ self.last_dir =3D os.path.dirname(path)=0D
+ fd =3D open(path, 'rb')=0D
+ bins =3D bytearray(fd.read())[:self.size]=0D
+ fd.close()=0D
+ bins.extend(b'\x00' * (self.size - len(bins)))=0D
+ return bins=0D
+=0D
+ return None=0D
+=0D
+ def click(self, event):=0D
+ row_id =3D self.identify_row(event.y)=0D
+ col_id =3D self.identify_column(event.x)=0D
+ if row_id =3D=3D '' and col_id =3D=3D '#1':=0D
+ # Clicked on "LOAD" cell=0D
+ bins =3D self.load_bin()=0D
+ self.refresh_bin(bins)=0D
+ return=0D
+=0D
+ if col_id =3D=3D '#1':=0D
+ # Clicked on column 1(Offset column)=0D
+ return=0D
+=0D
+ item =3D self.identify('item', event.x, event.y)=0D
+ if not item or not col_id:=0D
+ # Not clicked on valid cell=0D
+ return=0D
+=0D
+ # Clicked cell=0D
+ row =3D int('0x' + row_id[1:], 0) - 1=0D
+ col =3D int(col_id[1:]) - 1=0D
+ if row * self.cols + col > self.size:=0D
+ return=0D
+=0D
+ vals =3D self.item(item, 'values')=0D
+ if col < len(vals):=0D
+ txt =3D self.item(item, 'values')[col]=0D
+ self.entry.display(txt, row_id, col_id)=0D
+=0D
+ def get(self):=0D
+ bins =3D bytearray()=0D
+ row_ids =3D self.get_children()=0D
+ for row_id in row_ids:=0D
+ row =3D int('0x' + row_id[1:], 0) - 1=0D
+ for col in range(self.cols):=0D
+ idx =3D row * sum(self.col_byte_len) + \=0D
+ sum(self.col_byte_len[:col])=0D
+ byte_len =3D self.col_byte_len[col]=0D
+ if idx + byte_len > self.size:=0D
+ break=0D
+ hex =3D self.item(row_id, 'values')[col + 1]=0D
+ values =3D value_to_bytes(int(hex, 16)=0D
+ & ((1 << byte_len * 8) - 1), byte_=
len)=0D
+ bins.extend(values)=0D
+ return bins=0D
+=0D
+=0D
+class c_uint24(Structure):=0D
+ """Little-Endian 24-bit Unsigned Integer"""=0D
+ _pack_ =3D 1=0D
+ _fields_ =3D [('Data', (c_uint8 * 3))]=0D
+=0D
+ def __init__(self, val=3D0):=0D
+ self.set_value(val)=0D
+=0D
+ def __str__(self, indent=3D0):=0D
+ return '0x%.6x' % self.value=0D
+=0D
+ def __int__(self):=0D
+ return self.get_value()=0D
+=0D
+ def set_value(self, val):=0D
+ self.Data[0:3] =3D Val2Bytes(val, 3)=0D
+=0D
+ def get_value(self):=0D
+ return Bytes2Val(self.Data[0:3])=0D
+=0D
+ value =3D property(get_value, set_value)=0D
+=0D
+=0D
+class EFI_FIRMWARE_VOLUME_HEADER(Structure):=0D
+ _fields_ =3D [=0D
+ ('ZeroVector', ARRAY(c_uint8, 16)),=0D
+ ('FileSystemGuid', ARRAY(c_uint8, 16)),=0D
+ ('FvLength', c_uint64),=0D
+ ('Signature', ARRAY(c_char, 4)),=0D
+ ('Attributes', c_uint32),=0D
+ ('HeaderLength', c_uint16),=0D
+ ('Checksum', c_uint16),=0D
+ ('ExtHeaderOffset', c_uint16),=0D
+ ('Reserved', c_uint8),=0D
+ ('Revision', c_uint8)=0D
+ ]=0D
+=0D
+=0D
+class EFI_FIRMWARE_VOLUME_EXT_HEADER(Structure):=0D
+ _fields_ =3D [=0D
+ ('FvName', ARRAY(c_uint8, 16)),=0D
+ ('ExtHeaderSize', c_uint32)=0D
+ ]=0D
+=0D
+=0D
+class EFI_FFS_INTEGRITY_CHECK(Structure):=0D
+ _fields_ =3D [=0D
+ ('Header', c_uint8),=0D
+ ('File', c_uint8)=0D
+ ]=0D
+=0D
+=0D
+class EFI_FFS_FILE_HEADER(Structure):=0D
+ _fields_ =3D [=0D
+ ('Name', ARRAY(c_uint8, 16)),=0D
+ ('IntegrityCheck', EFI_FFS_INTEGRITY_CHECK),=0D
+ ('Type', c_uint8),=0D
+ ('Attributes', c_uint8),=0D
+ ('Size', c_uint24),=0D
+ ('State', c_uint8)=0D
+ ]=0D
+=0D
+=0D
+class EFI_COMMON_SECTION_HEADER(Structure):=0D
+ _fields_ =3D [=0D
+ ('Size', c_uint24),=0D
+ ('Type', c_uint8)=0D
+ ]=0D
+=0D
+=0D
+class EFI_SECTION_TYPE:=0D
+ """Enumeration of all valid firmware file section types."""=0D
+ ALL =3D 0x00=0D
+ COMPRESSION =3D 0x01=0D
+ GUID_DEFINED =3D 0x02=0D
+ DISPOSABLE =3D 0x03=0D
+ PE32 =3D 0x10=0D
+ PIC =3D 0x11=0D
+ TE =3D 0x12=0D
+ DXE_DEPEX =3D 0x13=0D
+ VERSION =3D 0x14=0D
+ USER_INTERFACE =3D 0x15=0D
+ COMPATIBILITY16 =3D 0x16=0D
+ FIRMWARE_VOLUME_IMAGE =3D 0x17=0D
+ FREEFORM_SUBTYPE_GUID =3D 0x18=0D
+ RAW =3D 0x19=0D
+ PEI_DEPEX =3D 0x1b=0D
+ SMM_DEPEX =3D 0x1c=0D
+=0D
+=0D
+class FSP_COMMON_HEADER(Structure):=0D
+ _fields_ =3D [=0D
+ ('Signature', ARRAY(c_char, 4)),=0D
+ ('HeaderLength', c_uint32)=0D
+ ]=0D
+=0D
+=0D
+class FSP_INFORMATION_HEADER(Structure):=0D
+ _fields_ =3D [=0D
+ ('Signature', ARRAY(c_char, 4)),=0D
+ ('HeaderLength', c_uint32),=0D
+ ('Reserved1', c_uint16),=0D
+ ('SpecVersion', c_uint8),=0D
+ ('HeaderRevision', c_uint8),=0D
+ ('ImageRevision', c_uint32),=0D
+ ('ImageId', ARRAY(c_char, 8)),=0D
+ ('ImageSize', c_uint32),=0D
+ ('ImageBase', c_uint32),=0D
+ ('ImageAttribute', c_uint16),=0D
+ ('ComponentAttribute', c_uint16),=0D
+ ('CfgRegionOffset', c_uint32),=0D
+ ('CfgRegionSize', c_uint32),=0D
+ ('Reserved2', c_uint32),=0D
+ ('TempRamInitEntryOffset', c_uint32),=0D
+ ('Reserved3', c_uint32),=0D
+ ('NotifyPhaseEntryOffset', c_uint32),=0D
+ ('FspMemoryInitEntryOffset', c_uint32),=0D
+ ('TempRamExitEntryOffset', c_uint32),=0D
+ ('FspSiliconInitEntryOffset', c_uint32)=0D
+ ]=0D
+=0D
+=0D
+class FSP_EXTENDED_HEADER(Structure):=0D
+ _fields_ =3D [=0D
+ ('Signature', ARRAY(c_char, 4)),=0D
+ ('HeaderLength', c_uint32),=0D
+ ('Revision', c_uint8),=0D
+ ('Reserved', c_uint8),=0D
+ ('FspProducerId', ARRAY(c_char, 6)),=0D
+ ('FspProducerRevision', c_uint32),=0D
+ ('FspProducerDataSize', c_uint32)=0D
+ ]=0D
+=0D
+=0D
+class FSP_PATCH_TABLE(Structure):=0D
+ _fields_ =3D [=0D
+ ('Signature', ARRAY(c_char, 4)),=0D
+ ('HeaderLength', c_uint16),=0D
+ ('HeaderRevision', c_uint8),=0D
+ ('Reserved', c_uint8),=0D
+ ('PatchEntryNum', c_uint32)=0D
+ ]=0D
+=0D
+=0D
+class Section:=0D
+ def __init__(self, offset, secdata):=0D
+ self.SecHdr =3D EFI_COMMON_SECTION_HEADER.from_buffer(secdata, 0)=
=0D
+ self.SecData =3D secdata[0:int(self.SecHdr.Size)]=0D
+ self.Offset =3D offset=0D
+=0D
+=0D
+def AlignPtr(offset, alignment=3D8):=0D
+ return (offset + alignment - 1) & ~(alignment - 1)=0D
+=0D
+=0D
+def Bytes2Val(bytes):=0D
+ return reduce(lambda x, y: (x << 8) | y, bytes[:: -1])=0D
+=0D
+=0D
+def Val2Bytes(value, blen):=0D
+ return [(value >> (i*8) & 0xff) for i in range(blen)]=0D
+=0D
+=0D
+class FirmwareFile:=0D
+ def __init__(self, offset, filedata):=0D
+ self.FfsHdr =3D EFI_FFS_FILE_HEADER.from_buffer(filedata, 0)=0D
+ self.FfsData =3D filedata[0:int(self.FfsHdr.Size)]=0D
+ self.Offset =3D offset=0D
+ self.SecList =3D []=0D
+=0D
+ def ParseFfs(self):=0D
+ ffssize =3D len(self.FfsData)=0D
+ offset =3D sizeof(self.FfsHdr)=0D
+ if self.FfsHdr.Name !=3D '\xff' * 16:=0D
+ while offset < (ffssize - sizeof(EFI_COMMON_SECTION_HEADER)):=
=0D
+ sechdr =3D EFI_COMMON_SECTION_HEADER.from_buffer(=0D
+ self.FfsData, offset)=0D
+ sec =3D Section(=0D
+ offset, self.FfsData[offset:offset + int(sechdr.Size)]=
)=0D
+ self.SecList.append(sec)=0D
+ offset +=3D int(sechdr.Size)=0D
+ offset =3D AlignPtr(offset, 4)=0D
+=0D
+=0D
+class FirmwareVolume:=0D
+ def __init__(self, offset, fvdata):=0D
+ self.FvHdr =3D EFI_FIRMWARE_VOLUME_HEADER.from_buffer(fvdata, 0)=0D
+ self.FvData =3D fvdata[0: self.FvHdr.FvLength]=0D
+ self.Offset =3D offset=0D
+ if self.FvHdr.ExtHeaderOffset > 0:=0D
+ self.FvExtHdr =3D EFI_FIRMWARE_VOLUME_EXT_HEADER.from_buffer(=
=0D
+ self.FvData, self.FvHdr.ExtHeaderOffset)=0D
+ else:=0D
+ self.FvExtHdr =3D None=0D
+ self.FfsList =3D []=0D
+=0D
+ def ParseFv(self):=0D
+ fvsize =3D len(self.FvData)=0D
+ if self.FvExtHdr:=0D
+ offset =3D self.FvHdr.ExtHeaderOffset + self.FvExtHdr.ExtHeade=
rSize=0D
+ else:=0D
+ offset =3D self.FvHdr.HeaderLength=0D
+ offset =3D AlignPtr(offset)=0D
+ while offset < (fvsize - sizeof(EFI_FFS_FILE_HEADER)):=0D
+ ffshdr =3D EFI_FFS_FILE_HEADER.from_buffer(self.FvData, offset=
)=0D
+ if (ffshdr.Name =3D=3D '\xff' * 16) and \=0D
+ (int(ffshdr.Size) =3D=3D 0xFFFFFF):=0D
+ offset =3D fvsize=0D
+ else:=0D
+ ffs =3D FirmwareFile(=0D
+ offset, self.FvData[offset:offset + int(ffshdr.Size)])=
=0D
+ ffs.ParseFfs()=0D
+ self.FfsList.append(ffs)=0D
+ offset +=3D int(ffshdr.Size)=0D
+ offset =3D AlignPtr(offset)=0D
+=0D
+=0D
+class FspImage:=0D
+ def __init__(self, offset, fih, fihoff, patch):=0D
+ self.Fih =3D fih=0D
+ self.FihOffset =3D fihoff=0D
+ self.Offset =3D offset=0D
+ self.FvIdxList =3D []=0D
+ self.Type =3D "XTMSXXXXOXXXXXXX"[(fih.ComponentAttribute >> 12) & =
0x0F]=0D
+ self.PatchList =3D patch=0D
+ self.PatchList.append(fihoff + 0x1C)=0D
+=0D
+ def AppendFv(self, FvIdx):=0D
+ self.FvIdxList.append(FvIdx)=0D
+=0D
+ def Patch(self, delta, fdbin):=0D
+ count =3D 0=0D
+ applied =3D 0=0D
+ for idx, patch in enumerate(self.PatchList):=0D
+ ptype =3D (patch >> 24) & 0x0F=0D
+ if ptype not in [0x00, 0x0F]:=0D
+ raise Exception('ERROR: Invalid patch type %d !' % ptype)=
=0D
+ if patch & 0x80000000:=0D
+ patch =3D self.Fih.ImageSize - (0x1000000 - (patch & 0xFFF=
FFF))=0D
+ else:=0D
+ patch =3D patch & 0xFFFFFF=0D
+ if (patch < self.Fih.ImageSize) and \=0D
+ (patch + sizeof(c_uint32) <=3D self.Fih.ImageSize):=0D
+ offset =3D patch + self.Offset=0D
+ value =3D Bytes2Val(fdbin[offset:offset+sizeof(c_uint32)])=
=0D
+ value +=3D delta=0D
+ fdbin[offset:offset+sizeof(c_uint32)] =3D Val2Bytes(=0D
+ value, sizeof(c_uint32))=0D
+ applied +=3D 1=0D
+ count +=3D 1=0D
+ # Don't count the FSP base address patch entry appended at the end=
=0D
+ if count !=3D 0:=0D
+ count -=3D 1=0D
+ applied -=3D 1=0D
+ return (count, applied)=0D
+=0D
+=0D
+class FirmwareDevice:=0D
+ def __init__(self, offset, FdData):=0D
+ self.FvList =3D []=0D
+ self.FspList =3D []=0D
+ self.FspExtList =3D []=0D
+ self.FihList =3D []=0D
+ self.BuildList =3D []=0D
+ self.OutputText =3D ""=0D
+ self.Offset =3D 0=0D
+ self.FdData =3D FdData=0D
+=0D
+ def ParseFd(self):=0D
+ offset =3D 0=0D
+ fdsize =3D len(self.FdData)=0D
+ self.FvList =3D []=0D
+ while offset < (fdsize - sizeof(EFI_FIRMWARE_VOLUME_HEADER)):=0D
+ fvh =3D EFI_FIRMWARE_VOLUME_HEADER.from_buffer(self.FdData, of=
fset)=0D
+ if b'_FVH' !=3D fvh.Signature:=0D
+ raise Exception("ERROR: Invalid FV header !")=0D
+ fv =3D FirmwareVolume(=0D
+ offset, self.FdData[offset:offset + fvh.FvLength])=0D
+ fv.ParseFv()=0D
+ self.FvList.append(fv)=0D
+ offset +=3D fv.FvHdr.FvLength=0D
+=0D
+ def CheckFsp(self):=0D
+ if len(self.FspList) =3D=3D 0:=0D
+ return=0D
+=0D
+ fih =3D None=0D
+ for fsp in self.FspList:=0D
+ if not fih:=0D
+ fih =3D fsp.Fih=0D
+ else:=0D
+ newfih =3D fsp.Fih=0D
+ if (newfih.ImageId !=3D fih.ImageId) or \=0D
+ (newfih.ImageRevision !=3D fih.ImageRevision):=0D
+ raise Exception(=0D
+ "ERROR: Inconsistent FSP ImageId or "=0D
+ "ImageRevision detected !")=0D
+=0D
+ def ParseFsp(self):=0D
+ flen =3D 0=0D
+ for idx, fv in enumerate(self.FvList):=0D
+ # Check if this FV contains FSP header=0D
+ if flen =3D=3D 0:=0D
+ if len(fv.FfsList) =3D=3D 0:=0D
+ continue=0D
+ ffs =3D fv.FfsList[0]=0D
+ if len(ffs.SecList) =3D=3D 0:=0D
+ continue=0D
+ sec =3D ffs.SecList[0]=0D
+ if sec.SecHdr.Type !=3D EFI_SECTION_TYPE.RAW:=0D
+ continue=0D
+ fihoffset =3D ffs.Offset + sec.Offset + sizeof(sec.SecHdr)=
=0D
+ fspoffset =3D fv.Offset=0D
+ offset =3D fspoffset + fihoffset=0D
+ fih =3D FSP_INFORMATION_HEADER.from_buffer(self.FdData, of=
fset)=0D
+ self.FihList.append(fih)=0D
+ if b'FSPH' !=3D fih.Signature:=0D
+ continue=0D
+=0D
+ offset +=3D fih.HeaderLength=0D
+=0D
+ offset =3D AlignPtr(offset, 2)=0D
+ Extfih =3D FSP_EXTENDED_HEADER.from_buffer(self.FdData, of=
fset)=0D
+ self.FspExtList.append(Extfih)=0D
+ offset =3D AlignPtr(offset, 4)=0D
+ plist =3D []=0D
+ while True:=0D
+ fch =3D FSP_COMMON_HEADER.from_buffer(self.FdData, off=
set)=0D
+ if b'FSPP' !=3D fch.Signature:=0D
+ offset +=3D fch.HeaderLength=0D
+ offset =3D AlignPtr(offset, 4)=0D
+ else:=0D
+ fspp =3D FSP_PATCH_TABLE.from_buffer(=0D
+ self.FdData, offset)=0D
+ offset +=3D sizeof(fspp)=0D
+ start_offset =3D offset + 32=0D
+ end_offset =3D offset + 32=0D
+ while True:=0D
+ end_offset +=3D 1=0D
+ if(self.FdData[=0D
+ end_offset: end_offset + 1] =3D=3D b'\=
xff'):=0D
+ break=0D
+ self.BuildList.append(=0D
+ self.FdData[start_offset:end_offset])=0D
+ pdata =3D (c_uint32 * fspp.PatchEntryNum).from_buf=
fer(=0D
+ self.FdData, offset)=0D
+ plist =3D list(pdata)=0D
+ break=0D
+=0D
+ fsp =3D FspImage(fspoffset, fih, fihoffset, plist)=0D
+ fsp.AppendFv(idx)=0D
+ self.FspList.append(fsp)=0D
+ flen =3D fsp.Fih.ImageSize - fv.FvHdr.FvLength=0D
+ else:=0D
+ fsp.AppendFv(idx)=0D
+ flen -=3D fv.FvHdr.FvLength=0D
+ if flen < 0:=0D
+ raise Exception("ERROR: Incorrect FV size in image !")=
=0D
+ self.CheckFsp()=0D
+=0D
+ def OutputFsp(self):=0D
+ def copy_text_to_clipboard():=0D
+ window.clipboard_clear()=0D
+ window.clipboard_append(self.OutputText)=0D
+=0D
+ window =3D tkinter.Tk()=0D
+ window.title("Fsp Headers")=0D
+ window.resizable(0, 0)=0D
+ # Window Size=0D
+ window.geometry("300x400+350+150")=0D
+ frame =3D tkinter.Frame(window)=0D
+ frame.pack(side=3Dtkinter.BOTTOM)=0D
+ # Vertical (y) Scroll Bar=0D
+ scroll =3D tkinter.Scrollbar(window)=0D
+ scroll.pack(side=3Dtkinter.RIGHT, fill=3Dtkinter.Y)=0D
+ text =3D tkinter.Text(window,=0D
+ wrap=3Dtkinter.NONE, yscrollcommand=3Dscroll.s=
et)=0D
+ i =3D 0=0D
+ self.OutputText =3D self.OutputText + "Fsp Header Details \n\n"=0D
+ while i < len(self.FihList):=0D
+ try:=0D
+ self.OutputText +=3D str(self.BuildList[i].decode()) + "\n=
"=0D
+ except Exception:=0D
+ self.OutputText +=3D "No description found\n"=0D
+ self.OutputText +=3D "FSP Header :\n "=0D
+ self.OutputText +=3D "Signature : " + \=0D
+ str(self.FihList[i].Signature.decode('utf-8')) + "\n "=0D
+ self.OutputText +=3D "Header Length : " + \=0D
+ str(hex(self.FihList[i].HeaderLength)) + "\n "=0D
+ self.OutputText +=3D "Header Revision : " + \=0D
+ str(hex(self.FihList[i].HeaderRevision)) + "\n "=0D
+ self.OutputText +=3D "Spec Version : " + \=0D
+ str(hex(self.FihList[i].SpecVersion)) + "\n "=0D
+ self.OutputText +=3D "Image Revision : " + \=0D
+ str(hex(self.FihList[i].ImageRevision)) + "\n "=0D
+ self.OutputText +=3D "Image Id : " + \=0D
+ str(self.FihList[i].ImageId.decode('utf-8')) + "\n "=0D
+ self.OutputText +=3D "Image Size : " + \=0D
+ str(hex(self.FihList[i].ImageSize)) + "\n "=0D
+ self.OutputText +=3D "Image Base : " + \=0D
+ str(hex(self.FihList[i].ImageBase)) + "\n "=0D
+ self.OutputText +=3D "Image Attribute : " + \=0D
+ str(hex(self.FihList[i].ImageAttribute)) + "\n "=0D
+ self.OutputText +=3D "Cfg Region Offset : " + \=0D
+ str(hex(self.FihList[i].CfgRegionOffset)) + "\n "=0D
+ self.OutputText +=3D "Cfg Region Size : " + \=0D
+ str(hex(self.FihList[i].CfgRegionSize)) + "\n "=0D
+ self.OutputText +=3D "API Entry Num : " + \=0D
+ str(hex(self.FihList[i].Reserved2)) + "\n "=0D
+ self.OutputText +=3D "Temp Ram Init Entry : " + \=0D
+ str(hex(self.FihList[i].TempRamInitEntryOffset)) + "\n "=0D
+ self.OutputText +=3D "FSP Init Entry : " + \=0D
+ str(hex(self.FihList[i].Reserved3)) + "\n "=0D
+ self.OutputText +=3D "Notify Phase Entry : " + \=0D
+ str(hex(self.FihList[i].NotifyPhaseEntryOffset)) + "\n "=0D
+ self.OutputText +=3D "Fsp Memory Init Entry : " + \=0D
+ str(hex(self.FihList[i].FspMemoryInitEntryOffset)) + "\n "=
=0D
+ self.OutputText +=3D "Temp Ram Exit Entry : " + \=0D
+ str(hex(self.FihList[i].TempRamExitEntryOffset)) + "\n "=0D
+ self.OutputText +=3D "Fsp Silicon Init Entry : " + \=0D
+ str(hex(self.FihList[i].FspSiliconInitEntryOffset)) + "\n\=
n"=0D
+ self.OutputText +=3D "FSP Extended Header:\n "=0D
+ self.OutputText +=3D "Signature : " + \=0D
+ str(self.FspExtList[i].Signature.decode('utf-8')) + "\n "=
=0D
+ self.OutputText +=3D "Header Length : " + \=0D
+ str(hex(self.FspExtList[i].HeaderLength)) + "\n "=0D
+ self.OutputText +=3D "Header Revision : " + \=0D
+ str(hex(self.FspExtList[i].Revision)) + "\n "=0D
+ self.OutputText +=3D "Fsp Producer Id : " + \=0D
+ str(self.FspExtList[i].FspProducerId.decode('utf-8')) + "\=
n "=0D
+ self.OutputText +=3D "FspProducerRevision : " + \=0D
+ str(hex(self.FspExtList[i].FspProducerRevision)) + "\n\n"=
=0D
+ i +=3D 1=0D
+ text.insert(tkinter.INSERT, self.OutputText)=0D
+ text.pack()=0D
+ # Configure the scrollbars=0D
+ scroll.config(command=3Dtext.yview)=0D
+ copy_button =3D tkinter.Button(=0D
+ window, text=3D"Copy to Clipboard", command=3Dcopy_text_to_cli=
pboard)=0D
+ copy_button.pack(in_=3Dframe, side=3Dtkinter.LEFT, padx=3D20, pady=
=3D10)=0D
+ exit_button =3D tkinter.Button(=0D
+ window, text=3D"Close", command=3Dwindow.destroy)=0D
+ exit_button.pack(in_=3Dframe, side=3Dtkinter.RIGHT, padx=3D20, pad=
y=3D10)=0D
+ window.mainloop()=0D
+=0D
+=0D
+class state:=0D
+ def __init__(self):=0D
+ self.state =3D False=0D
+=0D
+ def set(self, value):=0D
+ self.state =3D value=0D
+=0D
+ def get(self):=0D
+ return self.state=0D
+=0D
+=0D
+class application(tkinter.Frame):=0D
+ def __init__(self, master=3DNone):=0D
+ root =3D master=0D
+=0D
+ self.debug =3D True=0D
+ self.mode =3D 'FSP'=0D
+ self.last_dir =3D '.'=0D
+ self.page_id =3D ''=0D
+ self.page_list =3D {}=0D
+ self.conf_list =3D {}=0D
+ self.cfg_data_obj =3D None=0D
+ self.org_cfg_data_bin =3D None=0D
+ self.in_left =3D state()=0D
+ self.in_right =3D state()=0D
+=0D
+ # Check if current directory contains a file with a .yaml extensio=
n=0D
+ # if not default self.last_dir to a Platform directory where it is=
=0D
+ # easier to locate *BoardPkg\CfgData\*Def.yaml files=0D
+ self.last_dir =3D '.'=0D
+ if not any(fname.endswith('.yaml') for fname in os.listdir('.')):=
=0D
+ platform_path =3D Path(os.path.realpath(__file__)).parents[2].=
\=0D
+ joinpath('Platform')=0D
+ if platform_path.exists():=0D
+ self.last_dir =3D platform_path=0D
+=0D
+ tkinter.Frame.__init__(self, master, borderwidth=3D2)=0D
+=0D
+ self.menu_string =3D [=0D
+ 'Save Config Data to Binary', 'Load Config Data from Binary',=
=0D
+ 'Show Binary Information',=0D
+ 'Load Config Changes from Delta File',=0D
+ 'Save Config Changes to Delta File',=0D
+ 'Save Full Config Data to Delta File',=0D
+ 'Open Config BSF file'=0D
+ ]=0D
+=0D
+ root.geometry("1200x800")=0D
+=0D
+ paned =3D ttk.Panedwindow(root, orient=3Dtkinter.HORIZONTAL)=0D
+ paned.pack(fill=3Dtkinter.BOTH, expand=3DTrue, padx=3D(4, 4))=0D
+=0D
+ status =3D tkinter.Label(master, text=3D"", bd=3D1, relief=3Dtkint=
er.SUNKEN,=0D
+ anchor=3Dtkinter.W)=0D
+ status.pack(side=3Dtkinter.BOTTOM, fill=3Dtkinter.X)=0D
+=0D
+ frame_left =3D ttk.Frame(paned, height=3D800, relief=3D"groove")=0D
+=0D
+ self.left =3D ttk.Treeview(frame_left, show=3D"tree")=0D
+=0D
+ # Set up tree HScroller=0D
+ pady =3D (10, 10)=0D
+ self.tree_scroll =3D ttk.Scrollbar(frame_left,=0D
+ orient=3D"vertical",=0D
+ command=3Dself.left.yview)=0D
+ self.left.configure(yscrollcommand=3Dself.tree_scroll.set)=0D
+ self.left.bind("<<TreeviewSelect>>", self.on_config_page_select_ch=
ange)=0D
+ self.left.bind("<Enter>", lambda e: self.in_left.set(True))=0D
+ self.left.bind("<Leave>", lambda e: self.in_left.set(False))=0D
+ self.left.bind("<MouseWheel>", self.on_tree_scroll)=0D
+=0D
+ self.left.pack(side=3D'left',=0D
+ fill=3Dtkinter.BOTH,=0D
+ expand=3DTrue,=0D
+ padx=3D(5, 0),=0D
+ pady=3Dpady)=0D
+ self.tree_scroll.pack(side=3D'right', fill=3Dtkinter.Y,=0D
+ pady=3Dpady, padx=3D(0, 5))=0D
+=0D
+ frame_right =3D ttk.Frame(paned, relief=3D"groove")=0D
+ self.frame_right =3D frame_right=0D
+=0D
+ self.conf_canvas =3D tkinter.Canvas(frame_right, highlightthicknes=
s=3D0)=0D
+ self.page_scroll =3D ttk.Scrollbar(frame_right,=0D
+ orient=3D"vertical",=0D
+ command=3Dself.conf_canvas.yview)=
=0D
+ self.right_grid =3D ttk.Frame(self.conf_canvas)=0D
+ self.conf_canvas.configure(yscrollcommand=3Dself.page_scroll.set)=
=0D
+ self.conf_canvas.pack(side=3D'left',=0D
+ fill=3Dtkinter.BOTH,=0D
+ expand=3DTrue,=0D
+ pady=3Dpady,=0D
+ padx=3D(5, 0))=0D
+ self.page_scroll.pack(side=3D'right', fill=3Dtkinter.Y,=0D
+ pady=3Dpady, padx=3D(0, 5))=0D
+ self.conf_canvas.create_window(0, 0, window=3Dself.right_grid,=0D
+ anchor=3D'nw')=0D
+ self.conf_canvas.bind('<Enter>', lambda e: self.in_right.set(True)=
)=0D
+ self.conf_canvas.bind('<Leave>', lambda e: self.in_right.set(False=
))=0D
+ self.conf_canvas.bind("<Configure>", self.on_canvas_configure)=0D
+ self.conf_canvas.bind_all("<MouseWheel>", self.on_page_scroll)=0D
+=0D
+ paned.add(frame_left, weight=3D2)=0D
+ paned.add(frame_right, weight=3D10)=0D
+=0D
+ style =3D ttk.Style()=0D
+ style.layout("Treeview", [('Treeview.treearea', {'sticky': 'nswe'}=
)])=0D
+=0D
+ menubar =3D tkinter.Menu(root)=0D
+ file_menu =3D tkinter.Menu(menubar, tearoff=3D0)=0D
+ file_menu.add_command(label=3D"Open Config YAML file",=0D
+ command=3Dself.load_from_yaml)=0D
+ file_menu.add_command(label=3Dself.menu_string[6],=0D
+ command=3Dself.load_from_bsf_file)=0D
+ file_menu.add_command(label=3Dself.menu_string[2],=0D
+ command=3Dself.load_from_fd)=0D
+ file_menu.add_command(label=3Dself.menu_string[0],=0D
+ command=3Dself.save_to_bin,=0D
+ state=3D'disabled')=0D
+ file_menu.add_command(label=3Dself.menu_string[1],=0D
+ command=3Dself.load_from_bin,=0D
+ state=3D'disabled')=0D
+ file_menu.add_command(label=3Dself.menu_string[3],=0D
+ command=3Dself.load_from_delta,=0D
+ state=3D'disabled')=0D
+ file_menu.add_command(label=3Dself.menu_string[4],=0D
+ command=3Dself.save_to_delta,=0D
+ state=3D'disabled')=0D
+ file_menu.add_command(label=3Dself.menu_string[5],=0D
+ command=3Dself.save_full_to_delta,=0D
+ state=3D'disabled')=0D
+ file_menu.add_command(label=3D"About", command=3Dself.about)=0D
+ menubar.add_cascade(label=3D"File", menu=3Dfile_menu)=0D
+ self.file_menu =3D file_menu=0D
+=0D
+ root.config(menu=3Dmenubar)=0D
+=0D
+ if len(sys.argv) > 1:=0D
+ path =3D sys.argv[1]=0D
+ if not path.endswith('.yaml') and not path.endswith('.pkl'):=0D
+ messagebox.showerror('LOADING ERROR',=0D
+ "Unsupported file '%s' !" % path)=0D
+ return=0D
+ else:=0D
+ self.load_cfg_file(path)=0D
+=0D
+ if len(sys.argv) > 2:=0D
+ path =3D sys.argv[2]=0D
+ if path.endswith('.dlt'):=0D
+ self.load_delta_file(path)=0D
+ elif path.endswith('.bin'):=0D
+ self.load_bin_file(path)=0D
+ else:=0D
+ messagebox.showerror('LOADING ERROR',=0D
+ "Unsupported file '%s' !" % path)=0D
+ return=0D
+=0D
+ def set_object_name(self, widget, name):=0D
+ self.conf_list[id(widget)] =3D name=0D
+=0D
+ def get_object_name(self, widget):=0D
+ if id(widget) in self.conf_list:=0D
+ return self.conf_list[id(widget)]=0D
+ else:=0D
+ return None=0D
+=0D
+ def limit_entry_size(self, variable, limit):=0D
+ value =3D variable.get()=0D
+ if len(value) > limit:=0D
+ variable.set(value[:limit])=0D
+=0D
+ def on_canvas_configure(self, event):=0D
+ self.right_grid.grid_columnconfigure(0, minsize=3Devent.width)=0D
+=0D
+ def on_tree_scroll(self, event):=0D
+ if not self.in_left.get() and self.in_right.get():=0D
+ # This prevents scroll event from being handled by both left a=
nd=0D
+ # right frame at the same time.=0D
+ self.on_page_scroll(event)=0D
+ return 'break'=0D
+=0D
+ def on_page_scroll(self, event):=0D
+ if self.in_right.get():=0D
+ # Only scroll when it is in active area=0D
+ min, max =3D self.page_scroll.get()=0D
+ if not((min =3D=3D 0.0) and (max =3D=3D 1.0)):=0D
+ self.conf_canvas.yview_scroll(-1 * int(event.delta / 120),=
=0D
+ 'units')=0D
+=0D
+ def update_visibility_for_widget(self, widget, args):=0D
+=0D
+ visible =3D True=0D
+ item =3D self.get_config_data_item_from_widget(widget, True)=0D
+ if item is None:=0D
+ return visible=0D
+ elif not item:=0D
+ return visible=0D
+=0D
+ result =3D 1=0D
+ if item['condition']:=0D
+ result =3D self.evaluate_condition(item)=0D
+ if result =3D=3D 2:=0D
+ # Gray=0D
+ widget.configure(state=3D'disabled')=0D
+ elif result =3D=3D 0:=0D
+ # Hide=0D
+ visible =3D False=0D
+ widget.grid_remove()=0D
+ else:=0D
+ # Show=0D
+ widget.grid()=0D
+ widget.configure(state=3D'normal')=0D
+=0D
+ return visible=0D
+=0D
+ def update_widgets_visibility_on_page(self):=0D
+ self.walk_widgets_in_layout(self.right_grid,=0D
+ self.update_visibility_for_widget)=0D
+=0D
+ def combo_select_changed(self, event):=0D
+ self.update_config_data_from_widget(event.widget, None)=0D
+ self.update_widgets_visibility_on_page()=0D
+=0D
+ def edit_num_finished(self, event):=0D
+ widget =3D event.widget=0D
+ item =3D self.get_config_data_item_from_widget(widget)=0D
+ if not item:=0D
+ return=0D
+ parts =3D item['type'].split(',')=0D
+ if len(parts) > 3:=0D
+ min =3D parts[2].lstrip()[1:]=0D
+ max =3D parts[3].rstrip()[:-1]=0D
+ min_val =3D array_str_to_value(min)=0D
+ max_val =3D array_str_to_value(max)=0D
+ text =3D widget.get()=0D
+ if ',' in text:=0D
+ text =3D '{ %s }' % text=0D
+ try:=0D
+ value =3D array_str_to_value(text)=0D
+ if value < min_val or value > max_val:=0D
+ raise Exception('Invalid input!')=0D
+ self.set_config_item_value(item, text)=0D
+ except Exception:=0D
+ pass=0D
+=0D
+ text =3D item['value'].strip('{').strip('}').strip()=0D
+ widget.delete(0, tkinter.END)=0D
+ widget.insert(0, text)=0D
+=0D
+ self.update_widgets_visibility_on_page()=0D
+=0D
+ def update_page_scroll_bar(self):=0D
+ # Update scrollbar=0D
+ self.frame_right.update()=0D
+ self.conf_canvas.config(scrollregion=3Dself.conf_canvas.bbox("all"=
))=0D
+=0D
+ def on_config_page_select_change(self, event):=0D
+ self.update_config_data_on_page()=0D
+ sel =3D self.left.selection()=0D
+ if len(sel) > 0:=0D
+ page_id =3D sel[0]=0D
+ self.build_config_data_page(page_id)=0D
+ self.update_widgets_visibility_on_page()=0D
+ self.update_page_scroll_bar()=0D
+=0D
+ def walk_widgets_in_layout(self, parent, callback_function, args=3DNon=
e):=0D
+ for widget in parent.winfo_children():=0D
+ callback_function(widget, args)=0D
+=0D
+ def clear_widgets_inLayout(self, parent=3DNone):=0D
+ if parent is None:=0D
+ parent =3D self.right_grid=0D
+=0D
+ for widget in parent.winfo_children():=0D
+ widget.destroy()=0D
+=0D
+ parent.grid_forget()=0D
+ self.conf_list.clear()=0D
+=0D
+ def build_config_page_tree(self, cfg_page, parent):=0D
+ for page in cfg_page['child']:=0D
+ page_id =3D next(iter(page))=0D
+ # Put CFG items into related page list=0D
+ self.page_list[page_id] =3D self.cfg_data_obj.get_cfg_list(pag=
e_id)=0D
+ self.page_list[page_id].sort(key=3Dlambda x: x['order'])=0D
+ page_name =3D self.cfg_data_obj.get_page_title(page_id)=0D
+ child =3D self.left.insert(=0D
+ parent, 'end',=0D
+ iid=3Dpage_id, text=3Dpage_name,=0D
+ value=3D0)=0D
+ if len(page[page_id]) > 0:=0D
+ self.build_config_page_tree(page[page_id], child)=0D
+=0D
+ def is_config_data_loaded(self):=0D
+ return True if len(self.page_list) else False=0D
+=0D
+ def set_current_config_page(self, page_id):=0D
+ self.page_id =3D page_id=0D
+=0D
+ def get_current_config_page(self):=0D
+ return self.page_id=0D
+=0D
+ def get_current_config_data(self):=0D
+ page_id =3D self.get_current_config_page()=0D
+ if page_id in self.page_list:=0D
+ return self.page_list[page_id]=0D
+ else:=0D
+ return []=0D
+=0D
+ invalid_values =3D {}=0D
+=0D
+ def build_config_data_page(self, page_id):=0D
+ self.clear_widgets_inLayout()=0D
+ self.set_current_config_page(page_id)=0D
+ disp_list =3D []=0D
+ for item in self.get_current_config_data():=0D
+ disp_list.append(item)=0D
+ row =3D 0=0D
+ disp_list.sort(key=3Dlambda x: x['order'])=0D
+ for item in disp_list:=0D
+ self.add_config_item(item, row)=0D
+ row +=3D 2=0D
+ if self.invalid_values:=0D
+ string =3D 'The following contails invalid options/values \n\n=
'=0D
+ for i in self.invalid_values:=0D
+ string +=3D i + ": " + str(self.invalid_values[i]) + "\n"=
=0D
+ reply =3D messagebox.showwarning('Warning!', string)=0D
+ if reply =3D=3D 'ok':=0D
+ self.invalid_values.clear()=0D
+=0D
+ fsp_version =3D ''=0D
+=0D
+ def load_config_data(self, file_name):=0D
+ gen_cfg_data =3D CGenYamlCfg()=0D
+ if file_name.endswith('.pkl'):=0D
+ with open(file_name, "rb") as pkl_file:=0D
+ gen_cfg_data.__dict__ =3D marshal.load(pkl_file)=0D
+ gen_cfg_data.prepare_marshal(False)=0D
+ elif file_name.endswith('.yaml'):=0D
+ if gen_cfg_data.load_yaml(file_name) !=3D 0:=0D
+ raise Exception(gen_cfg_data.get_last_error())=0D
+ else:=0D
+ raise Exception('Unsupported file "%s" !' % file_name)=0D
+ # checking fsp version=0D
+ if gen_cfg_data.detect_fsp():=0D
+ self.fsp_version =3D '2.X'=0D
+ else:=0D
+ self.fsp_version =3D '1.X'=0D
+ return gen_cfg_data=0D
+=0D
+ def about(self):=0D
+ msg =3D 'Configuration Editor\n--------------------------------\n =
\=0D
+ Version 0.8\n2021'=0D
+ lines =3D msg.split('\n')=0D
+ width =3D 30=0D
+ text =3D []=0D
+ for line in lines:=0D
+ text.append(line.center(width, ' '))=0D
+ messagebox.showinfo('Config Editor', '\n'.join(text))=0D
+=0D
+ def update_last_dir(self, path):=0D
+ self.last_dir =3D os.path.dirname(path)=0D
+=0D
+ def get_open_file_name(self, ftype):=0D
+ if self.is_config_data_loaded():=0D
+ if ftype =3D=3D 'dlt':=0D
+ question =3D ''=0D
+ elif ftype =3D=3D 'bin':=0D
+ question =3D 'All configuration will be reloaded from BIN =
file, \=0D
+ continue ?'=0D
+ elif ftype =3D=3D 'yaml':=0D
+ question =3D ''=0D
+ elif ftype =3D=3D 'bsf':=0D
+ question =3D ''=0D
+ else:=0D
+ raise Exception('Unsupported file type !')=0D
+ if question:=0D
+ reply =3D messagebox.askquestion('', question, icon=3D'war=
ning')=0D
+ if reply =3D=3D 'no':=0D
+ return None=0D
+=0D
+ if ftype =3D=3D 'yaml':=0D
+ if self.mode =3D=3D 'FSP':=0D
+ file_type =3D 'YAML'=0D
+ file_ext =3D 'yaml'=0D
+ else:=0D
+ file_type =3D 'YAML or PKL'=0D
+ file_ext =3D 'pkl *.yaml'=0D
+ else:=0D
+ file_type =3D ftype.upper()=0D
+ file_ext =3D ftype=0D
+=0D
+ path =3D filedialog.askopenfilename(=0D
+ initialdir=3Dself.last_dir,=0D
+ title=3D"Load file",=0D
+ filetypes=3D(("%s files" % file_type, "*.%s" % file_ext), =
(=0D
+ "all files", "*.*")))=0D
+ if path:=0D
+ self.update_last_dir(path)=0D
+ return path=0D
+ else:=0D
+ return None=0D
+=0D
+ def load_from_delta(self):=0D
+ path =3D self.get_open_file_name('dlt')=0D
+ if not path:=0D
+ return=0D
+ self.load_delta_file(path)=0D
+=0D
+ def load_delta_file(self, path):=0D
+ self.reload_config_data_from_bin(self.org_cfg_data_bin)=0D
+ try:=0D
+ self.cfg_data_obj.override_default_value(path)=0D
+ except Exception as e:=0D
+ messagebox.showerror('LOADING ERROR', str(e))=0D
+ return=0D
+ self.update_last_dir(path)=0D
+ self.refresh_config_data_page()=0D
+=0D
+ def load_from_bin(self):=0D
+ path =3D filedialog.askopenfilename(=0D
+ initialdir=3Dself.last_dir,=0D
+ title=3D"Load file",=0D
+ filetypes=3D{("Binaries", "*.fv *.fd *.bin *.rom")})=0D
+ if not path:=0D
+ return=0D
+ self.load_bin_file(path)=0D
+=0D
+ def load_bin_file(self, path):=0D
+ with open(path, 'rb') as fd:=0D
+ bin_data =3D bytearray(fd.read())=0D
+ if len(bin_data) < len(self.org_cfg_data_bin):=0D
+ messagebox.showerror('Binary file size is smaller than what \=
=0D
+ YAML requires !')=0D
+ return=0D
+=0D
+ try:=0D
+ self.reload_config_data_from_bin(bin_data)=0D
+ except Exception as e:=0D
+ messagebox.showerror('LOADING ERROR', str(e))=0D
+ return=0D
+=0D
+ def load_from_bsf_file(self):=0D
+ path =3D self.get_open_file_name('bsf')=0D
+ if not path:=0D
+ return=0D
+ self.load_bsf_file(path)=0D
+=0D
+ def load_bsf_file(self, path):=0D
+ bsf_file =3D path=0D
+ dsc_file =3D os.path.splitext(bsf_file)[0] + '.dsc'=0D
+ yaml_file =3D os.path.splitext(bsf_file)[0] + '.yaml'=0D
+ bsf_to_dsc(bsf_file, dsc_file)=0D
+ dsc_to_yaml(dsc_file, yaml_file)=0D
+=0D
+ self.load_cfg_file(yaml_file)=0D
+ return=0D
+=0D
+ def load_from_fd(self):=0D
+ path =3D filedialog.askopenfilename(=0D
+ initialdir=3Dself.last_dir,=0D
+ title=3D"Load file",=0D
+ filetypes=3D{("Binaries", "*.fv *.fd *.bin *.rom")})=0D
+ if not path:=0D
+ return=0D
+ self.load_fd_file(path)=0D
+=0D
+ def load_fd_file(self, path):=0D
+ with open(path, 'rb') as fd:=0D
+ bin_data =3D bytearray(fd.read())=0D
+=0D
+ fd =3D FirmwareDevice(0, bin_data)=0D
+ fd.ParseFd()=0D
+ fd.ParseFsp()=0D
+ fd.OutputFsp()=0D
+=0D
+ def load_cfg_file(self, path):=0D
+ # Save current values in widget and clear database=0D
+ self.clear_widgets_inLayout()=0D
+ self.left.delete(*self.left.get_children())=0D
+=0D
+ self.cfg_data_obj =3D self.load_config_data(path)=0D
+=0D
+ self.update_last_dir(path)=0D
+ self.org_cfg_data_bin =3D self.cfg_data_obj.generate_binary_array(=
)=0D
+ self.build_config_page_tree(self.cfg_data_obj.get_cfg_page()['root=
'],=0D
+ '')=0D
+=0D
+ msg_string =3D 'Click YES if it is FULL FSP '\=0D
+ + self.fsp_version + ' Binary'=0D
+ reply =3D messagebox.askquestion('Form', msg_string)=0D
+ if reply =3D=3D 'yes':=0D
+ self.load_from_bin()=0D
+=0D
+ for menu in self.menu_string:=0D
+ self.file_menu.entryconfig(menu, state=3D"normal")=0D
+=0D
+ return 0=0D
+=0D
+ def load_from_yaml(self):=0D
+ path =3D self.get_open_file_name('yaml')=0D
+ if not path:=0D
+ return=0D
+=0D
+ self.load_cfg_file(path)=0D
+=0D
+ def get_save_file_name(self, extension):=0D
+ path =3D filedialog.asksaveasfilename(=0D
+ initialdir=3Dself.last_dir,=0D
+ title=3D"Save file",=0D
+ defaultextension=3Dextension)=0D
+ if path:=0D
+ self.last_dir =3D os.path.dirname(path)=0D
+ return path=0D
+ else:=0D
+ return None=0D
+=0D
+ def save_delta_file(self, full=3DFalse):=0D
+ path =3D self.get_save_file_name(".dlt")=0D
+ if not path:=0D
+ return=0D
+=0D
+ self.update_config_data_on_page()=0D
+ new_data =3D self.cfg_data_obj.generate_binary_array()=0D
+ self.cfg_data_obj.generate_delta_file_from_bin(path,=0D
+ self.org_cfg_data_b=
in,=0D
+ new_data, full)=0D
+=0D
+ def save_to_delta(self):=0D
+ self.save_delta_file()=0D
+=0D
+ def save_full_to_delta(self):=0D
+ self.save_delta_file(True)=0D
+=0D
+ def save_to_bin(self):=0D
+ path =3D self.get_save_file_name(".bin")=0D
+ if not path:=0D
+ return=0D
+=0D
+ self.update_config_data_on_page()=0D
+ bins =3D self.cfg_data_obj.save_current_to_bin()=0D
+=0D
+ with open(path, 'wb') as fd:=0D
+ fd.write(bins)=0D
+=0D
+ def refresh_config_data_page(self):=0D
+ self.clear_widgets_inLayout()=0D
+ self.on_config_page_select_change(None)=0D
+=0D
+ def reload_config_data_from_bin(self, bin_dat):=0D
+ self.cfg_data_obj.load_default_from_bin(bin_dat)=0D
+ self.refresh_config_data_page()=0D
+=0D
+ def set_config_item_value(self, item, value_str):=0D
+ itype =3D item['type'].split(',')[0]=0D
+ if itype =3D=3D "Table":=0D
+ new_value =3D value_str=0D
+ elif itype =3D=3D "EditText":=0D
+ length =3D (self.cfg_data_obj.get_cfg_item_length(item) + 7) /=
/ 8=0D
+ new_value =3D value_str[:length]=0D
+ if item['value'].startswith("'"):=0D
+ new_value =3D "'%s'" % new_value=0D
+ else:=0D
+ try:=0D
+ new_value =3D self.cfg_data_obj.reformat_value_str(=0D
+ value_str,=0D
+ self.cfg_data_obj.get_cfg_item_length(item),=0D
+ item['value'])=0D
+ except Exception:=0D
+ print("WARNING: Failed to format value string '%s' for '%s=
' !"=0D
+ % (value_str, item['path']))=0D
+ new_value =3D item['value']=0D
+=0D
+ if item['value'] !=3D new_value:=0D
+ if self.debug:=0D
+ print('Update %s from %s to %s !'=0D
+ % (item['cname'], item['value'], new_value))=0D
+ item['value'] =3D new_value=0D
+=0D
+ def get_config_data_item_from_widget(self, widget, label=3DFalse):=0D
+ name =3D self.get_object_name(widget)=0D
+ if not name or not len(self.page_list):=0D
+ return None=0D
+=0D
+ if name.startswith('LABEL_'):=0D
+ if label:=0D
+ path =3D name[6:]=0D
+ else:=0D
+ return None=0D
+ else:=0D
+ path =3D name=0D
+ item =3D self.cfg_data_obj.get_item_by_path(path)=0D
+ return item=0D
+=0D
+ def update_config_data_from_widget(self, widget, args):=0D
+ item =3D self.get_config_data_item_from_widget(widget)=0D
+ if item is None:=0D
+ return=0D
+ elif not item:=0D
+ if isinstance(widget, tkinter.Label):=0D
+ return=0D
+ raise Exception('Failed to find "%s" !' %=0D
+ self.get_object_name(widget))=0D
+=0D
+ itype =3D item['type'].split(',')[0]=0D
+ if itype =3D=3D "Combo":=0D
+ opt_list =3D self.cfg_data_obj.get_cfg_item_options(item)=0D
+ tmp_list =3D [opt[0] for opt in opt_list]=0D
+ idx =3D widget.current()=0D
+ if idx !=3D -1:=0D
+ self.set_config_item_value(item, tmp_list[idx])=0D
+ elif itype in ["EditNum", "EditText"]:=0D
+ self.set_config_item_value(item, widget.get())=0D
+ elif itype in ["Table"]:=0D
+ new_value =3D bytes_to_bracket_str(widget.get())=0D
+ self.set_config_item_value(item, new_value)=0D
+=0D
+ def evaluate_condition(self, item):=0D
+ try:=0D
+ result =3D self.cfg_data_obj.evaluate_condition(item)=0D
+ except Exception:=0D
+ print("WARNING: Condition '%s' is invalid for '%s' !"=0D
+ % (item['condition'], item['path']))=0D
+ result =3D 1=0D
+ return result=0D
+=0D
+ def add_config_item(self, item, row):=0D
+ parent =3D self.right_grid=0D
+=0D
+ name =3D tkinter.Label(parent, text=3Ditem['name'], anchor=3D"w")=
=0D
+=0D
+ parts =3D item['type'].split(',')=0D
+ itype =3D parts[0]=0D
+ widget =3D None=0D
+=0D
+ if itype =3D=3D "Combo":=0D
+ # Build=0D
+ opt_list =3D self.cfg_data_obj.get_cfg_item_options(item)=0D
+ current_value =3D self.cfg_data_obj.get_cfg_item_value(item, F=
alse)=0D
+ option_list =3D []=0D
+ current =3D None=0D
+=0D
+ for idx, option in enumerate(opt_list):=0D
+ option_str =3D option[0]=0D
+ try:=0D
+ option_value =3D self.cfg_data_obj.get_value(=0D
+ option_str,=0D
+ len(option_str), False)=0D
+ except Exception:=0D
+ option_value =3D 0=0D
+ print('WARNING: Option "%s" has invalid format for "%s=
" !'=0D
+ % (option_str, item['path']))=0D
+ if option_value =3D=3D current_value:=0D
+ current =3D idx=0D
+ option_list.append(option[1])=0D
+=0D
+ widget =3D ttk.Combobox(parent, value=3Doption_list, state=3D"=
readonly")=0D
+ widget.bind("<<ComboboxSelected>>", self.combo_select_changed)=
=0D
+ widget.unbind_class("TCombobox", "<MouseWheel>")=0D
+=0D
+ if current is None:=0D
+ print('WARNING: Value "%s" is an invalid option for "%s" !=
' %=0D
+ (current_value, item['path']))=0D
+ self.invalid_values[item['path']] =3D current_value=0D
+ else:=0D
+ widget.current(current)=0D
+=0D
+ elif itype in ["EditNum", "EditText"]:=0D
+ txt_val =3D tkinter.StringVar()=0D
+ widget =3D tkinter.Entry(parent, textvariable=3Dtxt_val)=0D
+ value =3D item['value'].strip("'")=0D
+ if itype in ["EditText"]:=0D
+ txt_val.trace(=0D
+ 'w',=0D
+ lambda *args: self.limit_entry_size=0D
+ (txt_val, (self.cfg_data_obj.get_cfg_item_length(item)=
=0D
+ + 7) // 8))=0D
+ elif itype in ["EditNum"]:=0D
+ value =3D item['value'].strip("{").strip("}").strip()=0D
+ widget.bind("<FocusOut>", self.edit_num_finished)=0D
+ txt_val.set(value)=0D
+=0D
+ elif itype in ["Table"]:=0D
+ bins =3D self.cfg_data_obj.get_cfg_item_value(item, True)=0D
+ col_hdr =3D item['option'].split(',')=0D
+ widget =3D custom_table(parent, col_hdr, bins)=0D
+=0D
+ else:=0D
+ if itype and itype not in ["Reserved"]:=0D
+ print("WARNING: Type '%s' is invalid for '%s' !" %=0D
+ (itype, item['path']))=0D
+ self.invalid_values[item['path']] =3D itype=0D
+=0D
+ if widget:=0D
+ create_tool_tip(widget, item['help'])=0D
+ self.set_object_name(name, 'LABEL_' + item['path'])=0D
+ self.set_object_name(widget, item['path'])=0D
+ name.grid(row=3Drow, column=3D0, padx=3D10, pady=3D5, sticky=
=3D"nsew")=0D
+ widget.grid(row=3Drow + 1, rowspan=3D1, column=3D0,=0D
+ padx=3D10, pady=3D5, sticky=3D"nsew")=0D
+=0D
+ def update_config_data_on_page(self):=0D
+ self.walk_widgets_in_layout(self.right_grid,=0D
+ self.update_config_data_from_widget)=0D
+=0D
+=0D
+if __name__ =3D=3D '__main__':=0D
+ root =3D tkinter.Tk()=0D
+ app =3D application(master=3Droot)=0D
+ root.title("Config Editor")=0D
+ root.mainloop()=0D
diff --git a/IntelFsp2Pkg/Tools/ConfigEditor/GenYamlCfg.py b/IntelFsp2Pkg/T=
ools/ConfigEditor/GenYamlCfg.py
new file mode 100644
index 0000000000..91b3539075
--- /dev/null
+++ b/IntelFsp2Pkg/Tools/ConfigEditor/GenYamlCfg.py
@@ -0,0 +1,2254 @@
+# @ GenYamlCfg.py=0D
+#=0D
+# Copyright (c) 2020, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+#=0D
+=0D
+import os=0D
+import sys=0D
+import re=0D
+import marshal=0D
+import string=0D
+import operator as op=0D
+import ast=0D
+import tkinter.messagebox as messagebox=0D
+=0D
+from datetime import date=0D
+from collections import OrderedDict=0D
+from CommonUtility import value_to_bytearray, value_to_bytes, \=0D
+ bytes_to_value, get_bits_from_bytes, set_bits_to_bytes=0D
+=0D
+# Generated file copyright header=0D
+__copyright_tmp__ =3D """/** @file=0D
+=0D
+ Platform Configuration %s File.=0D
+=0D
+ Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+ This file is automatically generated. Please do NOT modify !!!=0D
+=0D
+**/=0D
+"""=0D
+=0D
+=0D
+def get_copyright_header(file_type, allow_modify=3DFalse):=0D
+ file_description =3D {=0D
+ 'yaml': 'Boot Setting',=0D
+ 'dlt': 'Delta',=0D
+ 'inc': 'C Binary Blob',=0D
+ 'h': 'C Struct Header'=0D
+ }=0D
+ if file_type in ['yaml', 'dlt']:=0D
+ comment_char =3D '#'=0D
+ else:=0D
+ comment_char =3D ''=0D
+ lines =3D __copyright_tmp__.split('\n')=0D
+ if allow_modify:=0D
+ lines =3D [line for line in lines if 'Please do NOT modify' not in=
line]=0D
+ copyright_hdr =3D '\n'.join('%s%s' % (comment_char, line)=0D
+ for line in lines)[:-1] + '\n'=0D
+ return copyright_hdr % (file_description[file_type], date.today().year=
)=0D
+=0D
+=0D
+def check_quote(text):=0D
+ if (text[0] =3D=3D "'" and text[-1] =3D=3D "'") or (text[0] =3D=3D '"'=
=0D
+ and text[-1] =3D=3D '"'):=
=0D
+ return True=0D
+ return False=0D
+=0D
+=0D
+def strip_quote(text):=0D
+ new_text =3D text.strip()=0D
+ if check_quote(new_text):=0D
+ return new_text[1:-1]=0D
+ return text=0D
+=0D
+=0D
+def strip_delimiter(text, delim):=0D
+ new_text =3D text.strip()=0D
+ if new_text:=0D
+ if new_text[0] =3D=3D delim[0] and new_text[-1] =3D=3D delim[-1]:=
=0D
+ return new_text[1:-1]=0D
+ return text=0D
+=0D
+=0D
+def bytes_to_bracket_str(bytes):=0D
+ return '{ %s }' % (', '.join('0x%02x' % i for i in bytes))=0D
+=0D
+=0D
+def array_str_to_value(val_str):=0D
+ val_str =3D val_str.strip()=0D
+ val_str =3D strip_delimiter(val_str, '{}')=0D
+ val_str =3D strip_quote(val_str)=0D
+ value =3D 0=0D
+ for each in val_str.split(',')[::-1]:=0D
+ each =3D each.strip()=0D
+ value =3D (value << 8) | int(each, 0)=0D
+ return value=0D
+=0D
+=0D
+def write_lines(lines, file):=0D
+ fo =3D open(file, "w")=0D
+ fo.write(''.join([x[0] for x in lines]))=0D
+ fo.close()=0D
+=0D
+=0D
+def read_lines(file):=0D
+ if not os.path.exists(file):=0D
+ test_file =3D os.path.basename(file)=0D
+ if os.path.exists(test_file):=0D
+ file =3D test_file=0D
+ fi =3D open(file, 'r')=0D
+ lines =3D fi.readlines()=0D
+ fi.close()=0D
+ return lines=0D
+=0D
+=0D
+def expand_file_value(path, value_str):=0D
+ result =3D bytearray()=0D
+ match =3D re.match("\\{\\s*FILE:(.+)\\}", value_str)=0D
+ if match:=0D
+ file_list =3D match.group(1).split(',')=0D
+ for file in file_list:=0D
+ file =3D file.strip()=0D
+ bin_path =3D os.path.join(path, file)=0D
+ result.extend(bytearray(open(bin_path, 'rb').read()))=0D
+ print('\n\n result ', result)=0D
+ return result=0D
+=0D
+=0D
+class ExpressionEval(ast.NodeVisitor):=0D
+ operators =3D {=0D
+ ast.Add: op.add,=0D
+ ast.Sub: op.sub,=0D
+ ast.Mult: op.mul,=0D
+ ast.Div: op.floordiv,=0D
+ ast.Mod: op.mod,=0D
+ ast.Eq: op.eq,=0D
+ ast.NotEq: op.ne,=0D
+ ast.Gt: op.gt,=0D
+ ast.Lt: op.lt,=0D
+ ast.GtE: op.ge,=0D
+ ast.LtE: op.le,=0D
+ ast.BitXor: op.xor,=0D
+ ast.BitAnd: op.and_,=0D
+ ast.BitOr: op.or_,=0D
+ ast.Invert: op.invert,=0D
+ ast.USub: op.neg=0D
+ }=0D
+=0D
+ def __init__(self):=0D
+ self._debug =3D False=0D
+ self._expression =3D ''=0D
+ self._namespace =3D {}=0D
+ self._get_variable =3D None=0D
+=0D
+ def eval(self, expr, vars=3D{}):=0D
+ self._expression =3D expr=0D
+ if type(vars) is dict:=0D
+ self._namespace =3D vars=0D
+ self._get_variable =3D None=0D
+ else:=0D
+ self._namespace =3D {}=0D
+ self._get_variable =3D vars=0D
+ node =3D ast.parse(self._expression, mode=3D'eval')=0D
+ result =3D self.visit(node.body)=0D
+ if self._debug:=0D
+ print('EVAL [ %s ] =3D %s' % (expr, str(result)))=0D
+ return result=0D
+=0D
+ def visit_Name(self, node):=0D
+ if self._get_variable is not None:=0D
+ return self._get_variable(node.id)=0D
+ else:=0D
+ return self._namespace[node.id]=0D
+=0D
+ def visit_Num(self, node):=0D
+ return node.n=0D
+=0D
+ def visit_NameConstant(self, node):=0D
+ return node.value=0D
+=0D
+ def visit_BoolOp(self, node):=0D
+ result =3D False=0D
+ if isinstance(node.op, ast.And):=0D
+ for value in node.values:=0D
+ result =3D self.visit(value)=0D
+ if not result:=0D
+ break=0D
+ elif isinstance(node.op, ast.Or):=0D
+ for value in node.values:=0D
+ result =3D self.visit(value)=0D
+ if result:=0D
+ break=0D
+ return True if result else False=0D
+=0D
+ def visit_UnaryOp(self, node):=0D
+ val =3D self.visit(node.operand)=0D
+ return ExpressionEval.operators[type(node.op)](val)=0D
+=0D
+ def visit_BinOp(self, node):=0D
+ lhs =3D self.visit(node.left)=0D
+ rhs =3D self.visit(node.right)=0D
+ return ExpressionEval.operators[type(node.op)](lhs, rhs)=0D
+=0D
+ def visit_Compare(self, node):=0D
+ right =3D self.visit(node.left)=0D
+ result =3D True=0D
+ for operation, comp in zip(node.ops, node.comparators):=0D
+ if not result:=0D
+ break=0D
+ left =3D right=0D
+ right =3D self.visit(comp)=0D
+ result =3D ExpressionEval.operators[type(operation)](left, rig=
ht)=0D
+ return result=0D
+=0D
+ def visit_Call(self, node):=0D
+ if node.func.id in ['ternary']:=0D
+ condition =3D self.visit(node.args[0])=0D
+ val_true =3D self.visit(node.args[1])=0D
+ val_false =3D self.visit(node.args[2])=0D
+ return val_true if condition else val_false=0D
+ elif node.func.id in ['offset', 'length']:=0D
+ if self._get_variable is not None:=0D
+ return self._get_variable(node.args[0].s, node.func.id)=0D
+ else:=0D
+ raise ValueError("Unsupported function: " + repr(node))=0D
+=0D
+ def generic_visit(self, node):=0D
+ raise ValueError("malformed node or string: " + repr(node))=0D
+=0D
+=0D
+class CFG_YAML():=0D
+ TEMPLATE =3D 'template'=0D
+ CONFIGS =3D 'configs'=0D
+ VARIABLE =3D 'variable'=0D
+=0D
+ def __init__(self):=0D
+ self.log_line =3D False=0D
+ self.allow_template =3D False=0D
+ self.cfg_tree =3D None=0D
+ self.tmp_tree =3D None=0D
+ self.var_dict =3D None=0D
+ self.def_dict =3D {}=0D
+ self.yaml_path =3D ''=0D
+ self.lines =3D []=0D
+ self.full_lines =3D []=0D
+ self.index =3D 0=0D
+ self.re_expand =3D re.compile(=0D
+ r'(.+:\s+|\s*\-\s*)!expand\s+\{\s*(\w+_TMPL)\s*:\s*\[(.+)]\s*\=
}')=0D
+ self.re_include =3D re.compile(r'(.+:\s+|\s*\-\s*)!include\s+(.+)'=
)=0D
+=0D
+ @staticmethod=0D
+ def count_indent(line):=0D
+ return next((i for i, c in enumerate(line) if not c.isspace()),=0D
+ len(line))=0D
+=0D
+ @staticmethod=0D
+ def substitue_args(text, arg_dict):=0D
+ for arg in arg_dict:=0D
+ text =3D text.replace('$' + arg, arg_dict[arg])=0D
+ return text=0D
+=0D
+ @staticmethod=0D
+ def dprint(*args):=0D
+ pass=0D
+=0D
+ def process_include(self, line, insert=3DTrue):=0D
+ match =3D self.re_include.match(line)=0D
+ if not match:=0D
+ raise Exception("Invalid !include format '%s' !" % line.strip(=
))=0D
+=0D
+ prefix =3D match.group(1)=0D
+ include =3D match.group(2)=0D
+ if prefix.strip() =3D=3D '-':=0D
+ prefix =3D ''=0D
+ adjust =3D 0=0D
+ else:=0D
+ adjust =3D 2=0D
+=0D
+ include =3D strip_quote(include)=0D
+ request =3D CFG_YAML.count_indent(line) + adjust=0D
+=0D
+ if self.log_line:=0D
+ # remove the include line itself=0D
+ del self.full_lines[-1]=0D
+=0D
+ inc_path =3D os.path.join(self.yaml_path, include)=0D
+ if not os.path.exists(inc_path):=0D
+ # try relative path to project root=0D
+ try_path =3D os.path.join(os.path.dirname(os.path.realpath(__f=
ile__)=0D
+ ), "../..", include)=0D
+ if os.path.exists(try_path):=0D
+ inc_path =3D try_path=0D
+ else:=0D
+ raise Exception("ERROR: Cannot open file '%s'." % inc_path=
)=0D
+=0D
+ lines =3D read_lines(inc_path)=0D
+ current =3D 0=0D
+ same_line =3D False=0D
+ for idx, each in enumerate(lines):=0D
+ start =3D each.lstrip()=0D
+ if start =3D=3D '' or start[0] =3D=3D '#':=0D
+ continue=0D
+=0D
+ if start[0] =3D=3D '>':=0D
+ # append the content directly at the same line=0D
+ same_line =3D True=0D
+=0D
+ start =3D idx=0D
+ current =3D CFG_YAML.count_indent(each)=0D
+ break=0D
+=0D
+ lines =3D lines[start+1:] if same_line else lines[start:]=0D
+ leading =3D ''=0D
+ if same_line:=0D
+ request =3D len(prefix)=0D
+ leading =3D '>'=0D
+=0D
+ lines =3D [prefix + '%s\n' % leading] + [' ' * request +=0D
+ i[current:] for i in lines]=
=0D
+ if insert:=0D
+ self.lines =3D lines + self.lines=0D
+=0D
+ return lines=0D
+=0D
+ def process_expand(self, line):=0D
+ match =3D self.re_expand.match(line)=0D
+ if not match:=0D
+ raise Exception("Invalid !expand format '%s' !" % line.strip()=
)=0D
+ lines =3D []=0D
+ prefix =3D match.group(1)=0D
+ temp_name =3D match.group(2)=0D
+ args =3D match.group(3)=0D
+=0D
+ if prefix.strip() =3D=3D '-':=0D
+ indent =3D 0=0D
+ else:=0D
+ indent =3D 2=0D
+ lines =3D self.process_expand_template(temp_name, prefix, args, in=
dent)=0D
+ self.lines =3D lines + self.lines=0D
+=0D
+ def process_expand_template(self, temp_name, prefix, args, indent=3D2)=
:=0D
+ # expand text with arg substitution=0D
+ if temp_name not in self.tmp_tree:=0D
+ raise Exception("Could not find template '%s' !" % temp_name)=
=0D
+ parts =3D args.split(',')=0D
+ parts =3D [i.strip() for i in parts]=0D
+ num =3D len(parts)=0D
+ arg_dict =3D dict(zip(['(%d)' % (i + 1) for i in range(num)], part=
s))=0D
+ str_data =3D self.tmp_tree[temp_name]=0D
+ text =3D DefTemplate(str_data).safe_substitute(self.def_dict)=0D
+ text =3D CFG_YAML.substitue_args(text, arg_dict)=0D
+ target =3D CFG_YAML.count_indent(prefix) + indent=0D
+ current =3D CFG_YAML.count_indent(text)=0D
+ padding =3D target * ' '=0D
+ if indent =3D=3D 0:=0D
+ leading =3D []=0D
+ else:=0D
+ leading =3D [prefix + '\n']=0D
+ text =3D leading + [(padding + i + '\n')[current:]=0D
+ for i in text.splitlines()]=0D
+ return text=0D
+=0D
+ def load_file(self, yaml_file):=0D
+ self.index =3D 0=0D
+ self.lines =3D read_lines(yaml_file)=0D
+=0D
+ def peek_line(self):=0D
+ if len(self.lines) =3D=3D 0:=0D
+ return None=0D
+ else:=0D
+ return self.lines[0]=0D
+=0D
+ def put_line(self, line):=0D
+ self.lines.insert(0, line)=0D
+ if self.log_line:=0D
+ del self.full_lines[-1]=0D
+=0D
+ def get_line(self):=0D
+ if len(self.lines) =3D=3D 0:=0D
+ return None=0D
+ else:=0D
+ line =3D self.lines.pop(0)=0D
+ if self.log_line:=0D
+ self.full_lines.append(line.rstrip())=0D
+ return line=0D
+=0D
+ def get_multiple_line(self, indent):=0D
+ text =3D ''=0D
+ newind =3D indent + 1=0D
+ while True:=0D
+ line =3D self.peek_line()=0D
+ if line is None:=0D
+ break=0D
+ sline =3D line.strip()=0D
+ if sline !=3D '':=0D
+ newind =3D CFG_YAML.count_indent(line)=0D
+ if newind <=3D indent:=0D
+ break=0D
+ self.get_line()=0D
+ if sline !=3D '':=0D
+ text =3D text + line=0D
+ return text=0D
+=0D
+ def traverse_cfg_tree(self, handler):=0D
+ def _traverse_cfg_tree(root, level=3D0):=0D
+ # config structure=0D
+ for key in root:=0D
+ if type(root[key]) is OrderedDict:=0D
+ level +=3D 1=0D
+ handler(key, root[key], level)=0D
+ _traverse_cfg_tree(root[key], level)=0D
+ level -=3D 1=0D
+ _traverse_cfg_tree(self.cfg_tree)=0D
+=0D
+ def count(self):=0D
+ def _count(name, cfgs, level):=0D
+ num[0] +=3D 1=0D
+ num =3D [0]=0D
+ self.traverse_cfg_tree(_count)=0D
+ return num[0]=0D
+=0D
+ def parse(self, parent_name=3D'', curr=3DNone, level=3D0):=0D
+ child =3D None=0D
+ last_indent =3D None=0D
+ key =3D ''=0D
+ temp_chk =3D {}=0D
+=0D
+ while True:=0D
+ line =3D self.get_line()=0D
+ if line is None:=0D
+ break=0D
+=0D
+ curr_line =3D line.strip()=0D
+ if curr_line =3D=3D '' or curr_line[0] =3D=3D '#':=0D
+ continue=0D
+=0D
+ indent =3D CFG_YAML.count_indent(line)=0D
+ if last_indent is None:=0D
+ last_indent =3D indent=0D
+=0D
+ if indent !=3D last_indent:=0D
+ # outside of current block, put the line back to queue=0D
+ self.put_line(' ' * indent + curr_line)=0D
+=0D
+ if curr_line.endswith(': >'):=0D
+ # multiline marker=0D
+ old_count =3D len(self.full_lines)=0D
+ line =3D self.get_multiple_line(indent)=0D
+ if self.log_line and not self.allow_template \=0D
+ and '!include ' in line:=0D
+ # expand include in template=0D
+ new_lines =3D []=0D
+ lines =3D line.splitlines()=0D
+ for idx, each in enumerate(lines):=0D
+ if '!include ' in each:=0D
+ new_line =3D ''.join(self.process_include(each=
,=0D
+ False)=
)=0D
+ new_lines.append(new_line)=0D
+ else:=0D
+ new_lines.append(each)=0D
+ self.full_lines =3D self.full_lines[:old_count] + new_=
lines=0D
+ curr_line =3D curr_line + line=0D
+=0D
+ if indent > last_indent:=0D
+ # child nodes=0D
+ if child is None:=0D
+ raise Exception('Unexpected format at line: %s'=0D
+ % (curr_line))=0D
+=0D
+ level +=3D 1=0D
+ self.parse(key, child, level)=0D
+ level -=3D 1=0D
+ line =3D self.peek_line()=0D
+ if line is not None:=0D
+ curr_line =3D line.strip()=0D
+ indent =3D CFG_YAML.count_indent(line)=0D
+ if indent >=3D last_indent:=0D
+ # consume the line=0D
+ self.get_line()=0D
+ else:=0D
+ # end of file=0D
+ indent =3D -1=0D
+=0D
+ if curr is None:=0D
+ curr =3D OrderedDict()=0D
+=0D
+ if indent < last_indent:=0D
+ return curr=0D
+=0D
+ marker1 =3D curr_line[0]=0D
+ marker2 =3D curr_line[-1]=0D
+ start =3D 1 if marker1 =3D=3D '-' else 0=0D
+ pos =3D curr_line.find(': ')=0D
+ if pos > 0:=0D
+ child =3D None=0D
+ key =3D curr_line[start:pos].strip()=0D
+ if curr_line[pos + 2] =3D=3D '>':=0D
+ curr[key] =3D curr_line[pos + 3:]=0D
+ else:=0D
+ # XXXX: !include / !expand=0D
+ if '!include ' in curr_line:=0D
+ self.process_include(line)=0D
+ elif '!expand ' in curr_line:=0D
+ if self.allow_template and not self.log_line:=0D
+ self.process_expand(line)=0D
+ else:=0D
+ value_str =3D curr_line[pos + 2:].strip()=0D
+ curr[key] =3D value_str=0D
+ if self.log_line and value_str[0] =3D=3D '{':=0D
+ # expand {FILE: xxxx} format in the log line=0D
+ if value_str[1:].rstrip().startswith('FILE:'):=
=0D
+ value_bytes =3D expand_file_value(=0D
+ self.yaml_path, value_str)=0D
+ value_str =3D bytes_to_bracket_str(value_b=
ytes)=0D
+ self.full_lines[-1] =3D line[=0D
+ :indent] + curr_line[:pos + 2] + value=
_str=0D
+=0D
+ elif marker2 =3D=3D ':':=0D
+ child =3D OrderedDict()=0D
+ key =3D curr_line[start:-1].strip()=0D
+ if key =3D=3D '$ACTION':=0D
+ # special virtual nodes, rename to ensure unique key=0D
+ key =3D '$ACTION_%04X' % self.index=0D
+ self.index +=3D 1=0D
+ if key in curr:=0D
+ if key not in temp_chk:=0D
+ # check for duplicated keys at same level=0D
+ temp_chk[key] =3D 1=0D
+ else:=0D
+ raise Exception("Duplicated item '%s:%s' found !"=
=0D
+ % (parent_name, key))=0D
+=0D
+ curr[key] =3D child=0D
+ if self.var_dict is None and key =3D=3D CFG_YAML.VARIABLE:=
=0D
+ self.var_dict =3D child=0D
+ if self.tmp_tree is None and key =3D=3D CFG_YAML.TEMPLATE:=
=0D
+ self.tmp_tree =3D child=0D
+ if self.var_dict:=0D
+ for each in self.var_dict:=0D
+ txt =3D self.var_dict[each]=0D
+ if type(txt) is str:=0D
+ self.def_dict['(%s)' % each] =3D txt=0D
+ if self.tmp_tree and key =3D=3D CFG_YAML.CONFIGS:=0D
+ # apply template for the main configs=0D
+ self.allow_template =3D True=0D
+ else:=0D
+ child =3D None=0D
+ # - !include cfg_opt.yaml=0D
+ if '!include ' in curr_line:=0D
+ self.process_include(line)=0D
+=0D
+ return curr=0D
+=0D
+ def load_yaml(self, opt_file):=0D
+ self.var_dict =3D None=0D
+ self.yaml_path =3D os.path.dirname(opt_file)=0D
+ self.load_file(opt_file)=0D
+ yaml_tree =3D self.parse()=0D
+ self.tmp_tree =3D yaml_tree[CFG_YAML.TEMPLATE]=0D
+ self.cfg_tree =3D yaml_tree[CFG_YAML.CONFIGS]=0D
+ return self.cfg_tree=0D
+=0D
+ def expand_yaml(self, opt_file):=0D
+ self.log_line =3D True=0D
+ self.load_yaml(opt_file)=0D
+ self.log_line =3D False=0D
+ text =3D '\n'.join(self.full_lines)=0D
+ self.full_lines =3D []=0D
+ return text=0D
+=0D
+=0D
+class DefTemplate(string.Template):=0D
+ idpattern =3D '\\([_A-Z][_A-Z0-9]*\\)|[_A-Z][_A-Z0-9]*'=0D
+=0D
+=0D
+class CGenYamlCfg:=0D
+ STRUCT =3D '$STRUCT'=0D
+ bits_width =3D {'b': 1, 'B': 8, 'W': 16, 'D': 32, 'Q': 64}=0D
+ builtin_option =3D {'$EN_DIS': [('0', 'Disable'), ('1', 'Enable')]}=0D
+ exclude_struct =3D ['FSP_UPD_HEADER', 'FSPT_ARCH_UPD',=0D
+ 'FSPM_ARCH_UPD', 'FSPS_ARCH_UPD',=0D
+ 'GPIO_GPP_*', 'GPIO_CFG_DATA',=0D
+ 'GpioConfPad*', 'GpioPinConfig',=0D
+ 'BOOT_OPTION*', 'PLATFORMID_CFG_DATA', '\\w+_Half[01=
]']=0D
+ include_tag =3D ['GPIO_CFG_DATA']=0D
+ keyword_set =3D set(['name', 'type', 'option', 'help', 'length',=0D
+ 'value', 'order', 'struct', 'condition'])=0D
+=0D
+ def __init__(self):=0D
+ self._mode =3D ''=0D
+ self._debug =3D False=0D
+ self._macro_dict =3D {}=0D
+ self.initialize()=0D
+=0D
+ def initialize(self):=0D
+ self._old_bin =3D None=0D
+ self._cfg_tree =3D {}=0D
+ self._tmp_tree =3D {}=0D
+ self._cfg_list =3D []=0D
+ self._cfg_page =3D {'root': {'title': '', 'child': []}}=0D
+ self._cur_page =3D ''=0D
+ self._var_dict =3D {}=0D
+ self._def_dict =3D {}=0D
+ self._yaml_path =3D ''=0D
+=0D
+ @staticmethod=0D
+ def deep_convert_dict(layer):=0D
+ # convert OrderedDict to list + dict=0D
+ new_list =3D layer=0D
+ if isinstance(layer, OrderedDict):=0D
+ new_list =3D list(layer.items())=0D
+ for idx, pair in enumerate(new_list):=0D
+ new_node =3D CGenYamlCfg.deep_convert_dict(pair[1])=0D
+ new_list[idx] =3D dict({pair[0]: new_node})=0D
+ return new_list=0D
+=0D
+ @staticmethod=0D
+ def deep_convert_list(layer):=0D
+ if isinstance(layer, list):=0D
+ od =3D OrderedDict({})=0D
+ for each in layer:=0D
+ if isinstance(each, dict):=0D
+ key =3D next(iter(each))=0D
+ od[key] =3D CGenYamlCfg.deep_convert_list(each[key])=0D
+ return od=0D
+ else:=0D
+ return layer=0D
+=0D
+ @staticmethod=0D
+ def expand_include_files(file_path, cur_dir=3D''):=0D
+ if cur_dir =3D=3D '':=0D
+ cur_dir =3D os.path.dirname(file_path)=0D
+ file_path =3D os.path.basename(file_path)=0D
+=0D
+ input_file_path =3D os.path.join(cur_dir, file_path)=0D
+ file =3D open(input_file_path, "r")=0D
+ lines =3D file.readlines()=0D
+ file.close()=0D
+ new_lines =3D []=0D
+ for line_num, line in enumerate(lines):=0D
+ match =3D re.match("^!include\\s*(.+)?$", line.strip())=0D
+ if match:=0D
+ inc_path =3D match.group(1)=0D
+ tmp_path =3D os.path.join(cur_dir, inc_path)=0D
+ org_path =3D tmp_path=0D
+ if not os.path.exists(tmp_path):=0D
+ cur_dir =3D os.path.join(os.path.dirname=0D
+ (os.path.realpath(__file__)=0D
+ ), "..", "..")=0D
+ tmp_path =3D os.path.join(cur_dir, inc_path)=0D
+ if not os.path.exists(tmp_path):=0D
+ raise Exception("ERROR: Cannot open include\=0D
+ file '%s'." % org_path)=0D
+ else:=0D
+ new_lines.append(('# Included from file: %s\n' % inc_p=
ath,=0D
+ tmp_path, 0))=0D
+ new_lines.append(('# %s\n' % ('=3D' * 80), tmp_path, 0=
))=0D
+ new_lines.extend(CGenYamlCfg.expand_include_files=0D
+ (inc_path, cur_dir))=0D
+ else:=0D
+ new_lines.append((line, input_file_path, line_num))=0D
+=0D
+ return new_lines=0D
+=0D
+ @staticmethod=0D
+ def format_struct_field_name(input, count=3D0):=0D
+ name =3D ''=0D
+ cap =3D True=0D
+ if '_' in input:=0D
+ input =3D input.lower()=0D
+ for each in input:=0D
+ if each =3D=3D '_':=0D
+ cap =3D True=0D
+ continue=0D
+ elif cap:=0D
+ each =3D each.upper()=0D
+ cap =3D False=0D
+ name =3D name + each=0D
+=0D
+ if count > 1:=0D
+ name =3D '%s[%d]' % (name, count)=0D
+=0D
+ return name=0D
+=0D
+ def get_mode(self):=0D
+ return self._mode=0D
+=0D
+ def set_mode(self, mode):=0D
+ self._mode =3D mode=0D
+=0D
+ def get_last_error(self):=0D
+ return ''=0D
+=0D
+ def get_variable(self, var, attr=3D'value'):=0D
+ if var in self._var_dict:=0D
+ var =3D self._var_dict[var]=0D
+ return var=0D
+=0D
+ item =3D self.locate_cfg_item(var, False)=0D
+ if item is None:=0D
+ raise ValueError("Cannot find variable '%s' !" % var)=0D
+=0D
+ if item:=0D
+ if 'indx' in item:=0D
+ item =3D self.get_item_by_index(item['indx'])=0D
+ if attr =3D=3D 'offset':=0D
+ var =3D item['offset']=0D
+ elif attr =3D=3D 'length':=0D
+ var =3D item['length']=0D
+ elif attr =3D=3D 'value':=0D
+ var =3D self.get_cfg_item_value(item)=0D
+ else:=0D
+ raise ValueError("Unsupported variable attribute '%s' !" %=
=0D
+ attr)=0D
+ return var=0D
+=0D
+ def eval(self, expr):=0D
+ def _handler(pattern):=0D
+ if pattern.group(1):=0D
+ target =3D 1=0D
+ else:=0D
+ target =3D 2=0D
+ result =3D self.get_variable(pattern.group(target))=0D
+ if result is None:=0D
+ raise ValueError('Unknown variable $(%s) !' %=0D
+ pattern.group(target))=0D
+ return hex(result)=0D
+=0D
+ expr_eval =3D ExpressionEval()=0D
+ if '$' in expr:=0D
+ # replace known variable first=0D
+ expr =3D re.sub(r'\$\(([_a-zA-Z][\w\.]*)\)|\$([_a-zA-Z][\w\.]*=
)',=0D
+ _handler, expr)=0D
+ return expr_eval.eval(expr, self.get_variable)=0D
+=0D
+ def parse_macros(self, macro_def_str):=0D
+ # ['-DABC=3D1', '-D', 'CFG_DEBUG=3D1', '-D', 'CFG_OUTDIR=3DBuild']=
=0D
+ self._macro_dict =3D {}=0D
+ is_expression =3D False=0D
+ for macro in macro_def_str:=0D
+ if macro.startswith('-D'):=0D
+ is_expression =3D True=0D
+ if len(macro) > 2:=0D
+ macro =3D macro[2:]=0D
+ else:=0D
+ continue=0D
+ if is_expression:=0D
+ is_expression =3D False=0D
+ match =3D re.match("(\\w+)=3D(.+)", macro)=0D
+ if match:=0D
+ self._macro_dict[match.group(1)] =3D match.group(2)=0D
+ else:=0D
+ match =3D re.match("(\\w+)", macro)=0D
+ if match:=0D
+ self._macro_dict[match.group(1)] =3D ''=0D
+ if len(self._macro_dict) =3D=3D 0:=0D
+ error =3D 1=0D
+ else:=0D
+ error =3D 0=0D
+ if self._debug:=0D
+ print("INFO : Macro dictionary:")=0D
+ for each in self._macro_dict:=0D
+ print(" $(%s) =3D [ %s ]"=0D
+ % (each, self._macro_dict[each]))=0D
+ return error=0D
+=0D
+ def get_cfg_list(self, page_id=3DNone):=0D
+ if page_id is None:=0D
+ # return full list=0D
+ return self._cfg_list=0D
+ else:=0D
+ # build a new list for items under a page ID=0D
+ cfgs =3D [i for i in self._cfg_list if i['cname'] and=0D
+ (i['page'] =3D=3D page_id)]=0D
+ return cfgs=0D
+=0D
+ def get_cfg_page(self):=0D
+ return self._cfg_page=0D
+=0D
+ def get_cfg_item_length(self, item):=0D
+ return item['length']=0D
+=0D
+ def get_cfg_item_value(self, item, array=3DFalse):=0D
+ value_str =3D item['value']=0D
+ length =3D item['length']=0D
+ return self.get_value(value_str, length, array)=0D
+=0D
+ def format_value_to_str(self, value, bit_length, old_value=3D''):=0D
+ # value is always int=0D
+ length =3D (bit_length + 7) // 8=0D
+ fmt =3D ''=0D
+ if old_value.startswith('0x'):=0D
+ fmt =3D '0x'=0D
+ elif old_value and (old_value[0] in ['"', "'", '{']):=0D
+ fmt =3D old_value[0]=0D
+ else:=0D
+ fmt =3D ''=0D
+=0D
+ bvalue =3D value_to_bytearray(value, length)=0D
+ if fmt in ['"', "'"]:=0D
+ svalue =3D bvalue.rstrip(b'\x00').decode()=0D
+ value_str =3D fmt + svalue + fmt=0D
+ elif fmt =3D=3D "{":=0D
+ value_str =3D '{ ' + ', '.join(['0x%02x' % i for i in bvalue])=
+ ' }'=0D
+ elif fmt =3D=3D '0x':=0D
+ hex_len =3D length * 2=0D
+ if len(old_value) =3D=3D hex_len + 2:=0D
+ fstr =3D '0x%%0%dx' % hex_len=0D
+ else:=0D
+ fstr =3D '0x%x'=0D
+ value_str =3D fstr % value=0D
+ else:=0D
+ if length <=3D 2:=0D
+ value_str =3D '%d' % value=0D
+ elif length <=3D 8:=0D
+ value_str =3D '0x%x' % value=0D
+ else:=0D
+ value_str =3D '{ ' + ', '.join(['0x%02x' % i for i in=0D
+ bvalue]) + ' }'=0D
+ return value_str=0D
+=0D
+ def reformat_value_str(self, value_str, bit_length, old_value=3DNone):=
=0D
+ value =3D self.parse_value(value_str, bit_length, False)=0D
+ if old_value is None:=0D
+ old_value =3D value_str=0D
+ new_value =3D self.format_value_to_str(value, bit_length, old_valu=
e)=0D
+ return new_value=0D
+=0D
+ def get_value(self, value_str, bit_length, array=3DTrue):=0D
+ value_str =3D value_str.strip()=0D
+ if value_str[0] =3D=3D "'" and value_str[-1] =3D=3D "'" or \=0D
+ value_str[0] =3D=3D '"' and value_str[-1] =3D=3D '"':=0D
+ value_str =3D value_str[1:-1]=0D
+ bvalue =3D bytearray(value_str.encode())=0D
+ if len(bvalue) =3D=3D 0:=0D
+ bvalue =3D bytearray(b'\x00')=0D
+ if array:=0D
+ return bvalue=0D
+ else:=0D
+ return bytes_to_value(bvalue)=0D
+ else:=0D
+ if value_str[0] in '{':=0D
+ value_str =3D value_str[1:-1].strip()=0D
+ value =3D 0=0D
+ for each in value_str.split(',')[::-1]:=0D
+ each =3D each.strip()=0D
+ value =3D (value << 8) | int(each, 0)=0D
+ if array:=0D
+ length =3D (bit_length + 7) // 8=0D
+ return value_to_bytearray(value, length)=0D
+ else:=0D
+ return value=0D
+=0D
+ def parse_value(self, value_str, bit_length, array=3DTrue):=0D
+ length =3D (bit_length + 7) // 8=0D
+ if check_quote(value_str):=0D
+ value_str =3D bytes_to_bracket_str(value_str[1:-1].encode())=0D
+ elif (',' in value_str) and (value_str[0] !=3D '{'):=0D
+ value_str =3D '{ %s }' % value_str=0D
+ if value_str[0] =3D=3D '{':=0D
+ result =3D expand_file_value(self._yaml_path, value_str)=0D
+ if len(result) =3D=3D 0:=0D
+ bin_list =3D value_str[1:-1].split(',')=0D
+ value =3D 0=0D
+ bit_len =3D 0=0D
+ unit_len =3D 1=0D
+ for idx, element in enumerate(bin_list):=0D
+ each =3D element.strip()=0D
+ if len(each) =3D=3D 0:=0D
+ continue=0D
+=0D
+ in_bit_field =3D False=0D
+ if each[0] in "'" + '"':=0D
+ each_value =3D bytearray(each[1:-1], 'utf-8')=0D
+ elif ':' in each:=0D
+ match =3D re.match("^(.+):(\\d+)([b|B|W|D|Q])$", e=
ach)=0D
+ if match is None:=0D
+ raise SystemExit("Exception: Invald value\=0D
+list format '%s' !" % each)=0D
+ if match.group(1) =3D=3D '0' and match.group(2) =
=3D=3D '0':=0D
+ unit_len =3D CGenYamlCfg.bits_width[match.grou=
p(3)=0D
+ ] // 8=0D
+ cur_bit_len =3D int(match.group(2)=0D
+ ) * CGenYamlCfg.bits_width[=0D
+ match.group(3)]=0D
+ value +=3D ((self.eval(match.group(1)) & (=0D
+ 1 << cur_bit_len) - 1)) << bit_len=0D
+ bit_len +=3D cur_bit_len=0D
+ each_value =3D bytearray()=0D
+ if idx + 1 < len(bin_list):=0D
+ in_bit_field =3D True=0D
+ else:=0D
+ try:=0D
+ each_value =3D value_to_bytearray(=0D
+ self.eval(each.strip()), unit_len)=0D
+ except Exception:=0D
+ raise SystemExit("Exception: Value %d cannot \=
=0D
+fit into %s bytes !" % (each, unit_len))=0D
+=0D
+ if not in_bit_field:=0D
+ if bit_len > 0:=0D
+ if bit_len % 8 !=3D 0:=0D
+ raise SystemExit("Exception: Invalid bit \=
=0D
+field alignment '%s' !" % value_str)=0D
+ result.extend(value_to_bytes(value, bit_len //=
8))=0D
+ value =3D 0=0D
+ bit_len =3D 0=0D
+=0D
+ result.extend(each_value)=0D
+=0D
+ elif check_quote(value_str):=0D
+ result =3D bytearray(value_str[1:-1], 'utf-8') # Excluding qu=
otes=0D
+ else:=0D
+ result =3D value_to_bytearray(self.eval(value_str), length)=0D
+=0D
+ if len(result) < length:=0D
+ result.extend(b'\x00' * (length - len(result)))=0D
+ elif len(result) > length:=0D
+ raise SystemExit("Exception: Value '%s' is too big to fit \=0D
+into %d bytes !" % (value_str, length))=0D
+=0D
+ if array:=0D
+ return result=0D
+ else:=0D
+ return bytes_to_value(result)=0D
+=0D
+ return result=0D
+=0D
+ def get_cfg_item_options(self, item):=0D
+ tmp_list =3D []=0D
+ if item['type'] =3D=3D "Combo":=0D
+ if item['option'] in CGenYamlCfg.builtin_option:=0D
+ for op_val, op_str in CGenYamlCfg.builtin_option[item['opt=
ion'=0D
+ ]]:=
=0D
+ tmp_list.append((op_val, op_str))=0D
+ else:=0D
+ opt_list =3D item['option'].split(',')=0D
+ for option in opt_list:=0D
+ option =3D option.strip()=0D
+ try:=0D
+ (op_val, op_str) =3D option.split(':')=0D
+ except Exception:=0D
+ raise SystemExit("Exception: Invalide \=0D
+option format '%s' !" % option)=0D
+ tmp_list.append((op_val, op_str))=0D
+ return tmp_list=0D
+=0D
+ def get_page_title(self, page_id, top=3DNone):=0D
+ if top is None:=0D
+ top =3D self.get_cfg_page()['root']=0D
+ for node in top['child']:=0D
+ page_key =3D next(iter(node))=0D
+ if page_id =3D=3D page_key:=0D
+ return node[page_key]['title']=0D
+ else:=0D
+ result =3D self.get_page_title(page_id, node[page_key])=0D
+ if result is not None:=0D
+ return result=0D
+ return None=0D
+=0D
+ def print_pages(self, top=3DNone, level=3D0):=0D
+ if top is None:=0D
+ top =3D self.get_cfg_page()['root']=0D
+ for node in top['child']:=0D
+ page_id =3D next(iter(node))=0D
+ print('%s%s: %s' % (' ' * level, page_id, node[page_id]['titl=
e']))=0D
+ level +=3D 1=0D
+ self.print_pages(node[page_id], level)=0D
+ level -=3D 1=0D
+=0D
+ def get_item_by_index(self, index):=0D
+ return self._cfg_list[index]=0D
+=0D
+ def get_item_by_path(self, path):=0D
+ node =3D self.locate_cfg_item(path)=0D
+ if node:=0D
+ return self.get_item_by_index(node['indx'])=0D
+ else:=0D
+ return None=0D
+=0D
+ def locate_cfg_path(self, item):=0D
+ def _locate_cfg_path(root, level=3D0):=0D
+ # config structure=0D
+ if item is root:=0D
+ return path=0D
+ for key in root:=0D
+ if type(root[key]) is OrderedDict:=0D
+ level +=3D 1=0D
+ path.append(key)=0D
+ ret =3D _locate_cfg_path(root[key], level)=0D
+ if ret:=0D
+ return ret=0D
+ path.pop()=0D
+ return None=0D
+ path =3D []=0D
+ return _locate_cfg_path(self._cfg_tree)=0D
+=0D
+ def locate_cfg_item(self, path, allow_exp=3DTrue):=0D
+ def _locate_cfg_item(root, path, level=3D0):=0D
+ if len(path) =3D=3D level:=0D
+ return root=0D
+ next_root =3D root.get(path[level], None)=0D
+ if next_root is None:=0D
+ if allow_exp:=0D
+ raise Exception('Not a valid CFG config option path: %=
s' %=0D
+ '.'.join(path[:level+1]))=0D
+ else:=0D
+ return None=0D
+ return _locate_cfg_item(next_root, path, level + 1)=0D
+=0D
+ path_nodes =3D path.split('.')=0D
+ return _locate_cfg_item(self._cfg_tree, path_nodes)=0D
+=0D
+ def traverse_cfg_tree(self, handler, top=3DNone):=0D
+ def _traverse_cfg_tree(root, level=3D0):=0D
+ # config structure=0D
+ for key in root:=0D
+ if type(root[key]) is OrderedDict:=0D
+ level +=3D 1=0D
+ handler(key, root[key], level)=0D
+ _traverse_cfg_tree(root[key], level)=0D
+ level -=3D 1=0D
+=0D
+ if top is None:=0D
+ top =3D self._cfg_tree=0D
+ _traverse_cfg_tree(top)=0D
+=0D
+ def print_cfgs(self, root=3DNone, short=3DTrue, print_level=3D256):=0D
+ def _print_cfgs(name, cfgs, level):=0D
+=0D
+ if 'indx' in cfgs:=0D
+ act_cfg =3D self.get_item_by_index(cfgs['indx'])=0D
+ else:=0D
+ offset =3D 0=0D
+ length =3D 0=0D
+ value =3D ''=0D
+ if CGenYamlCfg.STRUCT in cfgs:=0D
+ cfg =3D cfgs[CGenYamlCfg.STRUCT]=0D
+ offset =3D int(cfg['offset'])=0D
+ length =3D int(cfg['length'])=0D
+ if 'value' in cfg:=0D
+ value =3D cfg['value']=0D
+ if length =3D=3D 0:=0D
+ return=0D
+ act_cfg =3D dict({'value': value, 'offset': offset,=0D
+ 'length': length})=0D
+ value =3D act_cfg['value']=0D
+ bit_len =3D act_cfg['length']=0D
+ offset =3D (act_cfg['offset'] + 7) // 8=0D
+ if value !=3D '':=0D
+ try:=0D
+ value =3D self.reformat_value_str(act_cfg['value'],=0D
+ act_cfg['length'])=0D
+ except Exception:=0D
+ value =3D act_cfg['value']=0D
+ length =3D bit_len // 8=0D
+ bit_len =3D '(%db)' % bit_len if bit_len % 8 else '' * 4=0D
+ if level <=3D print_level:=0D
+ if short and len(value) > 40:=0D
+ value =3D '%s ... %s' % (value[:20], value[-20:])=0D
+ print('%04X:%04X%-6s %s%s : %s' % (offset, length, bit_len=
,=0D
+ ' ' * level, name, val=
ue))=0D
+=0D
+ self.traverse_cfg_tree(_print_cfgs)=0D
+=0D
+ def build_var_dict(self):=0D
+ def _build_var_dict(name, cfgs, level):=0D
+ if level <=3D 2:=0D
+ if CGenYamlCfg.STRUCT in cfgs:=0D
+ struct_info =3D cfgs[CGenYamlCfg.STRUCT]=0D
+ self._var_dict['_LENGTH_%s_' % name] =3D struct_info[=
=0D
+ 'length'] // 8=0D
+ self._var_dict['_OFFSET_%s_' % name] =3D struct_info[=
=0D
+ 'offset'] // 8=0D
+=0D
+ self._var_dict =3D {}=0D
+ self.traverse_cfg_tree(_build_var_dict)=0D
+ self._var_dict['_LENGTH_'] =3D self._cfg_tree[CGenYamlCfg.STRUCT][=
=0D
+ 'length'] // 8=0D
+ return 0=0D
+=0D
+ def add_cfg_page(self, child, parent, title=3D''):=0D
+ def _add_cfg_page(cfg_page, child, parent):=0D
+ key =3D next(iter(cfg_page))=0D
+ if parent =3D=3D key:=0D
+ cfg_page[key]['child'].append({child: {'title': title,=0D
+ 'child': []}})=0D
+ return True=0D
+ else:=0D
+ result =3D False=0D
+ for each in cfg_page[key]['child']:=0D
+ if _add_cfg_page(each, child, parent):=0D
+ result =3D True=0D
+ break=0D
+ return result=0D
+=0D
+ return _add_cfg_page(self._cfg_page, child, parent)=0D
+=0D
+ def set_cur_page(self, page_str):=0D
+ if not page_str:=0D
+ return=0D
+=0D
+ if ',' in page_str:=0D
+ page_list =3D page_str.split(',')=0D
+ else:=0D
+ page_list =3D [page_str]=0D
+ for page_str in page_list:=0D
+ parts =3D page_str.split(':')=0D
+ if len(parts) in [1, 3]:=0D
+ page =3D parts[0].strip()=0D
+ if len(parts) =3D=3D 3:=0D
+ # it is a new page definition, add it into tree=0D
+ parent =3D parts[1] if parts[1] else 'root'=0D
+ parent =3D parent.strip()=0D
+ if parts[2][0] =3D=3D '"' and parts[2][-1] =3D=3D '"':=
=0D
+ parts[2] =3D parts[2][1:-1]=0D
+=0D
+ if not self.add_cfg_page(page, parent, parts[2]):=0D
+ raise SystemExit("Error: Cannot find parent page \=
=0D
+'%s'!" % parent)=0D
+ else:=0D
+ raise SystemExit("Error: Invalid page format '%s' !"=0D
+ % page_str)=0D
+ self._cur_page =3D page=0D
+=0D
+ def extend_variable(self, line):=0D
+ # replace all variables=0D
+ if line =3D=3D '':=0D
+ return line=0D
+ loop =3D 2=0D
+ while loop > 0:=0D
+ line_after =3D DefTemplate(line).safe_substitute(self._def_dic=
t)=0D
+ if line =3D=3D line_after:=0D
+ break=0D
+ loop -=3D 1=0D
+ line =3D line_after=0D
+ return line_after=0D
+=0D
+ def reformat_number_per_type(self, itype, value):=0D
+ if check_quote(value) or value.startswith('{'):=0D
+ return value=0D
+ parts =3D itype.split(',')=0D
+ if len(parts) > 3 and parts[0] =3D=3D 'EditNum':=0D
+ num_fmt =3D parts[1].strip()=0D
+ else:=0D
+ num_fmt =3D ''=0D
+ if num_fmt =3D=3D 'HEX' and not value.startswith('0x'):=0D
+ value =3D '0x%X' % int(value, 10)=0D
+ elif num_fmt =3D=3D 'DEC' and value.startswith('0x'):=0D
+ value =3D '%d' % int(value, 16)=0D
+ return value=0D
+=0D
+ def add_cfg_item(self, name, item, offset, path):=0D
+=0D
+ self.set_cur_page(item.get('page', ''))=0D
+=0D
+ if name[0] =3D=3D '$':=0D
+ # skip all virtual node=0D
+ return 0=0D
+=0D
+ if not set(item).issubset(CGenYamlCfg.keyword_set):=0D
+ for each in list(item):=0D
+ if each not in CGenYamlCfg.keyword_set:=0D
+ raise Exception("Invalid attribute '%s' for '%s'!" %=0D
+ (each, '.'.join(path)))=0D
+=0D
+ length =3D item.get('length', 0)=0D
+ if type(length) is str:=0D
+ match =3D re.match("^(\\d+)([b|B|W|D|Q])([B|W|D|Q]?)\\s*$", le=
ngth)=0D
+ if match:=0D
+ unit_len =3D CGenYamlCfg.bits_width[match.group(2)]=0D
+ length =3D int(match.group(1), 10) * unit_len=0D
+ else:=0D
+ try:=0D
+ length =3D int(length, 0) * 8=0D
+ except Exception:=0D
+ raise Exception("Invalid length field '%s' for '%s' !"=
%=0D
+ (length, '.'.join(path)))=0D
+=0D
+ if offset % 8 > 0:=0D
+ raise Exception("Invalid alignment for field '%s' for =
\=0D
+'%s' !" % (name, '.'.join(path)))=0D
+ else:=0D
+ # define is length in bytes=0D
+ length =3D length * 8=0D
+=0D
+ if not name.isidentifier():=0D
+ raise Exception("Invalid config name '%s' for '%s' !" %=0D
+ (name, '.'.join(path)))=0D
+=0D
+ itype =3D str(item.get('type', 'Reserved'))=0D
+ value =3D str(item.get('value', ''))=0D
+ if value:=0D
+ if not (check_quote(value) or value.startswith('{')):=0D
+ if ',' in value:=0D
+ value =3D '{ %s }' % value=0D
+ else:=0D
+ value =3D self.reformat_number_per_type(itype, value)=
=0D
+=0D
+ help =3D str(item.get('help', ''))=0D
+ if '\n' in help:=0D
+ help =3D ' '.join([i.strip() for i in help.splitlines()])=0D
+=0D
+ option =3D str(item.get('option', ''))=0D
+ if '\n' in option:=0D
+ option =3D ' '.join([i.strip() for i in option.splitlines()])=
=0D
+=0D
+ # extend variables for value and condition=0D
+ condition =3D str(item.get('condition', ''))=0D
+ if condition:=0D
+ condition =3D self.extend_variable(condition)=0D
+ value =3D self.extend_variable(value)=0D
+=0D
+ order =3D str(item.get('order', ''))=0D
+ if order:=0D
+ if '.' in order:=0D
+ (major, minor) =3D order.split('.')=0D
+ order =3D int(major, 16)=0D
+ else:=0D
+ order =3D int(order, 16)=0D
+ else:=0D
+ order =3D offset=0D
+=0D
+ cfg_item =3D dict()=0D
+ cfg_item['length'] =3D length=0D
+ cfg_item['offset'] =3D offset=0D
+ cfg_item['value'] =3D value=0D
+ cfg_item['type'] =3D itype=0D
+ cfg_item['cname'] =3D str(name)=0D
+ cfg_item['name'] =3D str(item.get('name', ''))=0D
+ cfg_item['help'] =3D help=0D
+ cfg_item['option'] =3D option=0D
+ cfg_item['page'] =3D self._cur_page=0D
+ cfg_item['order'] =3D order=0D
+ cfg_item['path'] =3D '.'.join(path)=0D
+ cfg_item['condition'] =3D condition=0D
+ if 'struct' in item:=0D
+ cfg_item['struct'] =3D item['struct']=0D
+ self._cfg_list.append(cfg_item)=0D
+=0D
+ item['indx'] =3D len(self._cfg_list) - 1=0D
+=0D
+ # remove used info for reducing pkl size=0D
+ item.pop('option', None)=0D
+ item.pop('condition', None)=0D
+ item.pop('help', None)=0D
+ item.pop('name', None)=0D
+ item.pop('page', None)=0D
+=0D
+ return length=0D
+=0D
+ def build_cfg_list(self, cfg_name=3D'', top=3DNone, path=3D[],=0D
+ info=3D{'offset': 0}):=0D
+ if top is None:=0D
+ top =3D self._cfg_tree=0D
+ info.clear()=0D
+ info =3D {'offset': 0}=0D
+=0D
+ start =3D info['offset']=0D
+ is_leaf =3D True=0D
+ for key in top:=0D
+ path.append(key)=0D
+ if type(top[key]) is OrderedDict:=0D
+ is_leaf =3D False=0D
+ self.build_cfg_list(key, top[key], path, info)=0D
+ path.pop()=0D
+=0D
+ if is_leaf:=0D
+ length =3D self.add_cfg_item(cfg_name, top, info['offset'], pa=
th)=0D
+ info['offset'] +=3D length=0D
+ elif cfg_name =3D=3D '' or (cfg_name and cfg_name[0] !=3D '$'):=0D
+ # check first element for struct=0D
+ first =3D next(iter(top))=0D
+ struct_str =3D CGenYamlCfg.STRUCT=0D
+ if first !=3D struct_str:=0D
+ struct_node =3D OrderedDict({})=0D
+ top[struct_str] =3D struct_node=0D
+ top.move_to_end(struct_str, False)=0D
+ else:=0D
+ struct_node =3D top[struct_str]=0D
+ struct_node['offset'] =3D start=0D
+ struct_node['length'] =3D info['offset'] - start=0D
+ if struct_node['length'] % 8 !=3D 0:=0D
+ raise SystemExit("Error: Bits length not aligned for %s !"=
%=0D
+ str(path))=0D
+=0D
+ def get_field_value(self, top=3DNone):=0D
+ def _get_field_value(name, cfgs, level):=0D
+ if 'indx' in cfgs:=0D
+ act_cfg =3D self.get_item_by_index(cfgs['indx'])=0D
+ if act_cfg['length'] =3D=3D 0:=0D
+ return=0D
+ value =3D self.get_value(act_cfg['value'], act_cfg['length=
'],=0D
+ False)=0D
+ set_bits_to_bytes(result, act_cfg['offset'] -=0D
+ struct_info['offset'], act_cfg['length']=
,=0D
+ value)=0D
+=0D
+ if top is None:=0D
+ top =3D self._cfg_tree=0D
+ struct_info =3D top[CGenYamlCfg.STRUCT]=0D
+ result =3D bytearray((struct_info['length'] + 7) // 8)=0D
+ self.traverse_cfg_tree(_get_field_value, top)=0D
+ return result=0D
+=0D
+ def set_field_value(self, top, value_bytes, force=3DFalse):=0D
+ def _set_field_value(name, cfgs, level):=0D
+ if 'indx' not in cfgs:=0D
+ return=0D
+ act_cfg =3D self.get_item_by_index(cfgs['indx'])=0D
+ if force or act_cfg['value'] =3D=3D '':=0D
+ value =3D get_bits_from_bytes(full_bytes,=0D
+ act_cfg['offset'] -=0D
+ struct_info['offset'],=0D
+ act_cfg['length'])=0D
+ act_val =3D act_cfg['value']=0D
+ if act_val =3D=3D '':=0D
+ act_val =3D '%d' % value=0D
+ act_val =3D self.reformat_number_per_type(act_cfg=0D
+ ['type'],=0D
+ act_val)=0D
+ act_cfg['value'] =3D self.format_value_to_str(=0D
+ value, act_cfg['length'], act_val)=0D
+=0D
+ if 'indx' in top:=0D
+ # it is config option=0D
+ value =3D bytes_to_value(value_bytes)=0D
+ act_cfg =3D self.get_item_by_index(top['indx'])=0D
+ act_cfg['value'] =3D self.format_value_to_str(=0D
+ value, act_cfg['length'], act_cfg['value'])=0D
+ else:=0D
+ # it is structure=0D
+ struct_info =3D top[CGenYamlCfg.STRUCT]=0D
+ length =3D struct_info['length'] // 8=0D
+ full_bytes =3D bytearray(value_bytes[:length])=0D
+ if len(full_bytes) < length:=0D
+ full_bytes.extend(bytearray(length - len(value_bytes)))=0D
+ self.traverse_cfg_tree(_set_field_value, top)=0D
+=0D
+ def update_def_value(self):=0D
+ def _update_def_value(name, cfgs, level):=0D
+ if 'indx' in cfgs:=0D
+ act_cfg =3D self.get_item_by_index(cfgs['indx'])=0D
+ if act_cfg['value'] !=3D '' and act_cfg['length'] > 0:=0D
+ try:=0D
+ act_cfg['value'] =3D self.reformat_value_str(=0D
+ act_cfg['value'], act_cfg['length'])=0D
+ except Exception:=0D
+ raise Exception("Invalid value expression '%s' \=0D
+for '%s' !" % (act_cfg['value'], act_cfg['path']))=0D
+ else:=0D
+ if CGenYamlCfg.STRUCT in cfgs and 'value' in \=0D
+ cfgs[CGenYamlCfg.STRUCT]:=0D
+ curr =3D cfgs[CGenYamlCfg.STRUCT]=0D
+ value_bytes =3D value_to_bytearray(self.eval(curr['val=
ue']),=0D
+ (curr['length'] + 7) =
// 8)=0D
+ self.set_field_value(cfgs, value_bytes)=0D
+=0D
+ self.traverse_cfg_tree(_update_def_value, self._cfg_tree)=0D
+=0D
+ def evaluate_condition(self, item):=0D
+ expr =3D item['condition']=0D
+ result =3D self.parse_value(expr, 1, False)=0D
+ return result=0D
+=0D
+ def detect_fsp(self):=0D
+ cfg_segs =3D self.get_cfg_segment()=0D
+ if len(cfg_segs) =3D=3D 3:=0D
+ fsp =3D True=0D
+ for idx, seg in enumerate(cfg_segs):=0D
+ if not seg[0].endswith('UPD_%s' % 'TMS'[idx]):=0D
+ fsp =3D False=0D
+ break=0D
+ else:=0D
+ fsp =3D False=0D
+ if fsp:=0D
+ self.set_mode('FSP')=0D
+ return fsp=0D
+=0D
+ def get_cfg_segment(self):=0D
+ def _get_cfg_segment(name, cfgs, level):=0D
+ if 'indx' not in cfgs:=0D
+ if name.startswith('$ACTION_'):=0D
+ if 'find' in cfgs:=0D
+ find[0] =3D cfgs['find']=0D
+ else:=0D
+ if find[0]:=0D
+ act_cfg =3D self.get_item_by_index(cfgs['indx'])=0D
+ segments.append([find[0], act_cfg['offset'] // 8, 0])=
=0D
+ find[0] =3D ''=0D
+ return=0D
+=0D
+ find =3D ['']=0D
+ segments =3D []=0D
+ self.traverse_cfg_tree(_get_cfg_segment, self._cfg_tree)=0D
+ cfg_len =3D self._cfg_tree[CGenYamlCfg.STRUCT]['length'] // 8=0D
+ if len(segments) =3D=3D 0:=0D
+ segments.append(['', 0, cfg_len])=0D
+=0D
+ segments.append(['', cfg_len, 0])=0D
+ cfg_segs =3D []=0D
+ for idx, each in enumerate(segments[:-1]):=0D
+ cfg_segs.append((each[0], each[1],=0D
+ segments[idx+1][1] - each[1]))=0D
+=0D
+ return cfg_segs=0D
+=0D
+ def get_bin_segment(self, bin_data):=0D
+ cfg_segs =3D self.get_cfg_segment()=0D
+ bin_segs =3D []=0D
+ for seg in cfg_segs:=0D
+ key =3D seg[0].encode()=0D
+ if key =3D=3D 0:=0D
+ bin_segs.append([seg[0], 0, len(bin_data)])=0D
+ break=0D
+ pos =3D bin_data.find(key)=0D
+ if pos >=3D 0:=0D
+ # ensure no other match for the key=0D
+ next_pos =3D bin_data.find(key, pos + len(seg[0]))=0D
+ if next_pos >=3D 0:=0D
+ # workaround to use 2nd instance for incompatible=0D
+ # FSP 1.X binary=0D
+ if key =3D=3D b'$SKLFSP$' or key =3D=3D b'$BSWFSP$':=0D
+ string =3D ('Warning: Multiple matches for %s in '=
=0D
+ 'binary!\n\nA workaround applied to such=
'=0D
+ 'FSP 1.x binary to use second'=0D
+ ' match instead of first match!' % key)=
=0D
+ messagebox.showwarning('Warning!', string)=0D
+ pos =3D next_pos=0D
+ else:=0D
+ print("Warning: Multiple matches for '%s' "=0D
+ "in binary, the 1st instance will be used !"=
=0D
+ % seg[0])=0D
+ bin_segs.append([seg[0], pos, seg[2]])=0D
+ else:=0D
+ raise Exception("Could not find '%s' in binary !"=0D
+ % seg[0])=0D
+=0D
+ return bin_segs=0D
+=0D
+ def extract_cfg_from_bin(self, bin_data):=0D
+ # get cfg bin length=0D
+ cfg_bins =3D bytearray()=0D
+ bin_segs =3D self.get_bin_segment(bin_data)=0D
+ for each in bin_segs:=0D
+ cfg_bins.extend(bin_data[each[1]:each[1] + each[2]])=0D
+ return cfg_bins=0D
+=0D
+ def save_current_to_bin(self):=0D
+ cfg_bins =3D self.generate_binary_array()=0D
+ if self._old_bin is None:=0D
+ return cfg_bins=0D
+=0D
+ bin_data =3D bytearray(self._old_bin)=0D
+ bin_segs =3D self.get_bin_segment(self._old_bin)=0D
+ cfg_off =3D 0=0D
+ for each in bin_segs:=0D
+ length =3D each[2]=0D
+ bin_data[each[1]:each[1] + length] =3D cfg_bins[cfg_off:=0D
+ cfg_off=0D
+ + length]=0D
+ cfg_off +=3D length=0D
+ print('Patched the loaded binary successfully !')=0D
+=0D
+ return bin_data=0D
+=0D
+ def load_default_from_bin(self, bin_data):=0D
+ self._old_bin =3D bin_data=0D
+ cfg_bins =3D self.extract_cfg_from_bin(bin_data)=0D
+ self.set_field_value(self._cfg_tree, cfg_bins, True)=0D
+ return cfg_bins=0D
+=0D
+ def generate_binary_array(self, path=3D''):=0D
+ if path =3D=3D '':=0D
+ top =3D None=0D
+ else:=0D
+ top =3D self.locate_cfg_item(path)=0D
+ if not top:=0D
+ raise Exception("Invalid configuration path '%s' !"=0D
+ % path)=0D
+ return self.get_field_value(top)=0D
+=0D
+ def generate_binary(self, bin_file_name, path=3D''):=0D
+ bin_file =3D open(bin_file_name, "wb")=0D
+ bin_file.write(self.generate_binary_array(path))=0D
+ bin_file.close()=0D
+ return 0=0D
+=0D
+ def write_delta_file(self, out_file, platform_id, out_lines):=0D
+ dlt_fd =3D open(out_file, "w")=0D
+ dlt_fd.write("%s\n" % get_copyright_header('dlt', True))=0D
+ if platform_id is not None:=0D
+ dlt_fd.write('#\n')=0D
+ dlt_fd.write('# Delta configuration values for '=0D
+ 'platform ID 0x%04X\n'=0D
+ % platform_id)=0D
+ dlt_fd.write('#\n\n')=0D
+ for line in out_lines:=0D
+ dlt_fd.write('%s\n' % line)=0D
+ dlt_fd.close()=0D
+=0D
+ def override_default_value(self, dlt_file):=0D
+ error =3D 0=0D
+ dlt_lines =3D CGenYamlCfg.expand_include_files(dlt_file)=0D
+=0D
+ platform_id =3D None=0D
+ for line, file_path, line_num in dlt_lines:=0D
+ line =3D line.strip()=0D
+ if not line or line.startswith('#'):=0D
+ continue=0D
+ match =3D re.match("\\s*([\\w\\.]+)\\s*\\|\\s*(.+)", line)=0D
+ if not match:=0D
+ raise Exception("Unrecognized line '%s' "=0D
+ "(File:'%s' Line:%d) !"=0D
+ % (line, file_path, line_num + 1))=0D
+=0D
+ path =3D match.group(1)=0D
+ value_str =3D match.group(2)=0D
+ top =3D self.locate_cfg_item(path)=0D
+ if not top:=0D
+ raise Exception(=0D
+ "Invalid configuration '%s' (File:'%s' Line:%d) !" %=0D
+ (path, file_path, line_num + 1))=0D
+=0D
+ if 'indx' in top:=0D
+ act_cfg =3D self.get_item_by_index(top['indx'])=0D
+ bit_len =3D act_cfg['length']=0D
+ else:=0D
+ struct_info =3D top[CGenYamlCfg.STRUCT]=0D
+ bit_len =3D struct_info['length']=0D
+=0D
+ value_bytes =3D self.parse_value(value_str, bit_len)=0D
+ self.set_field_value(top, value_bytes, True)=0D
+=0D
+ if path =3D=3D 'PLATFORMID_CFG_DATA.PlatformId':=0D
+ platform_id =3D value_str=0D
+=0D
+ if platform_id is None:=0D
+ raise Exception(=0D
+ "PLATFORMID_CFG_DATA.PlatformId is missing "=0D
+ "in file '%s' !" %=0D
+ (dlt_file))=0D
+=0D
+ return error=0D
+=0D
+ def generate_delta_file_from_bin(self, delta_file, old_data,=0D
+ new_data, full=3DFalse):=0D
+ new_data =3D self.load_default_from_bin(new_data)=0D
+ lines =3D []=0D
+ platform_id =3D None=0D
+ def_platform_id =3D 0=0D
+=0D
+ for item in self._cfg_list:=0D
+ if not full and (item['type'] in ['Reserved']):=0D
+ continue=0D
+ old_val =3D get_bits_from_bytes(old_data, item['offset'],=0D
+ item['length'])=0D
+ new_val =3D get_bits_from_bytes(new_data, item['offset'],=0D
+ item['length'])=0D
+=0D
+ full_name =3D item['path']=0D
+ if 'PLATFORMID_CFG_DATA.PlatformId' =3D=3D full_name:=0D
+ def_platform_id =3D old_val=0D
+ if new_val !=3D old_val or full:=0D
+ val_str =3D self.reformat_value_str(item['value'],=0D
+ item['length'])=0D
+ text =3D '%-40s | %s' % (full_name, val_str)=0D
+ lines.append(text)=0D
+=0D
+ if self.get_mode() !=3D 'FSP':=0D
+ if platform_id is None or def_platform_id =3D=3D platform_id:=
=0D
+ platform_id =3D def_platform_id=0D
+ print("WARNING: 'PlatformId' configuration is "=0D
+ "same as default %d!" % platform_id)=0D
+=0D
+ lines.insert(0, '%-40s | %s\n\n' %=0D
+ ('PLATFORMID_CFG_DATA.PlatformId',=0D
+ '0x%04X' % platform_id))=0D
+ else:=0D
+ platform_id =3D None=0D
+=0D
+ self.write_delta_file(delta_file, platform_id, lines)=0D
+=0D
+ return 0=0D
+=0D
+ def generate_delta_file(self, delta_file, bin_file, bin_file2, full=3D=
False):=0D
+ fd =3D open(bin_file, 'rb')=0D
+ new_data =3D self.extract_cfg_from_bin(bytearray(fd.read()))=0D
+ fd.close()=0D
+=0D
+ if bin_file2 =3D=3D '':=0D
+ old_data =3D self.generate_binary_array()=0D
+ else:=0D
+ old_data =3D new_data=0D
+ fd =3D open(bin_file2, 'rb')=0D
+ new_data =3D self.extract_cfg_from_bin(bytearray(fd.read()))=0D
+ fd.close()=0D
+=0D
+ return self.generate_delta_file_from_bin(delta_file,=0D
+ old_data, new_data, full)=
=0D
+=0D
+ def prepare_marshal(self, is_save):=0D
+ if is_save:=0D
+ # Ordered dict is not marshallable, convert to list=0D
+ self._cfg_tree =3D CGenYamlCfg.deep_convert_dict(self._cfg_tre=
e)=0D
+ else:=0D
+ # Revert it back=0D
+ self._cfg_tree =3D CGenYamlCfg.deep_convert_list(self._cfg_tre=
e)=0D
+=0D
+ def generate_yml_file(self, in_file, out_file):=0D
+ cfg_yaml =3D CFG_YAML()=0D
+ text =3D cfg_yaml.expand_yaml(in_file)=0D
+ yml_fd =3D open(out_file, "w")=0D
+ yml_fd.write(text)=0D
+ yml_fd.close()=0D
+ return 0=0D
+=0D
+ def write_cfg_header_file(self, hdr_file_name, tag_mode,=0D
+ tag_dict, struct_list):=0D
+ lines =3D []=0D
+ lines.append('\n\n')=0D
+ if self.get_mode() =3D=3D 'FSP':=0D
+ lines.append('#include <FspUpd.h>\n')=0D
+=0D
+ tag_mode =3D tag_mode & 0x7F=0D
+ tag_list =3D sorted(list(tag_dict.items()), key=3Dlambda x: x[1])=
=0D
+ for tagname, tagval in tag_list:=0D
+ if (tag_mode =3D=3D 0 and tagval >=3D 0x100) or \=0D
+ (tag_mode =3D=3D 1 and tagval < 0x100):=0D
+ continue=0D
+ lines.append('#define %-30s 0x%03X\n' % (=0D
+ 'CDATA_%s_TAG' % tagname[:-9], tagval))=0D
+ lines.append('\n\n')=0D
+=0D
+ name_dict =3D {}=0D
+ new_dict =3D {}=0D
+ for each in struct_list:=0D
+ if (tag_mode =3D=3D 0 and each['tag'] >=3D 0x100) or \=0D
+ (tag_mode =3D=3D 1 and each['tag'] < 0x100):=0D
+ continue=0D
+ new_dict[each['name']] =3D (each['alias'], each['count'])=0D
+ if each['alias'] not in name_dict:=0D
+ name_dict[each['alias']] =3D 1=0D
+ lines.extend(self.create_struct(each['alias'],=0D
+ each['node'], new_dict))=0D
+ lines.append('#pragma pack()\n\n')=0D
+=0D
+ self.write_header_file(lines, hdr_file_name)=0D
+=0D
+ def write_header_file(self, txt_body, file_name, type=3D'h'):=0D
+ file_name_def =3D os.path.basename(file_name).replace('.', '_')=0D
+ file_name_def =3D re.sub('(.)([A-Z][a-z]+)', r'\1_\2', file_name_d=
ef)=0D
+ file_name_def =3D re.sub('([a-z0-9])([A-Z])', r'\1_\2',=0D
+ file_name_def).upper()=0D
+=0D
+ lines =3D []=0D
+ lines.append("%s\n" % get_copyright_header(type))=0D
+ lines.append("#ifndef __%s__\n" % file_name_def)=0D
+ lines.append("#define __%s__\n\n" % file_name_def)=0D
+ if type =3D=3D 'h':=0D
+ lines.append("#pragma pack(1)\n\n")=0D
+ lines.extend(txt_body)=0D
+ if type =3D=3D 'h':=0D
+ lines.append("#pragma pack()\n\n")=0D
+ lines.append("#endif\n")=0D
+=0D
+ # Don't rewrite if the contents are the same=0D
+ create =3D True=0D
+ if os.path.exists(file_name):=0D
+ hdr_file =3D open(file_name, "r")=0D
+ org_txt =3D hdr_file.read()=0D
+ hdr_file.close()=0D
+=0D
+ new_txt =3D ''.join(lines)=0D
+ if org_txt =3D=3D new_txt:=0D
+ create =3D False=0D
+=0D
+ if create:=0D
+ hdr_file =3D open(file_name, "w")=0D
+ hdr_file.write(''.join(lines))=0D
+ hdr_file.close()=0D
+=0D
+ def generate_data_inc_file(self, dat_inc_file_name, bin_file=3DNone):=
=0D
+ # Put a prefix GUID before CFGDATA so that it can be located later=
on=0D
+ prefix =3D b'\xa7\xbd\x7f\x73\x20\x1e\x46\xd6\=0D
+xbe\x8f\x64\x12\x05\x8d\x0a\xa8'=0D
+ if bin_file:=0D
+ fin =3D open(bin_file, 'rb')=0D
+ bin_dat =3D prefix + bytearray(fin.read())=0D
+ fin.close()=0D
+ else:=0D
+ bin_dat =3D prefix + self.generate_binary_array()=0D
+=0D
+ file_name =3D os.path.basename(dat_inc_file_name).upper()=0D
+ file_name =3D file_name.replace('.', '_')=0D
+=0D
+ txt_lines =3D []=0D
+=0D
+ txt_lines.append("UINT8 mConfigDataBlob[%d] =3D {\n" % len(bin_da=
t))=0D
+ count =3D 0=0D
+ line =3D [' ']=0D
+ for each in bin_dat:=0D
+ line.append('0x%02X, ' % each)=0D
+ count =3D count + 1=0D
+ if (count & 0x0F) =3D=3D 0:=0D
+ line.append('\n')=0D
+ txt_lines.append(''.join(line))=0D
+ line =3D [' ']=0D
+ if len(line) > 1:=0D
+ txt_lines.append(''.join(line) + '\n')=0D
+=0D
+ txt_lines.append("};\n\n")=0D
+ self.write_header_file(txt_lines, dat_inc_file_name, 'inc')=0D
+=0D
+ return 0=0D
+=0D
+ def get_struct_array_info(self, input):=0D
+ parts =3D input.split(':')=0D
+ if len(parts) > 1:=0D
+ var =3D parts[1]=0D
+ input =3D parts[0]=0D
+ else:=0D
+ var =3D ''=0D
+ array_str =3D input.split('[')=0D
+ name =3D array_str[0]=0D
+ if len(array_str) > 1:=0D
+ num_str =3D ''.join(c for c in array_str[-1] if c.isdigit())=0D
+ num_str =3D '1000' if len(num_str) =3D=3D 0 else num_str=0D
+ array_num =3D int(num_str)=0D
+ else:=0D
+ array_num =3D 0=0D
+ return name, array_num, var=0D
+=0D
+ def process_multilines(self, string, max_char_length):=0D
+ multilines =3D ''=0D
+ string_length =3D len(string)=0D
+ current_string_start =3D 0=0D
+ string_offset =3D 0=0D
+ break_line_dict =3D []=0D
+ if len(string) <=3D max_char_length:=0D
+ while (string_offset < string_length):=0D
+ if string_offset >=3D 1:=0D
+ if string[string_offset - 1] =3D=3D '\\' and string[=0D
+ string_offset] =3D=3D 'n':=0D
+ break_line_dict.append(string_offset + 1)=0D
+ string_offset +=3D 1=0D
+ if break_line_dict !=3D []:=0D
+ for each in break_line_dict:=0D
+ multilines +=3D " %s\n" % string[=0D
+ current_string_start:each].lstrip()=0D
+ current_string_start =3D each=0D
+ if string_length - current_string_start > 0:=0D
+ multilines +=3D " %s\n" % string[=0D
+ current_string_start:].lstrip()=0D
+ else:=0D
+ multilines =3D " %s\n" % string=0D
+ else:=0D
+ new_line_start =3D 0=0D
+ new_line_count =3D 0=0D
+ found_space_char =3D False=0D
+ while (string_offset < string_length):=0D
+ if string_offset >=3D 1:=0D
+ if new_line_count >=3D max_char_length - 1:=0D
+ if string[string_offset] =3D=3D ' ' and \=0D
+ string_length - string_offset > 10:=0D
+ break_line_dict.append(new_line_start=0D
+ + new_line_count)=0D
+ new_line_start =3D new_line_start + new_line_c=
ount=0D
+ new_line_count =3D 0=0D
+ found_space_char =3D True=0D
+ elif string_offset =3D=3D string_length - 1 and \=
=0D
+ found_space_char is False:=0D
+ break_line_dict.append(0)=0D
+ if string[string_offset - 1] =3D=3D '\\' and string[=0D
+ string_offset] =3D=3D 'n':=0D
+ break_line_dict.append(string_offset + 1)=0D
+ new_line_start =3D string_offset + 1=0D
+ new_line_count =3D 0=0D
+ string_offset +=3D 1=0D
+ new_line_count +=3D 1=0D
+ if break_line_dict !=3D []:=0D
+ break_line_dict.sort()=0D
+ for each in break_line_dict:=0D
+ if each > 0:=0D
+ multilines +=3D " %s\n" % string[=0D
+ current_string_start:each].lstrip()=0D
+ current_string_start =3D each=0D
+ if string_length - current_string_start > 0:=0D
+ multilines +=3D " %s\n" % \=0D
+ string[current_string_start:].lstrip()=0D
+ return multilines=0D
+=0D
+ def create_field(self, item, name, length, offset, struct,=0D
+ bsf_name, help, option, bits_length=3DNone):=0D
+ pos_name =3D 28=0D
+ name_line =3D ''=0D
+ # help_line =3D ''=0D
+ # option_line =3D ''=0D
+=0D
+ if length =3D=3D 0 and name =3D=3D 'dummy':=0D
+ return '\n'=0D
+=0D
+ if bits_length =3D=3D 0:=0D
+ return '\n'=0D
+=0D
+ is_array =3D False=0D
+ if length in [1, 2, 4, 8]:=0D
+ type =3D "UINT%d" % (length * 8)=0D
+ else:=0D
+ is_array =3D True=0D
+ type =3D "UINT8"=0D
+=0D
+ if item and item['value'].startswith('{'):=0D
+ type =3D "UINT8"=0D
+ is_array =3D True=0D
+=0D
+ if struct !=3D '':=0D
+ struct_base =3D struct.rstrip('*')=0D
+ name =3D '*' * (len(struct) - len(struct_base)) + name=0D
+ struct =3D struct_base=0D
+ type =3D struct=0D
+ if struct in ['UINT8', 'UINT16', 'UINT32', 'UINT64']:=0D
+ is_array =3D True=0D
+ unit =3D int(type[4:]) // 8=0D
+ length =3D length / unit=0D
+ else:=0D
+ is_array =3D False=0D
+=0D
+ if is_array:=0D
+ name =3D name + '[%d]' % length=0D
+=0D
+ if len(type) < pos_name:=0D
+ space1 =3D pos_name - len(type)=0D
+ else:=0D
+ space1 =3D 1=0D
+=0D
+ if bsf_name !=3D '':=0D
+ name_line =3D " %s\n" % bsf_name=0D
+ else:=0D
+ name_line =3D "N/A\n"=0D
+=0D
+ # if help !=3D '':=0D
+ # help_line =3D self.process_multilines(help, 80)=0D
+=0D
+ # if option !=3D '':=0D
+ # option_line =3D self.process_multilines(option, 80)=0D
+=0D
+ if offset is None:=0D
+ offset_str =3D '????'=0D
+ else:=0D
+ offset_str =3D '0x%04X' % offset=0D
+=0D
+ if bits_length is None:=0D
+ bits_length =3D ''=0D
+ else:=0D
+ bits_length =3D ' : %d' % bits_length=0D
+=0D
+ # return "\n/** %s%s%s**/\n %s%s%s%s;\n" % (name_line, help_line,=
=0D
+ # option_line, type, ' ' * space1, name, bits_length)=0D
+ return "\n /* Offset %s: %s */\n %s%s%s%s;\n" % (=0D
+ offset_str, name_line.strip(), type, ' ' * space1,=0D
+ name, bits_length)=0D
+=0D
+ def create_struct(self, cname, top, struct_dict):=0D
+ index =3D 0=0D
+ last =3D ''=0D
+ lines =3D []=0D
+ off_base =3D -1=0D
+=0D
+ if cname in struct_dict:=0D
+ if struct_dict[cname][2]:=0D
+ return []=0D
+ lines.append('\ntypedef struct {\n')=0D
+ for field in top:=0D
+ if field[0] =3D=3D '$':=0D
+ continue=0D
+=0D
+ index +=3D 1=0D
+=0D
+ t_item =3D top[field]=0D
+ if 'indx' not in t_item:=0D
+ if CGenYamlCfg.STRUCT not in top[field]:=0D
+ continue=0D
+=0D
+ if struct_dict[field][1] =3D=3D 0:=0D
+ continue=0D
+=0D
+ append =3D True=0D
+ struct_info =3D top[field][CGenYamlCfg.STRUCT]=0D
+=0D
+ if 'struct' in struct_info:=0D
+ struct, array_num, var =3D self.get_struct_array_info(=
=0D
+ struct_info['struct'])=0D
+ if array_num > 0:=0D
+ if last =3D=3D struct:=0D
+ append =3D False=0D
+ last =3D struct=0D
+ if var =3D=3D '':=0D
+ var =3D field=0D
+=0D
+ field =3D CGenYamlCfg.format_struct_field_name(=0D
+ var, struct_dict[field][1])=0D
+ else:=0D
+ struct =3D struct_dict[field][0]=0D
+ field =3D CGenYamlCfg.format_struct_field_name(=0D
+ field, struct_dict[field][1])=0D
+=0D
+ if append:=0D
+ offset =3D t_item['$STRUCT']['offset'] // 8=0D
+ if off_base =3D=3D -1:=0D
+ off_base =3D offset=0D
+ line =3D self.create_field(None, field, 0, 0, struct,=
=0D
+ '', '', '')=0D
+ lines.append(' %s' % line)=0D
+ last =3D struct=0D
+ continue=0D
+=0D
+ item =3D self.get_item_by_index(t_item['indx'])=0D
+ if item['cname'] =3D=3D 'CfgHeader' and index =3D=3D 1 or \=0D
+ (item['cname'] =3D=3D 'CondValue' and index =3D=3D 2):=0D
+ continue=0D
+=0D
+ bit_length =3D None=0D
+ length =3D (item['length'] + 7) // 8=0D
+ match =3D re.match("^(\\d+)([b|B|W|D|Q])([B|W|D|Q]?)",=0D
+ t_item['length'])=0D
+ if match and match.group(2) =3D=3D 'b':=0D
+ bit_length =3D int(match.group(1))=0D
+ if match.group(3) !=3D '':=0D
+ length =3D CGenYamlCfg.bits_width[match.group(3)] // 8=
=0D
+ else:=0D
+ length =3D 4=0D
+ offset =3D item['offset'] // 8=0D
+ if off_base =3D=3D -1:=0D
+ off_base =3D offset=0D
+ struct =3D item.get('struct', '')=0D
+ name =3D field=0D
+ prompt =3D item['name']=0D
+ help =3D item['help']=0D
+ option =3D item['option']=0D
+ line =3D self.create_field(item, name, length, offset, struct,=
=0D
+ prompt, help, option, bit_length)=0D
+ lines.append(' %s' % line)=0D
+ last =3D struct=0D
+=0D
+ lines.append('\n} %s;\n\n' % cname)=0D
+=0D
+ return lines=0D
+=0D
+ def write_fsp_sig_header_file(self, hdr_file_name):=0D
+ hdr_fd =3D open(hdr_file_name, 'w')=0D
+ hdr_fd.write("%s\n" % get_copyright_header('h'))=0D
+ hdr_fd.write("#ifndef __FSPUPD_H__\n"=0D
+ "#define __FSPUPD_H__\n\n"=0D
+ "#include <FspEas.h>\n\n"=0D
+ "#pragma pack(1)\n\n")=0D
+ lines =3D []=0D
+ for fsp_comp in 'TMS':=0D
+ top =3D self.locate_cfg_item('FSP%s_UPD' % fsp_comp)=0D
+ if not top:=0D
+ raise Exception('Could not find FSP UPD definition !')=0D
+ bins =3D self.get_field_value(top)=0D
+ lines.append("#define FSP%s_UPD_SIGNATURE"=0D
+ " 0x%016X /* '%s' */\n\n"=0D
+ % (fsp_comp, bytes_to_value(bins[:8]),=0D
+ bins[:8].decode()))=0D
+ hdr_fd.write(''.join(lines))=0D
+ hdr_fd.write("#pragma pack()\n\n"=0D
+ "#endif\n")=0D
+ hdr_fd.close()=0D
+=0D
+ def create_header_file(self, hdr_file_name, com_hdr_file_name=3D'', pa=
th=3D''):=0D
+=0D
+ def _build_header_struct(name, cfgs, level):=0D
+ if CGenYamlCfg.STRUCT in cfgs:=0D
+ if 'CfgHeader' in cfgs:=0D
+ # collect CFGDATA TAG IDs=0D
+ cfghdr =3D self.get_item_by_index(cfgs['CfgHeader']['i=
ndx'])=0D
+ tag_val =3D array_str_to_value(cfghdr['value']) >> 20=
=0D
+ tag_dict[name] =3D tag_val=0D
+ if level =3D=3D 1:=0D
+ tag_curr[0] =3D tag_val=0D
+ struct_dict[name] =3D (level, tag_curr[0], cfgs)=0D
+ if path =3D=3D 'FSP_SIG':=0D
+ self.write_fsp_sig_header_file(hdr_file_name)=0D
+ return=0D
+ tag_curr =3D [0]=0D
+ tag_dict =3D {}=0D
+ struct_dict =3D {}=0D
+=0D
+ if path =3D=3D '':=0D
+ top =3D None=0D
+ else:=0D
+ top =3D self.locate_cfg_item(path)=0D
+ if not top:=0D
+ raise Exception("Invalid configuration path '%s' !" % path=
)=0D
+ _build_header_struct(path, top, 0)=0D
+ self.traverse_cfg_tree(_build_header_struct, top)=0D
+=0D
+ if tag_curr[0] =3D=3D 0:=0D
+ hdr_mode =3D 2=0D
+ else:=0D
+ hdr_mode =3D 1=0D
+=0D
+ if re.match('FSP[TMS]_UPD', path):=0D
+ hdr_mode |=3D 0x80=0D
+=0D
+ # filter out the items to be built for tags and structures=0D
+ struct_list =3D []=0D
+ for each in struct_dict:=0D
+ match =3D False=0D
+ for check in CGenYamlCfg.exclude_struct:=0D
+ if re.match(check, each):=0D
+ match =3D True=0D
+ if each in tag_dict:=0D
+ if each not in CGenYamlCfg.include_tag:=0D
+ del tag_dict[each]=0D
+ break=0D
+ if not match:=0D
+ struct_list.append({'name': each, 'alias': '', 'count': 0,=
=0D
+ 'level': struct_dict[each][0],=0D
+ 'tag': struct_dict[each][1],=0D
+ 'node': struct_dict[each][2]})=0D
+=0D
+ # sort by level so that the bottom level struct=0D
+ # will be build first to satisfy dependencies=0D
+ struct_list =3D sorted(struct_list, key=3Dlambda x: x['level'],=0D
+ reverse=3DTrue)=0D
+=0D
+ # Convert XXX_[0-9]+ to XXX as an array hint=0D
+ for each in struct_list:=0D
+ cfgs =3D each['node']=0D
+ if 'struct' in cfgs['$STRUCT']:=0D
+ each['alias'], array_num, var =3D self.get_struct_array_in=
fo(=0D
+ cfgs['$STRUCT']['struct'])=0D
+ else:=0D
+ match =3D re.match('(\\w+)(_\\d+)', each['name'])=0D
+ if match:=0D
+ each['alias'] =3D match.group(1)=0D
+ else:=0D
+ each['alias'] =3D each['name']=0D
+=0D
+ # count items for array build=0D
+ for idx, each in enumerate(struct_list):=0D
+ if idx > 0:=0D
+ last_struct =3D struct_list[idx-1]['node']['$STRUCT']=0D
+ curr_struct =3D each['node']['$STRUCT']=0D
+ if struct_list[idx-1]['alias'] =3D=3D each['alias'] and \=
=0D
+ curr_struct['length'] =3D=3D last_struct['length'] and =
\=0D
+ curr_struct['offset'] =3D=3D last_struct['offset'] + \=
=0D
+ last_struct['length']:=0D
+ for idx2 in range(idx-1, -1, -1):=0D
+ if struct_list[idx2]['count'] > 0:=0D
+ struct_list[idx2]['count'] +=3D 1=0D
+ break=0D
+ continue=0D
+ each['count'] =3D 1=0D
+=0D
+ # generate common header=0D
+ if com_hdr_file_name:=0D
+ self.write_cfg_header_file(com_hdr_file_name, 0, tag_dict,=0D
+ struct_list)=0D
+=0D
+ # generate platform header=0D
+ self.write_cfg_header_file(hdr_file_name, hdr_mode, tag_dict,=0D
+ struct_list)=0D
+=0D
+ return 0=0D
+=0D
+ def load_yaml(self, cfg_file):=0D
+ cfg_yaml =3D CFG_YAML()=0D
+ self.initialize()=0D
+ self._cfg_tree =3D cfg_yaml.load_yaml(cfg_file)=0D
+ self._def_dict =3D cfg_yaml.def_dict=0D
+ self._yaml_path =3D os.path.dirname(cfg_file)=0D
+ self.build_cfg_list()=0D
+ self.build_var_dict()=0D
+ self.update_def_value()=0D
+ return 0=0D
+=0D
+=0D
+def usage():=0D
+ print('\n'.join([=0D
+ "GenYamlCfg Version 0.50",=0D
+ "Usage:",=0D
+ " GenYamlCfg GENINC BinFile IncOutFile "=0D
+ " [-D Macros]",=0D
+=0D
+ " GenYamlCfg GENPKL YamlFile PklOutFile "=0D
+ " [-D Macros]",=0D
+ " GenYamlCfg GENBIN YamlFile[;DltFile] BinOutFile "=0D
+ " [-D Macros]",=0D
+ " GenYamlCfg GENDLT YamlFile[;BinFile] DltOutFile "=0D
+ " [-D Macros]",=0D
+ " GenYamlCfg GENYML YamlFile YamlOutFile"=0D
+ " [-D Macros]",=0D
+ " GenYamlCfg GENHDR YamlFile HdrOutFile "=0D
+ " [-D Macros]"=0D
+ ]))=0D
+=0D
+=0D
+def main():=0D
+ # Parse the options and args=0D
+ argc =3D len(sys.argv)=0D
+ if argc < 4:=0D
+ usage()=0D
+ return 1=0D
+=0D
+ gen_cfg_data =3D CGenYamlCfg()=0D
+ command =3D sys.argv[1].upper()=0D
+ out_file =3D sys.argv[3]=0D
+ if argc >=3D 5 and gen_cfg_data.parse_macros(sys.argv[4:]) !=3D 0:=0D
+ raise Exception("ERROR: Macro parsing failed !")=0D
+=0D
+ file_list =3D sys.argv[2].split(';')=0D
+ if len(file_list) >=3D 2:=0D
+ yml_file =3D file_list[0]=0D
+ dlt_file =3D file_list[1]=0D
+ elif len(file_list) =3D=3D 1:=0D
+ yml_file =3D file_list[0]=0D
+ dlt_file =3D ''=0D
+ else:=0D
+ raise Exception("ERROR: Invalid parameter '%s' !" % sys.argv[2])=0D
+ yml_scope =3D ''=0D
+ if '@' in yml_file:=0D
+ parts =3D yml_file.split('@')=0D
+ yml_file =3D parts[0]=0D
+ yml_scope =3D parts[1]=0D
+=0D
+ if command =3D=3D "GENDLT" and yml_file.endswith('.dlt'):=0D
+ # It needs to expand an existing DLT file=0D
+ dlt_file =3D yml_file=0D
+ lines =3D gen_cfg_data.expand_include_files(dlt_file)=0D
+ write_lines(lines, out_file)=0D
+ return 0=0D
+=0D
+ if command =3D=3D "GENYML":=0D
+ if not yml_file.lower().endswith('.yaml'):=0D
+ raise Exception('Only YAML file is supported !')=0D
+ gen_cfg_data.generate_yml_file(yml_file, out_file)=0D
+ return 0=0D
+=0D
+ bin_file =3D ''=0D
+ if (yml_file.lower().endswith('.bin')) and (command =3D=3D "GENINC"):=
=0D
+ # It is binary file=0D
+ bin_file =3D yml_file=0D
+ yml_file =3D ''=0D
+=0D
+ if bin_file:=0D
+ gen_cfg_data.generate_data_inc_file(out_file, bin_file)=0D
+ return 0=0D
+=0D
+ cfg_bin_file =3D ''=0D
+ cfg_bin_file2 =3D ''=0D
+ if dlt_file:=0D
+ if command =3D=3D "GENDLT":=0D
+ cfg_bin_file =3D dlt_file=0D
+ dlt_file =3D ''=0D
+ if len(file_list) >=3D 3:=0D
+ cfg_bin_file2 =3D file_list[2]=0D
+=0D
+ if yml_file.lower().endswith('.pkl'):=0D
+ with open(yml_file, "rb") as pkl_file:=0D
+ gen_cfg_data.__dict__ =3D marshal.load(pkl_file)=0D
+ gen_cfg_data.prepare_marshal(False)=0D
+=0D
+ # Override macro definition again for Pickle file=0D
+ if argc >=3D 5:=0D
+ gen_cfg_data.parse_macros(sys.argv[4:])=0D
+ else:=0D
+ gen_cfg_data.load_yaml(yml_file)=0D
+ if command =3D=3D 'GENPKL':=0D
+ gen_cfg_data.prepare_marshal(True)=0D
+ with open(out_file, "wb") as pkl_file:=0D
+ marshal.dump(gen_cfg_data.__dict__, pkl_file)=0D
+ json_file =3D os.path.splitext(out_file)[0] + '.json'=0D
+ fo =3D open(json_file, 'w')=0D
+ path_list =3D []=0D
+ cfgs =3D {'_cfg_page': gen_cfg_data._cfg_page,=0D
+ '_cfg_list': gen_cfg_data._cfg_list,=0D
+ '_path_list': path_list}=0D
+ # optimize to reduce size=0D
+ path =3D None=0D
+ for each in cfgs['_cfg_list']:=0D
+ new_path =3D each['path'][:-len(each['cname'])-1]=0D
+ if path !=3D new_path:=0D
+ path =3D new_path=0D
+ each['path'] =3D path=0D
+ path_list.append(path)=0D
+ else:=0D
+ del each['path']=0D
+ if each['order'] =3D=3D each['offset']:=0D
+ del each['order']=0D
+ del each['offset']=0D
+=0D
+ # value is just used to indicate display type=0D
+ value =3D each['value']=0D
+ if value.startswith('0x'):=0D
+ hex_len =3D ((each['length'] + 7) // 8) * 2=0D
+ if len(value) =3D=3D hex_len:=0D
+ value =3D 'x%d' % hex_len=0D
+ else:=0D
+ value =3D 'x'=0D
+ each['value'] =3D value=0D
+ elif value and value[0] in ['"', "'", '{']:=0D
+ each['value'] =3D value[0]=0D
+ else:=0D
+ del each['value']=0D
+=0D
+ fo.write(repr(cfgs))=0D
+ fo.close()=0D
+ return 0=0D
+=0D
+ if dlt_file:=0D
+ gen_cfg_data.override_default_value(dlt_file)=0D
+=0D
+ gen_cfg_data.detect_fsp()=0D
+=0D
+ if command =3D=3D "GENBIN":=0D
+ if len(file_list) =3D=3D 3:=0D
+ old_data =3D gen_cfg_data.generate_binary_array()=0D
+ fi =3D open(file_list[2], 'rb')=0D
+ new_data =3D bytearray(fi.read())=0D
+ fi.close()=0D
+ if len(new_data) !=3D len(old_data):=0D
+ raise Exception("Binary file '%s' length does not match, \=
=0D
+ignored !" % file_list[2])=0D
+ else:=0D
+ gen_cfg_data.load_default_from_bin(new_data)=0D
+ gen_cfg_data.override_default_value(dlt_file)=0D
+=0D
+ gen_cfg_data.generate_binary(out_file, yml_scope)=0D
+=0D
+ elif command =3D=3D "GENDLT":=0D
+ full =3D True if 'FULL' in gen_cfg_data._macro_dict else False=0D
+ gen_cfg_data.generate_delta_file(out_file, cfg_bin_file,=0D
+ cfg_bin_file2, full)=0D
+=0D
+ elif command =3D=3D "GENHDR":=0D
+ out_files =3D out_file.split(';')=0D
+ brd_out_file =3D out_files[0].strip()=0D
+ if len(out_files) > 1:=0D
+ com_out_file =3D out_files[1].strip()=0D
+ else:=0D
+ com_out_file =3D ''=0D
+ gen_cfg_data.create_header_file(brd_out_file, com_out_file, yml_sc=
ope)=0D
+=0D
+ elif command =3D=3D "GENINC":=0D
+ gen_cfg_data.generate_data_inc_file(out_file)=0D
+=0D
+ elif command =3D=3D "DEBUG":=0D
+ gen_cfg_data.print_cfgs()=0D
+=0D
+ else:=0D
+ raise Exception("Unsuported command '%s' !" % command)=0D
+=0D
+ return 0=0D
+=0D
+=0D
+if __name__ =3D=3D '__main__':=0D
+ sys.exit(main())=0D
diff --git a/IntelFsp2Pkg/Tools/ConfigEditor/SingleSign.py b/IntelFsp2Pkg/T=
ools/ConfigEditor/SingleSign.py
new file mode 100644
index 0000000000..868b29d528
--- /dev/null
+++ b/IntelFsp2Pkg/Tools/ConfigEditor/SingleSign.py
@@ -0,0 +1,324 @@
+#!/usr/bin/env python=0D
+# @ SingleSign.py=0D
+# Single signing script=0D
+#=0D
+# Copyright (c) 2020, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+import os=0D
+import sys=0D
+import re=0D
+import shutil=0D
+import subprocess=0D
+=0D
+SIGNING_KEY =3D {=0D
+ # Key Id | Key File Name start |=0D
+ # =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=0D
+ # KEY_ID_MASTER is used for signing Slimboot Key Hash Manifest \=0D
+ # container (KEYH Component)=0D
+ "KEY_ID_MASTER_RSA2048": "MasterTestKey_Priv_RSA2048.pem",=0D
+ "KEY_ID_MASTER_RSA3072": "MasterTestKey_Priv_RSA3072.pem",=0D
+=0D
+ # KEY_ID_CFGDATA is used for signing external Config data blob)=0D
+ "KEY_ID_CFGDATA_RSA2048": "ConfigTestKey_Priv_RSA2048.pem",=0D
+ "KEY_ID_CFGDATA_RSA3072": "ConfigTestKey_Priv_RSA3072.pem",=0D
+=0D
+ # KEY_ID_FIRMWAREUPDATE is used for signing capsule firmware update im=
age)=0D
+ "KEY_ID_FIRMWAREUPDATE_RSA2048": "FirmwareUpdateTestKey_Priv_RSA2048.p=
em",=0D
+ "KEY_ID_FIRMWAREUPDATE_RSA3072": "FirmwareUpdateTestKey_Priv_RSA3072.p=
em",=0D
+=0D
+ # KEY_ID_CONTAINER is used for signing container header with mono sign=
ature=0D
+ "KEY_ID_CONTAINER_RSA2048": "ContainerTestKey_Priv_RSA2048.pem",=0D
+ "KEY_ID_CONTAINER_RSA3072": "ContainerTestKey_Priv_RSA3072.pem",=0D
+=0D
+ # CONTAINER_COMP1_KEY_ID is used for signing container components=0D
+ "KEY_ID_CONTAINER_COMP_RSA2048": "ContainerCompTestKey_Priv_RSA2048.pe=
m",=0D
+ "KEY_ID_CONTAINER_COMP_RSA3072": "ContainerCompTestKey_Priv_RSA3072.pe=
m",=0D
+=0D
+ # KEY_ID_OS1_PUBLIC, KEY_ID_OS2_PUBLIC is used for referencing \=0D
+ # Boot OS public keys=0D
+ "KEY_ID_OS1_PUBLIC_RSA2048": "OS1_TestKey_Pub_RSA2048.pem",=0D
+ "KEY_ID_OS1_PUBLIC_RSA3072": "OS1_TestKey_Pub_RSA3072.pem",=0D
+=0D
+ "KEY_ID_OS2_PUBLIC_RSA2048": "OS2_TestKey_Pub_RSA2048.pem",=0D
+ "KEY_ID_OS2_PUBLIC_RSA3072": "OS2_TestKey_Pub_RSA3072.pem",=0D
+=0D
+ }=0D
+=0D
+MESSAGE_SBL_KEY_DIR =3D """!!! PRE-REQUISITE: Path to SBL_KEY_DIR has.=0D
+to be set with SBL KEYS DIRECTORY !!! \n!!! Generate keys.=0D
+using GenerateKeys.py available in BootloaderCorePkg/Tools.=0D
+directory !!! \n !!! Run $python.=0D
+BootloaderCorePkg/Tools/GenerateKeys.py -k $PATH_TO_SBL_KEY_DIR !!!\n=0D
+!!! Set SBL_KEY_DIR environ with path to SBL KEYS DIR !!!\n"=0D
+!!! Windows $set SBL_KEY_DIR=3D$PATH_TO_SBL_KEY_DIR !!!\n=0D
+!!! Linux $export SBL_KEY_DIR=3D$PATH_TO_SBL_KEY_DIR !!!\n"""=0D
+=0D
+=0D
+def get_openssl_path():=0D
+ if os.name =3D=3D 'nt':=0D
+ if 'OPENSSL_PATH' not in os.environ:=0D
+ openssl_dir =3D "C:\\Openssl\\bin\\"=0D
+ if os.path.exists(openssl_dir):=0D
+ os.environ['OPENSSL_PATH'] =3D openssl_dir=0D
+ else:=0D
+ os.environ['OPENSSL_PATH'] =3D "C:\\Openssl\\"=0D
+ if 'OPENSSL_CONF' not in os.environ:=0D
+ openssl_cfg =3D "C:\\Openssl\\openssl.cfg"=0D
+ if os.path.exists(openssl_cfg):=0D
+ os.environ['OPENSSL_CONF'] =3D openssl_cfg=0D
+ openssl =3D os.path.join(=0D
+ os.environ.get('OPENSSL_PATH', ''),=0D
+ 'openssl.exe')=0D
+ else:=0D
+ # Get openssl path for Linux cases=0D
+ openssl =3D shutil.which('openssl')=0D
+=0D
+ return openssl=0D
+=0D
+=0D
+def run_process(arg_list, print_cmd=3DFalse, capture_out=3DFalse):=0D
+ sys.stdout.flush()=0D
+ if print_cmd:=0D
+ print(' '.join(arg_list))=0D
+=0D
+ exc =3D None=0D
+ result =3D 0=0D
+ output =3D ''=0D
+ try:=0D
+ if capture_out:=0D
+ output =3D subprocess.check_output(arg_list).decode()=0D
+ else:=0D
+ result =3D subprocess.call(arg_list)=0D
+ except Exception as ex:=0D
+ result =3D 1=0D
+ exc =3D ex=0D
+=0D
+ if result:=0D
+ if not print_cmd:=0D
+ print('Error in running process:\n %s' % ' '.join(arg_list))=
=0D
+ if exc is None:=0D
+ sys.exit(1)=0D
+ else:=0D
+ raise exc=0D
+=0D
+ return output=0D
+=0D
+=0D
+def check_file_pem_format(priv_key):=0D
+ # Check for file .pem format=0D
+ key_name =3D os.path.basename(priv_key)=0D
+ if os.path.splitext(key_name)[1] =3D=3D ".pem":=0D
+ return True=0D
+ else:=0D
+ return False=0D
+=0D
+=0D
+def get_key_id(priv_key):=0D
+ # Extract base name if path is provided.=0D
+ key_name =3D os.path.basename(priv_key)=0D
+ # Check for KEY_ID in key naming.=0D
+ if key_name.startswith('KEY_ID'):=0D
+ return key_name=0D
+ else:=0D
+ return None=0D
+=0D
+=0D
+def get_sbl_key_dir():=0D
+ # Check Key store setting SBL_KEY_DIR path=0D
+ if 'SBL_KEY_DIR' not in os.environ:=0D
+ exception_string =3D "ERROR: SBL_KEY_DIR is not defined." \=0D
+ " Set SBL_KEY_DIR with SBL Keys directory!!\n"=0D
+ raise Exception(exception_string + MESSAGE_SBL_KEY_DIR)=0D
+=0D
+ sbl_key_dir =3D os.environ.get('SBL_KEY_DIR')=0D
+ if not os.path.exists(sbl_key_dir):=0D
+ exception_string =3D "ERROR:SBL_KEY_DIR set " + sbl_key_dir \=0D
+ + " is not valid." \=0D
+ " Set the correct SBL_KEY_DIR path !!\n" \=0D
+ + MESSAGE_SBL_KEY_DIR=0D
+ raise Exception(exception_string)=0D
+ else:=0D
+ return sbl_key_dir=0D
+=0D
+=0D
+def get_key_from_store(in_key):=0D
+=0D
+ # Check in_key is path to key=0D
+ if os.path.exists(in_key):=0D
+ return in_key=0D
+=0D
+ # Get Slimboot key dir path=0D
+ sbl_key_dir =3D get_sbl_key_dir()=0D
+=0D
+ # Extract if in_key is key_id=0D
+ priv_key =3D get_key_id(in_key)=0D
+ if priv_key is not None:=0D
+ if (priv_key in SIGNING_KEY):=0D
+ # Generate key file name from key id=0D
+ priv_key_file =3D SIGNING_KEY[priv_key]=0D
+ else:=0D
+ exception_string =3D "KEY_ID" + priv_key + "is not found " \=0D
+ "is not found in supported KEY IDs!!"=0D
+ raise Exception(exception_string)=0D
+ elif check_file_pem_format(in_key):=0D
+ # check if file name is provided in pem format=0D
+ priv_key_file =3D in_key=0D
+ else:=0D
+ priv_key_file =3D None=0D
+ raise Exception('key provided %s is not valid!' % in_key)=0D
+=0D
+ # Create a file path=0D
+ # Join Key Dir and priv_key_file=0D
+ try:=0D
+ priv_key =3D os.path.join(sbl_key_dir, priv_key_file)=0D
+ except Exception:=0D
+ raise Exception('priv_key is not found %s!' % priv_key)=0D
+=0D
+ # Check for priv_key construted based on KEY ID exists in specified pa=
th=0D
+ if not os.path.isfile(priv_key):=0D
+ exception_string =3D "!!! ERROR: Key file corresponding to" \=0D
+ + in_key + "do not exist in Sbl key " \=0D
+ "directory at" + sbl_key_dir + "!!! \n" \=0D
+ + MESSAGE_SBL_KEY_DIR=0D
+ raise Exception(exception_string)=0D
+=0D
+ return priv_key=0D
+=0D
+#=0D
+# Sign an file using openssl=0D
+#=0D
+# priv_key [Input] Key Id or Path to Private key=0D
+# hash_type [Input] Signing hash=0D
+# sign_scheme[Input] Sign/padding scheme=0D
+# in_file [Input] Input file to be signed=0D
+# out_file [Input/Output] Signed data file=0D
+#=0D
+=0D
+=0D
+def single_sign_file(priv_key, hash_type, sign_scheme, in_file, out_file):=
=0D
+=0D
+ _hash_type_string =3D {=0D
+ "SHA2_256": 'sha256',=0D
+ "SHA2_384": 'sha384',=0D
+ "SHA2_512": 'sha512',=0D
+ }=0D
+=0D
+ _hash_digest_Size =3D {=0D
+ # Hash_string : Hash_Size=0D
+ "SHA2_256": 32,=0D
+ "SHA2_384": 48,=0D
+ "SHA2_512": 64,=0D
+ "SM3_256": 32,=0D
+ }=0D
+=0D
+ _sign_scheme_string =3D {=0D
+ "RSA_PKCS1": 'pkcs1',=0D
+ "RSA_PSS": 'pss',=0D
+ }=0D
+=0D
+ priv_key =3D get_key_from_store(priv_key)=0D
+=0D
+ # Temporary files to store hash generated=0D
+ hash_file_tmp =3D out_file+'.hash.tmp'=0D
+ hash_file =3D out_file+'.hash'=0D
+=0D
+ # Generate hash using openssl dgst in hex format=0D
+ cmdargs =3D [get_openssl_path(),=0D
+ 'dgst',=0D
+ '-'+'%s' % _hash_type_string[hash_type],=0D
+ '-out', '%s' % hash_file_tmp, '%s' % in_file]=0D
+ run_process(cmdargs)=0D
+=0D
+ # Extract hash form dgst command output and convert to ascii=0D
+ with open(hash_file_tmp, 'r') as fin:=0D
+ hashdata =3D fin.read()=0D
+ fin.close()=0D
+=0D
+ try:=0D
+ hashdata =3D hashdata.rsplit('=3D', 1)[1].strip()=0D
+ except Exception:=0D
+ raise Exception('Hash Data not found for signing!')=0D
+=0D
+ if len(hashdata) !=3D (_hash_digest_Size[hash_type] * 2):=0D
+ raise Exception('Hash Data size do match with for hash type!')=0D
+=0D
+ hashdata_bytes =3D bytearray.fromhex(hashdata)=0D
+ open(hash_file, 'wb').write(hashdata_bytes)=0D
+=0D
+ print("Key used for Singing %s !!" % priv_key)=0D
+=0D
+ # sign using Openssl pkeyutl=0D
+ cmdargs =3D [get_openssl_path(),=0D
+ 'pkeyutl', '-sign', '-in', '%s' % hash_file,=0D
+ '-inkey', '%s' % priv_key, '-out',=0D
+ '%s' % out_file, '-pkeyopt',=0D
+ 'digest:%s' % _hash_type_string[hash_type],=0D
+ '-pkeyopt', 'rsa_padding_mode:%s' %=0D
+ _sign_scheme_string[sign_scheme]]=0D
+=0D
+ run_process(cmdargs)=0D
+=0D
+ return=0D
+=0D
+#=0D
+# Extract public key using openssl=0D
+#=0D
+# in_key [Input] Private key or public key in pem format=0D
+# pub_key_file [Input/Output] Public Key to a file=0D
+#=0D
+# return keydata (mod, exp) in bin format=0D
+#=0D
+=0D
+=0D
+def single_sign_gen_pub_key(in_key, pub_key_file=3DNone):=0D
+=0D
+ in_key =3D get_key_from_store(in_key)=0D
+=0D
+ # Expect key to be in PEM format=0D
+ is_prv_key =3D False=0D
+ cmdline =3D [get_openssl_path(), 'rsa', '-pubout', '-text', '-noout',=
=0D
+ '-in', '%s' % in_key]=0D
+ # Check if it is public key or private key=0D
+ text =3D open(in_key, 'r').read()=0D
+ if '-BEGIN RSA PRIVATE KEY-' in text:=0D
+ is_prv_key =3D True=0D
+ elif '-BEGIN PUBLIC KEY-' in text:=0D
+ cmdline.extend(['-pubin'])=0D
+ else:=0D
+ raise Exception('Unknown key format "%s" !' % in_key)=0D
+=0D
+ if pub_key_file:=0D
+ cmdline.extend(['-out', '%s' % pub_key_file])=0D
+ capture =3D False=0D
+ else:=0D
+ capture =3D True=0D
+=0D
+ output =3D run_process(cmdline, capture_out=3Dcapture)=0D
+ if not capture:=0D
+ output =3D text =3D open(pub_key_file, 'r').read()=0D
+ data =3D output.replace('\r', '')=0D
+ data =3D data.replace('\n', '')=0D
+ data =3D data.replace(' ', '')=0D
+=0D
+ # Extract the modulus=0D
+ if is_prv_key:=0D
+ match =3D re.search('modulus(.*)publicExponent:\\s+(\\d+)\\s+', da=
ta)=0D
+ else:=0D
+ match =3D re.search('Modulus(?:.*?):(.*)Exponent:\\s+(\\d+)\\s+', =
data)=0D
+ if not match:=0D
+ raise Exception('Public key not found!')=0D
+ modulus =3D match.group(1).replace(':', '')=0D
+ exponent =3D int(match.group(2))=0D
+=0D
+ mod =3D bytearray.fromhex(modulus)=0D
+ # Remove the '00' from the front if the MSB is 1=0D
+ if mod[0] =3D=3D 0 and (mod[1] & 0x80):=0D
+ mod =3D mod[1:]=0D
+ exp =3D bytearray.fromhex('{:08x}'.format(exponent))=0D
+=0D
+ keydata =3D mod + exp=0D
+=0D
+ return keydata=0D
diff --git a/IntelFsp2Pkg/Tools/FspDscBsf2Yaml.py b/IntelFsp2Pkg/Tools/FspD=
scBsf2Yaml.py
index d2ca7145ae..f9b2503414 100644
--- a/IntelFsp2Pkg/Tools/FspDscBsf2Yaml.py
+++ b/IntelFsp2Pkg/Tools/FspDscBsf2Yaml.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python=0D
-## @ FspDscBsf2Yaml.py=0D
-# This script convert DSC or BSF format file into YAML format=0D
-#=0D
-# Copyright(c) 2021, Intel Corporation. All rights reserved.<BR>=0D
+# @ FspBsf2Dsc.py=0D
+# This script convert FSP BSF format into DSC format=0D
+# Copyright (c) 2020, Intel Corporation. All rights reserved.<BR>=0D
# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
#=0D
##=0D
@@ -10,277 +9,38 @@
import os=0D
import re=0D
import sys=0D
-from datetime import date=0D
+=0D
from collections import OrderedDict=0D
-from functools import reduce=0D
+from datetime import date=0D
=0D
-from GenCfgOpt import CGenCfgOpt=0D
+from FspGenCfgData import CFspBsf2Dsc, CGenCfgData=0D
=0D
__copyright_tmp__ =3D """## @file=0D
#=0D
-# YAML CFGDATA %s File.=0D
+# Slim Bootloader CFGDATA %s File.=0D
#=0D
-# Copyright(c) %4d, Intel Corporation. All rights reserved.<BR>=0D
+# Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>=0D
# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
#=0D
##=0D
"""=0D
=0D
-__copyright_dsc__ =3D """## @file=0D
-#=0D
-# Copyright (c) %04d, Intel Corporation. All rights reserved.<BR>=0D
-# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
-#=0D
-##=0D
-=0D
-[PcdsDynamicVpd.Upd]=0D
- #=0D
- # Global definitions in BSF=0D
- # !BSF BLOCK:{NAME:"FSP UPD Configuration", VER:"0.1"}=0D
- #=0D
-=0D
-"""=0D
-=0D
-=0D
-def Bytes2Val(Bytes):=0D
- return reduce(lambda x, y: (x << 8) | y, Bytes[::-1])=0D
-=0D
-=0D
-def Str2Bytes(Value, Blen):=0D
- Result =3D bytearray(Value[1:-1], 'utf-8') # Excluding quotes=0D
- if len(Result) < Blen:=0D
- Result.extend(b'\x00' * (Blen - len(Result)))=0D
- return Result=0D
-=0D
-=0D
-class CFspBsf2Dsc:=0D
-=0D
- def __init__(self, bsf_file):=0D
- self.cfg_list =3D CFspBsf2Dsc.parse_bsf(bsf_file)=0D
-=0D
- def get_dsc_lines(self):=0D
- return CFspBsf2Dsc.generate_dsc(self.cfg_list)=0D
-=0D
- def save_dsc(self, dsc_file):=0D
- return CFspBsf2Dsc.generate_dsc(self.cfg_list, dsc_file)=0D
-=0D
- @staticmethod=0D
- def parse_bsf(bsf_file):=0D
-=0D
- fd =3D open(bsf_file, 'r')=0D
- bsf_txt =3D fd.read()=0D
- fd.close()=0D
-=0D
- find_list =3D []=0D
- regex =3D re.compile(r'\s+Find\s+"(.*?)"(.*?)^\s+\$(.*?)\s+', re.S=
| re.MULTILINE)=0D
- for match in regex.finditer(bsf_txt):=0D
- find =3D match.group(1)=0D
- name =3D match.group(3)=0D
- if not name.endswith('_Revision'):=0D
- raise Exception("Unexpected CFG item following 'Find' !")=
=0D
- find_list.append((name, find))=0D
-=0D
- idx =3D 0=0D
- count =3D 0=0D
- prefix =3D ''=0D
- chk_dict =3D {}=0D
- cfg_list =3D []=0D
- cfg_temp =3D {'find': '', 'cname': '', 'length': 0, 'value': '0', =
'type': 'Reserved',=0D
- 'embed': '', 'page': '', 'option': '', 'instance': 0}=
=0D
- regex =3D re.compile(r'^\s+(\$(.*?)|Skip)\s+(\d+)\s+bytes(\s+\$_DE=
FAULT_\s+=3D\s+(.+?))?$',=0D
- re.S | re.MULTILINE)=0D
-=0D
- for match in regex.finditer(bsf_txt):=0D
- dlen =3D int(match.group(3))=0D
- if match.group(1) =3D=3D 'Skip':=0D
- key =3D 'gPlatformFspPkgTokenSpaceGuid_BsfSkip%d' % idx=0D
- val =3D ', '.join(['%02X' % ord(i) for i in '\x00' * dlen]=
)=0D
- idx +=3D 1=0D
- option =3D '$SKIP'=0D
- else:=0D
- key =3D match.group(2)=0D
- val =3D match.group(5)=0D
- option =3D ''=0D
-=0D
- cfg_item =3D dict(cfg_temp)=0D
- finds =3D [i for i in find_list if i[0] =3D=3D key]=0D
- if len(finds) > 0:=0D
- if count >=3D 1:=0D
- # Append a dummy one=0D
- cfg_item['cname'] =3D 'Dummy'=0D
- cfg_list.append(dict(cfg_item))=0D
- cfg_list[-1]['embed'] =3D '%s:TAG_%03X:END' % (prefix,=
ord(prefix[-1]))=0D
- prefix =3D finds[0][1]=0D
- cfg_item['embed'] =3D '%s:TAG_%03X:START' % (prefix, ord(p=
refix[-1]))=0D
- cfg_item['find'] =3D prefix=0D
- cfg_item['cname'] =3D 'Signature'=0D
- cfg_item['length'] =3D len(finds[0][1])=0D
- str2byte =3D Str2Bytes("'" + finds[0][1] + "'", len(finds[=
0][1]))=0D
- cfg_item['value'] =3D '0x%X' % Bytes2Val(str2byte)=0D
- cfg_list.append(dict(cfg_item))=0D
- cfg_item =3D dict(cfg_temp)=0D
- find_list.pop(0)=0D
- count =3D 0=0D
-=0D
- cfg_item['cname'] =3D key=0D
- cfg_item['length'] =3D dlen=0D
- cfg_item['value'] =3D val=0D
- cfg_item['option'] =3D option=0D
-=0D
- if key not in chk_dict.keys():=0D
- chk_dict[key] =3D 0=0D
- else:=0D
- chk_dict[key] +=3D 1=0D
- cfg_item['instance'] =3D chk_dict[key]=0D
-=0D
- cfg_list.append(cfg_item)=0D
- count +=3D 1=0D
-=0D
- if prefix:=0D
- cfg_item =3D dict(cfg_temp)=0D
- cfg_item['cname'] =3D 'Dummy'=0D
- cfg_item['embed'] =3D '%s:%03X:END' % (prefix, ord(prefix[-1])=
)=0D
- cfg_list.append(cfg_item)=0D
-=0D
- option_dict =3D {}=0D
- selreg =3D re.compile(r'\s+Selection\s*(.+?)\s*,\s*"(.*?)"$', re.S=
| re.MULTILINE)=0D
- regex =3D re.compile(r'^List\s&(.+?)$(.+?)^EndList$', re.S | re.MU=
LTILINE)=0D
- for match in regex.finditer(bsf_txt):=0D
- key =3D match.group(1)=0D
- option_dict[key] =3D []=0D
- for select in selreg.finditer(match.group(2)):=0D
- option_dict[key].append((int(select.group(1), 0), select.g=
roup(2)))=0D
-=0D
- chk_dict =3D {}=0D
- pagereg =3D re.compile(r'^Page\s"(.*?)"$(.+?)^EndPage$', re.S | re=
.MULTILINE)=0D
- for match in pagereg.finditer(bsf_txt):=0D
- page =3D match.group(1)=0D
- for line in match.group(2).splitlines():=0D
- match =3D re.match(r'\s+(Combo|EditNum)\s\$(.+?),\s"(.*?)"=
,\s(.+?),$', line)=0D
- if match:=0D
- cname =3D match.group(2)=0D
- if cname not in chk_dict.keys():=0D
- chk_dict[cname] =3D 0=0D
- else:=0D
- chk_dict[cname] +=3D 1=0D
- instance =3D chk_dict[cname]=0D
- cfg_idxs =3D [i for i, j in enumerate(cfg_list) if j['=
cname'] =3D=3D cname and j['instance'] =3D=3D instance]=0D
- if len(cfg_idxs) !=3D 1:=0D
- raise Exception("Multiple CFG item '%s' found !" %=
cname)=0D
- cfg_item =3D cfg_list[cfg_idxs[0]]=0D
- cfg_item['page'] =3D page=0D
- cfg_item['type'] =3D match.group(1)=0D
- cfg_item['prompt'] =3D match.group(3)=0D
- cfg_item['range'] =3D None=0D
- if cfg_item['type'] =3D=3D 'Combo':=0D
- cfg_item['option'] =3D option_dict[match.group(4)[=
1:]]=0D
- elif cfg_item['type'] =3D=3D 'EditNum':=0D
- cfg_item['option'] =3D match.group(4)=0D
- match =3D re.match(r'\s+ Help\s"(.*?)"$', line)=0D
- if match:=0D
- cfg_item['help'] =3D match.group(1)=0D
-=0D
- match =3D re.match(r'\s+"Valid\srange:\s(.*)"$', line)=0D
- if match:=0D
- parts =3D match.group(1).split()=0D
- cfg_item['option'] =3D (=0D
- (int(parts[0], 0), int(parts[2], 0), cfg_item['opt=
ion']))=0D
-=0D
- return cfg_list=0D
-=0D
- @staticmethod=0D
- def generate_dsc(option_list, dsc_file=3DNone):=0D
- dsc_lines =3D []=0D
- header =3D '%s' % (__copyright_dsc__ % date.today().year)=0D
- dsc_lines.extend(header.splitlines())=0D
-=0D
- pages =3D []=0D
- for cfg_item in option_list:=0D
- if cfg_item['page'] and (cfg_item['page'] not in pages):=0D
- pages.append(cfg_item['page'])=0D
-=0D
- page_id =3D 0=0D
- for page in pages:=0D
- dsc_lines.append(' # !BSF PAGES:{PG%02X::"%s"}' % (page_id, p=
age))=0D
- page_id +=3D 1=0D
- dsc_lines.append('')=0D
-=0D
- last_page =3D ''=0D
- for option in option_list:=0D
- dsc_lines.append('')=0D
- default =3D option['value']=0D
- pos =3D option['cname'].find('_')=0D
- name =3D option['cname'][pos + 1:]=0D
-=0D
- if option['find']:=0D
- dsc_lines.append(' # !BSF FIND:{%s}' % option['find'])=0D
- dsc_lines.append('')=0D
-=0D
- if option['instance'] > 0:=0D
- name =3D name + '_%s' % option['instance']=0D
-=0D
- if option['embed']:=0D
- dsc_lines.append(' # !HDR EMBED:{%s}' % option['embed'])=
=0D
-=0D
- if option['type'] =3D=3D 'Reserved':=0D
- dsc_lines.append(' # !BSF NAME:{Reserved} TYPE:{Reserved}=
')=0D
- if option['option'] =3D=3D '$SKIP':=0D
- dsc_lines.append(' # !BSF OPTION:{$SKIP}')=0D
- else:=0D
- prompt =3D option['prompt']=0D
-=0D
- if last_page !=3D option['page']:=0D
- last_page =3D option['page']=0D
- dsc_lines.append(' # !BSF PAGE:{PG%02X}' % (pages.ind=
ex(option['page'])))=0D
-=0D
- if option['type'] =3D=3D 'Combo':=0D
- dsc_lines.append(' # !BSF NAME:{%s} TYPE:{%s}' %=0D
- (prompt, option['type']))=0D
- ops =3D []=0D
- for val, text in option['option']:=0D
- ops.append('0x%x:%s' % (val, text))=0D
- dsc_lines.append(' # !BSF OPTION:{%s}' % (', '.join(o=
ps)))=0D
- elif option['type'] =3D=3D 'EditNum':=0D
- cfg_len =3D option['length']=0D
- if ',' in default and cfg_len > 8:=0D
- dsc_lines.append(' # !BSF NAME:{%s} TYPE:{Table}'=
% (prompt))=0D
- if cfg_len > 16:=0D
- cfg_len =3D 16=0D
- ops =3D []=0D
- for i in range(cfg_len):=0D
- ops.append('%X:1:HEX' % i)=0D
- dsc_lines.append(' # !BSF OPTION:{%s}' % (', '.jo=
in(ops)))=0D
- else:=0D
- dsc_lines.append(=0D
- ' # !BSF NAME:{%s} TYPE:{%s, %s,(0x%X, 0x%X)}=
' %=0D
- (prompt, option['type'], option['option'][2],=
=0D
- option['option'][0], option['option'][1]))=0D
- dsc_lines.append(' # !BSF HELP:{%s}' % option['help'])=0D
-=0D
- if ',' in default:=0D
- default =3D '{%s}' % default=0D
- dsc_lines.append(' gCfgData.%-30s | * | 0x%04X | %s' %=0D
- (name, option['length'], default))=0D
-=0D
- if dsc_file:=0D
- fd =3D open(dsc_file, 'w')=0D
- fd.write('\n'.join(dsc_lines))=0D
- fd.close()=0D
-=0D
- return dsc_lines=0D
-=0D
=0D
class CFspDsc2Yaml():=0D
=0D
def __init__(self):=0D
self._Hdr_key_list =3D ['EMBED', 'STRUCT']=0D
- self._Bsf_key_list =3D ['NAME', 'HELP', 'TYPE', 'PAGE', 'PAGES', '=
OPTION',=0D
- 'CONDITION', 'ORDER', 'MARKER', 'SUBT', 'FIE=
LD', 'FIND']=0D
+ self._Bsf_key_list =3D ['NAME', 'HELP', 'TYPE', 'PAGE', 'PAGES',=0D
+ 'OPTION', 'CONDITION', 'ORDER', 'MARKER',=0D
+ 'SUBT', 'FIELD', 'FIND']=0D
self.gen_cfg_data =3D None=0D
- self.cfg_reg_exp =3D re.compile(r"^([_a-zA-Z0-9$\(\)]+)\s*\|\s*(0x=
[0-9A-F]+|\*)\s*\|"=0D
- + r"\s*(\d+|0x[0-9a-fA-F]+)\s*\|\s*(=
.+)")=0D
- self.bsf_reg_exp =3D re.compile(r"(%s):{(.+?)}(?:$|\s+)" % '|'.joi=
n(self._Bsf_key_list))=0D
- self.hdr_reg_exp =3D re.compile(r"(%s):{(.+?)}" % '|'.join(self._H=
dr_key_list))=0D
+ self.cfg_reg_exp =3D re.compile(=0D
+ "^([_a-zA-Z0-9$\\(\\)]+)\\s*\\|\\s*(0x[0-9A-F]+|\\*)"=0D
+ "\\s*\\|\\s*(\\d+|0x[0-9a-fA-F]+)\\s*\\|\\s*(.+)")=0D
+ self.bsf_reg_exp =3D re.compile("(%s):{(.+?)}(?:$|\\s+)"=0D
+ % '|'.join(self._Bsf_key_list))=0D
+ self.hdr_reg_exp =3D re.compile("(%s):{(.+?)}"=0D
+ % '|'.join(self._Hdr_key_list))=0D
self.prefix =3D ''=0D
self.unused_idx =3D 0=0D
self.offset =3D 0=0D
@@ -290,15 +50,15 @@ class CFspDsc2Yaml():
"""=0D
Load and parse a DSC CFGDATA file.=0D
"""=0D
- gen_cfg_data =3D CGenCfgOpt('FSP')=0D
+ gen_cfg_data =3D CGenCfgData('FSP')=0D
if file_name.endswith('.dsc'):=0D
- # if gen_cfg_data.ParseDscFileYaml(file_name, '') !=3D 0:=0D
- if gen_cfg_data.ParseDscFile(file_name, '') !=3D 0:=0D
+ if gen_cfg_data.ParseDscFile(file_name) !=3D 0:=0D
raise Exception('DSC file parsing error !')=0D
if gen_cfg_data.CreateVarDict() !=3D 0:=0D
raise Exception('DSC variable creation error !')=0D
else:=0D
raise Exception('Unsupported file "%s" !' % file_name)=0D
+ gen_cfg_data.UpdateDefaultValue()=0D
self.gen_cfg_data =3D gen_cfg_data=0D
=0D
def print_dsc_line(self):=0D
@@ -312,14 +72,15 @@ class CFspDsc2Yaml():
"""=0D
Format a CFGDATA item into YAML format.=0D
"""=0D
- if(not text.startswith('!expand')) and (': ' in text):=0D
+ if (not text.startswith('!expand')) and (': ' in text):=0D
tgt =3D ':' if field =3D=3D 'option' else '- '=0D
text =3D text.replace(': ', tgt)=0D
lines =3D text.splitlines()=0D
if len(lines) =3D=3D 1 and field !=3D 'help':=0D
return text=0D
else:=0D
- return '>\n ' + '\n '.join([indent + i.lstrip() for i in l=
ines])=0D
+ return '>\n ' + '\n '.join(=0D
+ [indent + i.lstrip() for i in lines])=0D
=0D
def reformat_pages(self, val):=0D
# Convert XXX:YYY into XXX::YYY format for page definition=0D
@@ -355,14 +116,16 @@ class CFspDsc2Yaml():
cfg['page'] =3D self.reformat_pages(cfg['page'])=0D
=0D
if 'struct' in cfg:=0D
- cfg['value'] =3D self.reformat_struct_value(cfg['struct'], cfg=
['value'])=0D
+ cfg['value'] =3D self.reformat_struct_value(=0D
+ cfg['struct'], cfg['value'])=0D
=0D
def parse_dsc_line(self, dsc_line, config_dict, init_dict, include):=0D
"""=0D
Parse a line in DSC and update the config dictionary accordingly.=
=0D
"""=0D
init_dict.clear()=0D
- match =3D re.match(r'g(CfgData|\w+FspPkgTokenSpaceGuid)\.(.+)', ds=
c_line)=0D
+ match =3D re.match('g(CfgData|\\w+FspPkgTokenSpaceGuid)\\.(.+)',=0D
+ dsc_line)=0D
if match:=0D
match =3D self.cfg_reg_exp.match(match.group(2))=0D
if not match:=0D
@@ -385,7 +148,7 @@ class CFspDsc2Yaml():
self.offset =3D offset + int(length, 0)=0D
return True=0D
=0D
- match =3D re.match(r"^\s*#\s+!([<>])\s+include\s+(.+)", dsc_line)=
=0D
+ match =3D re.match("^\\s*#\\s+!([<>])\\s+include\\s+(.+)", dsc_lin=
e)=0D
if match and len(config_dict) =3D=3D 0:=0D
# !include should not be inside a config field=0D
# if so, do not convert include into YAML=0D
@@ -398,7 +161,7 @@ class CFspDsc2Yaml():
config_dict['include'] =3D ''=0D
return True=0D
=0D
- match =3D re.match(r"^\s*#\s+(!BSF|!HDR)\s+(.+)", dsc_line)=0D
+ match =3D re.match("^\\s*#\\s+(!BSF|!HDR)\\s+(.+)", dsc_line)=0D
if not match:=0D
return False=0D
=0D
@@ -434,16 +197,19 @@ class CFspDsc2Yaml():
tmp_name =3D parts[0][:-5]=0D
if tmp_name =3D=3D 'CFGHDR':=0D
cfg_tag =3D '_$FFF_'=0D
- sval =3D '!expand { %s_TMPL : [ ' % tmp_name + '%s=
, %s, ' % (parts[1], cfg_tag) \=0D
- + ', '.join(parts[2:]) + ' ] }'=0D
+ sval =3D '!expand { %s_TMPL : [ ' % \=0D
+ tmp_name + '%s, %s, ' % (parts[1], cfg_tag) + =
\=0D
+ ', '.join(parts[2:]) + ' ] }'=0D
else:=0D
- sval =3D '!expand { %s_TMPL : [ ' % tmp_name + ', =
'.join(parts[1:]) + ' ] }'=0D
+ sval =3D '!expand { %s_TMPL : [ ' % \=0D
+ tmp_name + ', '.join(parts[1:]) + ' ] }'=0D
config_dict.clear()=0D
config_dict['cname'] =3D tmp_name=0D
config_dict['expand'] =3D sval=0D
return True=0D
else:=0D
- if key in ['name', 'help', 'option'] and val.startswit=
h('+'):=0D
+ if key in ['name', 'help', 'option'] and \=0D
+ val.startswith('+'):=0D
val =3D config_dict[key] + '\n' + val[1:]=0D
if val.strip() =3D=3D '':=0D
val =3D "''"=0D
@@ -493,21 +259,23 @@ class CFspDsc2Yaml():
include_file =3D ['.']=0D
=0D
for line in lines:=0D
- match =3D re.match(r"^\s*#\s+!([<>])\s+include\s+(.+)", line)=
=0D
+ match =3D re.match("^\\s*#\\s+!([<>])\\s+include\\s+(.+)", lin=
e)=0D
if match:=0D
if match.group(1) =3D=3D '<':=0D
include_file.append(match.group(2))=0D
else:=0D
include_file.pop()=0D
=0D
- match =3D re.match(r"^\s*#\s+(!BSF)\s+DEFT:{(.+?):(START|END)}=
", line)=0D
+ match =3D re.match(=0D
+ "^\\s*#\\s+(!BSF)\\s+DEFT:{(.+?):(START|END)}", line)=0D
if match:=0D
if match.group(3) =3D=3D 'START' and not template_name:=0D
template_name =3D match.group(2).strip()=0D
temp_file_dict[template_name] =3D list(include_file)=0D
bsf_temp_dict[template_name] =3D []=0D
- if match.group(3) =3D=3D 'END' and (template_name =3D=3D m=
atch.group(2).strip()) \=0D
- and template_name:=0D
+ if match.group(3) =3D=3D 'END' and \=0D
+ (template_name =3D=3D match.group(2).strip()) and =
\=0D
+ template_name:=0D
template_name =3D ''=0D
else:=0D
if template_name:=0D
@@ -531,12 +299,14 @@ class CFspDsc2Yaml():
init_dict.clear()=0D
padding_dict =3D {}=0D
cfgs.append(padding_dict)=0D
- padding_dict['cname'] =3D 'UnusedUpdSpace%d' % self.un=
used_idx=0D
+ padding_dict['cname'] =3D 'UnusedUpdSpace%d' % \=0D
+ self.unused_idx=0D
padding_dict['length'] =3D '0x%x' % num=0D
padding_dict['value'] =3D '{ 0 }'=0D
self.unused_idx +=3D 1=0D
=0D
- if cfgs and cfgs[-1]['cname'][0] !=3D '@' and config_dict[=
'cname'][0] =3D=3D '@':=0D
+ if cfgs and cfgs[-1]['cname'][0] !=3D '@' and \=0D
+ config_dict['cname'][0] =3D=3D '@':=0D
# it is a bit field, mark the previous one as virtual=
=0D
cname =3D cfgs[-1]['cname']=0D
new_cfg =3D dict(cfgs[-1])=0D
@@ -545,7 +315,8 @@ class CFspDsc2Yaml():
cfgs[-1]['cname'] =3D cname=0D
cfgs.append(new_cfg)=0D
=0D
- if cfgs and cfgs[-1]['cname'] =3D=3D 'CFGHDR' and config_d=
ict['cname'][0] =3D=3D '<':=0D
+ if cfgs and cfgs[-1]['cname'] =3D=3D 'CFGHDR' and \=0D
+ config_dict['cname'][0] =3D=3D '<':=0D
# swap CfgHeader and the CFG_DATA order=0D
if ':' in config_dict['cname']:=0D
# replace the real TAG for CFG_DATA=0D
@@ -661,7 +432,7 @@ class CFspDsc2Yaml():
lines =3D []=0D
for each in self.gen_cfg_data._MacroDict:=0D
key, value =3D self.variable_fixup(each)=0D
- lines.append('%-30s : %s' % (key, value))=0D
+ lines.append('%-30s : %s' % (key, value))=0D
return lines=0D
=0D
def output_template(self):=0D
@@ -671,7 +442,8 @@ class CFspDsc2Yaml():
self.offset =3D 0=0D
self.base_offset =3D 0=0D
start, end =3D self.get_section_range('PcdsDynamicVpd.Tmp')=0D
- bsf_temp_dict, temp_file_dict =3D self.process_template_lines(self=
.gen_cfg_data._DscLines[start:end])=0D
+ bsf_temp_dict, temp_file_dict =3D self.process_template_lines(=0D
+ self.gen_cfg_data._DscLines[start:end])=0D
template_dict =3D dict()=0D
lines =3D []=0D
file_lines =3D {}=0D
@@ -679,15 +451,18 @@ class CFspDsc2Yaml():
file_lines[last_file] =3D []=0D
=0D
for tmp_name in temp_file_dict:=0D
- temp_file_dict[tmp_name][-1] =3D self.normalize_file_name(temp=
_file_dict[tmp_name][-1], True)=0D
+ temp_file_dict[tmp_name][-1] =3D self.normalize_file_name(=0D
+ temp_file_dict[tmp_name][-1], True)=0D
if len(temp_file_dict[tmp_name]) > 1:=0D
- temp_file_dict[tmp_name][-2] =3D self.normalize_file_name(=
temp_file_dict[tmp_name][-2], True)=0D
+ temp_file_dict[tmp_name][-2] =3D self.normalize_file_name(=
=0D
+ temp_file_dict[tmp_name][-2], True)=0D
=0D
for tmp_name in bsf_temp_dict:=0D
file =3D temp_file_dict[tmp_name][-1]=0D
if last_file !=3D file and len(temp_file_dict[tmp_name]) > 1:=
=0D
inc_file =3D temp_file_dict[tmp_name][-2]=0D
- file_lines[inc_file].extend(['', '- !include %s' % temp_fi=
le_dict[tmp_name][-1], ''])=0D
+ file_lines[inc_file].extend(=0D
+ ['', '- !include %s' % temp_file_dict[tmp_name][-1], '=
'])=0D
last_file =3D file=0D
if file not in file_lines:=0D
file_lines[file] =3D []=0D
@@ -708,7 +483,8 @@ class CFspDsc2Yaml():
self.offset =3D 0=0D
self.base_offset =3D 0=0D
start, end =3D self.get_section_range('PcdsDynamicVpd.Upd')=0D
- cfgs =3D self.process_option_lines(self.gen_cfg_data._DscLines[sta=
rt:end])=0D
+ cfgs =3D self.process_option_lines(=0D
+ self.gen_cfg_data._DscLines[start:end])=0D
self.config_fixup(cfgs)=0D
file_lines =3D self.output_dict(cfgs, True)=0D
return file_lines=0D
@@ -726,8 +502,10 @@ class CFspDsc2Yaml():
=0D
if 'include' in each:=0D
if each['include']:=0D
- each['include'] =3D self.normalize_file_name(each['inc=
lude'])=0D
- file_lines[file].extend(['', '- !include %s' % each['i=
nclude'], ''])=0D
+ each['include'] =3D self.normalize_file_name(=0D
+ each['include'])=0D
+ file_lines[file].extend(=0D
+ ['', '- !include %s' % each['include'], ''])=0D
file =3D each['include']=0D
else:=0D
file =3D '.'=0D
@@ -766,7 +544,8 @@ class CFspDsc2Yaml():
for field in each:=0D
if field in ['cname', 'expand', 'include']:=0D
continue=0D
- value_str =3D self.format_value(field, each[field], paddin=
g + ' ' * 16)=0D
+ value_str =3D self.format_value(=0D
+ field, each[field], padding + ' ' * 16)=0D
full_line =3D ' %s %-12s : %s' % (padding, field, value_=
str)=0D
lines.extend(full_line.splitlines())=0D
=0D
@@ -802,11 +581,13 @@ def dsc_to_yaml(dsc_file, yaml_file):
if file =3D=3D '.':=0D
cfgs[cfg] =3D lines=0D
else:=0D
- if('/' in file or '\\' in file):=0D
+ if ('/' in file or '\\' in file):=0D
continue=0D
file =3D os.path.basename(file)=0D
- fo =3D open(os.path.join(file), 'w')=0D
- fo.write(__copyright_tmp__ % (cfg, date.today().year) + '\=
n\n')=0D
+ out_dir =3D os.path.dirname(file)=0D
+ fo =3D open(os.path.join(out_dir, file), 'w')=0D
+ fo.write(__copyright_tmp__ % (=0D
+ cfg, date.today().year) + '\n\n')=0D
for line in lines:=0D
fo.write(line + '\n')=0D
fo.close()=0D
@@ -821,13 +602,11 @@ def dsc_to_yaml(dsc_file, yaml_file):
=0D
fo.write('\n\ntemplate:\n')=0D
for line in cfgs['Template']:=0D
- if line !=3D '':=0D
- fo.write(' ' + line + '\n')=0D
+ fo.write(' ' + line + '\n')=0D
=0D
fo.write('\n\nconfigs:\n')=0D
for line in cfgs['Option']:=0D
- if line !=3D '':=0D
- fo.write(' ' + line + '\n')=0D
+ fo.write(' ' + line + '\n')=0D
=0D
fo.close()=0D
=0D
@@ -864,7 +643,8 @@ def main():
bsf_file =3D sys.argv[1]=0D
yaml_file =3D sys.argv[2]=0D
if os.path.isdir(yaml_file):=0D
- yaml_file =3D os.path.join(yaml_file, get_fsp_name_from_path(bsf_f=
ile) + '.yaml')=0D
+ yaml_file =3D os.path.join(=0D
+ yaml_file, get_fsp_name_from_path(bsf_file) + '.yaml')=0D
=0D
if bsf_file.endswith('.dsc'):=0D
dsc_file =3D bsf_file=0D
diff --git a/IntelFsp2Pkg/Tools/FspGenCfgData.py b/IntelFsp2Pkg/Tools/FspGe=
nCfgData.py
new file mode 100644
index 0000000000..decb3f1c5d
--- /dev/null
+++ b/IntelFsp2Pkg/Tools/FspGenCfgData.py
@@ -0,0 +1,2593 @@
+# @ GenCfgData.py=0D
+#=0D
+# Copyright (c) 2014 - 2018, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+import os=0D
+import re=0D
+import sys=0D
+import marshal=0D
+from functools import reduce=0D
+from datetime import date=0D
+=0D
+# Generated file copyright header=0D
+=0D
+__copyright_tmp__ =3D """/** @file=0D
+=0D
+ Configuration %s File.=0D
+=0D
+ Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+ This file is automatically generated. Please do NOT modify !!!=0D
+=0D
+**/=0D
+"""=0D
+=0D
+__copyright_dsc__ =3D """## @file=0D
+#=0D
+# Copyright (c) %04d, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[PcdsDynamicVpd.Upd]=0D
+ #=0D
+ # Global definitions in BSF=0D
+ # !BSF BLOCK:{NAME:"FSP UPD Configuration", VER:"0.1"}=0D
+ #=0D
+=0D
+"""=0D
+=0D
+=0D
+def Bytes2Val(Bytes):=0D
+ return reduce(lambda x, y: (x << 8) | y, Bytes[::-1])=0D
+=0D
+=0D
+def Bytes2Str(Bytes):=0D
+ return '{ %s }' % (', '.join('0x%02X' % i for i in Bytes))=0D
+=0D
+=0D
+def Str2Bytes(Value, Blen):=0D
+ Result =3D bytearray(Value[1:-1], 'utf-8') # Excluding quotes=0D
+ if len(Result) < Blen:=0D
+ Result.extend(b'\x00' * (Blen - len(Result)))=0D
+ return Result=0D
+=0D
+=0D
+def Val2Bytes(Value, Blen):=0D
+ return [(Value >> (i * 8) & 0xff) for i in range(Blen)]=0D
+=0D
+=0D
+def Array2Val(ValStr):=0D
+ ValStr =3D ValStr.strip()=0D
+ if ValStr.startswith('{'):=0D
+ ValStr =3D ValStr[1:]=0D
+ if ValStr.endswith('}'):=0D
+ ValStr =3D ValStr[:-1]=0D
+ if ValStr.startswith("'"):=0D
+ ValStr =3D ValStr[1:]=0D
+ if ValStr.endswith("'"):=0D
+ ValStr =3D ValStr[:-1]=0D
+ Value =3D 0=0D
+ for Each in ValStr.split(',')[::-1]:=0D
+ Each =3D Each.strip()=0D
+ if Each.startswith('0x'):=0D
+ Base =3D 16=0D
+ else:=0D
+ Base =3D 10=0D
+ Value =3D (Value << 8) | int(Each, Base)=0D
+ return Value=0D
+=0D
+=0D
+def GetCopyrightHeader(FileType, AllowModify=3DFalse):=0D
+ FileDescription =3D {=0D
+ 'bsf': 'Boot Setting',=0D
+ 'dsc': 'Definition',=0D
+ 'dlt': 'Delta',=0D
+ 'inc': 'C Binary Blob',=0D
+ 'h': 'C Struct Header'=0D
+ }=0D
+ if FileType in ['bsf', 'dsc', 'dlt']:=0D
+ CommentChar =3D '#'=0D
+ else:=0D
+ CommentChar =3D ''=0D
+ Lines =3D __copyright_tmp__.split('\n')=0D
+=0D
+ if AllowModify:=0D
+ Lines =3D [Line for Line in Lines if 'Please do NOT modify' not in=
Line]=0D
+=0D
+ CopyrightHdr =3D '\n'.join('%s%s' % (=0D
+ CommentChar, Line) for Line in Lines)[:-1] + '\n'=0D
+=0D
+ return CopyrightHdr % (FileDescription[FileType], date.today().year)=0D
+=0D
+=0D
+class CLogicalExpression:=0D
+ def __init__(self):=0D
+ self.index =3D 0=0D
+ self.string =3D ''=0D
+=0D
+ def errExit(self, err=3D''):=0D
+ print("ERROR: Express parsing for:")=0D
+ print(" %s" % self.string)=0D
+ print(" %s^" % (' ' * self.index))=0D
+ if err:=0D
+ print("INFO : %s" % err)=0D
+ raise SystemExit=0D
+=0D
+ def getNonNumber(self, n1, n2):=0D
+ if not n1.isdigit():=0D
+ return n1=0D
+ if not n2.isdigit():=0D
+ return n2=0D
+ return None=0D
+=0D
+ def getCurr(self, lens=3D1):=0D
+ try:=0D
+ if lens =3D=3D -1:=0D
+ return self.string[self.index:]=0D
+ else:=0D
+ if self.index + lens > len(self.string):=0D
+ lens =3D len(self.string) - self.index=0D
+ return self.string[self.index: self.index + lens]=0D
+ except Exception:=0D
+ return ''=0D
+=0D
+ def isLast(self):=0D
+ return self.index =3D=3D len(self.string)=0D
+=0D
+ def moveNext(self, len=3D1):=0D
+ self.index +=3D len=0D
+=0D
+ def skipSpace(self):=0D
+ while not self.isLast():=0D
+ if self.getCurr() in ' \t':=0D
+ self.moveNext()=0D
+ else:=0D
+ return=0D
+=0D
+ def normNumber(self, val):=0D
+ return True if val else False=0D
+=0D
+ def getNumber(self, var):=0D
+ var =3D var.strip()=0D
+ if re.match('^0x[a-fA-F0-9]+$', var):=0D
+ value =3D int(var, 16)=0D
+ elif re.match('^[+-]?\\d+$', var):=0D
+ value =3D int(var, 10)=0D
+ else:=0D
+ value =3D None=0D
+ return value=0D
+=0D
+ def parseValue(self):=0D
+ self.skipSpace()=0D
+ var =3D ''=0D
+ while not self.isLast():=0D
+ char =3D self.getCurr()=0D
+ if re.match('^[\\w.]', char):=0D
+ var +=3D char=0D
+ self.moveNext()=0D
+ else:=0D
+ break=0D
+ val =3D self.getNumber(var)=0D
+ if val is None:=0D
+ value =3D var=0D
+ else:=0D
+ value =3D "%d" % val=0D
+ return value=0D
+=0D
+ def parseSingleOp(self):=0D
+ self.skipSpace()=0D
+ if re.match('^NOT\\W', self.getCurr(-1)):=0D
+ self.moveNext(3)=0D
+ op =3D self.parseBrace()=0D
+ val =3D self.getNumber(op)=0D
+ if val is None:=0D
+ self.errExit("'%s' is not a number" % op)=0D
+ return "%d" % (not self.normNumber(int(op)))=0D
+ else:=0D
+ return self.parseValue()=0D
+=0D
+ def parseBrace(self):=0D
+ self.skipSpace()=0D
+ char =3D self.getCurr()=0D
+ if char =3D=3D '(':=0D
+ self.moveNext()=0D
+ value =3D self.parseExpr()=0D
+ self.skipSpace()=0D
+ if self.getCurr() !=3D ')':=0D
+ self.errExit("Expecting closing brace or operator")=0D
+ self.moveNext()=0D
+ return value=0D
+ else:=0D
+ value =3D self.parseSingleOp()=0D
+ return value=0D
+=0D
+ def parseCompare(self):=0D
+ value =3D self.parseBrace()=0D
+ while True:=0D
+ self.skipSpace()=0D
+ char =3D self.getCurr()=0D
+ if char in ['<', '>']:=0D
+ self.moveNext()=0D
+ next =3D self.getCurr()=0D
+ if next =3D=3D '=3D':=0D
+ op =3D char + next=0D
+ self.moveNext()=0D
+ else:=0D
+ op =3D char=0D
+ result =3D self.parseBrace()=0D
+ test =3D self.getNonNumber(result, value)=0D
+ if test is None:=0D
+ value =3D "%d" % self.normNumber(eval(value + op + res=
ult))=0D
+ else:=0D
+ self.errExit("'%s' is not a valid number for comparisi=
on"=0D
+ % test)=0D
+ elif char in ['=3D', '!']:=0D
+ op =3D self.getCurr(2)=0D
+ if op in ['=3D=3D', '!=3D']:=0D
+ self.moveNext(2)=0D
+ result =3D self.parseBrace()=0D
+ test =3D self.getNonNumber(result, value)=0D
+ if test is None:=0D
+ value =3D "%d" % self.normNumber((eval(value + op=
=0D
+ + result)))=0D
+ else:=0D
+ value =3D "%d" % self.normNumber(eval("'" + value =
+=0D
+ "'" + op + "'"=
+=0D
+ result + "'"))=
=0D
+ else:=0D
+ break=0D
+ else:=0D
+ break=0D
+ return value=0D
+=0D
+ def parseAnd(self):=0D
+ value =3D self.parseCompare()=0D
+ while True:=0D
+ self.skipSpace()=0D
+ if re.match('^AND\\W', self.getCurr(-1)):=0D
+ self.moveNext(3)=0D
+ result =3D self.parseCompare()=0D
+ test =3D self.getNonNumber(result, value)=0D
+ if test is None:=0D
+ value =3D "%d" % self.normNumber(int(value) & int(resu=
lt))=0D
+ else:=0D
+ self.errExit("'%s' is not a valid op number for AND" %=
=0D
+ test)=0D
+ else:=0D
+ break=0D
+ return value=0D
+=0D
+ def parseOrXor(self):=0D
+ value =3D self.parseAnd()=0D
+ op =3D None=0D
+ while True:=0D
+ self.skipSpace()=0D
+ op =3D None=0D
+ if re.match('^XOR\\W', self.getCurr(-1)):=0D
+ self.moveNext(3)=0D
+ op =3D '^'=0D
+ elif re.match('^OR\\W', self.getCurr(-1)):=0D
+ self.moveNext(2)=0D
+ op =3D '|'=0D
+ else:=0D
+ break=0D
+ if op:=0D
+ result =3D self.parseAnd()=0D
+ test =3D self.getNonNumber(result, value)=0D
+ if test is None:=0D
+ value =3D "%d" % self.normNumber(eval(value + op + res=
ult))=0D
+ else:=0D
+ self.errExit("'%s' is not a valid op number for XOR/OR=
" %=0D
+ test)=0D
+ return value=0D
+=0D
+ def parseExpr(self):=0D
+ return self.parseOrXor()=0D
+=0D
+ def getResult(self):=0D
+ value =3D self.parseExpr()=0D
+ self.skipSpace()=0D
+ if not self.isLast():=0D
+ self.errExit("Unexpected character found '%s'" % self.getCurr(=
))=0D
+ test =3D self.getNumber(value)=0D
+ if test is None:=0D
+ self.errExit("Result '%s' is not a number" % value)=0D
+ return int(value)=0D
+=0D
+ def evaluateExpress(self, Expr):=0D
+ self.index =3D 0=0D
+ self.string =3D Expr=0D
+ if self.getResult():=0D
+ Result =3D True=0D
+ else:=0D
+ Result =3D False=0D
+ return Result=0D
+=0D
+=0D
+class CFspBsf2Dsc:=0D
+=0D
+ def __init__(self, bsf_file):=0D
+ self.cfg_list =3D CFspBsf2Dsc.parse_bsf(bsf_file)=0D
+=0D
+ def get_dsc_lines(self):=0D
+ return CFspBsf2Dsc.generate_dsc(self.cfg_list)=0D
+=0D
+ def save_dsc(self, dsc_file):=0D
+ return CFspBsf2Dsc.generate_dsc(self.cfg_list, dsc_file)=0D
+=0D
+ @staticmethod=0D
+ def parse_bsf(bsf_file):=0D
+=0D
+ fd =3D open(bsf_file, 'r')=0D
+ bsf_txt =3D fd.read()=0D
+ fd.close()=0D
+=0D
+ find_list =3D []=0D
+ regex =3D re.compile(r'\s+Find\s+"(.*?)"(.*?)^\s+(\$(.*?)|Skip)\s+=
',=0D
+ re.S | re.MULTILINE)=0D
+ for match in regex.finditer(bsf_txt):=0D
+ find =3D match.group(1)=0D
+ name =3D match.group(3)=0D
+ line =3D bsf_txt[:match.end()].count("\n")=0D
+ find_list.append((name, find, line))=0D
+=0D
+ idx =3D 0=0D
+ count =3D 0=0D
+ prefix =3D ''=0D
+ chk_dict =3D {}=0D
+ cfg_list =3D []=0D
+ cfg_temp =3D {'find': '', 'cname': '', 'length': 0, 'value': '0',=
=0D
+ 'type': 'Reserved',=0D
+ 'embed': '', 'page': '', 'option': '', 'instance': 0}=
=0D
+ regex =3D re.compile(=0D
+ r'^\s+(\$(.*?)|Skip)\s+(\d+)\s+bytes(\s+\$_DEFAULT_\s'=0D
+ r'+=3D\s+(.+?))?$', re.S |=0D
+ re.MULTILINE)=0D
+=0D
+ for match in regex.finditer(bsf_txt):=0D
+ dlen =3D int(match.group(3))=0D
+ if match.group(1) =3D=3D 'Skip':=0D
+ key =3D 'gPlatformFspPkgTokenSpaceGuid_BsfSkip%d' % idx=0D
+ val =3D ', '.join(['%02X' % ord(i) for i in '\x00' * dlen]=
)=0D
+ idx +=3D 1=0D
+ option =3D '$SKIP'=0D
+ else:=0D
+ key =3D match.group(2)=0D
+ val =3D match.group(5)=0D
+ option =3D ''=0D
+=0D
+ cfg_item =3D dict(cfg_temp)=0D
+ line =3D bsf_txt[:match.end()].count("\n")=0D
+ finds =3D [i for i in find_list if line >=3D i[2]]=0D
+ if len(finds) > 0:=0D
+ prefix =3D finds[0][1]=0D
+ cfg_item['embed'] =3D '%s:TAG_%03X:START' % \=0D
+ (prefix, ord(prefix[-1]))=0D
+ cfg_item['find'] =3D prefix=0D
+ cfg_item['cname'] =3D 'Signature'=0D
+ cfg_item['length'] =3D len(finds[0][1])=0D
+ str2byte =3D Str2Bytes("'" + finds[0][1] + "'",=0D
+ len(finds[0][1]))=0D
+ cfg_item['value'] =3D '0x%X' % Bytes2Val(str2byte)=0D
+=0D
+ cfg_list.append(dict(cfg_item))=0D
+ cfg_item =3D dict(cfg_temp)=0D
+ find_list.pop(0)=0D
+ count =3D 0=0D
+=0D
+ cfg_item['cname'] =3D key=0D
+ cfg_item['length'] =3D dlen=0D
+ cfg_item['value'] =3D val=0D
+ cfg_item['option'] =3D option=0D
+=0D
+ if key not in chk_dict.keys():=0D
+ chk_dict[key] =3D 0=0D
+ else:=0D
+ chk_dict[key] +=3D 1=0D
+ cfg_item['instance'] =3D chk_dict[key]=0D
+=0D
+ cfg_list.append(cfg_item)=0D
+ count +=3D 1=0D
+=0D
+ if prefix:=0D
+ cfg_item =3D dict(cfg_temp)=0D
+ cfg_item['cname'] =3D 'Dummy'=0D
+ cfg_item['embed'] =3D '%s:%03X:END' % (prefix, ord(prefix[-1])=
)=0D
+ cfg_list.append(cfg_item)=0D
+=0D
+ option_dict =3D {}=0D
+ selreg =3D re.compile(=0D
+ r'\s+Selection\s*(.+?)\s*,\s*"(.*?)"$', re.S |=0D
+ re.MULTILINE)=0D
+ regex =3D re.compile(=0D
+ r'^List\s&(.+?)$(.+?)^EndList$', re.S | re.MULTILINE)=0D
+ for match in regex.finditer(bsf_txt):=0D
+ key =3D match.group(1)=0D
+ option_dict[key] =3D []=0D
+ for select in selreg.finditer(match.group(2)):=0D
+ option_dict[key].append(=0D
+ (int(select.group(1), 0), select.group(2)))=0D
+=0D
+ chk_dict =3D {}=0D
+ pagereg =3D re.compile(=0D
+ r'^Page\s"(.*?)"$(.+?)^EndPage$', re.S | re.MULTILINE)=0D
+ for match in pagereg.finditer(bsf_txt):=0D
+ page =3D match.group(1)=0D
+ for line in match.group(2).splitlines():=0D
+ match =3D re.match(=0D
+ r'\s+(Combo|EditNum)\s\$(.+?),\s"(.*?)",\s(.+?),$', li=
ne)=0D
+ if match:=0D
+ cname =3D match.group(2)=0D
+ if cname not in chk_dict.keys():=0D
+ chk_dict[cname] =3D 0=0D
+ else:=0D
+ chk_dict[cname] +=3D 1=0D
+ instance =3D chk_dict[cname]=0D
+ cfg_idxs =3D [i for i, j in enumerate(cfg_list)=0D
+ if j['cname'] =3D=3D cname and=0D
+ j['instance'] =3D=3D instance]=0D
+ if len(cfg_idxs) !=3D 1:=0D
+ raise Exception(=0D
+ "Multiple CFG item '%s' found !" % cname)=0D
+ cfg_item =3D cfg_list[cfg_idxs[0]]=0D
+ cfg_item['page'] =3D page=0D
+ cfg_item['type'] =3D match.group(1)=0D
+ cfg_item['prompt'] =3D match.group(3)=0D
+ cfg_item['range'] =3D None=0D
+ if cfg_item['type'] =3D=3D 'Combo':=0D
+ cfg_item['option'] =3D option_dict[match.group(4)[=
1:]]=0D
+ elif cfg_item['type'] =3D=3D 'EditNum':=0D
+ cfg_item['option'] =3D match.group(4)=0D
+ match =3D re.match(r'\s+ Help\s"(.*?)"$', line)=0D
+ if match:=0D
+ cfg_item['help'] =3D match.group(1)=0D
+=0D
+ match =3D re.match(r'\s+"Valid\srange:\s(.*)"$', line)=0D
+ if match:=0D
+ parts =3D match.group(1).split()=0D
+ cfg_item['option'] =3D (=0D
+ (int(parts[0], 0), int(parts[2], 0),=0D
+ cfg_item['option']))=0D
+=0D
+ return cfg_list=0D
+=0D
+ @staticmethod=0D
+ def generate_dsc(option_list, dsc_file=3DNone):=0D
+ dsc_lines =3D []=0D
+ header =3D '%s' % (__copyright_dsc__ % date.today().year)=0D
+ dsc_lines.extend(header.splitlines())=0D
+=0D
+ pages =3D []=0D
+ for cfg_item in option_list:=0D
+ if cfg_item['page'] and (cfg_item['page'] not in pages):=0D
+ pages.append(cfg_item['page'])=0D
+=0D
+ page_id =3D 0=0D
+ for page in pages:=0D
+ dsc_lines.append(' # !BSF PAGES:{PG%02X::"%s"}' % (page_id, p=
age))=0D
+ page_id +=3D 1=0D
+ dsc_lines.append('')=0D
+=0D
+ last_page =3D ''=0D
+ for option in option_list:=0D
+ dsc_lines.append('')=0D
+ default =3D option['value']=0D
+ pos =3D option['cname'].find('_')=0D
+ name =3D option['cname'][pos + 1:]=0D
+=0D
+ if option['find']:=0D
+ dsc_lines.append(' # !BSF FIND:{%s}' % option['find'])=0D
+ dsc_lines.append('')=0D
+=0D
+ if option['instance'] > 0:=0D
+ name =3D name + '_%s' % option['instance']=0D
+=0D
+ if option['embed']:=0D
+ dsc_lines.append(' # !HDR EMBED:{%s}' % option['embed'])=
=0D
+=0D
+ if option['type'] =3D=3D 'Reserved':=0D
+ dsc_lines.append(' # !BSF NAME:{Reserved} TYPE:{Reserved}=
')=0D
+ if option['option'] =3D=3D '$SKIP':=0D
+ dsc_lines.append(' # !BSF OPTION:{$SKIP}')=0D
+ else:=0D
+ prompt =3D option['prompt']=0D
+=0D
+ if last_page !=3D option['page']:=0D
+ last_page =3D option['page']=0D
+ dsc_lines.append(' # !BSF PAGE:{PG%02X}' %=0D
+ (pages.index(option['page'])))=0D
+=0D
+ if option['type'] =3D=3D 'Combo':=0D
+ dsc_lines.append(' # !BSF NAME:{%s} TYPE:{%s}' %=0D
+ (prompt, option['type']))=0D
+ ops =3D []=0D
+ for val, text in option['option']:=0D
+ ops.append('0x%x:%s' % (val, text))=0D
+ dsc_lines.append(' # !BSF OPTION:{%s}' % (', '.join(o=
ps)))=0D
+ elif option['type'] =3D=3D 'EditNum':=0D
+ cfg_len =3D option['length']=0D
+ if ',' in default and cfg_len > 8:=0D
+ dsc_lines.append(' # !BSF NAME:{%s} TYPE:{Table}'=
%=0D
+ (prompt))=0D
+ if cfg_len > 16:=0D
+ cfg_len =3D 16=0D
+ ops =3D []=0D
+ for i in range(cfg_len):=0D
+ ops.append('%X:1:HEX' % i)=0D
+ dsc_lines.append(' # !BSF OPTION:{%s}' %=0D
+ (', '.join(ops)))=0D
+ else:=0D
+ dsc_lines.append(=0D
+ ' # !BSF NAME:{%s} TYPE:{%s, %s, (0x%X, 0x%X)=
}' %=0D
+ (prompt, option['type'], option['option'][2],=
=0D
+ option['option'][0], option['option'][1]))=0D
+ dsc_lines.append(' # !BSF HELP:{%s}' % option['help'])=0D
+=0D
+ if ',' in default:=0D
+ default =3D '{%s}' % default=0D
+ dsc_lines.append(' gCfgData.%-30s | * | 0x%04X | %s' %=0D
+ (name, option['length'], default))=0D
+=0D
+ if dsc_file:=0D
+ fd =3D open(dsc_file, 'w')=0D
+ fd.write('\n'.join(dsc_lines))=0D
+ fd.close()=0D
+=0D
+ return dsc_lines=0D
+=0D
+=0D
+class CGenCfgData:=0D
+ def __init__(self, Mode=3D''):=0D
+ self.Debug =3D False=0D
+ self.Error =3D ''=0D
+ self.ReleaseMode =3D True=0D
+ self.Mode =3D Mode=0D
+ self._GlobalDataDef =3D """=0D
+GlobalDataDef=0D
+ SKUID =3D 0, "DEFAULT"=0D
+EndGlobalData=0D
+=0D
+"""=0D
+ self._BuidinOptionTxt =3D """=0D
+List &EN_DIS=0D
+ Selection 0x1 , "Enabled"=0D
+ Selection 0x0 , "Disabled"=0D
+EndList=0D
+=0D
+"""=0D
+ self._StructType =3D ['UINT8', 'UINT16', 'UINT32', 'UINT64']=0D
+ self._BsfKeyList =3D ['FIND', 'NAME', 'HELP', 'TYPE', 'PAGE', 'PAG=
ES',=0D
+ 'BLOCK', 'OPTION', 'CONDITION', 'ORDER', 'MARK=
ER',=0D
+ 'SUBT']=0D
+ self._HdrKeyList =3D ['HEADER', 'STRUCT', 'EMBED', 'COMMENT']=0D
+ self._BuidinOption =3D {'$EN_DIS': 'EN_DIS'}=0D
+=0D
+ self._MacroDict =3D {}=0D
+ self._VarDict =3D {}=0D
+ self._PcdsDict =3D {}=0D
+ self._CfgBlkDict =3D {}=0D
+ self._CfgPageDict =3D {}=0D
+ self._CfgOptsDict =3D {}=0D
+ self._BsfTempDict =3D {}=0D
+ self._CfgItemList =3D []=0D
+ self._DscLines =3D []=0D
+ self._DscFile =3D ''=0D
+ self._CfgPageTree =3D {}=0D
+=0D
+ self._MapVer =3D 0=0D
+ self._MinCfgTagId =3D 0x100=0D
+=0D
+ def ParseMacros(self, MacroDefStr):=0D
+ # ['-DABC=3D1', '-D', 'CFG_DEBUG=3D1', '-D', 'CFG_OUTDIR=3DBuild']=
=0D
+ self._MacroDict =3D {}=0D
+ IsExpression =3D False=0D
+ for Macro in MacroDefStr:=0D
+ if Macro.startswith('-D'):=0D
+ IsExpression =3D True=0D
+ if len(Macro) > 2:=0D
+ Macro =3D Macro[2:]=0D
+ else:=0D
+ continue=0D
+ if IsExpression:=0D
+ IsExpression =3D False=0D
+ Match =3D re.match("(\\w+)=3D(.+)", Macro)=0D
+ if Match:=0D
+ self._MacroDict[Match.group(1)] =3D Match.group(2)=0D
+ else:=0D
+ Match =3D re.match("(\\w+)", Macro)=0D
+ if Match:=0D
+ self._MacroDict[Match.group(1)] =3D ''=0D
+ if len(self._MacroDict) =3D=3D 0:=0D
+ Error =3D 1=0D
+ else:=0D
+ Error =3D 0=0D
+ if self.Debug:=0D
+ print("INFO : Macro dictionary:")=0D
+ for Each in self._MacroDict:=0D
+ print(" $(%s) =3D [ %s ]" % (Each,=0D
+ self._MacroDict[Each]=
))=0D
+ return Error=0D
+=0D
+ def EvaulateIfdef(self, Macro):=0D
+ Result =3D Macro in self._MacroDict=0D
+ if self.Debug:=0D
+ print("INFO : Eval Ifdef [%s] : %s" % (Macro, Result))=0D
+ return Result=0D
+=0D
+ def ExpandMacros(self, Input, Preserve=3DFalse):=0D
+ Line =3D Input=0D
+ Match =3D re.findall("\\$\\(\\w+\\)", Input)=0D
+ if Match:=0D
+ for Each in Match:=0D
+ Variable =3D Each[2:-1]=0D
+ if Variable in self._MacroDict:=0D
+ Line =3D Line.replace(Each, self._MacroDict[Variable])=
=0D
+ else:=0D
+ if self.Debug:=0D
+ print("WARN : %s is not defined" % Each)=0D
+ if not Preserve:=0D
+ Line =3D Line.replace(Each, Each[2:-1])=0D
+ return Line=0D
+=0D
+ def ExpandPcds(self, Input):=0D
+ Line =3D Input=0D
+ Match =3D re.findall("(\\w+\\.\\w+)", Input)=0D
+ if Match:=0D
+ for PcdName in Match:=0D
+ if PcdName in self._PcdsDict:=0D
+ Line =3D Line.replace(PcdName, self._PcdsDict[PcdName]=
)=0D
+ else:=0D
+ if self.Debug:=0D
+ print("WARN : %s is not defined" % PcdName)=0D
+ return Line=0D
+=0D
+ def EvaluateExpress(self, Expr):=0D
+ ExpExpr =3D self.ExpandPcds(Expr)=0D
+ ExpExpr =3D self.ExpandMacros(ExpExpr)=0D
+ LogExpr =3D CLogicalExpression()=0D
+ Result =3D LogExpr.evaluateExpress(ExpExpr)=0D
+ if self.Debug:=0D
+ print("INFO : Eval Express [%s] : %s" % (Expr, Result))=0D
+ return Result=0D
+=0D
+ def ValueToByteArray(self, ValueStr, Length):=0D
+ Match =3D re.match("\\{\\s*FILE:(.+)\\}", ValueStr)=0D
+ if Match:=0D
+ FileList =3D Match.group(1).split(',')=0D
+ Result =3D bytearray()=0D
+ for File in FileList:=0D
+ File =3D File.strip()=0D
+ BinPath =3D os.path.join(os.path.dirname(self._DscFile), F=
ile)=0D
+ Result.extend(bytearray(open(BinPath, 'rb').read()))=0D
+ else:=0D
+ try:=0D
+ Result =3D bytearray(self.ValueToList(ValueStr, Length))=0D
+ except ValueError:=0D
+ raise Exception("Bytes in '%s' must be in range 0~255 !" %=
=0D
+ ValueStr)=0D
+ if len(Result) < Length:=0D
+ Result.extend(b'\x00' * (Length - len(Result)))=0D
+ elif len(Result) > Length:=0D
+ raise Exception("Value '%s' is too big to fit into %d bytes !"=
%=0D
+ (ValueStr, Length))=0D
+=0D
+ return Result[:Length]=0D
+=0D
+ def ValueToList(self, ValueStr, Length):=0D
+ if ValueStr[0] =3D=3D '{':=0D
+ Result =3D []=0D
+ BinList =3D ValueStr[1:-1].split(',')=0D
+ InBitField =3D False=0D
+ LastInBitField =3D False=0D
+ Value =3D 0=0D
+ BitLen =3D 0=0D
+ for Element in BinList:=0D
+ InBitField =3D False=0D
+ Each =3D Element.strip()=0D
+ if len(Each) =3D=3D 0:=0D
+ pass=0D
+ else:=0D
+ if Each[0] in ['"', "'"]:=0D
+ Result.extend(list(bytearray(Each[1:-1], 'utf-8'))=
)=0D
+ elif ':' in Each:=0D
+ Match =3D re.match("(.+):(\\d+)b", Each)=0D
+ if Match is None:=0D
+ raise Exception("Invald value list format '%s'=
!"=0D
+ % Each)=0D
+ InBitField =3D True=0D
+ CurrentBitLen =3D int(Match.group(2))=0D
+ CurrentValue =3D ((self.EvaluateExpress(Match.grou=
p(1))=0D
+ & (1 << CurrentBitLen) - 1)) << B=
itLen=0D
+ else:=0D
+ Result.append(self.EvaluateExpress(Each.strip()))=
=0D
+ if InBitField:=0D
+ Value +=3D CurrentValue=0D
+ BitLen +=3D CurrentBitLen=0D
+ if LastInBitField and ((not InBitField) or (Element =3D=3D=
=0D
+ BinList[-1])):=
=0D
+ if BitLen % 8 !=3D 0:=0D
+ raise Exception("Invald bit field length!")=0D
+ Result.extend(Val2Bytes(Value, BitLen // 8))=0D
+ Value =3D 0=0D
+ BitLen =3D 0=0D
+ LastInBitField =3D InBitField=0D
+ elif ValueStr.startswith("'") and ValueStr.endswith("'"):=0D
+ Result =3D Str2Bytes(ValueStr, Length)=0D
+ elif ValueStr.startswith('"') and ValueStr.endswith('"'):=0D
+ Result =3D Str2Bytes(ValueStr, Length)=0D
+ else:=0D
+ Result =3D Val2Bytes(self.EvaluateExpress(ValueStr), Length)=0D
+ return Result=0D
+=0D
+ def FormatDeltaValue(self, ConfigDict):=0D
+ ValStr =3D ConfigDict['value']=0D
+ if ValStr[0] =3D=3D "'":=0D
+ # Remove padding \x00 in the value string=0D
+ ValStr =3D "'%s'" % ValStr[1:-1].rstrip('\x00')=0D
+=0D
+ Struct =3D ConfigDict['struct']=0D
+ if Struct in self._StructType:=0D
+ # Format the array using its struct type=0D
+ Unit =3D int(Struct[4:]) // 8=0D
+ Value =3D Array2Val(ConfigDict['value'])=0D
+ Loop =3D ConfigDict['length'] // Unit=0D
+ Values =3D []=0D
+ for Each in range(Loop):=0D
+ Values.append(Value & ((1 << (Unit * 8)) - 1))=0D
+ Value =3D Value >> (Unit * 8)=0D
+ ValStr =3D '{ ' + ', '.join([('0x%%0%dX' % (Unit * 2)) %=0D
+ x for x in Values]) + ' }'=0D
+=0D
+ return ValStr=0D
+=0D
+ def FormatListValue(self, ConfigDict):=0D
+ Struct =3D ConfigDict['struct']=0D
+ if Struct not in self._StructType:=0D
+ return=0D
+=0D
+ DataList =3D self.ValueToList(ConfigDict['value'], ConfigDict['len=
gth'])=0D
+ Unit =3D int(Struct[4:]) // 8=0D
+ if int(ConfigDict['length']) !=3D Unit * len(DataList):=0D
+ # Fallback to byte array=0D
+ Unit =3D 1=0D
+ if int(ConfigDict['length']) !=3D len(DataList):=0D
+ raise Exception("Array size is not proper for '%s' !" %=0D
+ ConfigDict['cname'])=0D
+=0D
+ ByteArray =3D []=0D
+ for Value in DataList:=0D
+ for Loop in range(Unit):=0D
+ ByteArray.append("0x%02X" % (Value & 0xFF))=0D
+ Value =3D Value >> 8=0D
+ NewValue =3D '{' + ','.join(ByteArray) + '}'=0D
+ ConfigDict['value'] =3D NewValue=0D
+=0D
+ return ""=0D
+=0D
+ def GetOrderNumber(self, Offset, Order, BitOff=3D0):=0D
+ if isinstance(Order, int):=0D
+ if Order =3D=3D -1:=0D
+ Order =3D Offset << 16=0D
+ else:=0D
+ (Major, Minor) =3D Order.split('.')=0D
+ Order =3D (int(Major, 16) << 16) + ((int(Minor, 16) & 0xFF) <<=
8)=0D
+ return Order + (BitOff & 0xFF)=0D
+=0D
+ def SubtituteLine(self, Line, Args):=0D
+ Args =3D Args.strip()=0D
+ Vars =3D Args.split(':')=0D
+ Line =3D self.ExpandMacros(Line, True)=0D
+ for Idx in range(len(Vars)-1, 0, -1):=0D
+ Line =3D Line.replace('$(%d)' % Idx, Vars[Idx].strip())=0D
+ return Line=0D
+=0D
+ def CfgDuplicationCheck(self, CfgDict, Name):=0D
+ if not self.Debug:=0D
+ return=0D
+=0D
+ if Name =3D=3D 'Dummy':=0D
+ return=0D
+=0D
+ if Name not in CfgDict:=0D
+ CfgDict[Name] =3D 1=0D
+ else:=0D
+ print("WARNING: Duplicated item found '%s' !" %=0D
+ CfgDict['cname'])=0D
+=0D
+ def AddBsfChildPage(self, Child, Parent=3D'root'):=0D
+ def AddBsfChildPageRecursive(PageTree, Parent, Child):=0D
+ Key =3D next(iter(PageTree))=0D
+ if Parent =3D=3D Key:=0D
+ PageTree[Key].append({Child: []})=0D
+ return True=0D
+ else:=0D
+ Result =3D False=0D
+ for Each in PageTree[Key]:=0D
+ if AddBsfChildPageRecursive(Each, Parent, Child):=0D
+ Result =3D True=0D
+ break=0D
+ return Result=0D
+=0D
+ return AddBsfChildPageRecursive(self._CfgPageTree, Parent, Child)=
=0D
+=0D
+ def ParseDscFile(self, DscFile):=0D
+ self._DscLines =3D []=0D
+ self._CfgItemList =3D []=0D
+ self._CfgPageDict =3D {}=0D
+ self._CfgBlkDict =3D {}=0D
+ self._BsfTempDict =3D {}=0D
+ self._CfgPageTree =3D {'root': []}=0D
+=0D
+ CfgDict =3D {}=0D
+=0D
+ SectionNameList =3D ["Defines".lower(), "PcdsFeatureFlag".lower(),=
=0D
+ "PcdsDynamicVpd.Tmp".lower(),=0D
+ "PcdsDynamicVpd.Upd".lower()]=0D
+=0D
+ IsDefSect =3D False=0D
+ IsPcdSect =3D False=0D
+ IsUpdSect =3D False=0D
+ IsTmpSect =3D False=0D
+=0D
+ TemplateName =3D ''=0D
+=0D
+ IfStack =3D []=0D
+ ElifStack =3D []=0D
+ Error =3D 0=0D
+ ConfigDict =3D {}=0D
+=0D
+ if type(DscFile) is list:=0D
+ # it is DSC lines already=0D
+ DscLines =3D DscFile=0D
+ self._DscFile =3D '.'=0D
+ else:=0D
+ DscFd =3D open(DscFile, "r")=0D
+ DscLines =3D DscFd.readlines()=0D
+ DscFd.close()=0D
+ self._DscFile =3D DscFile=0D
+=0D
+ BsfRegExp =3D re.compile("(%s):{(.+?)}(?:$|\\s+)" % '|'.=0D
+ join(self._BsfKeyList))=0D
+ HdrRegExp =3D re.compile("(%s):{(.+?)}" % '|'.join(self._HdrKeyLis=
t))=0D
+ CfgRegExp =3D re.compile("^([_a-zA-Z0-9]+)\\s*\\|\\s*\=0D
+(0x[0-9A-F]+|\\*)\\s*\\|\\s*(\\d+|0x[0-9a-fA-F]+)\\s*\\|\\s*(.+)")=0D
+ TksRegExp =3D re.compile("^(g[_a-zA-Z0-9]+\\.)(.+)")=0D
+ SkipLines =3D 0=0D
+ while len(DscLines):=0D
+ DscLine =3D DscLines.pop(0).strip()=0D
+ if SkipLines =3D=3D 0:=0D
+ self._DscLines.append(DscLine)=0D
+ else:=0D
+ SkipLines =3D SkipLines - 1=0D
+ if len(DscLine) =3D=3D 0:=0D
+ continue=0D
+=0D
+ Handle =3D False=0D
+ Match =3D re.match("^\\[(.+)\\]", DscLine)=0D
+ if Match is not None:=0D
+ IsDefSect =3D False=0D
+ IsPcdSect =3D False=0D
+ IsUpdSect =3D False=0D
+ IsTmpSect =3D False=0D
+ SectionName =3D Match.group(1).lower()=0D
+ if SectionName =3D=3D SectionNameList[0]:=0D
+ IsDefSect =3D True=0D
+ if SectionName =3D=3D SectionNameList[1]:=0D
+ IsPcdSect =3D True=0D
+ elif SectionName =3D=3D SectionNameList[2]:=0D
+ IsTmpSect =3D True=0D
+ elif SectionName =3D=3D SectionNameList[3]:=0D
+ ConfigDict =3D {=0D
+ 'header': 'ON',=0D
+ 'page': '',=0D
+ 'name': '',=0D
+ 'find': '',=0D
+ 'struct': '',=0D
+ 'embed': '',=0D
+ 'marker': '',=0D
+ 'option': '',=0D
+ 'comment': '',=0D
+ 'condition': '',=0D
+ 'order': -1,=0D
+ 'subreg': []=0D
+ }=0D
+ IsUpdSect =3D True=0D
+ Offset =3D 0=0D
+ else:=0D
+ if IsDefSect or IsPcdSect or IsUpdSect or IsTmpSect:=0D
+ Match =3D False if DscLine[0] !=3D '!' else True=0D
+ if Match:=0D
+ Match =3D re.match("^!(else|endif|ifdef|ifndef|if|=
elseif\=0D
+|include)\\s*(.+)?$", DscLine.split("#")[0])=0D
+ Keyword =3D Match.group(1) if Match else ''=0D
+ Remaining =3D Match.group(2) if Match else ''=0D
+ Remaining =3D '' if Remaining is None else Remaining.s=
trip()=0D
+=0D
+ if Keyword in ['if', 'elseif', 'ifdef', 'ifndef', 'inc=
lude'=0D
+ ] and not Remaining:=0D
+ raise Exception("ERROR: Expression is expected aft=
er \=0D
+'!if' or !elseif' for line '%s'" % DscLine)=0D
+=0D
+ if Keyword =3D=3D 'else':=0D
+ if IfStack:=0D
+ IfStack[-1] =3D not IfStack[-1]=0D
+ else:=0D
+ raise Exception("ERROR: No paired '!if' found =
for \=0D
+'!else' for line '%s'" % DscLine)=0D
+ elif Keyword =3D=3D 'endif':=0D
+ if IfStack:=0D
+ IfStack.pop()=0D
+ Level =3D ElifStack.pop()=0D
+ if Level > 0:=0D
+ del IfStack[-Level:]=0D
+ else:=0D
+ raise Exception("ERROR: No paired '!if' found =
for \=0D
+'!endif' for line '%s'" % DscLine)=0D
+ elif Keyword =3D=3D 'ifdef' or Keyword =3D=3D 'ifndef'=
:=0D
+ Result =3D self.EvaulateIfdef(Remaining)=0D
+ if Keyword =3D=3D 'ifndef':=0D
+ Result =3D not Result=0D
+ IfStack.append(Result)=0D
+ ElifStack.append(0)=0D
+ elif Keyword =3D=3D 'if' or Keyword =3D=3D 'elseif':=0D
+ Result =3D self.EvaluateExpress(Remaining)=0D
+ if Keyword =3D=3D "if":=0D
+ ElifStack.append(0)=0D
+ IfStack.append(Result)=0D
+ else: # elseif=0D
+ if IfStack:=0D
+ IfStack[-1] =3D not IfStack[-1]=0D
+ IfStack.append(Result)=0D
+ ElifStack[-1] =3D ElifStack[-1] + 1=0D
+ else:=0D
+ raise Exception("ERROR: No paired '!if' fo=
und for \=0D
+'!elif' for line '%s'" % DscLine)=0D
+ else:=0D
+ if IfStack:=0D
+ Handle =3D reduce(lambda x, y: x and y, IfStac=
k)=0D
+ else:=0D
+ Handle =3D True=0D
+ if Handle:=0D
+ if Keyword =3D=3D 'include':=0D
+ Remaining =3D self.ExpandMacros(Remaining)=
=0D
+ # Relative to DSC filepath=0D
+ IncludeFilePath =3D os.path.join(=0D
+ os.path.dirname(self._DscFile), Remain=
ing)=0D
+ if not os.path.exists(IncludeFilePath):=0D
+ # Relative to repository to find \=0D
+ # dsc in common platform=0D
+ IncludeFilePath =3D os.path.join(=0D
+ os.path.dirname(self._DscFile), ".=
.",=0D
+ Remaining)=0D
+=0D
+ try:=0D
+ IncludeDsc =3D open(IncludeFilePath, "=
r")=0D
+ except Exception:=0D
+ raise Exception("ERROR: Cannot open \=
=0D
+file '%s'." % IncludeFilePath)=0D
+ NewDscLines =3D IncludeDsc.readlines()=0D
+ IncludeDsc.close()=0D
+ DscLines =3D NewDscLines + DscLines=0D
+ del self._DscLines[-1]=0D
+ else:=0D
+ if DscLine.startswith('!'):=0D
+ raise Exception("ERROR: Unrecoginized =
\=0D
+directive for line '%s'" % DscLine)=0D
+=0D
+ if not Handle:=0D
+ del self._DscLines[-1]=0D
+ continue=0D
+=0D
+ if IsDefSect:=0D
+ Match =3D re.match("^\\s*(?:DEFINE\\s+)*(\\w+)\\s*=3D\\s*(=
.+)",=0D
+ DscLine)=0D
+ if Match:=0D
+ self._MacroDict[Match.group(1)] =3D Match.group(2)=0D
+ if self.Debug:=0D
+ print("INFO : DEFINE %s =3D [ %s ]" % (Match.group=
(1),=0D
+ Match.group(2=
)))=0D
+=0D
+ elif IsPcdSect:=0D
+ Match =3D re.match("^\\s*([\\w\\.]+)\\s*\\|\\s*(\\w+)", Ds=
cLine)=0D
+ if Match:=0D
+ self._PcdsDict[Match.group(1)] =3D Match.group(2)=0D
+ if self.Debug:=0D
+ print("INFO : PCD %s =3D [ %s ]" % (Match.group(1)=
,=0D
+ Match.group(2)))=
=0D
+=0D
+ elif IsTmpSect:=0D
+ # !BSF DEFT:{GPIO_TMPL:START}=0D
+ Match =3D re.match("^\\s*#\\s+(!BSF)\\s+DEFT:{(.+?):\=0D
+(START|END)}", DscLine)=0D
+ if Match:=0D
+ if Match.group(3) =3D=3D 'START' and not TemplateName:=
=0D
+ TemplateName =3D Match.group(2).strip()=0D
+ self._BsfTempDict[TemplateName] =3D []=0D
+ if Match.group(3) =3D=3D 'END' and (=0D
+ TemplateName =3D=3D Match.group(2).strip()=0D
+ ) and TemplateName:=0D
+ TemplateName =3D ''=0D
+ else:=0D
+ if TemplateName:=0D
+ Match =3D re.match("^!include\\s*(.+)?$", DscLine)=
=0D
+ if Match:=0D
+ continue=0D
+ self._BsfTempDict[TemplateName].append(DscLine)=0D
+=0D
+ else:=0D
+ Match =3D re.match("^\\s*#\\s+(!BSF|!HDR)\\s+(.+)", DscLin=
e)=0D
+ if Match:=0D
+ Remaining =3D Match.group(2)=0D
+ if Match.group(1) =3D=3D '!BSF':=0D
+ Result =3D BsfRegExp.findall(Remaining)=0D
+ if Result:=0D
+ for Each in Result:=0D
+ Key =3D Each[0]=0D
+ Remaining =3D Each[1]=0D
+=0D
+ if Key =3D=3D 'BLOCK':=0D
+ Match =3D re.match(=0D
+ "NAME:\"(.+)\"\\s*,\\s*\=0D
+VER:\"(.+)\"\\s*", Remaining)=0D
+ if Match:=0D
+ self._CfgBlkDict['name'] =3D \=0D
+ Match.gro=
up(1)=0D
+ self._CfgBlkDict['ver'] =3D Match.=
group(2=0D
+ =
)=0D
+=0D
+ elif Key =3D=3D 'SUBT':=0D
+ # GPIO_TMPL:1:2:3=0D
+ Remaining =3D Remaining.strip()=0D
+ Match =3D re.match("(\\w+)\\s*:", Rema=
ining)=0D
+ if Match:=0D
+ TemplateName =3D Match.group(1)=0D
+ for Line in self._BsfTempDict[=0D
+ TemplateName][::-1]:=0D
+ NewLine =3D self.SubtituteLine=
(=0D
+ Line, Remaining)=0D
+ DscLines.insert(0, NewLine)=0D
+ SkipLines +=3D 1=0D
+=0D
+ elif Key =3D=3D 'PAGES':=0D
+ # !BSF PAGES:{HSW:"Haswell System Agen=
t", \=0D
+ # LPT:"Lynx Point PCH"}=0D
+ PageList =3D Remaining.split(',')=0D
+ for Page in PageList:=0D
+ Page =3D Page.strip()=0D
+ Match =3D re.match('(\\w+):\=0D
+(\\w*:)?\\"(.+)\\"', Page)=0D
+ if Match:=0D
+ PageName =3D Match.group(1)=0D
+ ParentName =3D Match.group(2)=
=0D
+ if not ParentName or \=0D
+ ParentName =3D=3D ':':=0D
+ ParentName =3D 'root'=0D
+ else:=0D
+ ParentName =3D ParentName[=
:-1]=0D
+ if not self.AddBsfChildPage(=0D
+ PageName, ParentName):=
=0D
+ raise Exception("Cannot fi=
nd \=0D
+parent page '%s'!" % ParentName)=0D
+ self._CfgPageDict[=0D
+ PageName] =3D Match.group(=
3)=0D
+ else:=0D
+ raise Exception("Invalid page =
\=0D
+definitions '%s'!" % Page)=0D
+=0D
+ elif Key in ['NAME', 'HELP', 'OPTION'=0D
+ ] and Remaining.startswith('+=
'):=0D
+ # Allow certain options to be extended=
\=0D
+ # to multiple lines=0D
+ ConfigDict[Key.lower()] +=3D Remaining=
[1:]=0D
+=0D
+ else:=0D
+ if Key =3D=3D 'NAME':=0D
+ Remaining =3D Remaining.strip()=0D
+ elif Key =3D=3D 'CONDITION':=0D
+ Remaining =3D self.ExpandMacros(=0D
+ Remaining.strip())=0D
+ ConfigDict[Key.lower()] =3D Remaining=
=0D
+ else:=0D
+ Match =3D HdrRegExp.match(Remaining)=0D
+ if Match:=0D
+ Key =3D Match.group(1)=0D
+ Remaining =3D Match.group(2)=0D
+ if Key =3D=3D 'EMBED':=0D
+ Parts =3D Remaining.split(':')=0D
+ Names =3D Parts[0].split(',')=0D
+ DummyDict =3D ConfigDict.copy()=0D
+ if len(Names) > 1:=0D
+ Remaining =3D Names[0] + ':' + ':'.joi=
n(=0D
+ Parts[1:])=0D
+ DummyDict['struct'] =3D Names[1]=0D
+ else:=0D
+ DummyDict['struct'] =3D Names[0]=0D
+ DummyDict['cname'] =3D 'Dummy'=0D
+ DummyDict['name'] =3D ''=0D
+ DummyDict['embed'] =3D Remaining=0D
+ DummyDict['offset'] =3D Offset=0D
+ DummyDict['length'] =3D 0=0D
+ DummyDict['value'] =3D '0'=0D
+ DummyDict['type'] =3D 'Reserved'=0D
+ DummyDict['help'] =3D ''=0D
+ DummyDict['subreg'] =3D []=0D
+ self._CfgItemList.append(DummyDict)=0D
+ else:=0D
+ ConfigDict[Key.lower()] =3D Remaining=0D
+ # Check CFG line=0D
+ # gCfgData.VariableName | * | 0x01 | 0x1=0D
+ Clear =3D False=0D
+=0D
+ Match =3D TksRegExp.match(DscLine)=0D
+ if Match:=0D
+ DscLine =3D 'gCfgData.%s' % Match.group(2)=0D
+=0D
+ if DscLine.startswith('gCfgData.'):=0D
+ Match =3D CfgRegExp.match(DscLine[9:])=0D
+ else:=0D
+ Match =3D None=0D
+ if Match:=0D
+ ConfigDict['space'] =3D 'gCfgData'=0D
+ ConfigDict['cname'] =3D Match.group(1)=0D
+ if Match.group(2) !=3D '*':=0D
+ Offset =3D int(Match.group(2), 16)=0D
+ ConfigDict['offset'] =3D Offset=0D
+ ConfigDict['order'] =3D self.GetOrderNumber(=0D
+ ConfigDict['offset'], ConfigDict['order'])=0D
+=0D
+ Value =3D Match.group(4).strip()=0D
+ if Match.group(3).startswith("0x"):=0D
+ Length =3D int(Match.group(3), 16)=0D
+ else:=0D
+ Length =3D int(Match.group(3))=0D
+=0D
+ Offset +=3D Length=0D
+=0D
+ ConfigDict['length'] =3D Length=0D
+ Match =3D re.match("\\$\\((\\w+)\\)", Value)=0D
+ if Match:=0D
+ if Match.group(1) in self._MacroDict:=0D
+ Value =3D self._MacroDict[Match.group(1)]=0D
+=0D
+ ConfigDict['value'] =3D Value=0D
+ if re.match("\\{\\s*FILE:(.+)\\}", Value):=0D
+ # Expand embedded binary file=0D
+ ValArray =3D self.ValueToByteArray(ConfigDict['val=
ue'],=0D
+ ConfigDict['lengt=
h'])=0D
+ NewValue =3D Bytes2Str(ValArray)=0D
+ self._DscLines[-1] =3D re.sub(r'(.*)(\{\s*FILE:.+\=
})',=0D
+ r'\1 %s' % NewValue,=0D
+ self._DscLines[-1])=0D
+ ConfigDict['value'] =3D NewValue=0D
+=0D
+ if ConfigDict['name'] =3D=3D '':=0D
+ # Clear BSF specific items=0D
+ ConfigDict['bsfname'] =3D ''=0D
+ ConfigDict['help'] =3D ''=0D
+ ConfigDict['type'] =3D ''=0D
+ ConfigDict['option'] =3D ''=0D
+=0D
+ self.CfgDuplicationCheck(CfgDict, ConfigDict['cname'])=
=0D
+ self._CfgItemList.append(ConfigDict.copy())=0D
+ Clear =3D True=0D
+=0D
+ else:=0D
+ # It could be a virtual item as below=0D
+ # !BSF FIELD:{SerialDebugPortAddress0:1}=0D
+ # or=0D
+ # @Bsf FIELD:{SerialDebugPortAddress0:1b}=0D
+ Match =3D re.match(r"^\s*#\s+(!BSF)\s+FIELD:{(.+)}", D=
scLine)=0D
+ if Match:=0D
+ BitFieldTxt =3D Match.group(2)=0D
+ Match =3D re.match("(.+):(\\d+)b([BWDQ])?", BitFie=
ldTxt)=0D
+ if not Match:=0D
+ raise Exception("Incorrect bit field \=0D
+format '%s' !" % BitFieldTxt)=0D
+ UnitBitLen =3D 1=0D
+ SubCfgDict =3D ConfigDict.copy()=0D
+ SubCfgDict['cname'] =3D Match.group(1)=0D
+ SubCfgDict['bitlength'] =3D int(=0D
+ Match.group(2)) * UnitBitLen=0D
+ if SubCfgDict['bitlength'] > 0:=0D
+ LastItem =3D self._CfgItemList[-1]=0D
+ if len(LastItem['subreg']) =3D=3D 0:=0D
+ SubOffset =3D 0=0D
+ else:=0D
+ SubOffset =3D \=0D
+ LastItem['subreg'][-1]['bitoffse=
t'] \=0D
+ + LastItem['subreg'][-1]['bitlen=
gth']=0D
+ if Match.group(3) =3D=3D 'B':=0D
+ SubCfgDict['bitunit'] =3D 1=0D
+ elif Match.group(3) =3D=3D 'W':=0D
+ SubCfgDict['bitunit'] =3D 2=0D
+ elif Match.group(3) =3D=3D 'Q':=0D
+ SubCfgDict['bitunit'] =3D 8=0D
+ else:=0D
+ SubCfgDict['bitunit'] =3D 4=0D
+ SubCfgDict['bitoffset'] =3D SubOffset=0D
+ SubCfgDict['order'] =3D self.GetOrderNumber(=0D
+ SubCfgDict['offset'], SubCfgDict['order'],=
=0D
+ SubOffset)=0D
+ SubCfgDict['value'] =3D ''=0D
+ SubCfgDict['cname'] =3D '%s_%s' % (LastItem['c=
name'],=0D
+ Match.group(1=
))=0D
+ self.CfgDuplicationCheck(CfgDict,=0D
+ SubCfgDict['cname'])=
=0D
+ LastItem['subreg'].append(SubCfgDict.copy())=0D
+ Clear =3D True=0D
+=0D
+ if Clear:=0D
+ ConfigDict['name'] =3D ''=0D
+ ConfigDict['find'] =3D ''=0D
+ ConfigDict['struct'] =3D ''=0D
+ ConfigDict['embed'] =3D ''=0D
+ ConfigDict['marker'] =3D ''=0D
+ ConfigDict['comment'] =3D ''=0D
+ ConfigDict['order'] =3D -1=0D
+ ConfigDict['subreg'] =3D []=0D
+ ConfigDict['option'] =3D ''=0D
+ ConfigDict['condition'] =3D ''=0D
+=0D
+ return Error=0D
+=0D
+ def GetBsfBitFields(self, subitem, bytes):=0D
+ start =3D subitem['bitoffset']=0D
+ end =3D start + subitem['bitlength']=0D
+ bitsvalue =3D ''.join('{0:08b}'.format(i) for i in bytes[::-1])=0D
+ bitsvalue =3D bitsvalue[::-1]=0D
+ bitslen =3D len(bitsvalue)=0D
+ if start > bitslen or end > bitslen:=0D
+ raise Exception("Invalid bits offset [%d,%d] %d for %s" %=0D
+ (start, end, bitslen, subitem['name']))=0D
+ return '0x%X' % (int(bitsvalue[start:end][::-1], 2))=0D
+=0D
+ def UpdateBsfBitFields(self, SubItem, NewValue, ValueArray):=0D
+ Start =3D SubItem['bitoffset']=0D
+ End =3D Start + SubItem['bitlength']=0D
+ Blen =3D len(ValueArray)=0D
+ BitsValue =3D ''.join('{0:08b}'.format(i) for i in ValueArray[::-1=
])=0D
+ BitsValue =3D BitsValue[::-1]=0D
+ BitsLen =3D len(BitsValue)=0D
+ if Start > BitsLen or End > BitsLen:=0D
+ raise Exception("Invalid bits offset [%d,%d] %d for %s" %=0D
+ (Start, End, BitsLen, SubItem['name']))=0D
+ BitsValue =3D BitsValue[:Start] + '{0:0{1}b}'.format(=0D
+ NewValue, SubItem['bitlength'])[::-1] + BitsValue[End:]=0D
+ ValueArray[:] =3D bytearray.fromhex(=0D
+ '{0:0{1}x}'.format(int(BitsValue[::-1], 2), Blen * 2))[::-1]=0D
+=0D
+ def CreateVarDict(self):=0D
+ Error =3D 0=0D
+ self._VarDict =3D {}=0D
+ if len(self._CfgItemList) > 0:=0D
+ Item =3D self._CfgItemList[-1]=0D
+ self._VarDict['_LENGTH_'] =3D '%d' % (Item['offset'] +=0D
+ Item['length'])=0D
+ for Item in self._CfgItemList:=0D
+ Embed =3D Item['embed']=0D
+ Match =3D re.match("^(\\w+):(\\w+):(START|END)", Embed)=0D
+ if Match:=0D
+ StructName =3D Match.group(1)=0D
+ VarName =3D '_%s_%s_' % (Match.group(3), StructName)=0D
+ if Match.group(3) =3D=3D 'END':=0D
+ self._VarDict[VarName] =3D Item['offset'] + Item['leng=
th']=0D
+ self._VarDict['_LENGTH_%s_' % StructName] =3D \=0D
+ self._VarDict['_END_%s_' % StructName] - \=0D
+ self._VarDict['_START_%s_' % StructName]=0D
+ if Match.group(2).startswith('TAG_'):=0D
+ if (self.Mode !=3D 'FSP') and (self._VarDict=0D
+ ['_LENGTH_%s_' %=0D
+ StructName] % 4):=0D
+ raise Exception("Size of structure '%s' is %d,=
\=0D
+not DWORD aligned !" % (StructName, self._VarDict['_LENGTH_%s_' % StructNa=
me]))=0D
+ self._VarDict['_TAG_%s_' % StructName] =3D int(=0D
+ Match.group(2)[4:], 16) & 0xFFF=0D
+ else:=0D
+ self._VarDict[VarName] =3D Item['offset']=0D
+ if Item['marker']:=0D
+ self._VarDict['_OFFSET_%s_' % Item['marker'].strip()] =3D =
\=0D
+ Item['offset']=0D
+ return Error=0D
+=0D
+ def UpdateBsfBitUnit(self, Item):=0D
+ BitTotal =3D 0=0D
+ BitOffset =3D 0=0D
+ StartIdx =3D 0=0D
+ Unit =3D None=0D
+ UnitDec =3D {1: 'BYTE', 2: 'WORD', 4: 'DWORD', 8: 'QWORD'}=0D
+ for Idx, SubItem in enumerate(Item['subreg']):=0D
+ if Unit is None:=0D
+ Unit =3D SubItem['bitunit']=0D
+ BitLength =3D SubItem['bitlength']=0D
+ BitTotal +=3D BitLength=0D
+ BitOffset +=3D BitLength=0D
+=0D
+ if BitOffset > 64 or BitOffset > Unit * 8:=0D
+ break=0D
+=0D
+ if BitOffset =3D=3D Unit * 8:=0D
+ for SubIdx in range(StartIdx, Idx + 1):=0D
+ Item['subreg'][SubIdx]['bitunit'] =3D Unit=0D
+ BitOffset =3D 0=0D
+ StartIdx =3D Idx + 1=0D
+ Unit =3D None=0D
+=0D
+ if BitOffset > 0:=0D
+ raise Exception("Bit fields cannot fit into %s for \=0D
+'%s.%s' !" % (UnitDec[Unit], Item['cname'], SubItem['cname']))=0D
+=0D
+ ExpectedTotal =3D Item['length'] * 8=0D
+ if Item['length'] * 8 !=3D BitTotal:=0D
+ raise Exception("Bit fields total length (%d) does not match \=
=0D
+length (%d) of '%s' !" % (BitTotal, ExpectedTotal, Item['cname']))=0D
+=0D
+ def UpdateDefaultValue(self):=0D
+ Error =3D 0=0D
+ for Idx, Item in enumerate(self._CfgItemList):=0D
+ if len(Item['subreg']) =3D=3D 0:=0D
+ Value =3D Item['value']=0D
+ if (len(Value) > 0) and (Value[0] =3D=3D '{' or Value[0] =
=3D=3D "'" or=0D
+ Value[0] =3D=3D '"'):=0D
+ # {XXX} or 'XXX' strings=0D
+ self.FormatListValue(self._CfgItemList[Idx])=0D
+ else:=0D
+ Match =3D re.match("(0x[0-9a-fA-F]+|[0-9]+)", Value)=0D
+ if not Match:=0D
+ NumValue =3D self.EvaluateExpress(Value)=0D
+ Item['value'] =3D '0x%X' % NumValue=0D
+ else:=0D
+ ValArray =3D self.ValueToByteArray(Item['value'], Item['le=
ngth'])=0D
+ for SubItem in Item['subreg']:=0D
+ SubItem['value'] =3D self.GetBsfBitFields(SubItem, Val=
Array)=0D
+ self.UpdateBsfBitUnit(Item)=0D
+ return Error=0D
+=0D
+ @staticmethod=0D
+ def ExpandIncludeFiles(FilePath, CurDir=3D''):=0D
+ if CurDir =3D=3D '':=0D
+ CurDir =3D os.path.dirname(FilePath)=0D
+ FilePath =3D os.path.basename(FilePath)=0D
+=0D
+ InputFilePath =3D os.path.join(CurDir, FilePath)=0D
+ File =3D open(InputFilePath, "r")=0D
+ Lines =3D File.readlines()=0D
+ File.close()=0D
+=0D
+ NewLines =3D []=0D
+ for LineNum, Line in enumerate(Lines):=0D
+ Match =3D re.match("^!include\\s*(.+)?$", Line)=0D
+ if Match:=0D
+ IncPath =3D Match.group(1)=0D
+ TmpPath =3D os.path.join(CurDir, IncPath)=0D
+ OrgPath =3D TmpPath=0D
+ if not os.path.exists(TmpPath):=0D
+ CurDir =3D os.path.join(os.path.dirname(=0D
+ os.path.realpath(__file__)), "..", "..")=0D
+ TmpPath =3D os.path.join(CurDir, IncPath)=0D
+ if not os.path.exists(TmpPath):=0D
+ raise Exception("ERROR: Cannot open include file '%s'.=
" %=0D
+ OrgPath)=0D
+ else:=0D
+ NewLines.append(('# Included from file: %s\n' %=0D
+ IncPath, TmpPath, 0))=0D
+ NewLines.append(('# %s\n' % ('=3D' * 80), TmpPath, 0))=
=0D
+ NewLines.extend(CGenCfgData.ExpandIncludeFiles=0D
+ (IncPath, CurDir))=0D
+ else:=0D
+ NewLines.append((Line, InputFilePath, LineNum))=0D
+=0D
+ return NewLines=0D
+=0D
+ def OverrideDefaultValue(self, DltFile):=0D
+ Error =3D 0=0D
+ DltLines =3D CGenCfgData.ExpandIncludeFiles(DltFile)=0D
+=0D
+ PlatformId =3D None=0D
+ for Line, FilePath, LineNum in DltLines:=0D
+ Line =3D Line.strip()=0D
+ if not Line or Line.startswith('#'):=0D
+ continue=0D
+ Match =3D re.match("\\s*(\\w+)\\.(\\w+)(\\.\\w+)?\\s*\\|\\s*(.=
+)",=0D
+ Line)=0D
+ if not Match:=0D
+ raise Exception("Unrecognized line '%s' (File:'%s' Line:%d=
) !"=0D
+ % (Line, FilePath, LineNum + 1))=0D
+=0D
+ Found =3D False=0D
+ InScope =3D False=0D
+ for Idx, Item in enumerate(self._CfgItemList):=0D
+ if not InScope:=0D
+ if not (Item['embed'].endswith(':START') and=0D
+ Item['embed'].startswith(Match.group(1))):=0D
+ continue=0D
+ InScope =3D True=0D
+ if Item['cname'] =3D=3D Match.group(2):=0D
+ Found =3D True=0D
+ break=0D
+ if Item['embed'].endswith(':END') and \=0D
+ Item['embed'].startswith(Match.group(1)):=0D
+ break=0D
+ Name =3D '%s.%s' % (Match.group(1), Match.group(2))=0D
+ if not Found:=0D
+ ErrItem =3D Match.group(2) if InScope else Match.group(1)=
=0D
+ raise Exception("Invalid configuration '%s' in '%s' \=0D
+(File:'%s' Line:%d) !" % (ErrItem, Name, FilePath, LineNum + 1))=0D
+=0D
+ ValueStr =3D Match.group(4).strip()=0D
+ if Match.group(3) is not None:=0D
+ # This is a subregion item=0D
+ BitField =3D Match.group(3)[1:]=0D
+ Found =3D False=0D
+ if len(Item['subreg']) > 0:=0D
+ for SubItem in Item['subreg']:=0D
+ if SubItem['cname'] =3D=3D '%s_%s' % \=0D
+ (Item['cname'], BitField):=0D
+ Found =3D True=0D
+ break=0D
+ if not Found:=0D
+ raise Exception("Invalid configuration bit field \=0D
+'%s' in '%s.%s' (File:'%s' Line:%d) !" % (BitField, Name, BitField,=0D
+ FilePath, LineNum + 1))=0D
+=0D
+ try:=0D
+ Value =3D int(ValueStr, 16) if ValueStr.startswith('0x=
') \=0D
+ else int(ValueStr, 10)=0D
+ except Exception:=0D
+ raise Exception("Invalid value '%s' for bit field '%s.=
%s' \=0D
+(File:'%s' Line:%d) !" % (ValueStr, Name, BitField, FilePath, LineNum + 1)=
)=0D
+=0D
+ if Value >=3D 2 ** SubItem['bitlength']:=0D
+ raise Exception("Invalid configuration bit field value=
\=0D
+'%s' for '%s.%s' (File:'%s' Line:%d) !" % (Value, Name, BitField,=0D
+ FilePath, LineNum + 1))=0D
+=0D
+ ValArray =3D self.ValueToByteArray(Item['value'], Item['le=
ngth'])=0D
+ self.UpdateBsfBitFields(SubItem, Value, ValArray)=0D
+=0D
+ if Item['value'].startswith('{'):=0D
+ Item['value'] =3D '{' + ', '.join('0x%02X' % i=0D
+ for i in ValArray) + '=
}'=0D
+ else:=0D
+ BitsValue =3D ''.join('{0:08b}'.format(i)=0D
+ for i in ValArray[::-1])=0D
+ Item['value'] =3D '0x%X' % (int(BitsValue, 2))=0D
+ else:=0D
+ if Item['value'].startswith('{') and \=0D
+ not ValueStr.startswith('{'):=0D
+ raise Exception("Data array required for '%s' \=0D
+(File:'%s' Line:%d) !" % (Name, FilePath, LineNum + 1))=0D
+ Item['value'] =3D ValueStr=0D
+=0D
+ if Name =3D=3D 'PLATFORMID_CFG_DATA.PlatformId':=0D
+ PlatformId =3D ValueStr=0D
+=0D
+ if (PlatformId is None) and (self.Mode !=3D 'FSP'):=0D
+ raise Exception("PLATFORMID_CFG_DATA.PlatformId is missing=
\=0D
+in file '%s' !" % (DltFile))=0D
+=0D
+ return Error=0D
+=0D
+ def ProcessMultilines(self, String, MaxCharLength):=0D
+ Multilines =3D ''=0D
+ StringLength =3D len(String)=0D
+ CurrentStringStart =3D 0=0D
+ StringOffset =3D 0=0D
+ BreakLineDict =3D []=0D
+ if len(String) <=3D MaxCharLength:=0D
+ while (StringOffset < StringLength):=0D
+ if StringOffset >=3D 1:=0D
+ if String[StringOffset - 1] =3D=3D '\\' and \=0D
+ String[StringOffset] =3D=3D 'n':=0D
+ BreakLineDict.append(StringOffset + 1)=0D
+ StringOffset +=3D 1=0D
+ if BreakLineDict !=3D []:=0D
+ for Each in BreakLineDict:=0D
+ Multilines +=3D " %s\n" % String[CurrentStringStart:E=
ach].\=0D
+ lstrip()=0D
+ CurrentStringStart =3D Each=0D
+ if StringLength - CurrentStringStart > 0:=0D
+ Multilines +=3D " %s\n" % String[CurrentStringStart:]=
.\=0D
+ lstrip()=0D
+ else:=0D
+ Multilines =3D " %s\n" % String=0D
+ else:=0D
+ NewLineStart =3D 0=0D
+ NewLineCount =3D 0=0D
+ FoundSpaceChar =3D False=0D
+ while(StringOffset < StringLength):=0D
+ if StringOffset >=3D 1:=0D
+ if NewLineCount >=3D MaxCharLength - 1:=0D
+ if String[StringOffset] =3D=3D ' ' and \=0D
+ StringLength - StringOffset > 10:=0D
+ BreakLineDict.append(NewLineStart + NewLineCou=
nt)=0D
+ NewLineStart =3D NewLineStart + NewLineCount=0D
+ NewLineCount =3D 0=0D
+ FoundSpaceChar =3D True=0D
+ elif StringOffset =3D=3D StringLength - 1 \=0D
+ and FoundSpaceChar is False:=0D
+ BreakLineDict.append(0)=0D
+ if String[StringOffset - 1] =3D=3D '\\' and \=0D
+ String[StringOffset] =3D=3D 'n':=0D
+ BreakLineDict.append(StringOffset + 1)=0D
+ NewLineStart =3D StringOffset + 1=0D
+ NewLineCount =3D 0=0D
+ StringOffset +=3D 1=0D
+ NewLineCount +=3D 1=0D
+ if BreakLineDict !=3D []:=0D
+ BreakLineDict.sort()=0D
+ for Each in BreakLineDict:=0D
+ if Each > 0:=0D
+ Multilines +=3D " %s\n" % String[=0D
+ CurrentStringStart:Each].lstrip()=0D
+ CurrentStringStart =3D Each=0D
+ if StringLength - CurrentStringStart > 0:=0D
+ Multilines +=3D " %s\n" % String[CurrentStringStart:]=
.\=0D
+ lstrip()=0D
+ return Multilines=0D
+=0D
+ def CreateField(self, Item, Name, Length, Offset, Struct,=0D
+ BsfName, Help, Option, BitsLength=3DNone):=0D
+ PosName =3D 28=0D
+ NameLine =3D ''=0D
+ HelpLine =3D ''=0D
+ OptionLine =3D ''=0D
+=0D
+ if Length =3D=3D 0 and Name =3D=3D 'Dummy':=0D
+ return '\n'=0D
+=0D
+ IsArray =3D False=0D
+ if Length in [1, 2, 4, 8]:=0D
+ Type =3D "UINT%d" % (Length * 8)=0D
+ else:=0D
+ IsArray =3D True=0D
+ Type =3D "UINT8"=0D
+=0D
+ if Item and Item['value'].startswith('{'):=0D
+ Type =3D "UINT8"=0D
+ IsArray =3D True=0D
+=0D
+ if Struct !=3D '':=0D
+ Type =3D Struct=0D
+ if Struct in ['UINT8', 'UINT16', 'UINT32', 'UINT64']:=0D
+ IsArray =3D True=0D
+ Unit =3D int(Type[4:]) // 8=0D
+ Length =3D Length / Unit=0D
+ else:=0D
+ IsArray =3D False=0D
+=0D
+ if IsArray:=0D
+ Name =3D Name + '[%d]' % Length=0D
+=0D
+ if len(Type) < PosName:=0D
+ Space1 =3D PosName - len(Type)=0D
+ else:=0D
+ Space1 =3D 1=0D
+=0D
+ if BsfName !=3D '':=0D
+ NameLine =3D " %s\n" % BsfName=0D
+ else:=0D
+ NameLine =3D "\n"=0D
+=0D
+ if Help !=3D '':=0D
+ HelpLine =3D self.ProcessMultilines(Help, 80)=0D
+=0D
+ if Option !=3D '':=0D
+ OptionLine =3D self.ProcessMultilines(Option, 80)=0D
+=0D
+ if BitsLength is None:=0D
+ BitsLength =3D ''=0D
+ else:=0D
+ BitsLength =3D ' : %d' % BitsLength=0D
+=0D
+ return "\n/** %s%s%s**/\n %s%s%s%s;\n" % \=0D
+ (NameLine, HelpLine, OptionLine, Type, ' ' * Space1, Name,=
=0D
+ BitsLength)=0D
+=0D
+ def SplitTextBody(self, TextBody):=0D
+ Marker1 =3D '{ /* _COMMON_STRUCT_START_ */'=0D
+ Marker2 =3D '; /* _COMMON_STRUCT_END_ */'=0D
+ ComBody =3D []=0D
+ TxtBody =3D []=0D
+ IsCommon =3D False=0D
+ for Line in TextBody:=0D
+ if Line.strip().endswith(Marker1):=0D
+ Line =3D Line.replace(Marker1[1:], '')=0D
+ IsCommon =3D True=0D
+ if Line.strip().endswith(Marker2):=0D
+ Line =3D Line.replace(Marker2[1:], '')=0D
+ if IsCommon:=0D
+ ComBody.append(Line)=0D
+ IsCommon =3D False=0D
+ continue=0D
+ if IsCommon:=0D
+ ComBody.append(Line)=0D
+ else:=0D
+ TxtBody.append(Line)=0D
+ return ComBody, TxtBody=0D
+=0D
+ def GetStructArrayInfo(self, Input):=0D
+ ArrayStr =3D Input.split('[')=0D
+ Name =3D ArrayStr[0]=0D
+ if len(ArrayStr) > 1:=0D
+ NumStr =3D ''.join(c for c in ArrayStr[-1] if c.isdigit())=0D
+ NumStr =3D '1000' if len(NumStr) =3D=3D 0 else NumStr=0D
+ ArrayNum =3D int(NumStr)=0D
+ else:=0D
+ ArrayNum =3D 0=0D
+ return Name, ArrayNum=0D
+=0D
+ def PostProcessBody(self, TextBody, IncludeEmbedOnly=3DTrue):=0D
+ NewTextBody =3D []=0D
+ OldTextBody =3D []=0D
+ IncTextBody =3D []=0D
+ StructBody =3D []=0D
+ IncludeLine =3D False=0D
+ EmbedFound =3D False=0D
+ StructName =3D ''=0D
+ ArrayVarName =3D ''=0D
+ VariableName =3D ''=0D
+ Count =3D 0=0D
+ Level =3D 0=0D
+ IsCommonStruct =3D False=0D
+=0D
+ for Line in TextBody:=0D
+ if Line.startswith('#define '):=0D
+ IncTextBody.append(Line)=0D
+ continue=0D
+=0D
+ if not Line.startswith('/* EMBED_STRUCT:'):=0D
+ Match =3D False=0D
+ else:=0D
+ Match =3D re.match("^/\\*\\sEMBED_STRUCT:([\\w\\[\\]\\*]+)=
:\=0D
+([\\w\\[\\]\\*]+):(\\w+):(START|END)([\\s\\d]+)\\*/([\\s\\S]*)", Line)=0D
+=0D
+ if Match:=0D
+ ArrayMarker =3D Match.group(5)=0D
+ if Match.group(4) =3D=3D 'END':=0D
+ Level -=3D 1=0D
+ if Level =3D=3D 0:=0D
+ Line =3D Match.group(6)=0D
+ else: # 'START'=0D
+ Level +=3D 1=0D
+ if Level =3D=3D 1:=0D
+ Line =3D Match.group(6)=0D
+ else:=0D
+ EmbedFound =3D True=0D
+ TagStr =3D Match.group(3)=0D
+ if TagStr.startswith('TAG_'):=0D
+ try:=0D
+ TagVal =3D int(TagStr[4:], 16)=0D
+ except Exception:=0D
+ TagVal =3D -1=0D
+ if (TagVal >=3D 0) and (TagVal < self._MinCfgTagId=
):=0D
+ IsCommonStruct =3D True=0D
+=0D
+ if Level =3D=3D 1:=0D
+ if IsCommonStruct:=0D
+ Suffix =3D ' /* _COMMON_STRUCT_START_ */'=0D
+ else:=0D
+ Suffix =3D ''=0D
+ StructBody =3D ['typedef struct {%s' % Suffix]=0D
+ StructName =3D Match.group(1)=0D
+ StructType =3D Match.group(2)=0D
+ VariableName =3D Match.group(3)=0D
+ MatchOffset =3D re.search('/\\*\\*\\sOffset\\s0x\=
=0D
+([a-fA-F0-9]+)', Line)=0D
+ if MatchOffset:=0D
+ Offset =3D int(MatchOffset.group(1), 16)=0D
+ else:=0D
+ Offset =3D None=0D
+ IncludeLine =3D True=0D
+=0D
+ ModifiedStructType =3D StructType.rstrip()=0D
+ if ModifiedStructType.endswith(']'):=0D
+ Idx =3D ModifiedStructType.index('[')=0D
+ if ArrayMarker !=3D ' ':=0D
+ # Auto array size=0D
+ OldTextBody.append('')=0D
+ ArrayVarName =3D VariableName=0D
+ if int(ArrayMarker) =3D=3D 1000:=0D
+ Count =3D 1=0D
+ else:=0D
+ Count =3D int(ArrayMarker) + 1000=0D
+ else:=0D
+ if Count < 1000:=0D
+ Count +=3D 1=0D
+=0D
+ VariableTemp =3D ArrayVarName + '[%d]' % (=0D
+ Count if Count < 1000 else Count - 1000)=0D
+ OldTextBody[-1] =3D self.CreateField(=0D
+ None, VariableTemp, 0, Offset,=0D
+ ModifiedStructType[:Idx], '',=0D
+ 'Structure Array', '')=0D
+ else:=0D
+ ArrayVarName =3D ''=0D
+ OldTextBody.append(self.CreateField(=0D
+ None, VariableName, 0, Offset,=0D
+ ModifiedStructType, '', '', ''))=0D
+=0D
+ if IncludeLine:=0D
+ StructBody.append(Line)=0D
+ else:=0D
+ OldTextBody.append(Line)=0D
+=0D
+ if Match and Match.group(4) =3D=3D 'END':=0D
+ if Level =3D=3D 0:=0D
+ if (StructType !=3D Match.group(2)) or \=0D
+ (VariableName !=3D Match.group(3)):=0D
+ print("Unmatched struct name '%s' and '%s' !" %=0D
+ (StructName, Match.group(2)))=0D
+ else:=0D
+ if IsCommonStruct:=0D
+ Suffix =3D ' /* _COMMON_STRUCT_END_ */'=0D
+ else:=0D
+ Suffix =3D ''=0D
+ Line =3D '} %s;%s\n\n\n' % (StructName, Suffix)=0D
+ StructBody.append(Line)=0D
+ if (Line not in NewTextBody) and \=0D
+ (Line not in OldTextBody):=0D
+ NewTextBody.extend(StructBody)=0D
+ IncludeLine =3D False=0D
+ IsCommonStruct =3D False=0D
+=0D
+ if not IncludeEmbedOnly:=0D
+ NewTextBody.extend(OldTextBody)=0D
+=0D
+ if EmbedFound:=0D
+ NewTextBody =3D self.PostProcessBody(NewTextBody, False)=0D
+=0D
+ NewTextBody =3D IncTextBody + NewTextBody=0D
+ return NewTextBody=0D
+=0D
+ def WriteHeaderFile(self, TxtBody, FileName, Type=3D'h'):=0D
+ FileNameDef =3D os.path.basename(FileName).replace('.', '_')=0D
+ FileNameDef =3D re.sub('(.)([A-Z][a-z]+)', r'\1_\2', FileNameDef)=
=0D
+ FileNameDef =3D re.sub('([a-z0-9])([A-Z])', r'\1_\2',=0D
+ FileNameDef).upper()=0D
+=0D
+ Lines =3D []=0D
+ Lines.append("%s\n" % GetCopyrightHeader(Type))=0D
+ Lines.append("#ifndef __%s__\n" % FileNameDef)=0D
+ Lines.append("#define __%s__\n\n" % FileNameDef)=0D
+ if Type =3D=3D 'h':=0D
+ Lines.append("#pragma pack(1)\n\n")=0D
+ Lines.extend(TxtBody)=0D
+ if Type =3D=3D 'h':=0D
+ Lines.append("#pragma pack()\n\n")=0D
+ Lines.append("#endif\n")=0D
+=0D
+ # Don't rewrite if the contents are the same=0D
+ Create =3D True=0D
+ if os.path.exists(FileName):=0D
+ HdrFile =3D open(FileName, "r")=0D
+ OrgTxt =3D HdrFile.read()=0D
+ HdrFile.close()=0D
+=0D
+ NewTxt =3D ''.join(Lines)=0D
+ if OrgTxt =3D=3D NewTxt:=0D
+ Create =3D False=0D
+=0D
+ if Create:=0D
+ HdrFile =3D open(FileName, "w")=0D
+ HdrFile.write(''.join(Lines))=0D
+ HdrFile.close()=0D
+=0D
+ def CreateHeaderFile(self, HdrFileName, ComHdrFileName=3D''):=0D
+ LastStruct =3D ''=0D
+ SpaceIdx =3D 0=0D
+ Offset =3D 0=0D
+ FieldIdx =3D 0=0D
+ LastFieldIdx =3D 0=0D
+ ResvOffset =3D 0=0D
+ ResvIdx =3D 0=0D
+ TxtBody =3D []=0D
+ LineBuffer =3D []=0D
+ CfgTags =3D []=0D
+ LastVisible =3D True=0D
+=0D
+ TxtBody.append("typedef struct {\n")=0D
+ for Item in self._CfgItemList:=0D
+ # Search for CFGDATA tags=0D
+ Embed =3D Item["embed"].upper()=0D
+ if Embed.endswith(':START'):=0D
+ Match =3D re.match(r'(\w+)_CFG_DATA:TAG_([0-9A-F]+):START'=
,=0D
+ Embed)=0D
+ if Match:=0D
+ TagName =3D Match.group(1)=0D
+ TagId =3D int(Match.group(2), 16)=0D
+ CfgTags.append((TagId, TagName))=0D
+=0D
+ # Only process visible items=0D
+ NextVisible =3D LastVisible=0D
+=0D
+ if LastVisible and (Item['header'] =3D=3D 'OFF'):=0D
+ NextVisible =3D False=0D
+ ResvOffset =3D Item['offset']=0D
+ elif (not LastVisible) and Item['header'] =3D=3D 'ON':=0D
+ NextVisible =3D True=0D
+ Name =3D "ReservedUpdSpace%d" % ResvIdx=0D
+ ResvIdx =3D ResvIdx + 1=0D
+ TxtBody.append(self.CreateField(=0D
+ Item, Name, Item["offset"] - ResvOffset,=0D
+ ResvOffset, '', '', '', ''))=0D
+ FieldIdx +=3D 1=0D
+=0D
+ if Offset < Item["offset"]:=0D
+ if LastVisible:=0D
+ Name =3D "UnusedUpdSpace%d" % SpaceIdx=0D
+ LineBuffer.append(self.CreateField=0D
+ (Item, Name, Item["offset"] -=0D
+ Offset, Offset, '', '', '', ''))=0D
+ FieldIdx +=3D 1=0D
+ SpaceIdx =3D SpaceIdx + 1=0D
+ Offset =3D Item["offset"]=0D
+=0D
+ LastVisible =3D NextVisible=0D
+=0D
+ Offset =3D Offset + Item["length"]=0D
+ if LastVisible:=0D
+ for Each in LineBuffer:=0D
+ TxtBody.append(Each)=0D
+ LineBuffer =3D []=0D
+ Embed =3D Item["embed"].upper()=0D
+ if Embed.endswith(':START') or Embed.endswith(':END'):=0D
+ # EMBED_STRUCT: StructName : \=0D
+ # ItemName : VariableName : START|END=0D
+ Name, ArrayNum =3D self.GetStructArrayInfo(Item["struc=
t"])=0D
+ Remaining =3D Item["embed"]=0D
+ if (LastFieldIdx + 1 =3D=3D FieldIdx) and (LastStruct =
=3D=3D Name):=0D
+ ArrayMarker =3D ' '=0D
+ else:=0D
+ ArrayMarker =3D '%d' % ArrayNum=0D
+ LastFieldIdx =3D FieldIdx=0D
+ LastStruct =3D Name=0D
+ Marker =3D '/* EMBED_STRUCT:%s:%s%s*/ ' % (Name, Remai=
ning,=0D
+ ArrayMarker)=
=0D
+ # if Embed.endswith(':START') and Comment !=3D '':=0D
+ # Marker =3D '/* COMMENT:%s */ \n' % Item["comment"] +=
Marker=0D
+ else:=0D
+ if Embed =3D=3D '':=0D
+ Marker =3D ''=0D
+ else:=0D
+ self.Error =3D "Invalid embedded structure \=0D
+format '%s'!\n" % Item["embed"]=0D
+ return 4=0D
+=0D
+ # Generate bit fields for structure=0D
+ if len(Item['subreg']) > 0 and Item["struct"]:=0D
+ StructType =3D Item["struct"]=0D
+ StructName, ArrayNum =3D self.GetStructArrayInfo(Struc=
tType)=0D
+ if (LastFieldIdx + 1 =3D=3D FieldIdx) and \=0D
+ (LastStruct =3D=3D Item["struct"]):=0D
+ ArrayMarker =3D ' '=0D
+ else:=0D
+ ArrayMarker =3D '%d' % ArrayNum=0D
+ TxtBody.append('/* EMBED_STRUCT:%s:%s:%s:START%s*/\n' =
%=0D
+ (StructName, StructType, Item["cname"],=
=0D
+ ArrayMarker))=0D
+ for SubItem in Item['subreg']:=0D
+ Name =3D SubItem["cname"]=0D
+ if Name.startswith(Item["cname"]):=0D
+ Name =3D Name[len(Item["cname"]) + 1:]=0D
+ Line =3D self.CreateField(=0D
+ SubItem, Name, SubItem["bitunit"],=0D
+ SubItem["offset"], SubItem['struct'],=0D
+ SubItem['name'], SubItem['help'],=0D
+ SubItem['option'], SubItem['bitlength'])=0D
+ TxtBody.append(Line)=0D
+ TxtBody.append('/* EMBED_STRUCT:%s:%s:%s:END%s*/\n' %=
=0D
+ (StructName, StructType, Item["cname"],=
=0D
+ ArrayMarker))=0D
+ LastFieldIdx =3D FieldIdx=0D
+ LastStruct =3D Item["struct"]=0D
+ FieldIdx +=3D 1=0D
+ else:=0D
+ FieldIdx +=3D 1=0D
+ Line =3D Marker + self.CreateField(=0D
+ Item, Item["cname"], Item["length"], Item["offset"=
],=0D
+ Item['struct'], Item['name'], Item['help'],=0D
+ Item['option'])=0D
+ TxtBody.append(Line)=0D
+=0D
+ TxtBody.append("}\n\n")=0D
+=0D
+ # Handle the embedded data structure=0D
+ TxtBody =3D self.PostProcessBody(TxtBody)=0D
+ ComBody, TxtBody =3D self.SplitTextBody(TxtBody)=0D
+=0D
+ # Prepare TAG defines=0D
+ PltTagDefTxt =3D ['\n']=0D
+ ComTagDefTxt =3D ['\n']=0D
+ for TagId, TagName in sorted(CfgTags):=0D
+ TagLine =3D '#define %-30s 0x%03X\n' % ('CDATA_%s_TAG' %=0D
+ TagName, TagId)=0D
+ if TagId < self._MinCfgTagId:=0D
+ # TAG ID < 0x100, it is a generic TAG=0D
+ ComTagDefTxt.append(TagLine)=0D
+ else:=0D
+ PltTagDefTxt.append(TagLine)=0D
+ PltTagDefTxt.append('\n\n')=0D
+ ComTagDefTxt.append('\n\n')=0D
+=0D
+ # Write file back=0D
+ self.WriteHeaderFile(PltTagDefTxt + TxtBody, HdrFileName)=0D
+ if ComHdrFileName:=0D
+ self.WriteHeaderFile(ComTagDefTxt + ComBody, ComHdrFileName)=0D
+=0D
+ return 0=0D
+=0D
+ def UpdateConfigItemValue(self, Item, ValueStr):=0D
+ IsArray =3D True if Item['value'].startswith('{') else False=0D
+ IsString =3D True if Item['value'].startswith("'") else False=0D
+ Bytes =3D self.ValueToByteArray(ValueStr, Item['length'])=0D
+ if IsString:=0D
+ NewValue =3D "'%s'" % Bytes.decode("utf-8")=0D
+ elif IsArray:=0D
+ NewValue =3D Bytes2Str(Bytes)=0D
+ else:=0D
+ Fmt =3D '0x%X' if Item['value'].startswith('0x') else '%d'=0D
+ NewValue =3D Fmt % Bytes2Val(Bytes)=0D
+ Item['value'] =3D NewValue=0D
+=0D
+ def LoadDefaultFromBinaryArray(self, BinDat, IgnoreFind=3DFalse):=0D
+ FindOff =3D 0=0D
+ StartOff =3D 0=0D
+ for Item in self._CfgItemList:=0D
+ if Item['length'] =3D=3D 0:=0D
+ continue=0D
+ if not IgnoreFind and Item['find']:=0D
+ FindBin =3D Item['find'].encode()=0D
+ Offset =3D BinDat.find(FindBin)=0D
+ if Offset >=3D 0:=0D
+ TestOff =3D BinDat[Offset+len(FindBin):].find(FindBin)=
=0D
+ if TestOff >=3D 0:=0D
+ raise Exception('Multiple match found for "%s" !' =
%=0D
+ Item['find'])=0D
+ FindOff =3D Offset + len(FindBin)=0D
+ StartOff =3D Item['offset']=0D
+ else:=0D
+ raise Exception('Could not find "%s" !' % Item['find']=
)=0D
+ if Item['offset'] + Item['length'] > len(BinDat):=0D
+ raise Exception('Mismatching format between DSC \=0D
+and BIN files !')=0D
+ Offset =3D FindOff + (Item['offset'] - StartOff)=0D
+ ValStr =3D Bytes2Str(BinDat[Offset: Offset + Item['length']])=
=0D
+ self.UpdateConfigItemValue(Item, ValStr)=0D
+=0D
+ self.UpdateDefaultValue()=0D
+=0D
+ def PatchBinaryArray(self, BinDat):=0D
+ FileOff =3D 0=0D
+ Offset =3D 0=0D
+ FindOff =3D 0=0D
+=0D
+ PatchList =3D []=0D
+ CfgBin =3D bytearray()=0D
+ for Item in self._CfgItemList:=0D
+ if Item['length'] =3D=3D 0:=0D
+ continue=0D
+=0D
+ if Item['find']:=0D
+ if len(CfgBin) > 0:=0D
+ PatchList.append((FileOff, CfgBin))=0D
+ FindBin =3D Item['find'].encode()=0D
+ FileOff =3D BinDat.find(FindBin)=0D
+ if FileOff < 0:=0D
+ raise Exception('Could not find "%s" !' % Item['find']=
)=0D
+ else:=0D
+ TestOff =3D BinDat[FileOff+len(FindBin):].find(FindBin=
)=0D
+ if TestOff >=3D 0:=0D
+ raise Exception('Multiple match found for "%s" !' =
%=0D
+ Item['find'])=0D
+ FileOff +=3D len(FindBin)=0D
+ Offset =3D Item['offset']=0D
+ FindOff =3D Offset=0D
+ CfgBin =3D bytearray()=0D
+=0D
+ if Item['offset'] > Offset:=0D
+ Gap =3D Item['offset'] - Offset=0D
+ CfgBin.extend(b'\x00' * Gap)=0D
+=0D
+ if Item['type'] =3D=3D 'Reserved' and Item['option'] =3D=3D '$=
SKIP':=0D
+ # keep old data=0D
+ NewOff =3D FileOff + (Offset - FindOff)=0D
+ FileData =3D bytearray(BinDat[NewOff: NewOff + Item['lengt=
h']])=0D
+ CfgBin.extend(FileData)=0D
+ else:=0D
+ CfgBin.extend(self.ValueToByteArray(Item['value'],=0D
+ Item['length']))=0D
+ Offset =3D Item['offset'] + Item['length']=0D
+=0D
+ if len(CfgBin) > 0:=0D
+ PatchList.append((FileOff, CfgBin))=0D
+=0D
+ for FileOff, CfgBin in PatchList:=0D
+ Length =3D len(CfgBin)=0D
+ if FileOff + Length < len(BinDat):=0D
+ BinDat[FileOff:FileOff+Length] =3D CfgBin[:]=0D
+=0D
+ return BinDat=0D
+=0D
+ def GenerateBinaryArray(self):=0D
+ Offset =3D 0=0D
+ BinDat =3D bytearray()=0D
+ for Item in self._CfgItemList:=0D
+ if Item['offset'] > Offset:=0D
+ Gap =3D Item['offset'] - Offset=0D
+ BinDat.extend(b'\x00' * Gap)=0D
+ BinDat.extend(self.ValueToByteArray(Item['value'], Item['lengt=
h']))=0D
+ Offset =3D Item['offset'] + Item['length']=0D
+ return BinDat=0D
+=0D
+ def GenerateBinary(self, BinFileName):=0D
+ BinFile =3D open(BinFileName, "wb")=0D
+ BinFile.write(self.GenerateBinaryArray())=0D
+ BinFile.close()=0D
+ return 0=0D
+=0D
+ def GenerateDataIncFile(self, DatIncFileName, BinFile=3DNone):=0D
+ # Put a prefix GUID before CFGDATA so that it can be located later=
on=0D
+ Prefix =3D b'\xa7\xbd\x7f\x73\x20\x1e\x46\xd6\xbe\x8f\=0D
+x64\x12\x05\x8d\x0a\xa8'=0D
+ if BinFile:=0D
+ Fin =3D open(BinFile, 'rb')=0D
+ BinDat =3D Prefix + bytearray(Fin.read())=0D
+ Fin.close()=0D
+ else:=0D
+ BinDat =3D Prefix + self.GenerateBinaryArray()=0D
+=0D
+ FileName =3D os.path.basename(DatIncFileName).upper()=0D
+ FileName =3D FileName.replace('.', '_')=0D
+=0D
+ TxtLines =3D []=0D
+=0D
+ TxtLines.append("UINT8 mConfigDataBlob[%d] =3D {\n" % len(BinDat)=
)=0D
+ Count =3D 0=0D
+ Line =3D [' ']=0D
+ for Each in BinDat:=0D
+ Line.append('0x%02X, ' % Each)=0D
+ Count =3D Count + 1=0D
+ if (Count & 0x0F) =3D=3D 0:=0D
+ Line.append('\n')=0D
+ TxtLines.append(''.join(Line))=0D
+ Line =3D [' ']=0D
+ if len(Line) > 1:=0D
+ TxtLines.append(''.join(Line) + '\n')=0D
+=0D
+ TxtLines.append("};\n\n")=0D
+=0D
+ self.WriteHeaderFile(TxtLines, DatIncFileName, 'inc')=0D
+=0D
+ return 0=0D
+=0D
+ def CheckCfgData(self):=0D
+ # Check if CfgData contains any duplicated name=0D
+ def AddItem(Item, ChkList):=0D
+ Name =3D Item['cname']=0D
+ if Name in ChkList:=0D
+ return Item=0D
+ if Name not in ['Dummy', 'Reserved', 'CfgHeader', 'CondValue']=
:=0D
+ ChkList.append(Name)=0D
+ return None=0D
+=0D
+ Duplicate =3D None=0D
+ ChkList =3D []=0D
+ for Item in self._CfgItemList:=0D
+ Duplicate =3D AddItem(Item, ChkList)=0D
+ if not Duplicate:=0D
+ for SubItem in Item['subreg']:=0D
+ Duplicate =3D AddItem(SubItem, ChkList)=0D
+ if Duplicate:=0D
+ break=0D
+ if Duplicate:=0D
+ break=0D
+ if Duplicate:=0D
+ self.Error =3D "Duplicated CFGDATA '%s' found !\n" % \=0D
+ Duplicate['cname']=0D
+ return -1=0D
+ return 0=0D
+=0D
+ def PrintData(self):=0D
+ for Item in self._CfgItemList:=0D
+ if not Item['length']:=0D
+ continue=0D
+ print("%-10s @Offset:0x%04X Len:%3d Val:%s" %=0D
+ (Item['cname'], Item['offset'], Item['length'],=0D
+ Item['value']))=0D
+ for SubItem in Item['subreg']:=0D
+ print(" %-20s BitOff:0x%04X BitLen:%-3d Val:%s" %=0D
+ (SubItem['cname'], SubItem['bitoffset'],=0D
+ SubItem['bitlength'], SubItem['value']))=0D
+=0D
+ def FormatArrayValue(self, Input, Length):=0D
+ Dat =3D self.ValueToByteArray(Input, Length)=0D
+ return ','.join('0x%02X' % Each for Each in Dat)=0D
+=0D
+ def GetItemOptionList(self, Item):=0D
+ TmpList =3D []=0D
+ if Item['type'] =3D=3D "Combo":=0D
+ if not Item['option'] in self._BuidinOption:=0D
+ OptList =3D Item['option'].split(',')=0D
+ for Option in OptList:=0D
+ Option =3D Option.strip()=0D
+ try:=0D
+ (OpVal, OpStr) =3D Option.split(':')=0D
+ except Exception:=0D
+ raise Exception("Invalide option format '%s' !" %=
=0D
+ Option)=0D
+ TmpList.append((OpVal, OpStr))=0D
+ return TmpList=0D
+=0D
+ def WriteBsfStruct(self, BsfFd, Item):=0D
+ if Item['type'] =3D=3D "None":=0D
+ Space =3D "gPlatformFspPkgTokenSpaceGuid"=0D
+ else:=0D
+ Space =3D Item['space']=0D
+ Line =3D " $%s_%s" % (Space, Item['cname'])=0D
+ Match =3D re.match("\\s*(\\{.+\\})\\s*", Item['value'])=0D
+ if Match:=0D
+ DefaultValue =3D self.FormatArrayValue(Match.group(1).strip(),=
=0D
+ Item['length'])=0D
+ else:=0D
+ DefaultValue =3D Item['value'].strip()=0D
+ if 'bitlength' in Item:=0D
+ if Item['bitlength']:=0D
+ BsfFd.write(" %s%s%4d bits $_DEFAULT_ =3D %s\n" %=0D
+ (Line, ' ' * (64 - len(Line)), Item['bitlength=
'],=0D
+ DefaultValue))=0D
+ else:=0D
+ if Item['length']:=0D
+ BsfFd.write(" %s%s%4d bytes $_DEFAULT_ =3D %s\n" %=0D
+ (Line, ' ' * (64 - len(Line)), Item['length'],=
=0D
+ DefaultValue))=0D
+=0D
+ return self.GetItemOptionList(Item)=0D
+=0D
+ def GetBsfOption(self, OptionName):=0D
+ if OptionName in self._CfgOptsDict:=0D
+ return self._CfgOptsDict[OptionName]=0D
+ else:=0D
+ return OptionName=0D
+=0D
+ def WriteBsfOption(self, BsfFd, Item):=0D
+ PcdName =3D Item['space'] + '_' + Item['cname']=0D
+ WriteHelp =3D 0=0D
+ BsfLines =3D []=0D
+ if Item['type'] =3D=3D "Combo":=0D
+ if Item['option'] in self._BuidinOption:=0D
+ Options =3D self._BuidinOption[Item['option']]=0D
+ else:=0D
+ Options =3D self.GetBsfOption(PcdName)=0D
+ BsfLines.append(' %s $%s, "%s", &%s,\n' % (=0D
+ Item['type'], PcdName, Item['name'], Options))=0D
+ WriteHelp =3D 1=0D
+ elif Item['type'].startswith("EditNum"):=0D
+ Match =3D re.match("EditNum\\s*,\\s*(HEX|DEC)\\s*,\\s*\\(\=0D
+(\\d+|0x[0-9A-Fa-f]+)\\s*,\\s*(\\d+|0x[0-9A-Fa-f]+)\\)", Item['type'])=0D
+ if Match:=0D
+ BsfLines.append(' EditNum $%s, "%s", %s,\n' % (=0D
+ PcdName, Item['name'], Match.group(1)))=0D
+ WriteHelp =3D 2=0D
+ elif Item['type'].startswith("EditText"):=0D
+ BsfLines.append(' %s $%s, "%s",\n' % (Item['type'], PcdName=
,=0D
+ Item['name']))=0D
+ WriteHelp =3D 1=0D
+ elif Item['type'] =3D=3D "Table":=0D
+ Columns =3D Item['option'].split(',')=0D
+ if len(Columns) !=3D 0:=0D
+ BsfLines.append(' %s $%s "%s",' % (Item['type'], PcdNam=
e,=0D
+ Item['name']))=0D
+ for Col in Columns:=0D
+ Fmt =3D Col.split(':')=0D
+ if len(Fmt) !=3D 3:=0D
+ raise Exception("Column format '%s' is invalid !" =
%=0D
+ Fmt)=0D
+ try:=0D
+ Dtype =3D int(Fmt[1].strip())=0D
+ except Exception:=0D
+ raise Exception("Column size '%s' is invalid !" %=
=0D
+ Fmt[1])=0D
+ BsfLines.append('\n Column "%s", %d bytes, %s' =
%=0D
+ (Fmt[0].strip(), Dtype, Fmt[2].strip()=
))=0D
+ BsfLines.append(',\n')=0D
+ WriteHelp =3D 1=0D
+=0D
+ if WriteHelp > 0:=0D
+ HelpLines =3D Item['help'].split('\\n\\r')=0D
+ FirstLine =3D True=0D
+ for HelpLine in HelpLines:=0D
+ if FirstLine:=0D
+ FirstLine =3D False=0D
+ BsfLines.append(' Help "%s"\n' % (HelpLine))=0D
+ else:=0D
+ BsfLines.append(' "%s"\n' % (HelpLine))=0D
+ if WriteHelp =3D=3D 2:=0D
+ BsfLines.append(' "Valid range: %s ~ %s"\n' %=
=0D
+ (Match.group(2), Match.group(3)))=0D
+=0D
+ if len(Item['condition']) > 4:=0D
+ CondList =3D Item['condition'].split(',')=0D
+ Idx =3D 0=0D
+ for Cond in CondList:=0D
+ Cond =3D Cond.strip()=0D
+ if Cond.startswith('#'):=0D
+ BsfLines.insert(Idx, Cond + '\n')=0D
+ Idx +=3D 1=0D
+ elif Cond.startswith('@#'):=0D
+ BsfLines.append(Cond[1:] + '\n')=0D
+=0D
+ for Line in BsfLines:=0D
+ BsfFd.write(Line)=0D
+=0D
+ def WriteBsfPages(self, PageTree, BsfFd):=0D
+ BsfFd.write('\n')=0D
+ Key =3D next(iter(PageTree))=0D
+ for Page in PageTree[Key]:=0D
+ PageName =3D next(iter(Page))=0D
+ BsfFd.write('Page "%s"\n' % self._CfgPageDict[PageName])=0D
+ if len(PageTree[Key]):=0D
+ self.WriteBsfPages(Page, BsfFd)=0D
+=0D
+ BsfItems =3D []=0D
+ for Item in self._CfgItemList:=0D
+ if Item['name'] !=3D '':=0D
+ if Item['page'] !=3D PageName:=0D
+ continue=0D
+ if len(Item['subreg']) > 0:=0D
+ for SubItem in Item['subreg']:=0D
+ if SubItem['name'] !=3D '':=0D
+ BsfItems.append(SubItem)=0D
+ else:=0D
+ BsfItems.append(Item)=0D
+=0D
+ BsfItems.sort(key=3Dlambda x: x['order'])=0D
+=0D
+ for Item in BsfItems:=0D
+ self.WriteBsfOption(BsfFd, Item)=0D
+ BsfFd.write("EndPage\n\n")=0D
+=0D
+ def GenerateBsfFile(self, BsfFile):=0D
+=0D
+ if BsfFile =3D=3D '':=0D
+ self.Error =3D "BSF output file '%s' is invalid" % BsfFile=0D
+ return 1=0D
+=0D
+ Error =3D 0=0D
+ OptionDict =3D {}=0D
+ BsfFd =3D open(BsfFile, "w")=0D
+ BsfFd.write("%s\n" % GetCopyrightHeader('bsf'))=0D
+ BsfFd.write("%s\n" % self._GlobalDataDef)=0D
+ BsfFd.write("StructDef\n")=0D
+ NextOffset =3D -1=0D
+ for Item in self._CfgItemList:=0D
+ if Item['find'] !=3D '':=0D
+ BsfFd.write('\n Find "%s"\n' % Item['find'])=0D
+ NextOffset =3D Item['offset'] + Item['length']=0D
+ if Item['name'] !=3D '':=0D
+ if NextOffset !=3D Item['offset']:=0D
+ BsfFd.write(" Skip %d bytes\n" %=0D
+ (Item['offset'] - NextOffset))=0D
+ if len(Item['subreg']) > 0:=0D
+ NextOffset =3D Item['offset']=0D
+ BitsOffset =3D NextOffset * 8=0D
+ for SubItem in Item['subreg']:=0D
+ BitsOffset +=3D SubItem['bitlength']=0D
+ if SubItem['name'] =3D=3D '':=0D
+ if 'bitlength' in SubItem:=0D
+ BsfFd.write(" Skip %d bits\n" %=0D
+ (SubItem['bitlength']))=0D
+ else:=0D
+ BsfFd.write(" Skip %d bytes\n" %=0D
+ (SubItem['length']))=0D
+ else:=0D
+ Options =3D self.WriteBsfStruct(BsfFd, SubItem=
)=0D
+ if len(Options) > 0:=0D
+ OptionDict[SubItem=0D
+ ['space']+'_'+SubItem=0D
+ ['cname']] =3D Options=0D
+=0D
+ NextBitsOffset =3D (Item['offset'] + Item['length']) *=
8=0D
+ if NextBitsOffset > BitsOffset:=0D
+ BitsGap =3D NextBitsOffset - BitsOffset=0D
+ BitsRemain =3D BitsGap % 8=0D
+ if BitsRemain:=0D
+ BsfFd.write(" Skip %d bits\n" % BitsRem=
ain)=0D
+ BitsGap -=3D BitsRemain=0D
+ BytesRemain =3D BitsGap // 8=0D
+ if BytesRemain:=0D
+ BsfFd.write(" Skip %d bytes\n" %=0D
+ BytesRemain)=0D
+ NextOffset =3D Item['offset'] + Item['length']=0D
+ else:=0D
+ NextOffset =3D Item['offset'] + Item['length']=0D
+ Options =3D self.WriteBsfStruct(BsfFd, Item)=0D
+ if len(Options) > 0:=0D
+ OptionDict[Item['space']+'_'+Item['cname']] =3D Op=
tions=0D
+ BsfFd.write("\nEndStruct\n\n")=0D
+=0D
+ BsfFd.write("%s" % self._BuidinOptionTxt)=0D
+=0D
+ NameList =3D []=0D
+ OptionList =3D []=0D
+ for Each in sorted(OptionDict):=0D
+ if OptionDict[Each] not in OptionList:=0D
+ NameList.append(Each)=0D
+ OptionList.append(OptionDict[Each])=0D
+ BsfFd.write("List &%s\n" % Each)=0D
+ for Item in OptionDict[Each]:=0D
+ BsfFd.write(' Selection %s , "%s"\n' %=0D
+ (self.EvaluateExpress(Item[0]), Item[1]))=
=0D
+ BsfFd.write("EndList\n\n")=0D
+ else:=0D
+ # Item has idential options as other item=0D
+ # Try to reuse the previous options instead=0D
+ Idx =3D OptionList.index(OptionDict[Each])=0D
+ self._CfgOptsDict[Each] =3D NameList[Idx]=0D
+=0D
+ BsfFd.write("BeginInfoBlock\n")=0D
+ BsfFd.write(' PPVer "%s"\n' % (self._CfgBlkDict['ver']))=
=0D
+ BsfFd.write(' Description "%s"\n' % (self._CfgBlkDict['name']))=
=0D
+ BsfFd.write("EndInfoBlock\n\n")=0D
+=0D
+ self.WriteBsfPages(self._CfgPageTree, BsfFd)=0D
+=0D
+ BsfFd.close()=0D
+ return Error=0D
+=0D
+ def WriteDeltaLine(self, OutLines, Name, ValStr, IsArray):=0D
+ if IsArray:=0D
+ Output =3D '%s | { %s }' % (Name, ValStr)=0D
+ else:=0D
+ Output =3D '%s | 0x%X' % (Name, Array2Val(ValStr))=0D
+ OutLines.append(Output)=0D
+=0D
+ def WriteDeltaFile(self, OutFile, PlatformId, OutLines):=0D
+ DltFd =3D open(OutFile, "w")=0D
+ DltFd.write("%s\n" % GetCopyrightHeader('dlt', True))=0D
+ if PlatformId is not None:=0D
+ DltFd.write('#\n')=0D
+ DltFd.write('# Delta configuration values \=0D
+for platform ID 0x%04X\n' % PlatformId)=0D
+ DltFd.write('#\n\n')=0D
+ for Line in OutLines:=0D
+ DltFd.write('%s\n' % Line)=0D
+ DltFd.close()=0D
+=0D
+ def GenerateDeltaFile(self, OutFile, AbsfFile):=0D
+ # Parse ABSF Build in dict=0D
+ if not os.path.exists(AbsfFile):=0D
+ Lines =3D []=0D
+ else:=0D
+ with open(AbsfFile) as Fin:=0D
+ Lines =3D Fin.readlines()=0D
+=0D
+ AbsfBuiltValDict =3D {}=0D
+ Process =3D False=0D
+ for Line in Lines:=0D
+ Line =3D Line.strip()=0D
+ if Line.startswith('StructDef'):=0D
+ Process =3D True=0D
+ if Line.startswith('EndStruct'):=0D
+ break=0D
+ if not Process:=0D
+ continue=0D
+ Match =3D re.match('\\s*\\$gCfgData_(\\w+)\\s+\=0D
+(\\d+)\\s+(bits|bytes)\\s+\\$_AS_BUILT_\\s+=3D\\s+(.+)\\$', Line)=0D
+ if Match:=0D
+ if Match.group(1) not in AbsfBuiltValDict:=0D
+ AbsfBuiltValDict[Match.group(1)] =3D Match.group(4).st=
rip()=0D
+ else:=0D
+ raise Exception("Duplicated configuration \=0D
+name '%s' found !", Match.group(1))=0D
+=0D
+ # Match config item in DSC=0D
+ PlatformId =3D None=0D
+ OutLines =3D []=0D
+ TagName =3D ''=0D
+ Level =3D 0=0D
+ for Item in self._CfgItemList:=0D
+ Name =3D None=0D
+ if Level =3D=3D 0 and Item['embed'].endswith(':START'):=0D
+ TagName =3D Item['embed'].split(':')[0]=0D
+ Level +=3D 1=0D
+ if Item['cname'] in AbsfBuiltValDict:=0D
+ ValStr =3D AbsfBuiltValDict[Item['cname']]=0D
+ Name =3D '%s.%s' % (TagName, Item['cname'])=0D
+ if not Item['subreg'] and Item['value'].startswith('{'):=0D
+ Value =3D Array2Val(Item['value'])=0D
+ IsArray =3D True=0D
+ else:=0D
+ Value =3D int(Item['value'], 16)=0D
+ IsArray =3D False=0D
+ AbsfVal =3D Array2Val(ValStr)=0D
+ if AbsfVal !=3D Value:=0D
+ if 'PLATFORMID_CFG_DATA.PlatformId' =3D=3D Name:=0D
+ PlatformId =3D AbsfVal=0D
+ self.WriteDeltaLine(OutLines, Name, ValStr, IsArray)=0D
+ else:=0D
+ if 'PLATFORMID_CFG_DATA.PlatformId' =3D=3D Name:=0D
+ raise Exception("'PlatformId' has the \=0D
+same value as DSC default !")=0D
+=0D
+ if Item['subreg']:=0D
+ for SubItem in Item['subreg']:=0D
+ if SubItem['cname'] in AbsfBuiltValDict:=0D
+ ValStr =3D AbsfBuiltValDict[SubItem['cname']]=0D
+ if Array2Val(ValStr) =3D=3D int(SubItem['value'], =
16):=0D
+ continue=0D
+ Name =3D '%s.%s.%s' % (TagName, Item['cname'],=0D
+ SubItem['cname'])=0D
+ self.WriteDeltaLine(OutLines, Name, ValStr, False)=
=0D
+=0D
+ if Item['embed'].endswith(':END'):=0D
+ Level -=3D 1=0D
+=0D
+ if PlatformId is None and Lines:=0D
+ raise Exception("'PlatformId' configuration \=0D
+is missing in ABSF file!")=0D
+ else:=0D
+ PlatformId =3D 0=0D
+=0D
+ self.WriteDeltaFile(OutFile, PlatformId, Lines)=0D
+=0D
+ return 0=0D
+=0D
+ def GenerateDscFile(self, OutFile):=0D
+ DscFd =3D open(OutFile, "w")=0D
+ for Line in self._DscLines:=0D
+ DscFd.write(Line + '\n')=0D
+ DscFd.close()=0D
+ return 0=0D
+=0D
+=0D
+def Usage():=0D
+ print('\n'.join([=0D
+ "GenCfgData Version 0.01",=0D
+ "Usage:",=0D
+ " GenCfgData GENINC BinFile \=0D
+IncOutFile [-D Macros]",=0D
+ " GenCfgData GENPKL DscFile \=0D
+PklOutFile [-D Macros]",=0D
+ " GenCfgData GENINC DscFile[;DltFile] \=0D
+IncOutFile [-D Macros]",=0D
+ " GenCfgData GENBIN DscFile[;DltFile] \=0D
+BinOutFile [-D Macros]",=0D
+ " GenCfgData GENBSF DscFile[;DltFile] \=0D
+BsfOutFile [-D Macros]",=0D
+ " GenCfgData GENDLT DscFile[;AbsfFile] \=0D
+DltOutFile [-D Macros]",=0D
+ " GenCfgData GENDSC DscFile \=0D
+DscOutFile [-D Macros]",=0D
+ " GenCfgData GENHDR DscFile[;DltFile] \=0D
+HdrOutFile[;ComHdrOutFile] [-D Macros]"=0D
+ ]))=0D
+=0D
+=0D
+def Main():=0D
+ #=0D
+ # Parse the options and args=0D
+ #=0D
+ argc =3D len(sys.argv)=0D
+ if argc < 4:=0D
+ Usage()=0D
+ return 1=0D
+=0D
+ GenCfgData =3D CGenCfgData()=0D
+ Command =3D sys.argv[1].upper()=0D
+ OutFile =3D sys.argv[3]=0D
+=0D
+ if argc > 5 and GenCfgData.ParseMacros(sys.argv[4:]) !=3D 0:=0D
+ raise Exception("ERROR: Macro parsing failed !")=0D
+=0D
+ FileList =3D sys.argv[2].split(';')=0D
+ if len(FileList) =3D=3D 2:=0D
+ DscFile =3D FileList[0]=0D
+ DltFile =3D FileList[1]=0D
+ elif len(FileList) =3D=3D 1:=0D
+ DscFile =3D FileList[0]=0D
+ DltFile =3D ''=0D
+ else:=0D
+ raise Exception("ERROR: Invalid parameter '%s' !" % sys.argv[2])=0D
+=0D
+ if Command =3D=3D "GENDLT" and DscFile.endswith('.dlt'):=0D
+ # It needs to expand an existing DLT file=0D
+ DltFile =3D DscFile=0D
+ Lines =3D CGenCfgData.ExpandIncludeFiles(DltFile)=0D
+ OutTxt =3D ''.join([x[0] for x in Lines])=0D
+ OutFile =3D open(OutFile, "w")=0D
+ OutFile.write(OutTxt)=0D
+ OutFile.close()=0D
+ return 0=0D
+=0D
+ if not os.path.exists(DscFile):=0D
+ raise Exception("ERROR: Cannot open file '%s' !" % DscFile)=0D
+=0D
+ CfgBinFile =3D ''=0D
+ if DltFile:=0D
+ if not os.path.exists(DltFile):=0D
+ raise Exception("ERROR: Cannot open file '%s' !" % DltFile)=0D
+ if Command =3D=3D "GENDLT":=0D
+ CfgBinFile =3D DltFile=0D
+ DltFile =3D ''=0D
+=0D
+ BinFile =3D ''=0D
+ if (DscFile.lower().endswith('.bin')) and (Command =3D=3D "GENINC"):=0D
+ # It is binary file=0D
+ BinFile =3D DscFile=0D
+ DscFile =3D ''=0D
+=0D
+ if BinFile:=0D
+ if GenCfgData.GenerateDataIncFile(OutFile, BinFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+ return 0=0D
+=0D
+ if DscFile.lower().endswith('.pkl'):=0D
+ with open(DscFile, "rb") as PklFile:=0D
+ GenCfgData.__dict__ =3D marshal.load(PklFile)=0D
+ else:=0D
+ if GenCfgData.ParseDscFile(DscFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ # if GenCfgData.CheckCfgData() !=3D 0:=0D
+ # raise Exception(GenCfgData.Error)=0D
+=0D
+ if GenCfgData.CreateVarDict() !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ if Command =3D=3D 'GENPKL':=0D
+ with open(OutFile, "wb") as PklFile:=0D
+ marshal.dump(GenCfgData.__dict__, PklFile)=0D
+ return 0=0D
+=0D
+ if DltFile and Command in ['GENHDR', 'GENBIN', 'GENINC', 'GENBSF']:=0D
+ if GenCfgData.OverrideDefaultValue(DltFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ if GenCfgData.UpdateDefaultValue() !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ # GenCfgData.PrintData ()=0D
+=0D
+ if sys.argv[1] =3D=3D "GENBIN":=0D
+ if GenCfgData.GenerateBinary(OutFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ elif sys.argv[1] =3D=3D "GENHDR":=0D
+ OutFiles =3D OutFile.split(';')=0D
+ BrdOutFile =3D OutFiles[0].strip()=0D
+ if len(OutFiles) > 1:=0D
+ ComOutFile =3D OutFiles[1].strip()=0D
+ else:=0D
+ ComOutFile =3D ''=0D
+ if GenCfgData.CreateHeaderFile(BrdOutFile, ComOutFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ elif sys.argv[1] =3D=3D "GENBSF":=0D
+ if GenCfgData.GenerateBsfFile(OutFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ elif sys.argv[1] =3D=3D "GENINC":=0D
+ if GenCfgData.GenerateDataIncFile(OutFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ elif sys.argv[1] =3D=3D "GENDLT":=0D
+ if GenCfgData.GenerateDeltaFile(OutFile, CfgBinFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ elif sys.argv[1] =3D=3D "GENDSC":=0D
+ if GenCfgData.GenerateDscFile(OutFile) !=3D 0:=0D
+ raise Exception(GenCfgData.Error)=0D
+=0D
+ else:=0D
+ raise Exception("Unsuported command '%s' !" % Command)=0D
+=0D
+ return 0=0D
+=0D
+=0D
+if __name__ =3D=3D '__main__':=0D
+ sys.exit(Main())=0D
--=20
2.28.0.windows.1


回复: [EXTERNAL] 回复: [edk2][PATCH V1] MdePkg : Add IPMI Macro and Structure Defintions to resolve the IPMI build error

gaoliming
 

Manic:
The patch content is good. But, the commit message misses Signed-off-by: Contributor Name <contributor@email.server>

And, please run BaseTools\Scripts\PatchCheck.py to check the commit message format.

Thanks
Liming

-----邮件原件-----
发件人: Manickavasakam Karpagavinayagam <manickavasakamk@ami.com>
发送时间: 2021年6月18日 1:42
收件人: gaoliming <gaoliming@byosoft.com.cn>; devel@edk2.groups.io
抄送: isaac.w.oram@intel.com; nathaniel.l.desimone@intel.com; Felix
Polyudov <Felixp@ami.com>; Harikrishna Doppalapudi
<Harikrishnad@ami.com>; Manish Jha <manishj@ami.com>; Zachary Bobroff
<zacharyb@ami.com>
主题: RE: [EXTERNAL] 回复: [edk2][PATCH V1] MdePkg : Add IPMI Macro
and Structure Defintions to resolve the IPMI build error

Liming :

Thank you for the review comments. Created [edk2] [PATCH V2] MdePkg :
Add IPMI Macro and Structure Defintions to resolve build errors and sent for
review.

-Manic

-----Original Message-----
From: gaoliming <gaoliming@byosoft.com.cn>
Sent: Wednesday, June 16, 2021 10:51 PM
To: Manickavasakam Karpagavinayagam <manickavasakamk@ami.com>;
devel@edk2.groups.io
Cc: isaac.w.oram@intel.com; nathaniel.l.desimone@intel.com; Felix Polyudov
<Felixp@ami.com>; Harikrishna Doppalapudi <Harikrishnad@ami.com>;
Manish Jha <manishj@ami.com>; Zachary Bobroff <zacharyb@ami.com>
Subject: [EXTERNAL] 回复: [edk2][PATCH V1] MdePkg : Add IPMI Macro and
Structure Defintions to resolve the IPMI build error


**CAUTION: The e-mail below is from an external source. Please exercise
caution before opening attachments, clicking links, or following guidance.**

Manickavasakam:
Please update this patch. It also includes
0001-MdePkg-Add-IPMI-Macro-and-Structure-Defintions-to-re.patch.

The patch should only include the code changes in MdePkg.

Thanks
Liming
-----邮件原件-----
发件人: gaoliming <gaoliming@byosoft.com.cn>
发送时间: 2021年6月17日 10:50
收件人: 'manickavasakam karpagavinayagam'
<manickavasakamk@ami.com>; 'devel@edk2.groups.io'
<devel@edk2.groups.io>
抄送: 'isaac.w.oram@intel.com' <isaac.w.oram@intel.com>;
'nathaniel.l.desimone@intel.com' <nathaniel.l.desimone@intel.com>;
'Felixp@ami.com' <Felixp@ami.com>; 'Harikrishnad@ami.com'
<Harikrishnad@ami.com>; 'manishj@ami.com' <manishj@ami.com>;
'zacharyb@ami.com' <zacharyb@ami.com>
主题: 回复: [edk2][PATCH V1] MdePkg : Add IPMI Macro and Structure
Defintions to resolve the IPMI build error



-----邮件原件-----
发件人: manickavasakam karpagavinayagam
<manickavasakamk@ami.com>
发送时间: 2021年6月12日 5:50
收件人: devel@edk2.groups.io
抄送: isaac.w.oram@intel.com; nathaniel.l.desimone@intel.com;
Felixp@ami.com; Harikrishnad@ami.com; manishj@ami.com;
zacharyb@ami.com; manickavasakamk@ami.com;
gaoliming@byosoft.com.cn
主题: [edk2][PATCH V1] MdePkg : Add IPMI Macro and Structure
Defintions
to resolve the IPMI build error

Build error reported for missing structures
IPMI_SET_BOOT_OPTIONS_RESPONSE,
EFI_IPMI_MSG_GET_BMC_EXEC_RSP and
macros EFI_FIRMWARE_GET_BMC_EXECUTION_CONTEXT
EFI_FIRMWARE_BMC_IN_FULL_RUNTIME/EFI_FIRMWARE_BMC_IN_FORCE
D_UPDATE_MODE
when using
edk2-platforms\Features\Intel\OutOfBandManagement\IpmiFeaturePkg

MdePkg : Rename IPMI Macro and Structure Defintions

Rename the EFI_IPMI_MSG_GET_BMC_EXEC_RSPB,
EFI_FIRMWARE_GET_BMC_EXECUTION_CONTEXT
EFI_FIRMWARE_BMC_IN_FORCED_UPDATE_MODE to
IPMI_MSG_GET_BMC_EXEC_RSPB,IPMI_GET_BMC_EXECUTION_CONTEXT
IPMI_BMC_IN_FORCED_UPDATE_MODE
---

Notes:
V1 :
- Rename the EFI_IPMI_MSG_GET_BMC_EXEC_RSPB,
EFI_FIRMWARE_GET_BMC_EXECUTION_CONTEXT
- EFI_FIRMWARE_BMC_IN_FORCED_UPDATE_MODE to
IPMI_MSG_GET_BMC_EXEC_RSPB,IPMI_GET_BMC_EXECUTION_CONTEXT
- IPMI_BMC_IN_FORCED_UPDATE_MODE

0001-MdePkg-Add-IPMI-Macro-and-Structure-Defintions-to-re.patch |
61
++++++++++++++++++++
MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
|
4 ++
MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
|
18 ++++++
3 files changed, 83 insertions(+)

diff --git
a/0001-MdePkg-Add-IPMI-Macro-and-Structure-Defintions-to-re.patch
b/0001-MdePkg-Add-IPMI-Macro-and-Structure-Defintions-to-re.patch
new file mode 100644
index 0000000000..16d149e2d8
--- /dev/null
+++
b/0001-MdePkg-Add-IPMI-Macro-and-Structure-Defintions-to-re.patc
+++ h
@@ -0,0 +1,61 @@
+From c5e221cfe5d815883f39b71667b6e8f644a27390 Mon Sep 17
00:00:00
2001
+From: manickavasakam karpagavinayagam
<manickavasakamk@ami.com>
+Date: Thu, 10 Jun 2021 14:59:22 -0400
+Subject: [edk2][PATCH] MdePkg : Add IPMI Macro and Structure
+Defintions
to resolve
+ the IPMI build error
+
+Build error reported for missing structures
IPMI_SET_BOOT_OPTIONS_RESPONSE,
+EFI_IPMI_MSG_GET_BMC_EXEC_RSP and macros
EFI_FIRMWARE_GET_BMC_EXECUTION_CONTEXT
+EFI_FIRMWARE_BMC_IN_FULL_RUNTIME/EFI_FIRMWARE_BMC_IN_FORC
ED_UPDATE_MODE
+when using
edk2-platforms\Features\Intel\OutOfBandManagement\IpmiFeaturePkg
+---
+ MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h | 4 ++++
+MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h | 19
+++++++++++++++++++
+ 2 files changed, 23 insertions(+)
+
+diff --git a/MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
b/MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
+index 79db55523d..d7cdd3a865 100644
+--- a/MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
++++ b/MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
+@@ -186,6 +186,10 @@ typedef struct {
+ UINT8 ParameterData[0];
+ } IPMI_SET_BOOT_OPTIONS_REQUEST;
+
++typedef struct {
++ UINT8 CompletionCode:8;
++} IPMI_SET_BOOT_OPTIONS_RESPONSE;
++
+ //
+ // Definitions for Get System Boot options command // diff --git
+a/MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
b/MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
+index 2d892dbd5a..1c692cc792 100644
+--- a/MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
++++ b/MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
+@@ -17,4 +17,23 @@
+ // All Firmware commands and their structure definitions to follow
here
+ //
+
++/*--------------------------------------------------------------------
++----
---------------
-
++ Definitions for Get BMC Execution Context
++----------------------------------------------------------------------
++----
--------------*
/
++#define EFI_FIRMWARE_GET_BMC_EXECUTION_CONTEXT 0x23
++
++//
++// Constants and Structure definitions for "Get Device ID"
++command to
follow here
++//
++typedef struct {
++ UINT8 CurrentExecutionContext;
++ UINT8 PartitionPointer;
++} EFI_IPMI_MSG_GET_BMC_EXEC_RSP;
++
++//
++// Current Execution Context responses //
++#define EFI_FIRMWARE_BMC_IN_FULL_RUNTIME 0x10
++#define EFI_FIRMWARE_BMC_IN_FORCED_UPDATE_MODE 0x11
++
+ #endif
+--
+2.25.0.windows.1
+
diff --git a/MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
b/MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
index 79db55523d..d7cdd3a865 100644
--- a/MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
+++ b/MdePkg/Include/IndustryStandard/IpmiNetFnChassis.h
@@ -186,6 +186,10 @@ typedef struct {
UINT8 ParameterData[0];

} IPMI_SET_BOOT_OPTIONS_REQUEST;



+typedef struct {

+ UINT8 CompletionCode:8;

+} IPMI_SET_BOOT_OPTIONS_RESPONSE;

+

//

// Definitions for Get System Boot options command

//

diff --git a/MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
b/MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
index 2d892dbd5a..c4cbe2349b 100644
--- a/MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
+++ b/MdePkg/Include/IndustryStandard/IpmiNetFnFirmware.h
@@ -17,4 +17,22 @@
// All Firmware commands and their structure definitions to follow
here

//



+//
----------------------------------------------------------------------------
------------

+// Definitions for Get BMC Execution Context

+//
----------------------------------------------------------------------------
------------

+#define IPMI_GET_BMC_EXECUTION_CONTEXT 0x23

+

+//

+// Constants and Structure definitions for "Get Device ID" command
+to
follow here

+//

+typedef struct {

+ UINT8 CurrentExecutionContext;

+ UINT8 PartitionPointer;

+} IPMI_MSG_GET_BMC_EXEC_RSP;

+

+//

+// Current Execution Context responses

+//

+#define IPMI_BMC_IN_FORCED_UPDATE_MODE 0x11

+

#endif

--
2.25.0.windows.1


Please consider the environment before printing this email.

The information contained in this message may be confidential and
proprietary to American Megatrends (AMI). This communication is
intended
to be read only by the individual or entity to whom it is addressed
or
by their
designee. If the reader of this message is not the intended
recipient,
you are
on notice that any distribution of this message, in any form, is
strictly
prohibited. Please promptly notify the sender by reply e-mail or by
telephone at 770-246-8600, and then delete or destroy all copies of
the transmission.

-The information contained in this message may be confidential and
proprietary to American Megatrends (AMI). This communication is intended to
be read only by the individual or entity to whom it is addressed or by their
designee. If the reader of this message is not the intended recipient, you are
on notice that any distribution of this message, in any form, is strictly
prohibited. Please promptly notify the sender by reply e-mail or by telephone
at 770-246-8600, and then delete or destroy all copies of the transmission.


回复: [PATCH v1 1/1] MdeModulePkg/BdsDxe: Update BdsEntry to use Variable Policy

gaoliming
 

Ken:
This version looks good to me. If no other comment is got, I will merge
it.

Thanks
Liming

-----邮件原件-----
发件人: kenlautner3@gmail.com <kenlautner3@gmail.com>
发送时间: 2021年6月18日 0:07
收件人: devel@edk2.groups.io
抄送: Jian J Wang <jian.j.wang@intel.com>; Hao A Wu
<hao.a.wu@intel.com>; Zhichao Gao <zhichao.gao@intel.com>; Ray Ni
<ray.ni@intel.com>; Liming Gao <gaoliming@byosoft.com.cn>
主题: [PATCH v1 1/1] MdeModulePkg/BdsDxe: Update BdsEntry to use
Variable Policy

From: Ken Lautner <klautner@microsoft.com>

Changed BdsEntry.c to use Variable Policy instead of Variable Lock
as Variable Lock will be Deprecated eventually

Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Hao A Wu <hao.a.wu@intel.com>
Cc: Zhichao Gao <zhichao.gao@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>

Signed-off-by: Kenneth Lautner <kenlautner3@gmail.com>
Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
---
MdeModulePkg/Universal/BdsDxe/Bds.h | 1 -
MdeModulePkg/Universal/BdsDxe/BdsDxe.inf | 4 +++-
MdeModulePkg/Universal/BdsDxe/BdsEntry.c | 20 +++++++++++++++-----
3 files changed, 18 insertions(+), 7 deletions(-)

diff --git a/MdeModulePkg/Universal/BdsDxe/Bds.h
b/MdeModulePkg/Universal/BdsDxe/Bds.h
index e7a9b5b4b7cb..84548041e861 100644
--- a/MdeModulePkg/Universal/BdsDxe/Bds.h
+++ b/MdeModulePkg/Universal/BdsDxe/Bds.h
@@ -17,7 +17,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent


#include <Protocol/Bds.h>

#include <Protocol/LoadedImage.h>

-#include <Protocol/VariableLock.h>

#include <Protocol/DeferredImageLoad.h>



#include <Library/UefiDriverEntryPoint.h>

diff --git a/MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
b/MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
index 9310b4dccb18..76ff6a0f5fc3 100644
--- a/MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
+++ b/MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
@@ -50,6 +50,8 @@
BaseMemoryLib

DebugLib

UefiBootManagerLib

+ VariablePolicyLib

+ VariablePolicyHelperLib

PlatformBootManagerLib

PcdLib

PrintLib

@@ -77,7 +79,7 @@
[Protocols]

gEfiBdsArchProtocolGuid ## PRODUCES

gEfiSimpleTextInputExProtocolGuid ## CONSUMES

- gEdkiiVariableLockProtocolGuid ##
SOMETIMES_CONSUMES

+ gEdkiiVariablePolicyProtocolGuid ##
SOMETIMES_CONSUMES

gEfiDeferredImageLoadProtocolGuid ## CONSUMES



[FeaturePcd]

diff --git a/MdeModulePkg/Universal/BdsDxe/BdsEntry.c
b/MdeModulePkg/Universal/BdsDxe/BdsEntry.c
index 83b773a2fa5f..13c10bdc5bf8 100644
--- a/MdeModulePkg/Universal/BdsDxe/BdsEntry.c
+++ b/MdeModulePkg/Universal/BdsDxe/BdsEntry.c
@@ -15,6 +15,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
#include "Bds.h"

#include "Language.h"

#include "HwErrRecSupport.h"

+#include <Library/VariablePolicyHelperLib.h>



#define SET_BOOT_OPTION_SUPPORT_KEY_COUNT(a, c) { \

(a) = ((a) & ~EFI_BOOT_OPTION_SUPPORT_COUNT) | (((c) <<
LowBitSet32 (EFI_BOOT_OPTION_SUPPORT_COUNT)) &
EFI_BOOT_OPTION_SUPPORT_COUNT); \

@@ -670,7 +671,7 @@ BdsEntry (
EFI_STATUS Status;

UINT32 BootOptionSupport;

UINT16 BootTimeOut;

- EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock;

+ EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy;

UINTN Index;

EFI_BOOT_MANAGER_LOAD_OPTION LoadOption;

UINT16 *BootNext;

@@ -716,12 +717,21 @@ BdsEntry (
//

// Mark the read-only variables if the Variable Lock protocol exists

//

- Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL,
(VOID **) &VariableLock);

- DEBUG ((EFI_D_INFO, "[BdsDxe] Locate Variable Lock protocol - %r\n",
Status));

+ Status = gBS->LocateProtocol(&gEdkiiVariablePolicyProtocolGuid, NULL,
(VOID**)&VariablePolicy);

+ DEBUG((DEBUG_INFO, "[BdsDxe] Locate Variable Policy protocol - %r\n",
Status));

if (!EFI_ERROR (Status)) {

for (Index = 0; Index < ARRAY_SIZE (mReadOnlyVariables); Index++) {

- Status = VariableLock->RequestToLock (VariableLock,
mReadOnlyVariables[Index], &gEfiGlobalVariableGuid);

- ASSERT_EFI_ERROR (Status);

+ Status = RegisterBasicVariablePolicy(

+ VariablePolicy,

+ &gEfiGlobalVariableGuid,

+ mReadOnlyVariables[Index],

+ VARIABLE_POLICY_NO_MIN_SIZE,

+ VARIABLE_POLICY_NO_MAX_SIZE,

+ VARIABLE_POLICY_NO_MUST_ATTR,

+ VARIABLE_POLICY_NO_CANT_ATTR,

+ VARIABLE_POLICY_TYPE_LOCK_NOW

+ );

+ ASSERT_EFI_ERROR(Status);

}

}



--
2.31.1.windows.1


回复: [edk2-devel] [PATCH v2 0/8] IORT Rev E.b specification updates

gaoliming
 

Sami:
I agree this change. With this patch, will you update the existing
platform to use the matched version macro EFI_ACPI_IO_REMAPPING_TABLE_REV0?

Thanks
Liming

-----邮件原件-----
发件人: devel@edk2.groups.io <devel@edk2.groups.io> 代表 Sami
Mujawar
发送时间: 2021年6月17日 17:55
收件人: devel@edk2.groups.io
抄送: Sami Mujawar <sami.mujawar@arm.com>; Alexei.Fedorov@arm.com;
ardb+tianocore@kernel.org; Matteo.Carlini@arm.com;
Ben.Adderson@arm.com; steven.price@arm.com;
Lorenzo.Pieralisi@arm.com; michael.d.kinney@intel.com;
gaoliming@byosoft.com.cn; zhiguang.liu@intel.com; ray.ni@intel.com;
zhichao.gao@intel.com; nd@arm.com
主题: [edk2-devel] [PATCH v2 0/8] IORT Rev E.b specification updates

Bugzilla: 3458 - Add support IORT Rev E.b specification updates
(https://bugzilla.tianocore.org/show_bug.cgi?id=3458)

The IO Remapping Table (IORT) specification has been updated to
rev E.b. The following updates are introduced including the errata
to rev E and E.a:
- increments the IORT table revision to 3.
- updates the node definition to add an 'Identifier' field.
- adds definition of node type 6 - Reserved Memory Range node.
- adds definition for Memory Range Descriptors.
- adds flag to indicate PRI support for root complexes.
- adds flag to indicate if the root complex supports forwarding
of PASID information on translated transactions to the SMMU.

The v1 patch series:
- Updates the IORT header file to match the Rev E.b specification.
- Add support to parse IORT Rev E.b tables
- Add support to generate IORT Rev E.b compliant ACPI tables
using Dynamic Tables Framework.

This v2 patch series includes all changes from v1 patch series
except the following 2 patches have been modified to set the
EFI_ACPI_IO_REMAPPING_TABLE_REVISION macro to Rev 0 as setting
to Rev 3 will break existing platforms, the problem being that
the Identifier field in the IORT nodes would not be unique.
- MdePkg: IORT header update for IORT Rev E.b spec
- DynamicTablesPkg: IORT generator updates for Rev E.b spec

The changes can be seen at:
https://github.com/samimujawar/edk2/tree/1527_iort_rev_eb_v2

Sami Mujawar (8):
MdePkg: Fix IORT header file include guard
MdePkg: IORT header update for IORT Rev E.b spec
ShellPkg: Acpiview: Abbreviate field names to preserve alignment
ShellPkg: Acpiview: IORT parser update for IORT Rev E.b spec
DynamicTablesPkg: IORT set reference to Id array only if present
DynamicTablesPkg: IORT set reference to interrupt array if present
DynamicTablesPkg: Update ArmNameSpaceObjects for IORT Rev E.b
DynamicTablesPkg: IORT generator updates for Rev E.b spec

DynamicTablesPkg/Include/ArmNameSpaceObjects.h
| 58 ++
DynamicTablesPkg/Library/Acpi/Arm/AcpiIortLibArm/IortGenerator.c
| 772 ++++++++++++++++++--
DynamicTablesPkg/Library/Acpi/Arm/AcpiIortLibArm/IortGenerator.h
| 5 +-
MdePkg/Include/IndustryStandard/IoRemappingTable.h
| 71 +-
ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Iort/IortParser.c |
207 +++++-
5 files changed, 1013 insertions(+), 100 deletions(-)

--
'Guid(CE165669-3EF3-493F-B85D-6190EE5B9759)'





Re: [edk2-platforms][PATCH v1 1/1] MinPlatformPkg: Add missing components to DSC

Michael Kubacki
 

MinPlatformPkg maintainers, can we please get this in soon if there are no concerns?

Thanks,
Michael

On 6/7/2021 10:30 AM, Michael Kubacki wrote:
From: Michael Kubacki <michael.kubacki@microsoft.com>
REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3033
Adds several libraries and modules to the MinPlatformPkg build that
are currently missing.
Cc: Chasel Chiu <chasel.chiu@intel.com>
Cc: Nate DeSimone <nathaniel.l.desimone@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Eric Dong <eric.dong@intel.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
---
Platform/Intel/MinPlatformPkg/MinPlatformPkg.dsc | 14 ++++++++++++--
1 file changed, 12 insertions(+), 2 deletions(-)
diff --git a/Platform/Intel/MinPlatformPkg/MinPlatformPkg.dsc b/Platform/Intel/MinPlatformPkg/MinPlatformPkg.dsc
index 35cbd40abb05..c64f784275bb 100644
--- a/Platform/Intel/MinPlatformPkg/MinPlatformPkg.dsc
+++ b/Platform/Intel/MinPlatformPkg/MinPlatformPkg.dsc
@@ -156,7 +156,9 @@ [Components]
MinPlatformPkg/Acpi/Library/BoardAcpiTableLibNull/BoardAcpiTableLibNull.inf
MinPlatformPkg/Acpi/Library/MultiBoardAcpiSupportLib/DxeMultiBoardAcpiSupportLib.inf
MinPlatformPkg/Acpi/Library/MultiBoardAcpiSupportLib/SmmMultiBoardAcpiSupportLib.inf
+ MinPlatformPkg/Acpi/MinDsdt/MinDsdt.inf
+ MinPlatformPkg/Bds/Library/BoardBootManagerLibNull/BoardBootManagerLibNull.inf
MinPlatformPkg/Bds/Library/DxePlatformBootManagerLib/DxePlatformBootManagerLib.inf
MinPlatformPkg/Flash/SpiFvbService/SpiFvbServiceSmm.inf
@@ -169,9 +171,15 @@ [Components]
MinPlatformPkg/FspWrapper/Library/PeiFspWrapperPlatformLib/PeiFspWrapperPlatformLib.inf
MinPlatformPkg/FspWrapper/Library/DxeFspWrapperPlatformLib/DxeFspWrapperPlatformLib.inf
+ MinPlatformPkg/Library/CompressLib/CompressLib.inf
+ MinPlatformPkg/Library/SetCacheMtrrLib/SetCacheMtrrLib.inf
+ MinPlatformPkg/Library/SetCacheMtrrLib/SetCacheMtrrLibNull.inf
+ MinPlatformPkg/Library/SerialPortTerminalLib/SerialPortTerminalLib.inf
+
MinPlatformPkg/Hsti/HstiIbvPlatformDxe/HstiIbvPlatformDxe.inf
MinPlatformPkg/Pci/Library/PciHostBridgeLibSimple/PciHostBridgeLibSimple.inf
+ MinPlatformPkg/Pci/Library/PciSegmentInfoLibSimple/PciSegmentInfoLibSimple.inf
MinPlatformPkg/PlatformInit/ReportFv/ReportFvPei.inf
MinPlatformPkg/PlatformInit/PlatformInitPei/PlatformInitPreMem.inf
@@ -182,6 +190,8 @@ [Components]
MinPlatformPkg/PlatformInit/Library/BoardInitLibNull/BoardInitLibNull.inf
MinPlatformPkg/PlatformInit/Library/MultiBoardInitSupportLib/PeiMultiBoardInitSupportLib.inf
MinPlatformPkg/PlatformInit/Library/MultiBoardInitSupportLib/DxeMultiBoardInitSupportLib.inf
+ MinPlatformPkg/PlatformInit/Library/PeiReportFvLib/PeiReportFvLib.inf
+ MinPlatformPkg/PlatformInit/Library/ReportCpuHobLib/ReportCpuHobLib.inf
MinPlatformPkg/PlatformInit/SiliconPolicyPei/SiliconPolicyPeiPreMem.inf
MinPlatformPkg/PlatformInit/SiliconPolicyPei/SiliconPolicyPeiPostMem.inf
MinPlatformPkg/PlatformInit/SiliconPolicyDxe/SiliconPolicyDxe.inf
@@ -194,16 +204,16 @@ [Components]
MinPlatformPkg/Test/Library/TestPointCheckLib/SecTestPointCheckLib.inf
MinPlatformPkg/Test/Library/TestPointCheckLib/PeiTestPointCheckLib.inf
MinPlatformPkg/Test/Library/TestPointCheckLib/DxeTestPointCheckLib.inf
+ MinPlatformPkg/Test/Library/TestPointCheckLib/SmmTestPointCheckLib.inf
MinPlatformPkg/Test/Library/TestPointLib/DxeTestPointLib.inf
MinPlatformPkg/Test/Library/TestPointLib/PeiTestPointLib.inf
MinPlatformPkg/Test/Library/TestPointLib/SmmTestPointLib.inf
MinPlatformPkg/Test/TestPointStubDxe/TestPointStubDxe.inf
MinPlatformPkg/Test/TestPointDumpApp/TestPointDumpApp.inf
-!if gMinPlatformPkgTokenSpaceGuid.PcdTpm2Enable == TRUE
+ MinPlatformPkg/Tcg/Library/TpmPlatformHierarchyLib/TpmPlatformHierarchyLib.inf
MinPlatformPkg/Tcg/Tcg2PlatformPei/Tcg2PlatformPei.inf
MinPlatformPkg/Tcg/Tcg2PlatformDxe/Tcg2PlatformDxe.inf
-!endif
[BuildOptions]
*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES


Re: [edk2-platforms][PATCH v2 0/4] MinPlatformPkg: Add TPM platform hier disable support

Michael Kubacki
 

MinPlatformPkg maintainers, can we please get this in soon if there's no concern?

Thanks,
Michael

On 6/15/2021 8:41 PM, Yao, Jiewen wrote:
Thank you, Michael.
Acked-by: Jiewen Yao <Jiewen.yao@intel.com>

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Michael
Kubacki
Sent: Wednesday, June 16, 2021 4:57 AM
To: devel@edk2.groups.io
Cc: Chiu, Chasel <chasel.chiu@intel.com>; Desimone, Nathaniel L
<nathaniel.l.desimone@intel.com>; Liming Gao <gaoliming@byosoft.com.cn>;
Dong, Eric <eric.dong@intel.com>; Yao, Jiewen <jiewen.yao@intel.com>;
Jeremiah Cox <jerecox@microsoft.com>
Subject: Re: [edk2-devel] [edk2-platforms][PATCH v2 0/4] MinPlatformPkg: Add
TPM platform hier disable support

It's been a week and I haven't seen any feedback. Please review when
possible.

Thanks,
Michael

On 6/7/2021 12:05 PM, Michael Kubacki wrote:
From: Michael Kubacki <michael.kubacki@microsoft.com>

REF:https://bugzilla.tianocore.org/show_bug.cgi?id=3411

This patch series adds support in TpmPlatformHierarchyLib to either
randomize the platform auth (current behavior) or disable the
platform auth (new behavior) based on a new PCD introduced to
MinPlatformPkg: PcdRandomizePlatformHierarchy.

Some platforms that would like to adopt MinPlatformPkg prefer to
disable the platform hierarchy as opposed to the randomization
approach.

Minor changes are included to eliminate code duplication in impacted
code.

V2 changes:
1. Update code that randomizes the platform auth in Tcg2PlatformPei
to use the TpmPlatformHierarchyLib interface for platform
hierarchy configuration.
2. Remove pre-existing redundant code in Tcg2PlatformPei.
3. Add a PCD to allow the platform integrator to choose how to
configure the TPM platform hierarchy.

Cc: Chasel Chiu <chasel.chiu@intel.com>
Cc: Nate DeSimone <nathaniel.l.desimone@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jeremiah Cox <jerecox@microsoft.com>
Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>

Michael Kubacki (4):
MinPlatformPkg: Add TpmPlatformHierarchyLib to Components in DSC
MinPlatformPkg/TpmPlatformHierarchyLib: Add PEI support
MinPlatformPkg/Tcg2PlatformPei: Use TpmPlatformHierarchyLib
MinPlatformPkg/TpmPlatformHierarchyLib: Add disable support

Platform/Intel/MinPlatformPkg/Tcg/Library/{TpmPlatformHierarchyLib/TpmPlat
formHierarchyLib.c =>
PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.c} | 72
+++++++++--
Platform/Intel/MinPlatformPkg/Tcg/Tcg2PlatformPei/Tcg2PlatformPei.c
| 130 +-------------------
Platform/Intel/MinPlatformPkg/Include/Library/TpmPlatformHierarchyLib.h
| 4 +-
Platform/Intel/MinPlatformPkg/MinPlatformPkg.dec
| 1 +
Platform/Intel/MinPlatformPkg/MinPlatformPkg.dsc
| 4 +-
Platform/Intel/MinPlatformPkg/Tcg/Library/{TpmPlatformHierarchyLib/TpmPlat
formHierarchyLib.inf =>
PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.inf} | 22 ++--
Platform/Intel/MinPlatformPkg/Tcg/Tcg2PlatformPei/Tcg2PlatformPei.inf
| 2 +
7 files changed, 85 insertions(+), 150 deletions(-)
rename
Platform/Intel/MinPlatformPkg/Tcg/Library/{TpmPlatformHierarchyLib/TpmPlat
formHierarchyLib.c =>
PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.c} (70%)
rename
Platform/Intel/MinPlatformPkg/Tcg/Library/{TpmPlatformHierarchyLib/TpmPlat
formHierarchyLib.inf =>
PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.inf} (66%)


9481 - 9500 of 86113