Date   

Re: [PATCH v3 0/3] Add PayloadLoaderPeim which can load ELF payload

Ni, Ray
 

Since the V3 did a very straightforward change which is to change PLD_ to
UNIVERSAL_PAYLOAD_.
I will carry all the Reviewed-by/Acked-by from V2 and merge directly.

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Ni, Ray
Sent: Wednesday, June 16, 2021 2:59 PM
To: devel@edk2.groups.io
Subject: [edk2-devel] [PATCH v3 0/3] Add PayloadLoaderPeim which can load
ELF payload

v3:
Change PLD_ to UNIVERSAL_PAYLOAD_ based on Mike's comments.

v2:
Separate the patch set from the patch that adds CLANGDWARF toolchain.
Add missing function header commments.
Change DEBUG_ERROR to DEBUG_INFO for information debug message.


Ray Ni (3):
MdeModulePkg/UniversalPayload: Add definition for extra info in
payload
UefiPayloadPkg: Add PayloadLoaderPeim which can load ELF payload
PeiCore: Remove assertion when failing to load PE image

MdeModulePkg/Core/Pei/Image/Image.c | 5 +-
.../Include/UniversalPayload/ExtraData.h | 28 +
.../UniversalPayload/UniversalPayload.h | 24 +
MdeModulePkg/MdeModulePkg.dec | 3 +
UefiPayloadPkg/PayloadLoaderPeim/ElfLib.h | 122 +++
.../PayloadLoaderPeim/ElfLib/Elf32.h | 252 +++++
.../PayloadLoaderPeim/ElfLib/Elf32Lib.c | 451 ++++++++
.../PayloadLoaderPeim/ElfLib/Elf64.h | 254 +++++
.../PayloadLoaderPeim/ElfLib/Elf64Lib.c | 460 ++++++++
.../PayloadLoaderPeim/ElfLib/ElfCommon.h | 983 ++++++++++++++++++
.../PayloadLoaderPeim/ElfLib/ElfLib.c | 473 +++++++++
.../PayloadLoaderPeim/ElfLib/ElfLibInternal.h | 109 ++
.../PayloadLoaderPeim/PayloadLoaderPeim.c | 187 ++++
.../PayloadLoaderPeim/PayloadLoaderPeim.inf | 59 ++
14 files changed, 3406 insertions(+), 4 deletions(-)
create mode 100644 MdeModulePkg/Include/UniversalPayload/ExtraData.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32Lib.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64Lib.c
create mode 100644
UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfCommon.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLib.c
create mode 100644
UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLibInternal.h
create mode 100644
UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c
create mode 100644
UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf

--
2.31.1.windows.1





[PATCH v3 3/3] PeiCore: Remove assertion when failing to load PE image

Ni, Ray
 

EFI_PEI_LOAD_FILE_PPI is invoked by DxeIpl for loading DxeCore.
It's possible that the instance produced by PeiCore fails to load but
other instances of EFI_PEI_LOAD_FILE_PPI can load.

Signed-off-by: Ray Ni <ray.ni@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Acked-by: Hao A Wu <hao.a.wu@intel.com>
Cc: Dandan Bi <dandan.bi@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
---
MdeModulePkg/Core/Pei/Image/Image.c | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/MdeModulePkg/Core/Pei/Image/Image.c b/MdeModulePkg/Core/Pei/Im=
age/Image.c
index 1d15774527..5af3895191 100644
--- a/MdeModulePkg/Core/Pei/Image/Image.c
+++ b/MdeModulePkg/Core/Pei/Image/Image.c
@@ -1,7 +1,7 @@
/** @file=0D
Pei Core Load Image Support=0D
=0D
-Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>=0D
+Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.<BR>=0D
SPDX-License-Identifier: BSD-2-Clause-Patent=0D
=0D
**/=0D
@@ -661,9 +661,6 @@ PeiLoadImageLoadImage (
&ImageEntryPoint=0D
);=0D
=0D
- ASSERT_EFI_ERROR (Status);=0D
-=0D
-=0D
if (EFI_ERROR (Status)) {=0D
return Status;=0D
}=0D
--=20
2.31.1.windows.1


[PATCH v3 2/3] UefiPayloadPkg: Add PayloadLoaderPeim which can load ELF payload

Ni, Ray
 

Per universal payload spec, the payload is in ELF format.
The patch adds a payload loader that supports to load ELF image.

The location of extra data sections whose names start with "upld."
is stored in UNIVERSAL_PAYLOAD_EXTRA_DATA HOB.

Signed-off-by: Maurice Ma <maurice.ma@intel.com>
Signed-off-by: Ray Ni <ray.ni@intel.com>
Cc: Maurice Ma <maurice.ma@intel.com>
Reviewed-by: Guo Dong <guo.dong@intel.com>
Cc: Benjamin You <benjamin.you@intel.com>
---
UefiPayloadPkg/PayloadLoaderPeim/ElfLib.h | 122 +++
.../PayloadLoaderPeim/ElfLib/Elf32.h | 252 +++++
.../PayloadLoaderPeim/ElfLib/Elf32Lib.c | 451 ++++++++
.../PayloadLoaderPeim/ElfLib/Elf64.h | 254 +++++
.../PayloadLoaderPeim/ElfLib/Elf64Lib.c | 460 ++++++++
.../PayloadLoaderPeim/ElfLib/ElfCommon.h | 983 ++++++++++++++++++
.../PayloadLoaderPeim/ElfLib/ElfLib.c | 473 +++++++++
.../PayloadLoaderPeim/ElfLib/ElfLibInternal.h | 109 ++
.../PayloadLoaderPeim/PayloadLoaderPeim.c | 187 ++++
.../PayloadLoaderPeim/PayloadLoaderPeim.inf | 59 ++
10 files changed, 3350 insertions(+)
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32Lib.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64Lib.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfCommon.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLib.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLibInternal.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf

diff --git a/UefiPayloadPkg/PayloadLoaderPeim/ElfLib.h b/UefiPayloadPkg/Pay=
loadLoaderPeim/ElfLib.h
new file mode 100644
index 0000000000..9cfc2912cf
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/ElfLib.h
@@ -0,0 +1,122 @@
+/** @file=0D
+ ELF library=0D
+=0D
+ Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef ELF_LIB_H_=0D
+#define ELF_LIB_H_=0D
+=0D
+#include <PiPei.h>=0D
+=0D
+#define ELF_CLASS32 1=0D
+#define ELF_CLASS64 2=0D
+=0D
+#define ELF_PT_LOAD 1=0D
+=0D
+typedef struct {=0D
+ RETURN_STATUS ParseStatus; ///< Return the status after Pars=
eElfImage().=0D
+ UINT8 *FileBase; ///< The source location in memor=
y.=0D
+ UINTN FileSize; ///< The size including sections =
that don't require loading.=0D
+ UINT8 *PreferredImageAddress; ///< The preferred image to be lo=
aded. No relocation is needed if loaded to this address.=0D
+ BOOLEAN ReloadRequired; ///< The image needs a new memory=
location for running.=0D
+ UINT8 *ImageAddress; ///< The destination memory addre=
ss set by caller.=0D
+ UINTN ImageSize; ///< The memory size for loading =
and execution.=0D
+ UINT32 EiClass;=0D
+ UINT32 ShNum;=0D
+ UINT32 PhNum;=0D
+ UINTN ShStrOff;=0D
+ UINTN ShStrLen;=0D
+ UINTN EntryPoint; ///< Return the actual entry poin=
t after LoadElfImage().=0D
+} ELF_IMAGE_CONTEXT;=0D
+=0D
+=0D
+typedef struct {=0D
+ UINT32 PtType;=0D
+ UINTN Offset;=0D
+ UINTN Length;=0D
+ UINTN MemLen;=0D
+ UINTN MemAddr;=0D
+ UINTN Alignment;=0D
+} SEGMENT_INFO;=0D
+=0D
+/**=0D
+ Parse the ELF image info.=0D
+=0D
+ @param[in] ImageBase Memory address of an image.=0D
+ @param[out] ElfCt The EFL image context pointer.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER Input parameters are not valid.=0D
+ @retval EFI_UNSUPPORTED Unsupported binary type.=0D
+ @retval EFI_LOAD_ERROR ELF binary loading error.=0D
+ @retval EFI_SUCCESS ELF binary is loaded successfully.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+ParseElfImage (=0D
+ IN VOID *ImageBase,=0D
+ OUT ELF_IMAGE_CONTEXT *ElfCt=0D
+ );=0D
+=0D
+/**=0D
+ Load the ELF segments to specified address in ELF header.=0D
+=0D
+ This function loads ELF image segments into memory address specified=0D
+ in ELF program header.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER Input parameters are not valid.=0D
+ @retval EFI_UNSUPPORTED Unsupported binary type.=0D
+ @retval EFI_LOAD_ERROR ELF binary loading error.=0D
+ @retval EFI_SUCCESS ELF binary is loaded successfully.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LoadElfImage (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ );=0D
+=0D
+/**=0D
+ Get a ELF section name from its index.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+ @param[in] SectionIndex ELF section index.=0D
+ @param[out] SectionName The pointer to the section name.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER ElfCt or SecName is NULL.=0D
+ @retval EFI_NOT_FOUND Could not find the section.=0D
+ @retval EFI_SUCCESS Section name was filled successfully.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+GetElfSectionName (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt,=0D
+ IN UINT32 SectionIndex,=0D
+ OUT CHAR8 **SectionName=0D
+ );=0D
+=0D
+/**=0D
+ Get the offset and size of x-th ELF section.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+ @param[in] Index ELF section index.=0D
+ @param[out] Offset Return the offset of the specific sectio=
n.=0D
+ @param[out] Size Return the size of the specific section.=
=0D
+=0D
+ @retval EFI_INVALID_PARAMETER ImageBase, Offset or Size is NULL.=0D
+ @retval EFI_INVALID_PARAMETER EiClass doesn't equal to ELFCLASS32 or E=
LFCLASS64.=0D
+ @retval EFI_NOT_FOUND Could not find the section.=0D
+ @retval EFI_SUCCESS Offset and Size are returned.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+GetElfSectionPos (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt,=0D
+ IN UINT32 Index,=0D
+ OUT UINTN *Offset,=0D
+ OUT UINTN *Size=0D
+ );=0D
+#endif /* ELF_LIB_H_ */=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32.h b/UefiPayloadP=
kg/PayloadLoaderPeim/ElfLib/Elf32.h
new file mode 100644
index 0000000000..ebed5f00c3
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32.h
@@ -0,0 +1,252 @@
+/** @file=0D
+Ported ELF include files from FreeBSD=0D
+=0D
+Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>=0D
+SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+=0D
+**/=0D
+/*-=0D
+ * Copyright (c) 1996-1998 John D. Polstra.=0D
+ * All rights reserved.=0D
+ *=0D
+ * Redistribution and use in source and binary forms, with or without=0D
+ * modification, are permitted provided that the following conditions=0D
+ * are met:=0D
+ * 1. Redistributions of source code must retain the above copyright=0D
+ * notice, this list of conditions and the following disclaimer.=0D
+ * 2. Redistributions in binary form must reproduce the above copyright=0D
+ * notice, this list of conditions and the following disclaimer in the=
=0D
+ * documentation and/or other materials provided with the distribution.=
=0D
+ *=0D
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND=
=0D
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=0D
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=0D
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE=
=0D
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=0D
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=
=0D
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=0D
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=0D
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=0D
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=
=0D
+ * SUCH DAMAGE.=0D
+ *=0D
+ * $FreeBSD: src/sys/sys/elf32.h,v 1.8.14.2 2007/12/03 21:30:36 marius Exp=
$=0D
+ */=0D
+=0D
+#ifndef _SYS_ELF32_H_=0D
+#define _SYS_ELF32_H_ 1=0D
+=0D
+=0D
+/*=0D
+ * ELF definitions common to all 32-bit architectures.=0D
+ */=0D
+=0D
+typedef UINT32 Elf32_Addr;=0D
+typedef UINT16 Elf32_Half;=0D
+typedef UINT32 Elf32_Off;=0D
+typedef INT32 Elf32_Sword;=0D
+typedef UINT32 Elf32_Word;=0D
+typedef UINT64 Elf32_Lword;=0D
+=0D
+typedef Elf32_Word Elf32_Hashelt;=0D
+=0D
+/* Non-standard class-dependent datatype used for abstraction. */=0D
+typedef Elf32_Word Elf32_Size;=0D
+typedef Elf32_Sword Elf32_Ssize;=0D
+=0D
+/*=0D
+ * ELF header.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ unsigned char e_ident[EI_NIDENT]; /* File identification. */=0D
+ Elf32_Half e_type; /* File type. */=0D
+ Elf32_Half e_machine; /* Machine architecture. */=0D
+ Elf32_Word e_version; /* ELF format version. */=0D
+ Elf32_Addr e_entry; /* Entry point. */=0D
+ Elf32_Off e_phoff; /* Program header file offset. */=0D
+ Elf32_Off e_shoff; /* Section header file offset. */=0D
+ Elf32_Word e_flags; /* Architecture-specific flags. */=0D
+ Elf32_Half e_ehsize; /* Size of ELF header in bytes. */=0D
+ Elf32_Half e_phentsize; /* Size of program header entry. */=0D
+ Elf32_Half e_phnum; /* Number of program header entries. */=0D
+ Elf32_Half e_shentsize; /* Size of section header entry. */=0D
+ Elf32_Half e_shnum; /* Number of section header entries. */=0D
+ Elf32_Half e_shstrndx; /* Section name strings section. */=0D
+} Elf32_Ehdr;=0D
+=0D
+/*=0D
+ * Section header.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ Elf32_Word sh_name; /* Section name (index into the=0D
+ section header string table). */=0D
+ Elf32_Word sh_type; /* Section type. */=0D
+ Elf32_Word sh_flags; /* Section flags. */=0D
+ Elf32_Addr sh_addr; /* Address in memory image. */=0D
+ Elf32_Off sh_offset; /* Offset in file. */=0D
+ Elf32_Word sh_size; /* Size in bytes. */=0D
+ Elf32_Word sh_link; /* Index of a related section. */=0D
+ Elf32_Word sh_info; /* Depends on section type. */=0D
+ Elf32_Word sh_addralign; /* Alignment in bytes. */=0D
+ Elf32_Word sh_entsize; /* Size of each entry in section. */=0D
+} Elf32_Shdr;=0D
+=0D
+/*=0D
+ * Program header.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ Elf32_Word p_type; /* Entry type. */=0D
+ Elf32_Off p_offset; /* File offset of contents. */=0D
+ Elf32_Addr p_vaddr; /* Virtual address in memory image. */=0D
+ Elf32_Addr p_paddr; /* Physical address (not used). */=0D
+ Elf32_Word p_filesz; /* Size of contents in file. */=0D
+ Elf32_Word p_memsz; /* Size of contents in memory. */=0D
+ Elf32_Word p_flags; /* Access permission flags. */=0D
+ Elf32_Word p_align; /* Alignment in memory and file. */=0D
+} Elf32_Phdr;=0D
+=0D
+/*=0D
+ * Dynamic structure. The ".dynamic" section contains an array of them.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ Elf32_Sword d_tag; /* Entry type. */=0D
+ union {=0D
+ Elf32_Word d_val; /* Integer value. */=0D
+ Elf32_Addr d_ptr; /* Address value. */=0D
+ } d_un;=0D
+} Elf32_Dyn;=0D
+=0D
+/*=0D
+ * Relocation entries.=0D
+ */=0D
+=0D
+/* Relocations that don't need an addend field. */=0D
+typedef struct {=0D
+ Elf32_Addr r_offset; /* Location to be relocated. */=0D
+ Elf32_Word r_info; /* Relocation type and symbol index. */=0D
+} Elf32_Rel;=0D
+=0D
+/* Relocations that need an addend field. */=0D
+typedef struct {=0D
+ Elf32_Addr r_offset; /* Location to be relocated. */=0D
+ Elf32_Word r_info; /* Relocation type and symbol index. */=0D
+ Elf32_Sword r_addend; /* Addend. */=0D
+} Elf32_Rela;=0D
+=0D
+/* Macros for accessing the fields of r_info. */=0D
+#define ELF32_R_SYM(info) ((info) >> 8)=0D
+#define ELF32_R_TYPE(info) ((unsigned char)(info))=0D
+=0D
+/* Macro for constructing r_info from field values. */=0D
+#define ELF32_R_INFO(sym, type) (((sym) << 8) + (unsigned char)(type))=0D
+=0D
+/*=0D
+ * Note entry header=0D
+ */=0D
+typedef Elf_Note Elf32_Nhdr;=0D
+=0D
+/*=0D
+ * Move entry=0D
+ */=0D
+typedef struct {=0D
+ Elf32_Lword m_value; /* symbol value */=0D
+ Elf32_Word m_info; /* size + index */=0D
+ Elf32_Word m_poffset; /* symbol offset */=0D
+ Elf32_Half m_repeat; /* repeat count */=0D
+ Elf32_Half m_stride; /* stride info */=0D
+} Elf32_Move;=0D
+=0D
+/*=0D
+ * The macros compose and decompose values for Move.r_info=0D
+ *=0D
+ * sym =3D ELF32_M_SYM(M.m_info)=0D
+ * size =3D ELF32_M_SIZE(M.m_info)=0D
+ * M.m_info =3D ELF32_M_INFO(sym, size)=0D
+ */=0D
+#define ELF32_M_SYM(info) ((info)>>8)=0D
+#define ELF32_M_SIZE(info) ((unsigned char)(info))=0D
+#define ELF32_M_INFO(sym, size) (((sym)<<8)+(unsigned char)(size))=0D
+=0D
+/*=0D
+ * Hardware/Software capabilities entry=0D
+ */=0D
+typedef struct {=0D
+ Elf32_Word c_tag; /* how to interpret value */=0D
+ union {=0D
+ Elf32_Word c_val;=0D
+ Elf32_Addr c_ptr;=0D
+ } c_un;=0D
+} Elf32_Cap;=0D
+=0D
+/*=0D
+ * Symbol table entries.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ Elf32_Word st_name; /* String table index of name. */=0D
+ Elf32_Addr st_value; /* Symbol value. */=0D
+ Elf32_Word st_size; /* Size of associated object. */=0D
+ unsigned char st_info; /* Type and binding information. */=0D
+ unsigned char st_other; /* Reserved (not used). */=0D
+ Elf32_Half st_shndx; /* Section index of symbol. */=0D
+} Elf32_Sym;=0D
+=0D
+/* Macros for accessing the fields of st_info. */=0D
+#define ELF32_ST_BIND(info) ((info) >> 4)=0D
+#define ELF32_ST_TYPE(info) ((info) & 0xf)=0D
+=0D
+/* Macro for constructing st_info from field values. */=0D
+#define ELF32_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))=0D
+=0D
+/* Macro for accessing the fields of st_other. */=0D
+#define ELF32_ST_VISIBILITY(oth) ((oth) & 0x3)=0D
+=0D
+/* Structures used by Sun & GNU symbol versioning. */=0D
+typedef struct=0D
+{=0D
+ Elf32_Half vd_version;=0D
+ Elf32_Half vd_flags;=0D
+ Elf32_Half vd_ndx;=0D
+ Elf32_Half vd_cnt;=0D
+ Elf32_Word vd_hash;=0D
+ Elf32_Word vd_aux;=0D
+ Elf32_Word vd_next;=0D
+} Elf32_Verdef;=0D
+=0D
+typedef struct=0D
+{=0D
+ Elf32_Word vda_name;=0D
+ Elf32_Word vda_next;=0D
+} Elf32_Verdaux;=0D
+=0D
+typedef struct=0D
+{=0D
+ Elf32_Half vn_version;=0D
+ Elf32_Half vn_cnt;=0D
+ Elf32_Word vn_file;=0D
+ Elf32_Word vn_aux;=0D
+ Elf32_Word vn_next;=0D
+} Elf32_Verneed;=0D
+=0D
+typedef struct=0D
+{=0D
+ Elf32_Word vna_hash;=0D
+ Elf32_Half vna_flags;=0D
+ Elf32_Half vna_other;=0D
+ Elf32_Word vna_name;=0D
+ Elf32_Word vna_next;=0D
+} Elf32_Vernaux;=0D
+=0D
+typedef Elf32_Half Elf32_Versym;=0D
+=0D
+typedef struct {=0D
+ Elf32_Half si_boundto; /* direct bindings - symbol bound to */=0D
+ Elf32_Half si_flags; /* per symbol flags */=0D
+} Elf32_Syminfo;=0D
+=0D
+#endif /* !_SYS_ELF32_H_ */=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32Lib.c b/UefiPaylo=
adPkg/PayloadLoaderPeim/ElfLib/Elf32Lib.c
new file mode 100644
index 0000000000..3fa100ce4a
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32Lib.c
@@ -0,0 +1,451 @@
+/** @file=0D
+ ELF library=0D
+=0D
+ Copyright (c) 2019 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include "ElfLibInternal.h"=0D
+=0D
+/**=0D
+ Return the section header specified by Index.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Index The section index.=0D
+=0D
+ @return Pointer to the section header.=0D
+**/=0D
+Elf32_Shdr *=0D
+GetElf32SectionByIndex (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Index=0D
+ )=0D
+{=0D
+ Elf32_Ehdr *Ehdr;=0D
+=0D
+ Ehdr =3D (Elf32_Ehdr *)ImageBase;=0D
+ if (Index >=3D Ehdr->e_shnum) {=0D
+ return NULL;=0D
+ }=0D
+=0D
+ return (Elf32_Shdr *)(ImageBase + Ehdr->e_shoff + Index * Ehdr->e_shents=
ize);=0D
+}=0D
+=0D
+/**=0D
+ Return the segment header specified by Index.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Index The segment index.=0D
+=0D
+ @return Pointer to the segment header.=0D
+**/=0D
+Elf32_Phdr *=0D
+GetElf32SegmentByIndex (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Index=0D
+ )=0D
+{=0D
+ Elf32_Ehdr *Ehdr;=0D
+=0D
+ Ehdr =3D (Elf32_Ehdr *)ImageBase;=0D
+ if (Index >=3D Ehdr->e_phnum) {=0D
+ return NULL;=0D
+ }=0D
+=0D
+ return (Elf32_Phdr *)(ImageBase + Ehdr->e_phoff + Index * Ehdr->e_phents=
ize);=0D
+}=0D
+=0D
+/**=0D
+ Return the section header specified by the range.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Offset The section offset.=0D
+ @param Size The section size.=0D
+=0D
+ @return Pointer to the section header.=0D
+**/=0D
+Elf32_Shdr *=0D
+GetElf32SectionByRange (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Offset,=0D
+ IN UINT32 Size=0D
+ )=0D
+{=0D
+ UINT32 Index;=0D
+ Elf32_Ehdr *Ehdr;=0D
+ Elf32_Shdr *Shdr;=0D
+=0D
+ Ehdr =3D (Elf32_Ehdr *)ImageBase;=0D
+=0D
+ Shdr =3D (Elf32_Shdr *) (ImageBase + Ehdr->e_shoff);=0D
+ for (Index =3D 0; Index < Ehdr->e_shnum; Index++) {=0D
+ if ((Shdr->sh_offset =3D=3D Offset) && (Shdr->sh_size =3D=3D Size)) {=
=0D
+ return Shdr;=0D
+ }=0D
+ Shdr =3D ELF_NEXT_ENTRY (Elf32_Shdr, Shdr, Ehdr->e_shentsize);=0D
+ }=0D
+ return NULL;=0D
+}=0D
+=0D
+/**=0D
+ Fix up the image based on the relocation entries.=0D
+=0D
+ @param Rela Relocation entries.=0D
+ @param RelaSize Total size of relocation entries.=0D
+ @param RelaEntrySize Relocation entry size.=0D
+ @param RelaType Type of relocation entry.=0D
+ @param Delta The delta between preferred image base and th=
e actual image base.=0D
+ @param DynamicLinking TRUE when fixing up according to dynamic relo=
cation.=0D
+=0D
+ @retval EFI_SUCCESS The image fix up is processed successfully.=0D
+**/=0D
+EFI_STATUS=0D
+ProcessRelocation32 (=0D
+ IN Elf32_Rela *Rela,=0D
+ IN UINT32 RelaSize,=0D
+ IN UINT32 RelaEntrySize,=0D
+ IN UINT32 RelaType,=0D
+ IN INTN Delta,=0D
+ IN BOOLEAN DynamicLinking=0D
+ )=0D
+{=0D
+ UINTN Index;=0D
+ UINT32 *Ptr;=0D
+ UINT32 Type;=0D
+=0D
+ for ( Index =3D 0=0D
+ ; RelaEntrySize * Index < RelaSize=0D
+ ; Index++, Rela =3D ELF_NEXT_ENTRY (Elf32_Rela, Rela, RelaEntrySize)=
=0D
+ ) {=0D
+ //=0D
+ // r_offset is the virtual address of the storage unit affected by the=
relocation.=0D
+ //=0D
+ Ptr =3D (UINT32 *)(UINTN)(Rela->r_offset + Delta);=0D
+ Type =3D ELF32_R_TYPE(Rela->r_info);=0D
+ switch (Type) {=0D
+ case R_386_NONE:=0D
+ case R_386_PC32:=0D
+ //=0D
+ // No fixup entry required.=0D
+ //=0D
+ break;=0D
+=0D
+ case R_386_32:=0D
+ if (DynamicLinking) {=0D
+ //=0D
+ // Dynamic section doesn't contain entries of this type.=0D
+ //=0D
+ DEBUG ((DEBUG_INFO, "Unsupported relocation type %02X\n", Type))=
;=0D
+ ASSERT (FALSE);=0D
+ } else {=0D
+ *Ptr +=3D (UINT32) Delta;=0D
+ }=0D
+ break;=0D
+=0D
+ case R_386_RELATIVE:=0D
+ if (DynamicLinking) {=0D
+ //=0D
+ // A: Represents the addend used to compute the value of the rel=
ocatable field.=0D
+ // B: Represents the base address at which a shared object has b=
een loaded into memory during execution.=0D
+ // Generally, a shared object is built with a 0 base virtual =
address, but the execution address will be different.=0D
+ //=0D
+ // B (Base Address) in ELF spec is slightly different:=0D
+ // An executable or shared object file's base address (on plat=
forms that support the concept) is calculated during=0D
+ // execution from three values: the virtual memory load addres=
s, the maximum page size, and the lowest virtual address=0D
+ // of a program's loadable segment. To compute the base addres=
s, one determines the memory address associated with the=0D
+ // lowest p_vaddr value for a PT_LOAD segment. This address is=
truncated to the nearest multiple of the maximum page size.=0D
+ // The corresponding p_vaddr value itself is also truncated to=
the nearest multiple of the maximum page size.=0D
+ //=0D
+ // *** The base address is the difference between the truncate=
d memory address and the truncated p_vaddr value. ***=0D
+ //=0D
+ // Delta in this function is B.=0D
+ //=0D
+ // Calculation: B + A=0D
+ //=0D
+ if (RelaType =3D=3D SHT_RELA) {=0D
+ ASSERT (*Ptr =3D=3D 0);=0D
+ *Ptr =3D (UINT32) Delta + Rela->r_addend;=0D
+ } else {=0D
+ //=0D
+ // A is stored in the field of relocation for REL type.=0D
+ //=0D
+ *Ptr =3D (UINT32) Delta + *Ptr;=0D
+ }=0D
+ } else {=0D
+ //=0D
+ // non-Dynamic section doesn't contain entries of this type.=0D
+ //=0D
+ DEBUG ((DEBUG_INFO, "Unsupported relocation type %02X\n", Type))=
;=0D
+ ASSERT (FALSE);=0D
+ }=0D
+ break;=0D
+=0D
+ default:=0D
+ DEBUG ((DEBUG_INFO, "Unsupported relocation type %02X\n", Type));=
=0D
+ }=0D
+ }=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Relocate the DYN type image.=0D
+=0D
+ @param ElfCt Point to image context.=0D
+=0D
+ @retval EFI_SUCCESS The relocation succeeds.=0D
+ @retval EFI_UNSUPPORTED The image doesn't contain a dynamic section.=0D
+**/=0D
+EFI_STATUS=0D
+RelocateElf32Dynamic (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ )=0D
+{=0D
+ UINT32 Index;=0D
+ Elf32_Phdr *Phdr;=0D
+ Elf32_Shdr *DynShdr;=0D
+ Elf32_Shdr *RelShdr;=0D
+ Elf32_Dyn *Dyn;=0D
+ UINT32 RelaOffset;=0D
+ UINT32 RelaCount;=0D
+ UINT32 RelaSize;=0D
+ UINT32 RelaEntrySize;=0D
+ UINT32 RelaType;=0D
+=0D
+ //=0D
+ // 1. Locate the dynamic section.=0D
+ //=0D
+ // If an object file participates in dynamic linking, its program header=
table=0D
+ // will have an element of type PT_DYNAMIC.=0D
+ // This ``segment'' contains the .dynamic section. A special symbol, _DY=
NAMIC,=0D
+ // labels the section, which contains an array of Elf32_Dyn or Elf64_Dyn=
.=0D
+ //=0D
+ DynShdr =3D NULL;=0D
+ for (Index =3D 0; Index < ElfCt->PhNum; Index++) {=0D
+ Phdr =3D GetElf32SegmentByIndex (ElfCt->FileBase, Index);=0D
+ ASSERT (Phdr !=3D NULL);=0D
+ if (Phdr->p_type =3D=3D PT_DYNAMIC) {=0D
+ //=0D
+ // Verify the existence of the dynamic section.=0D
+ //=0D
+ DynShdr =3D GetElf32SectionByRange (ElfCt->FileBase, Phdr->p_offset,=
Phdr->p_filesz);=0D
+ break;=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // It's abnormal a DYN ELF doesn't contain a dynamic section.=0D
+ //=0D
+ ASSERT (DynShdr !=3D NULL);=0D
+ if (DynShdr =3D=3D NULL) {=0D
+ return EFI_UNSUPPORTED;=0D
+ }=0D
+ ASSERT (DynShdr->sh_type =3D=3D SHT_DYNAMIC);=0D
+ ASSERT (DynShdr->sh_entsize >=3D sizeof (*Dyn));=0D
+=0D
+ //=0D
+ // 2. Locate the relocation section from the dynamic section.=0D
+ //=0D
+ RelaOffset =3D MAX_UINT32;=0D
+ RelaSize =3D 0;=0D
+ RelaCount =3D 0;=0D
+ RelaEntrySize =3D 0;=0D
+ RelaType =3D 0;=0D
+ for ( Index =3D 0, Dyn =3D (Elf32_Dyn *) (ElfCt->FileBase + DynShdr->sh_=
offset)=0D
+ ; Index < DynShdr->sh_size / DynShdr->sh_entsize=0D
+ ; Index++, Dyn =3D ELF_NEXT_ENTRY (Elf32_Dyn, Dyn, DynShdr->sh_entsi=
ze)=0D
+ ) {=0D
+ switch (Dyn->d_tag) {=0D
+ case DT_RELA:=0D
+ case DT_REL:=0D
+ //=0D
+ // DT_REL represent program virtual addresses.=0D
+ // A file's virtual addresses might not match the memory virtual a=
ddresses during execution.=0D
+ // When interpreting addresses contained in the dynamic structure,=
the dynamic linker computes actual addresses,=0D
+ // based on the original file value and the memory base address.=0D
+ // For consistency, files do not contain relocation entries to ``c=
orrect'' addresses in the dynamic structure.=0D
+ //=0D
+ RelaOffset =3D Dyn->d_un.d_ptr - (UINT32) (UINTN) ElfCt->Preferred=
ImageAddress;=0D
+ RelaType =3D (Dyn->d_tag =3D=3D DT_RELA) ? SHT_RELA: SHT_REL;=0D
+ break;=0D
+ case DT_RELACOUNT:=0D
+ case DT_RELCOUNT:=0D
+ RelaCount =3D Dyn->d_un.d_val;=0D
+ break;=0D
+ case DT_RELENT:=0D
+ case DT_RELAENT:=0D
+ RelaEntrySize =3D Dyn->d_un.d_val;=0D
+ break;=0D
+ case DT_RELSZ:=0D
+ case DT_RELASZ:=0D
+ RelaSize =3D Dyn->d_un.d_val;=0D
+ break;=0D
+ default:=0D
+ break;=0D
+ }=0D
+ }=0D
+=0D
+ if (RelaOffset =3D=3D MAX_UINT64) {=0D
+ ASSERT (RelaCount =3D=3D 0);=0D
+ ASSERT (RelaEntrySize =3D=3D 0);=0D
+ ASSERT (RelaSize =3D=3D 0);=0D
+ //=0D
+ // It's fine that a DYN ELF doesn't contain relocation section.=0D
+ //=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+=0D
+ //=0D
+ // Verify the existence of the relocation section.=0D
+ //=0D
+ RelShdr =3D GetElf32SectionByRange (ElfCt->FileBase, RelaOffset, RelaSiz=
e);=0D
+ ASSERT (RelShdr !=3D NULL);=0D
+ if (RelShdr =3D=3D NULL) {=0D
+ return EFI_UNSUPPORTED;=0D
+ }=0D
+ ASSERT (RelShdr->sh_type =3D=3D RelaType);=0D
+ ASSERT (RelShdr->sh_entsize =3D=3D RelaEntrySize);=0D
+=0D
+ //=0D
+ // 3. Process the relocation section.=0D
+ //=0D
+ ProcessRelocation32 (=0D
+ (Elf32_Rela *) (ElfCt->FileBase + RelShdr->sh_offset),=0D
+ RelShdr->sh_size, RelShdr->sh_entsize, RelShdr->sh_type,=0D
+ (UINTN) ElfCt->ImageAddress - (UINTN) ElfCt->PreferredImageAddress,=0D
+ TRUE=0D
+ );=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Relocate all sections in a ELF image.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+=0D
+ @retval EFI_UNSUPPORTED Relocation is not supported.=0D
+ @retval EFI_SUCCESS ELF image was relocated successfully.=0D
+**/=0D
+EFI_STATUS=0D
+RelocateElf32Sections (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ Elf32_Ehdr *Ehdr;=0D
+ Elf32_Shdr *RelShdr;=0D
+ Elf32_Shdr *Shdr;=0D
+ UINT32 Index;=0D
+ UINTN Delta;=0D
+=0D
+ Ehdr =3D (Elf32_Ehdr *)ElfCt->FileBase;=0D
+ if (Ehdr->e_machine !=3D EM_386) {=0D
+ return EFI_UNSUPPORTED;=0D
+ }=0D
+=0D
+ Delta =3D (UINTN) ElfCt->ImageAddress - (UINTN) ElfCt->PreferredImageAdd=
ress;=0D
+ ElfCt->EntryPoint =3D (UINTN)(Ehdr->e_entry + Delta);=0D
+=0D
+ //=0D
+ // 1. Relocate dynamic ELF using the relocation section pointed by dynam=
ic section=0D
+ //=0D
+ if (Ehdr->e_type =3D=3D ET_DYN) {=0D
+ DEBUG ((DEBUG_INFO, "DYN ELF: Relocate using dynamic sections...\n"));=
=0D
+ Status =3D RelocateElf32Dynamic (ElfCt);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+ return Status;=0D
+ }=0D
+=0D
+ //=0D
+ // 2. Executable ELF: Fix up the delta between actual image address and =
preferred image address.=0D
+ //=0D
+ // Linker already fixed up EXEC ELF based on the preferred image addres=
s.=0D
+ // A ELF loader in modern OS only loads it into the preferred image add=
ress.=0D
+ // The below relocation is unneeded in that case.=0D
+ // But the ELF loader in firmware supports to load the image to a diffe=
rent address.=0D
+ // The below relocation is needed in this case.=0D
+ //=0D
+ DEBUG ((DEBUG_INFO, "EXEC ELF: Fix actual/preferred base address delta .=
..\n"));=0D
+ for ( Index =3D 0, RelShdr =3D (Elf32_Shdr *) (ElfCt->FileBase + Ehdr->e=
_shoff)=0D
+ ; Index < Ehdr->e_shnum=0D
+ ; Index++, RelShdr =3D ELF_NEXT_ENTRY (Elf32_Shdr, RelShdr, Ehdr->=
e_shentsize)=0D
+ ) {=0D
+ if ((RelShdr->sh_type !=3D SHT_REL) && (RelShdr->sh_type !=3D SHT_RELA=
)) {=0D
+ continue;=0D
+ }=0D
+ Shdr =3D GetElf32SectionByIndex (ElfCt->FileBase, RelShdr->sh_info);=0D
+ if ((Shdr->sh_flags & SHF_ALLOC) =3D=3D SHF_ALLOC) {=0D
+ //=0D
+ // Only fix up sections that occupy memory during process execution.=
=0D
+ //=0D
+ ProcessRelocation32 (=0D
+ (Elf32_Rela *)((UINT8*)Ehdr + RelShdr->sh_offset),=0D
+ RelShdr->sh_size, RelShdr->sh_entsize, RelShdr->sh_type,=0D
+ Delta, FALSE=0D
+ );=0D
+ }=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Load ELF image which has 32-bit architecture.=0D
+=0D
+ Caller should set Context.ImageAddress to a proper value, either pointin=
g to=0D
+ a new allocated memory whose size equal to Context.ImageSize, or pointin=
g=0D
+ to Context.PreferredImageAddress.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+=0D
+ @retval EFI_SUCCESS ELF binary is loaded successfully.=0D
+ @retval Others Loading ELF binary fails.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+LoadElf32Image (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ )=0D
+{=0D
+ Elf32_Ehdr *Ehdr;=0D
+ Elf32_Phdr *Phdr;=0D
+ UINT16 Index;=0D
+ UINTN Delta;=0D
+=0D
+ ASSERT (ElfCt !=3D NULL);=0D
+=0D
+ //=0D
+ // Per the sprit of ELF, loading to memory only consumes info from progr=
am headers.=0D
+ //=0D
+ Ehdr =3D (Elf32_Ehdr *)ElfCt->FileBase;=0D
+=0D
+ for ( Index =3D 0, Phdr =3D (Elf32_Phdr *)(ElfCt->FileBase + Ehdr->e_pho=
ff)=0D
+ ; Index < Ehdr->e_phnum=0D
+ ; Index++, Phdr =3D ELF_NEXT_ENTRY (Elf32_Phdr, Phdr, Ehdr->e_phents=
ize)=0D
+ ) {=0D
+ //=0D
+ // Skip segments that don't require load (type tells, or size is 0)=0D
+ //=0D
+ if ((Phdr->p_type !=3D PT_LOAD) ||=0D
+ (Phdr->p_memsz =3D=3D 0)) {=0D
+ continue;=0D
+ }=0D
+=0D
+ //=0D
+ // The memory offset of segment relative to the image base=0D
+ // Note: CopyMem() does nothing when the dst equals to src.=0D
+ //=0D
+ Delta =3D Phdr->p_paddr - (UINT32) (UINTN) ElfCt->PreferredImageAddres=
s;=0D
+ CopyMem (ElfCt->ImageAddress + Delta, ElfCt->FileBase + Phdr->p_offset=
, Phdr->p_filesz);=0D
+ ZeroMem (ElfCt->ImageAddress + Delta + Phdr->p_filesz, Phdr->p_memsz -=
Phdr->p_filesz);=0D
+ }=0D
+=0D
+ //=0D
+ // Relocate when new new image base is not the preferred image base.=0D
+ //=0D
+ if (ElfCt->ImageAddress !=3D ElfCt->PreferredImageAddress) {=0D
+ RelocateElf32Sections (ElfCt);=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64.h b/UefiPayloadP=
kg/PayloadLoaderPeim/ElfLib/Elf64.h
new file mode 100644
index 0000000000..d64dc64a6a
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64.h
@@ -0,0 +1,254 @@
+/** @file=0D
+Ported ELF include files from FreeBSD=0D
+=0D
+Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>=0D
+SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+/*-=0D
+ * Copyright (c) 1996-1998 John D. Polstra.=0D
+ * All rights reserved.=0D
+ *=0D
+ * Redistribution and use in source and binary forms, with or without=0D
+ * modification, are permitted provided that the following conditions=0D
+ * are met:=0D
+ * 1. Redistributions of source code must retain the above copyright=0D
+ * notice, this list of conditions and the following disclaimer.=0D
+ * 2. Redistributions in binary form must reproduce the above copyright=0D
+ * notice, this list of conditions and the following disclaimer in the=
=0D
+ * documentation and/or other materials provided with the distribution.=
=0D
+ *=0D
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND=
=0D
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=0D
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=0D
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE=
=0D
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=0D
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=
=0D
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=0D
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=0D
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=0D
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=
=0D
+ * SUCH DAMAGE.=0D
+ *=0D
+ * $FreeBSD: src/sys/sys/elf64.h,v 1.10.14.2 2007/12/03 21:30:36 marius Ex=
p $=0D
+ */=0D
+=0D
+#ifndef _SYS_ELF64_H_=0D
+#define _SYS_ELF64_H_ 1=0D
+=0D
+=0D
+/*=0D
+ * ELF definitions common to all 64-bit architectures.=0D
+ */=0D
+=0D
+typedef UINT64 Elf64_Addr;=0D
+typedef UINT16 Elf64_Half;=0D
+typedef UINT64 Elf64_Off;=0D
+typedef INT32 Elf64_Sword;=0D
+typedef INT64 Elf64_Sxword;=0D
+typedef UINT32 Elf64_Word;=0D
+typedef UINT64 Elf64_Lword;=0D
+typedef UINT64 Elf64_Xword;=0D
+=0D
+/*=0D
+ * Types of dynamic symbol hash table bucket and chain elements.=0D
+ *=0D
+ * This is inconsistent among 64 bit architectures, so a machine dependent=
=0D
+ * typedef is required.=0D
+ */=0D
+=0D
+typedef Elf64_Word Elf64_Hashelt;=0D
+=0D
+/* Non-standard class-dependent datatype used for abstraction. */=0D
+typedef Elf64_Xword Elf64_Size;=0D
+typedef Elf64_Sxword Elf64_Ssize;=0D
+=0D
+/*=0D
+ * ELF header.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ unsigned char e_ident[EI_NIDENT]; /* File identification. */=0D
+ Elf64_Half e_type; /* File type. */=0D
+ Elf64_Half e_machine; /* Machine architecture. */=0D
+ Elf64_Word e_version; /* ELF format version. */=0D
+ Elf64_Addr e_entry; /* Entry point. */=0D
+ Elf64_Off e_phoff; /* Program header file offset. */=0D
+ Elf64_Off e_shoff; /* Section header file offset. */=0D
+ Elf64_Word e_flags; /* Architecture-specific flags. */=0D
+ Elf64_Half e_ehsize; /* Size of ELF header in bytes. */=0D
+ Elf64_Half e_phentsize; /* Size of program header entry. */=0D
+ Elf64_Half e_phnum; /* Number of program header entries. */=0D
+ Elf64_Half e_shentsize; /* Size of section header entry. */=0D
+ Elf64_Half e_shnum; /* Number of section header entries. */=0D
+ Elf64_Half e_shstrndx; /* Section name strings section. */=0D
+} Elf64_Ehdr;=0D
+=0D
+/*=0D
+ * Section header.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ Elf64_Word sh_name; /* Section name (index into the=0D
+ section header string table). */=0D
+ Elf64_Word sh_type; /* Section type. */=0D
+ Elf64_Xword sh_flags; /* Section flags. */=0D
+ Elf64_Addr sh_addr; /* Address in memory image. */=0D
+ Elf64_Off sh_offset; /* Offset in file. */=0D
+ Elf64_Xword sh_size; /* Size in bytes. */=0D
+ Elf64_Word sh_link; /* Index of a related section. */=0D
+ Elf64_Word sh_info; /* Depends on section type. */=0D
+ Elf64_Xword sh_addralign; /* Alignment in bytes. */=0D
+ Elf64_Xword sh_entsize; /* Size of each entry in section. */=0D
+} Elf64_Shdr;=0D
+=0D
+/*=0D
+ * Program header.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ Elf64_Word p_type; /* Entry type. */=0D
+ Elf64_Word p_flags; /* Access permission flags. */=0D
+ Elf64_Off p_offset; /* File offset of contents. */=0D
+ Elf64_Addr p_vaddr; /* Virtual address in memory image. */=0D
+ Elf64_Addr p_paddr; /* Physical address (not used). */=0D
+ Elf64_Xword p_filesz; /* Size of contents in file. */=0D
+ Elf64_Xword p_memsz; /* Size of contents in memory. */=0D
+ Elf64_Xword p_align; /* Alignment in memory and file. */=0D
+} Elf64_Phdr;=0D
+=0D
+/*=0D
+ * Dynamic structure. The ".dynamic" section contains an array of them.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ Elf64_Sxword d_tag; /* Entry type. */=0D
+ union {=0D
+ Elf64_Xword d_val; /* Integer value. */=0D
+ Elf64_Addr d_ptr; /* Address value. */=0D
+ } d_un;=0D
+} Elf64_Dyn;=0D
+=0D
+/*=0D
+ * Relocation entries.=0D
+ */=0D
+=0D
+/* Relocations that don't need an addend field. */=0D
+typedef struct {=0D
+ Elf64_Addr r_offset; /* Location to be relocated. */=0D
+ Elf64_Xword r_info; /* Relocation type and symbol index. */=0D
+} Elf64_Rel;=0D
+=0D
+/* Relocations that need an addend field. */=0D
+typedef struct {=0D
+ Elf64_Addr r_offset; /* Location to be relocated. */=0D
+ Elf64_Xword r_info; /* Relocation type and symbol index. */=0D
+ Elf64_Sxword r_addend; /* Addend. */=0D
+} Elf64_Rela;=0D
+=0D
+/* Macros for accessing the fields of r_info. */=0D
+#define ELF64_R_SYM(info) ((UINT32) RShiftU64 ((info), 32))=0D
+#define ELF64_R_TYPE(info) ((info) & 0xffffffffL)=0D
+=0D
+/* Macro for constructing r_info from field values. */=0D
+#define ELF64_R_INFO(sym, type) (((sym) << 32) + ((type) & 0xffffffffL))=
=0D
+=0D
+#define ELF64_R_TYPE_DATA(info) (((Elf64_Xword)(info)<<32)>>40)=0D
+#define ELF64_R_TYPE_ID(info) (((Elf64_Xword)(info)<<56)>>56)=0D
+#define ELF64_R_TYPE_INFO(data, type) \=0D
+ (((Elf64_Xword)(data)<<8)+(Elf64_Xword)(type))=0D
+=0D
+/*=0D
+ * Note entry header=0D
+ */=0D
+typedef Elf_Note Elf64_Nhdr;=0D
+=0D
+/*=0D
+ * Move entry=0D
+ */=0D
+typedef struct {=0D
+ Elf64_Lword m_value; /* symbol value */=0D
+ Elf64_Xword m_info; /* size + index */=0D
+ Elf64_Xword m_poffset; /* symbol offset */=0D
+ Elf64_Half m_repeat; /* repeat count */=0D
+ Elf64_Half m_stride; /* stride info */=0D
+} Elf64_Move;=0D
+=0D
+#define ELF64_M_SYM(info) ((info)>>8)=0D
+#define ELF64_M_SIZE(info) ((unsigned char)(info))=0D
+#define ELF64_M_INFO(sym, size) (((sym)<<8)+(unsigned char)(size))=0D
+=0D
+/*=0D
+ * Hardware/Software capabilities entry=0D
+ */=0D
+typedef struct {=0D
+ Elf64_Xword c_tag; /* how to interpret value */=0D
+ union {=0D
+ Elf64_Xword c_val;=0D
+ Elf64_Addr c_ptr;=0D
+ } c_un;=0D
+} Elf64_Cap;=0D
+=0D
+/*=0D
+ * Symbol table entries.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ Elf64_Word st_name; /* String table index of name. */=0D
+ unsigned char st_info; /* Type and binding information. */=0D
+ unsigned char st_other; /* Reserved (not used). */=0D
+ Elf64_Half st_shndx; /* Section index of symbol. */=0D
+ Elf64_Addr st_value; /* Symbol value. */=0D
+ Elf64_Xword st_size; /* Size of associated object. */=0D
+} Elf64_Sym;=0D
+=0D
+/* Macros for accessing the fields of st_info. */=0D
+#define ELF64_ST_BIND(info) ((info) >> 4)=0D
+#define ELF64_ST_TYPE(info) ((info) & 0xf)=0D
+=0D
+/* Macro for constructing st_info from field values. */=0D
+#define ELF64_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))=0D
+=0D
+/* Macro for accessing the fields of st_other. */=0D
+#define ELF64_ST_VISIBILITY(oth) ((oth) & 0x3)=0D
+=0D
+/* Structures used by Sun & GNU-style symbol versioning. */=0D
+typedef struct {=0D
+ Elf64_Half vd_version;=0D
+ Elf64_Half vd_flags;=0D
+ Elf64_Half vd_ndx;=0D
+ Elf64_Half vd_cnt;=0D
+ Elf64_Word vd_hash;=0D
+ Elf64_Word vd_aux;=0D
+ Elf64_Word vd_next;=0D
+} Elf64_Verdef;=0D
+=0D
+typedef struct {=0D
+ Elf64_Word vda_name;=0D
+ Elf64_Word vda_next;=0D
+} Elf64_Verdaux;=0D
+=0D
+typedef struct {=0D
+ Elf64_Half vn_version;=0D
+ Elf64_Half vn_cnt;=0D
+ Elf64_Word vn_file;=0D
+ Elf64_Word vn_aux;=0D
+ Elf64_Word vn_next;=0D
+} Elf64_Verneed;=0D
+=0D
+typedef struct {=0D
+ Elf64_Word vna_hash;=0D
+ Elf64_Half vna_flags;=0D
+ Elf64_Half vna_other;=0D
+ Elf64_Word vna_name;=0D
+ Elf64_Word vna_next;=0D
+} Elf64_Vernaux;=0D
+=0D
+typedef Elf64_Half Elf64_Versym;=0D
+=0D
+typedef struct {=0D
+ Elf64_Half si_boundto; /* direct bindings - symbol bound to */=0D
+ Elf64_Half si_flags; /* per symbol flags */=0D
+} Elf64_Syminfo;=0D
+=0D
+#endif /* !_SYS_ELF64_H_ */=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64Lib.c b/UefiPaylo=
adPkg/PayloadLoaderPeim/ElfLib/Elf64Lib.c
new file mode 100644
index 0000000000..e364807007
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64Lib.c
@@ -0,0 +1,460 @@
+/** @file=0D
+ ELF library=0D
+=0D
+ Copyright (c) 2019 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include "ElfLibInternal.h"=0D
+=0D
+/**=0D
+ Return the section header specified by Index.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Index The section index.=0D
+=0D
+ @return Pointer to the section header.=0D
+**/=0D
+Elf64_Shdr *=0D
+GetElf64SectionByIndex (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Index=0D
+ )=0D
+{=0D
+ Elf64_Ehdr *Ehdr;=0D
+=0D
+ Ehdr =3D (Elf64_Ehdr *)ImageBase;=0D
+ if (Index >=3D Ehdr->e_shnum) {=0D
+ return NULL;=0D
+ }=0D
+=0D
+ return (Elf64_Shdr *)(ImageBase + Ehdr->e_shoff + Index * Ehdr->e_shents=
ize);=0D
+}=0D
+=0D
+/**=0D
+ Return the segment header specified by Index.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Index The segment index.=0D
+=0D
+ @return Pointer to the segment header.=0D
+**/=0D
+Elf64_Phdr *=0D
+GetElf64SegmentByIndex (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Index=0D
+ )=0D
+{=0D
+ Elf64_Ehdr *Ehdr;=0D
+=0D
+ Ehdr =3D (Elf64_Ehdr *)ImageBase;=0D
+ if (Index >=3D Ehdr->e_phnum) {=0D
+ return NULL;=0D
+ }=0D
+=0D
+ return (Elf64_Phdr *)(ImageBase + Ehdr->e_phoff + Index * Ehdr->e_phents=
ize);=0D
+}=0D
+=0D
+/**=0D
+ Return the section header specified by the range.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Offset The section offset.=0D
+ @param Size The section size.=0D
+=0D
+ @return Pointer to the section header.=0D
+**/=0D
+Elf64_Shdr *=0D
+GetElf64SectionByRange (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT64 Offset,=0D
+ IN UINT64 Size=0D
+ )=0D
+{=0D
+ UINT32 Index;=0D
+ Elf64_Ehdr *Ehdr;=0D
+ Elf64_Shdr *Shdr;=0D
+=0D
+ Ehdr =3D (Elf64_Ehdr *)ImageBase;=0D
+=0D
+ Shdr =3D (Elf64_Shdr *) (ImageBase + Ehdr->e_shoff);=0D
+ for (Index =3D 0; Index < Ehdr->e_shnum; Index++) {=0D
+ if ((Shdr->sh_offset =3D=3D Offset) && (Shdr->sh_size =3D=3D Size)) {=
=0D
+ return Shdr;=0D
+ }=0D
+ Shdr =3D ELF_NEXT_ENTRY (Elf64_Shdr, Shdr, Ehdr->e_shentsize);=0D
+ }=0D
+ return NULL;=0D
+}=0D
+=0D
+/**=0D
+ Fix up the image based on the relocation entries.=0D
+=0D
+ @param Rela Relocation entries.=0D
+ @param RelaSize Total size of relocation entries.=0D
+ @param RelaEntrySize Relocation entry size.=0D
+ @param RelaType Type of relocation entry.=0D
+ @param Delta The delta between preferred image base and th=
e actual image base.=0D
+ @param DynamicLinking TRUE when fixing up according to dynamic relo=
cation.=0D
+=0D
+ @retval EFI_SUCCESS The image fix up is processed successfully.=0D
+**/=0D
+EFI_STATUS=0D
+ProcessRelocation64 (=0D
+ IN Elf64_Rela *Rela,=0D
+ IN UINT64 RelaSize,=0D
+ IN UINT64 RelaEntrySize,=0D
+ IN UINT64 RelaType,=0D
+ IN INTN Delta,=0D
+ IN BOOLEAN DynamicLinking=0D
+ )=0D
+{=0D
+ UINTN Index;=0D
+ UINT64 *Ptr;=0D
+ UINT32 Type;=0D
+=0D
+ for ( Index =3D 0=0D
+ ; MultU64x64 (RelaEntrySize, Index) < RelaSize=0D
+ ; Index++, Rela =3D ELF_NEXT_ENTRY (Elf64_Rela, Rela, RelaEntrySize)=
=0D
+ ) {=0D
+ //=0D
+ // r_offset is the virtual address of the storage unit affected by the=
relocation.=0D
+ //=0D
+ Ptr =3D (UINT64 *)(UINTN)(Rela->r_offset + Delta);=0D
+ Type =3D ELF64_R_TYPE(Rela->r_info);=0D
+ switch (Type) {=0D
+ case R_X86_64_NONE:=0D
+ case R_X86_64_PC32:=0D
+ case R_X86_64_PLT32:=0D
+ case R_X86_64_GOTPCREL:=0D
+ case R_X86_64_GOTPCRELX:=0D
+ case R_X86_64_REX_GOTPCRELX:=0D
+ break;=0D
+=0D
+ case R_X86_64_64:=0D
+ if (DynamicLinking) {=0D
+ //=0D
+ // Dynamic section doesn't contain entries of this type.=0D
+ //=0D
+ DEBUG ((DEBUG_INFO, "Unsupported relocation type %02X\n", Type))=
;=0D
+ ASSERT (FALSE);=0D
+ } else {=0D
+ *Ptr +=3D Delta;=0D
+ }=0D
+ break;=0D
+=0D
+ case R_X86_64_32:=0D
+ //=0D
+ // Dynamic section doesn't contain entries of this type.=0D
+ //=0D
+ DEBUG ((DEBUG_INFO, "Unsupported relocation type %02X\n", Type));=
=0D
+ ASSERT (FALSE);=0D
+ break;=0D
+=0D
+ case R_X86_64_RELATIVE:=0D
+ if (DynamicLinking) {=0D
+ //=0D
+ // A: Represents the addend used to compute the value of the rel=
ocatable field.=0D
+ // B: Represents the base address at which a shared object has b=
een loaded into memory during execution.=0D
+ // Generally, a shared object is built with a 0 base virtual =
address, but the execution address will be different.=0D
+ //=0D
+ // B (Base Address) in ELF spec is slightly different:=0D
+ // An executable or shared object file's base address (on plat=
forms that support the concept) is calculated during=0D
+ // execution from three values: the virtual memory load addres=
s, the maximum page size, and the lowest virtual address=0D
+ // of a program's loadable segment. To compute the base addres=
s, one determines the memory address associated with the=0D
+ // lowest p_vaddr value for a PT_LOAD segment. This address is=
truncated to the nearest multiple of the maximum page size.=0D
+ // The corresponding p_vaddr value itself is also truncated to=
the nearest multiple of the maximum page size.=0D
+ //=0D
+ // *** The base address is the difference between the truncate=
d memory address and the truncated p_vaddr value. ***=0D
+ //=0D
+ // Delta in this function is B.=0D
+ //=0D
+ // Calculation: B + A=0D
+ //=0D
+ if (RelaType =3D=3D SHT_RELA) {=0D
+ ASSERT (*Ptr =3D=3D 0);=0D
+ *Ptr =3D Delta + Rela->r_addend;=0D
+ } else {=0D
+ //=0D
+ // A is stored in the field of relocation for REL type.=0D
+ //=0D
+ *Ptr =3D Delta + *Ptr;=0D
+ }=0D
+ } else {=0D
+ //=0D
+ // non-Dynamic section doesn't contain entries of this type.=0D
+ //=0D
+ DEBUG ((DEBUG_INFO, "Unsupported relocation type %02X\n", Type))=
;=0D
+ ASSERT (FALSE);=0D
+ }=0D
+ break;=0D
+=0D
+ default:=0D
+ DEBUG ((DEBUG_INFO, "Unsupported relocation type %02X\n", Type));=
=0D
+ }=0D
+ }=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Relocate the DYN type image.=0D
+=0D
+ @param ElfCt Point to image context.=0D
+=0D
+ @retval EFI_SUCCESS The relocation succeeds.=0D
+ @retval EFI_UNSUPPORTED The image doesn't contain a dynamic section.=0D
+**/=0D
+EFI_STATUS=0D
+RelocateElf64Dynamic (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ )=0D
+{=0D
+ UINT32 Index;=0D
+ Elf64_Phdr *Phdr;=0D
+ Elf64_Shdr *DynShdr;=0D
+ Elf64_Shdr *RelShdr;=0D
+ Elf64_Dyn *Dyn;=0D
+ UINT64 RelaOffset;=0D
+ UINT64 RelaCount;=0D
+ UINT64 RelaSize;=0D
+ UINT64 RelaEntrySize;=0D
+ UINT64 RelaType;=0D
+=0D
+ //=0D
+ // 1. Locate the dynamic section.=0D
+ //=0D
+ // If an object file participates in dynamic linking, its program header=
table=0D
+ // will have an element of type PT_DYNAMIC.=0D
+ // This ``segment'' contains the .dynamic section. A special symbol, _DY=
NAMIC,=0D
+ // labels the section, which contains an array of Elf32_Dyn or Elf64_Dyn=
.=0D
+ //=0D
+ DynShdr =3D NULL;=0D
+ for (Index =3D 0; Index < ElfCt->PhNum; Index++) {=0D
+ Phdr =3D GetElf64SegmentByIndex (ElfCt->FileBase, Index);=0D
+ ASSERT (Phdr !=3D NULL);=0D
+ if (Phdr->p_type =3D=3D PT_DYNAMIC) {=0D
+ //=0D
+ // Verify the existence of the dynamic section.=0D
+ //=0D
+ DynShdr =3D GetElf64SectionByRange (ElfCt->FileBase, Phdr->p_offset,=
Phdr->p_filesz);=0D
+ break;=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // It's abnormal a DYN ELF doesn't contain a dynamic section.=0D
+ //=0D
+ ASSERT (DynShdr !=3D NULL);=0D
+ if (DynShdr =3D=3D NULL) {=0D
+ return EFI_UNSUPPORTED;=0D
+ }=0D
+ ASSERT (DynShdr->sh_type =3D=3D SHT_DYNAMIC);=0D
+ ASSERT (DynShdr->sh_entsize >=3D sizeof (*Dyn));=0D
+=0D
+ //=0D
+ // 2. Locate the relocation section from the dynamic section.=0D
+ //=0D
+ RelaOffset =3D MAX_UINT64;=0D
+ RelaSize =3D 0;=0D
+ RelaCount =3D 0;=0D
+ RelaEntrySize =3D 0;=0D
+ RelaType =3D 0;=0D
+ for ( Index =3D 0, Dyn =3D (Elf64_Dyn *) (ElfCt->FileBase + DynShdr->sh_=
offset)=0D
+ ; Index < DivU64x64Remainder (DynShdr->sh_size, DynShdr->sh_entsize,=
NULL)=0D
+ ; Index++, Dyn =3D ELF_NEXT_ENTRY (Elf64_Dyn, Dyn, DynShdr->sh_entsi=
ze)=0D
+ ) {=0D
+ switch (Dyn->d_tag) {=0D
+ case DT_RELA:=0D
+ case DT_REL:=0D
+ //=0D
+ // DT_REL represent program virtual addresses.=0D
+ // A file's virtual addresses might not match the memory virtual a=
ddresses during execution.=0D
+ // When interpreting addresses contained in the dynamic structure,=
the dynamic linker computes actual addresses,=0D
+ // based on the original file value and the memory base address.=0D
+ // For consistency, files do not contain relocation entries to ``c=
orrect'' addresses in the dynamic structure.=0D
+ //=0D
+ RelaOffset =3D Dyn->d_un.d_ptr - (UINTN) ElfCt->PreferredImageAddr=
ess;=0D
+ RelaType =3D (Dyn->d_tag =3D=3D DT_RELA) ? SHT_RELA: SHT_REL;=0D
+ break;=0D
+ case DT_RELACOUNT:=0D
+ case DT_RELCOUNT:=0D
+ RelaCount =3D Dyn->d_un.d_val;=0D
+ break;=0D
+ case DT_RELENT:=0D
+ case DT_RELAENT:=0D
+ RelaEntrySize =3D Dyn->d_un.d_val;=0D
+ break;=0D
+ case DT_RELSZ:=0D
+ case DT_RELASZ:=0D
+ RelaSize =3D Dyn->d_un.d_val;=0D
+ break;=0D
+ default:=0D
+ break;=0D
+ }=0D
+ }=0D
+=0D
+ if (RelaOffset =3D=3D MAX_UINT64) {=0D
+ ASSERT (RelaCount =3D=3D 0);=0D
+ ASSERT (RelaEntrySize =3D=3D 0);=0D
+ ASSERT (RelaSize =3D=3D 0);=0D
+ //=0D
+ // It's fine that a DYN ELF doesn't contain relocation section.=0D
+ //=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+=0D
+ //=0D
+ // Verify the existence of the relocation section.=0D
+ //=0D
+ RelShdr =3D GetElf64SectionByRange (ElfCt->FileBase, RelaOffset, RelaSiz=
e);=0D
+ ASSERT (RelShdr !=3D NULL);=0D
+ if (RelShdr =3D=3D NULL) {=0D
+ return EFI_UNSUPPORTED;=0D
+ }=0D
+ ASSERT (RelShdr->sh_type =3D=3D RelaType);=0D
+ ASSERT (RelShdr->sh_entsize =3D=3D RelaEntrySize);=0D
+=0D
+ //=0D
+ // 3. Process the relocation section.=0D
+ //=0D
+ ProcessRelocation64 (=0D
+ (Elf64_Rela *) (ElfCt->FileBase + RelShdr->sh_offset),=0D
+ RelShdr->sh_size, RelShdr->sh_entsize, RelShdr->sh_type,=0D
+ (UINTN) ElfCt->ImageAddress - (UINTN) ElfCt->PreferredImageAddress,=0D
+ TRUE=0D
+ );=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Relocate all sections in a ELF image.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+=0D
+ @retval EFI_UNSUPPORTED Relocation is not supported.=0D
+ @retval EFI_SUCCESS ELF image was relocated successfully.=0D
+**/=0D
+EFI_STATUS=0D
+RelocateElf64Sections (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ Elf64_Ehdr *Ehdr;=0D
+ Elf64_Shdr *RelShdr;=0D
+ Elf64_Shdr *Shdr;=0D
+ UINT32 Index;=0D
+ UINTN Delta;=0D
+=0D
+ Ehdr =3D (Elf64_Ehdr *)ElfCt->FileBase;=0D
+ if (Ehdr->e_machine !=3D EM_X86_64) {=0D
+ return EFI_UNSUPPORTED;=0D
+ }=0D
+=0D
+ Delta =3D (UINTN) ElfCt->ImageAddress - (UINTN) ElfCt->PreferredImageAdd=
ress;=0D
+ ElfCt->EntryPoint =3D (UINTN)(Ehdr->e_entry + Delta);=0D
+=0D
+ //=0D
+ // 1. Relocate dynamic ELF using the relocation section pointed by dynam=
ic section=0D
+ //=0D
+ if (Ehdr->e_type =3D=3D ET_DYN) {=0D
+ DEBUG ((DEBUG_INFO, "DYN ELF: Relocate using dynamic sections...\n"));=
=0D
+ Status =3D RelocateElf64Dynamic (ElfCt);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+ return Status;=0D
+ }=0D
+=0D
+ //=0D
+ // 2. Executable ELF: Fix up the delta between actual image address and =
preferred image address.=0D
+ //=0D
+ // Linker already fixed up EXEC ELF based on the preferred image addres=
s.=0D
+ // A ELF loader in modern OS only loads it into the preferred image add=
ress.=0D
+ // The below relocation is unneeded in that case.=0D
+ // But the ELF loader in firmware supports to load the image to a diffe=
rent address.=0D
+ // The below relocation is needed in this case.=0D
+ //=0D
+ DEBUG ((DEBUG_INFO, "EXEC ELF: Fix actual/preferred base address delta .=
..\n"));=0D
+ for ( Index =3D 0, RelShdr =3D (Elf64_Shdr *) (ElfCt->FileBase + Ehdr->e=
_shoff)=0D
+ ; Index < Ehdr->e_shnum=0D
+ ; Index++, RelShdr =3D ELF_NEXT_ENTRY (Elf64_Shdr, RelShdr, Ehdr->=
e_shentsize)=0D
+ ) {=0D
+ if ((RelShdr->sh_type !=3D SHT_REL) && (RelShdr->sh_type !=3D SHT_RELA=
)) {=0D
+ continue;=0D
+ }=0D
+ Shdr =3D GetElf64SectionByIndex (ElfCt->FileBase, RelShdr->sh_info);=0D
+ if ((Shdr->sh_flags & SHF_ALLOC) =3D=3D SHF_ALLOC) {=0D
+ //=0D
+ // Only fix up sections that occupy memory during process execution.=
=0D
+ //=0D
+ ProcessRelocation64 (=0D
+ (Elf64_Rela *)((UINT8*)Ehdr + RelShdr->sh_offset),=0D
+ RelShdr->sh_size, RelShdr->sh_entsize, RelShdr->sh_type,=0D
+ Delta, FALSE=0D
+ );=0D
+ }=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Load ELF image which has 64-bit architecture.=0D
+=0D
+ Caller should set Context.ImageAddress to a proper value, either pointin=
g to=0D
+ a new allocated memory whose size equal to Context.ImageSize, or pointin=
g=0D
+ to Context.PreferredImageAddress.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+=0D
+ @retval EFI_SUCCESS ELF binary is loaded successfully.=0D
+ @retval Others Loading ELF binary fails.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+LoadElf64Image (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ )=0D
+{=0D
+ Elf64_Ehdr *Ehdr;=0D
+ Elf64_Phdr *Phdr;=0D
+ UINT16 Index;=0D
+ UINTN Delta;=0D
+=0D
+ ASSERT (ElfCt !=3D NULL);=0D
+=0D
+ //=0D
+ // Per the sprit of ELF, loading to memory only consumes info from progr=
am headers.=0D
+ //=0D
+ Ehdr =3D (Elf64_Ehdr *)ElfCt->FileBase;=0D
+=0D
+ for ( Index =3D 0, Phdr =3D (Elf64_Phdr *)(ElfCt->FileBase + Ehdr->e_pho=
ff)=0D
+ ; Index < Ehdr->e_phnum=0D
+ ; Index++, Phdr =3D ELF_NEXT_ENTRY (Elf64_Phdr, Phdr, Ehdr->e_phents=
ize)=0D
+ ) {=0D
+ //=0D
+ // Skip segments that don't require load (type tells, or size is 0)=0D
+ //=0D
+ if ((Phdr->p_type !=3D PT_LOAD) ||=0D
+ (Phdr->p_memsz =3D=3D 0)) {=0D
+ continue;=0D
+ }=0D
+=0D
+ //=0D
+ // The memory offset of segment relative to the image base=0D
+ // Note: CopyMem() does nothing when the dst equals to src.=0D
+ //=0D
+ Delta =3D (UINTN) Phdr->p_paddr - (UINTN) ElfCt->PreferredImageAddress=
;=0D
+ CopyMem (ElfCt->ImageAddress + Delta, ElfCt->FileBase + (UINTN) Phdr->=
p_offset, (UINTN) Phdr->p_filesz);=0D
+ ZeroMem (ElfCt->ImageAddress + Delta + (UINTN) Phdr->p_filesz, (UINTN)=
(Phdr->p_memsz - Phdr->p_filesz));=0D
+ }=0D
+=0D
+ //=0D
+ // Relocate when new new image base is not the preferred image base.=0D
+ //=0D
+ if (ElfCt->ImageAddress !=3D ElfCt->PreferredImageAddress) {=0D
+ RelocateElf64Sections (ElfCt);=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfCommon.h b/UefiPayl=
oadPkg/PayloadLoaderPeim/ElfLib/ElfCommon.h
new file mode 100644
index 0000000000..15c9e33d3f
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfCommon.h
@@ -0,0 +1,983 @@
+/** @file=0D
+Ported ELF include files from FreeBSD=0D
+=0D
+Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>=0D
+Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>=0D
+SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+=0D
+**/=0D
+/*-=0D
+ * Copyright (c) 1998 John D. Polstra.=0D
+ * All rights reserved.=0D
+ *=0D
+ * Redistribution and use in source and binary forms, with or without=0D
+ * modification, are permitted provided that the following conditions=0D
+ * are met:=0D
+ * 1. Redistributions of source code must retain the above copyright=0D
+ * notice, this list of conditions and the following disclaimer.=0D
+ * 2. Redistributions in binary form must reproduce the above copyright=0D
+ * notice, this list of conditions and the following disclaimer in the=
=0D
+ * documentation and/or other materials provided with the distribution.=
=0D
+ *=0D
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND=
=0D
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=0D
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=0D
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE=
=0D
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=0D
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=
=0D
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=0D
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=0D
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=0D
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=
=0D
+ * SUCH DAMAGE.=0D
+ *=0D
+ * $FreeBSD: src/sys/sys/elf_common.h,v 1.15.8.2 2007/12/03 21:30:36 mariu=
s Exp $=0D
+ */=0D
+=0D
+#ifndef _SYS_ELF_COMMON_H_=0D
+#define _SYS_ELF_COMMON_H_ 1=0D
+=0D
+/*=0D
+ * ELF definitions that are independent of architecture or word size.=0D
+ */=0D
+=0D
+/*=0D
+ * Note header. The ".note" section contains an array of notes. Each=0D
+ * begins with this header, aligned to a word boundary. Immediately=0D
+ * following the note header is n_namesz bytes of name, padded to the=0D
+ * next word boundary. Then comes n_descsz bytes of descriptor, again=0D
+ * padded to a word boundary. The values of n_namesz and n_descsz do=0D
+ * not include the padding.=0D
+ */=0D
+=0D
+typedef struct {=0D
+ UINT32 n_namesz; /* Length of name. */=0D
+ UINT32 n_descsz; /* Length of descriptor. */=0D
+ UINT32 n_type; /* Type of this note. */=0D
+} Elf_Note;=0D
+=0D
+/* Indexes into the e_ident array. Keep synced with=0D
+ http://www.sco.com/developers/gabi/latest/ch4.eheader.html */=0D
+#define EI_MAG0 0 /* Magic number, byte 0. */=0D
+#define EI_MAG1 1 /* Magic number, byte 1. */=0D
+#define EI_MAG2 2 /* Magic number, byte 2. */=0D
+#define EI_MAG3 3 /* Magic number, byte 3. */=0D
+#define EI_CLASS 4 /* Class of machine. */=0D
+#define EI_DATA 5 /* Data format. */=0D
+#define EI_VERSION 6 /* ELF format version. */=0D
+#define EI_OSABI 7 /* Operating system / ABI identification */=0D
+#define EI_ABIVERSION 8 /* ABI version */=0D
+#define OLD_EI_BRAND 8 /* Start of architecture identification. */=0D
+#define EI_PAD 9 /* Start of padding (per SVR4 ABI). */=0D
+#define EI_NIDENT 16 /* Size of e_ident array. */=0D
+=0D
+/* Values for the magic number bytes. */=0D
+#define ELFMAG0 0x7f=0D
+#define ELFMAG1 'E'=0D
+#define ELFMAG2 'L'=0D
+#define ELFMAG3 'F'=0D
+#define ELFMAG "\177ELF" /* magic string */=0D
+#define SELFMAG 4 /* magic string size */=0D
+=0D
+/* Values for e_ident[EI_VERSION] and e_version. */=0D
+#define EV_NONE 0=0D
+#define EV_CURRENT 1=0D
+=0D
+/* Values for e_ident[EI_CLASS]. */=0D
+#define ELFCLASSNONE 0 /* Unknown class. */=0D
+#define ELFCLASS32 1 /* 32-bit architecture. */=0D
+#define ELFCLASS64 2 /* 64-bit architecture. */=0D
+=0D
+/* Values for e_ident[EI_DATA]. */=0D
+#define ELFDATANONE 0 /* Unknown data format. */=0D
+#define ELFDATA2LSB 1 /* 2's complement little-endian. */=0D
+#define ELFDATA2MSB 2 /* 2's complement big-endian. */=0D
+=0D
+/* Values for e_ident[EI_OSABI]. */=0D
+#define ELFOSABI_NONE 0 /* UNIX System V ABI */=0D
+#define ELFOSABI_HPUX 1 /* HP-UX operating system */=0D
+#define ELFOSABI_NETBSD 2 /* NetBSD */=0D
+#define ELFOSABI_LINUX 3 /* GNU/Linux */=0D
+#define ELFOSABI_HURD 4 /* GNU/Hurd */=0D
+#define ELFOSABI_86OPEN 5 /* 86Open common IA32 ABI */=0D
+#define ELFOSABI_SOLARIS 6 /* Solaris */=0D
+#define ELFOSABI_AIX 7 /* AIX */=0D
+#define ELFOSABI_IRIX 8 /* IRIX */=0D
+#define ELFOSABI_FREEBSD 9 /* FreeBSD */=0D
+#define ELFOSABI_TRU64 10 /* TRU64 UNIX */=0D
+#define ELFOSABI_MODESTO 11 /* Novell Modesto */=0D
+#define ELFOSABI_OPENBSD 12 /* OpenBSD */=0D
+#define ELFOSABI_OPENVMS 13 /* Open VMS */=0D
+#define ELFOSABI_NSK 14 /* HP Non-Stop Kernel */=0D
+#define ELFOSABI_ARM 97 /* ARM */=0D
+#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */=
=0D
+=0D
+#define ELFOSABI_SYSV ELFOSABI_NONE /* symbol used in old spec */=0D
+#define ELFOSABI_MONTEREY ELFOSABI_AIX /* Monterey */=0D
+=0D
+/* e_ident */=0D
+#define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] =3D=3D ELFMAG0 && \=0D
+ (ehdr).e_ident[EI_MAG1] =3D=3D ELFMAG1 && \=0D
+ (ehdr).e_ident[EI_MAG2] =3D=3D ELFMAG2 && \=0D
+ (ehdr).e_ident[EI_MAG3] =3D=3D ELFMAG3)=0D
+=0D
+/* Values for e_type. */=0D
+#define ET_NONE 0 /* Unknown type. */=0D
+#define ET_REL 1 /* Relocatable. */=0D
+#define ET_EXEC 2 /* Executable. */=0D
+#define ET_DYN 3 /* Shared object. */=0D
+#define ET_CORE 4 /* Core file. */=0D
+#define ET_LOOS 0xfe00 /* First operating system specific. */=0D
+#define ET_HIOS 0xfeff /* Last operating system-specific. */=0D
+#define ET_LOPROC 0xff00 /* First processor-specific. */=0D
+#define ET_HIPROC 0xffff /* Last processor-specific. */=0D
+=0D
+/* Values for e_machine. */=0D
+#define EM_NONE 0 /* Unknown machine. */=0D
+#define EM_M32 1 /* AT&T WE32100. */=0D
+#define EM_SPARC 2 /* Sun SPARC. */=0D
+#define EM_386 3 /* Intel i386. */=0D
+#define EM_68K 4 /* Motorola 68000. */=0D
+#define EM_88K 5 /* Motorola 88000. */=0D
+#define EM_860 7 /* Intel i860. */=0D
+#define EM_MIPS 8 /* MIPS R3000 Big-Endian only. */=0D
+#define EM_S370 9 /* IBM System/370. */=0D
+#define EM_MIPS_RS3_LE 10 /* MIPS R3000 Little-Endian. */=0D
+#define EM_PARISC 15 /* HP PA-RISC. */=0D
+#define EM_VPP500 17 /* Fujitsu VPP500. */=0D
+#define EM_SPARC32PLUS 18 /* SPARC v8plus. */=0D
+#define EM_960 19 /* Intel 80960. */=0D
+#define EM_PPC 20 /* PowerPC 32-bit. */=0D
+#define EM_PPC64 21 /* PowerPC 64-bit. */=0D
+#define EM_S390 22 /* IBM System/390. */=0D
+#define EM_V800 36 /* NEC V800. */=0D
+#define EM_FR20 37 /* Fujitsu FR20. */=0D
+#define EM_RH32 38 /* TRW RH-32. */=0D
+#define EM_RCE 39 /* Motorola RCE. */=0D
+#define EM_ARM 40 /* ARM. */=0D
+#define EM_SH 42 /* Hitachi SH. */=0D
+#define EM_SPARCV9 43 /* SPARC v9 64-bit. */=0D
+#define EM_TRICORE 44 /* Siemens TriCore embedded processor. */=0D
+#define EM_ARC 45 /* Argonaut RISC Core. */=0D
+#define EM_H8_300 46 /* Hitachi H8/300. */=0D
+#define EM_H8_300H 47 /* Hitachi H8/300H. */=0D
+#define EM_H8S 48 /* Hitachi H8S. */=0D
+#define EM_H8_500 49 /* Hitachi H8/500. */=0D
+#define EM_MIPS_X 51 /* Stanford MIPS-X. */=0D
+#define EM_COLDFIRE 52 /* Motorola ColdFire. */=0D
+#define EM_68HC12 53 /* Motorola M68HC12. */=0D
+#define EM_MMA 54 /* Fujitsu MMA. */=0D
+#define EM_PCP 55 /* Siemens PCP. */=0D
+#define EM_NCPU 56 /* Sony nCPU. */=0D
+#define EM_NDR1 57 /* Denso NDR1 microprocessor. */=0D
+#define EM_STARCORE 58 /* Motorola Star*Core processor. */=0D
+#define EM_ME16 59 /* Toyota ME16 processor. */=0D
+#define EM_ST100 60 /* STMicroelectronics ST100 processor. */=0D
+#define EM_TINYJ 61 /* Advanced Logic Corp. TinyJ processor. */=0D
+#define EM_X86_64 62 /* Advanced Micro Devices x86-64 */=0D
+#define EM_AMD64 EM_X86_64 /* Advanced Micro Devices x86-64 (compat) */=
=0D
+#define EM_AARCH64 183 /* ARM 64bit Architecture */=0D
+=0D
+/* Non-standard or deprecated. */=0D
+#define EM_486 6 /* Intel i486. */=0D
+#define EM_MIPS_RS4_BE 10 /* MIPS R4000 Big-Endian */=0D
+#define EM_ALPHA_STD 41 /* Digital Alpha (standard value). */=0D
+#define EM_ALPHA 0x9026 /* Alpha (written in the absence of an ABI) */=0D
+=0D
+/* Special section indexes. */=0D
+#define SHN_UNDEF 0 /* Undefined, missing, irrelevant. */=0D
+#define SHN_LORESERVE 0xff00 /* First of reserved range. */=0D
+#define SHN_LOPROC 0xff00 /* First processor-specific. */=0D
+#define SHN_HIPROC 0xff1f /* Last processor-specific. */=0D
+#define SHN_LOOS 0xff20 /* First operating system-specific. */=0D
+#define SHN_HIOS 0xff3f /* Last operating system-specific. */=0D
+#define SHN_ABS 0xfff1 /* Absolute values. */=0D
+#define SHN_COMMON 0xfff2 /* Common data. */=0D
+#define SHN_XINDEX 0xffff /* Escape -- index stored elsewhere. */=0D
+#define SHN_HIRESERVE 0xffff /* Last of reserved range. */=0D
+=0D
+/* sh_type */=0D
+#define SHT_NULL 0 /* inactive */=0D
+#define SHT_PROGBITS 1 /* program defined information */=0D
+#define SHT_SYMTAB 2 /* symbol table section */=0D
+#define SHT_STRTAB 3 /* string table section */=0D
+#define SHT_RELA 4 /* relocation section with addends */=0D
+#define SHT_HASH 5 /* symbol hash table section */=0D
+#define SHT_DYNAMIC 6 /* dynamic section */=0D
+#define SHT_NOTE 7 /* note section */=0D
+#define SHT_NOBITS 8 /* no space section */=0D
+#define SHT_REL 9 /* relocation section - no addends */=0D
+#define SHT_SHLIB 10 /* reserved - purpose unknown */=0D
+#define SHT_DYNSYM 11 /* dynamic symbol table section */=0D
+#define SHT_INIT_ARRAY 14 /* Initialization function pointers. */=0D
+#define SHT_FINI_ARRAY 15 /* Termination function pointers. */=0D
+#define SHT_PREINIT_ARRAY 16 /* Pre-initialization function ptrs. */=0D
+#define SHT_GROUP 17 /* Section group. */=0D
+#define SHT_SYMTAB_SHNDX 18 /* Section indexes (see SHN_XINDEX). */=0D
+#define SHT_LOOS 0x60000000 /* First of OS specific semantics */=0D
+#define SHT_LOSUNW 0x6ffffff4=0D
+#define SHT_SUNW_dof 0x6ffffff4=0D
+#define SHT_SUNW_cap 0x6ffffff5=0D
+#define SHT_SUNW_SIGNATURE 0x6ffffff6=0D
+#define SHT_SUNW_ANNOTATE 0x6ffffff7=0D
+#define SHT_SUNW_DEBUGSTR 0x6ffffff8=0D
+#define SHT_SUNW_DEBUG 0x6ffffff9=0D
+#define SHT_SUNW_move 0x6ffffffa=0D
+#define SHT_SUNW_COMDAT 0x6ffffffb=0D
+#define SHT_SUNW_syminfo 0x6ffffffc=0D
+#define SHT_SUNW_verdef 0x6ffffffd=0D
+#define SHT_GNU_verdef 0x6ffffffd /* Symbol versions provided */=0D
+#define SHT_SUNW_verneed 0x6ffffffe=0D
+#define SHT_GNU_verneed 0x6ffffffe /* Symbol versions required */=0D
+#define SHT_SUNW_versym 0x6fffffff=0D
+#define SHT_GNU_versym 0x6fffffff /* Symbol version table */=0D
+#define SHT_HISUNW 0x6fffffff=0D
+#define SHT_HIOS 0x6fffffff /* Last of OS specific semantics */=0D
+#define SHT_LOPROC 0x70000000 /* reserved range for processor */=0D
+#define SHT_AMD64_UNWIND 0x70000001 /* unwind information */=0D
+#define SHT_HIPROC 0x7fffffff /* specific section header types */=0D
+#define SHT_LOUSER 0x80000000 /* reserved range for application */=0D
+#define SHT_HIUSER 0xffffffff /* specific indexes */=0D
+=0D
+/* Flags for sh_flags. */=0D
+#define SHF_WRITE 0x1 /* Section contains writable data. */=0D
+#define SHF_ALLOC 0x2 /* Section occupies memory. */=0D
+#define SHF_EXECINSTR 0x4 /* Section contains instructions. */=0D
+#define SHF_MERGE 0x10 /* Section may be merged. */=0D
+#define SHF_STRINGS 0x20 /* Section contains strings. */=0D
+#define SHF_INFO_LINK 0x40 /* sh_info holds section index. */=0D
+#define SHF_LINK_ORDER 0x80 /* Special ordering requirements. */=0D
+#define SHF_OS_NONCONFORMING 0x100 /* OS-specific processing required. *=
/=0D
+#define SHF_GROUP 0x200 /* Member of section group. */=0D
+#define SHF_TLS 0x400 /* Section contains TLS data. */=0D
+#define SHF_MASKOS 0x0ff00000 /* OS-specific semantics. */=0D
+#define SHF_MASKPROC 0xf0000000 /* Processor-specific semantics. */=0D
+=0D
+/* Values for p_type. */=0D
+#define PT_NULL 0 /* Unused entry. */=0D
+#define PT_LOAD 1 /* Loadable segment. */=0D
+#define PT_DYNAMIC 2 /* Dynamic linking information segment. */=0D
+#define PT_INTERP 3 /* Pathname of interpreter. */=0D
+#define PT_NOTE 4 /* Auxiliary information. */=0D
+#define PT_SHLIB 5 /* Reserved (not used). */=0D
+#define PT_PHDR 6 /* Location of program header itself. */=0D
+#define PT_TLS 7 /* Thread local storage segment */=0D
+#define PT_LOOS 0x60000000 /* First OS-specific. */=0D
+#define PT_SUNW_UNWIND 0x6464e550 /* amd64 UNWIND program header */=0D
+#define PT_GNU_EH_FRAME 0x6474e550=0D
+#define PT_LOSUNW 0x6ffffffa=0D
+#define PT_SUNWBSS 0x6ffffffa /* Sun Specific segment */=0D
+#define PT_SUNWSTACK 0x6ffffffb /* describes the stack segment */=0D
+#define PT_SUNWDTRACE 0x6ffffffc /* private */=0D
+#define PT_SUNWCAP 0x6ffffffd /* hard/soft capabilities segment */=0D
+#define PT_HISUNW 0x6fffffff=0D
+#define PT_HIOS 0x6fffffff /* Last OS-specific. */=0D
+#define PT_LOPROC 0x70000000 /* First processor-specific type. */=0D
+#define PT_HIPROC 0x7fffffff /* Last processor-specific type. */=0D
+=0D
+/* Values for p_flags. */=0D
+#define PF_X 0x1 /* Executable. */=0D
+#define PF_W 0x2 /* Writable. */=0D
+#define PF_R 0x4 /* Readable. */=0D
+#define PF_MASKOS 0x0ff00000 /* Operating system-specific. */=0D
+#define PF_MASKPROC 0xf0000000 /* Processor-specific. */=0D
+=0D
+/* Extended program header index. */=0D
+#define PN_XNUM 0xffff=0D
+=0D
+/* Values for d_tag. */=0D
+#define DT_NULL 0 /* Terminating entry. */=0D
+#define DT_NEEDED 1 /* String table offset of a needed shared=0D
+ library. */=0D
+#define DT_PLTRELSZ 2 /* Total size in bytes of PLT relocations. */=0D
+#define DT_PLTGOT 3 /* Processor-dependent address. */=0D
+#define DT_HASH 4 /* Address of symbol hash table. */=0D
+#define DT_STRTAB 5 /* Address of string table. */=0D
+#define DT_SYMTAB 6 /* Address of symbol table. */=0D
+#define DT_RELA 7 /* Address of ElfNN_Rela relocations. */=0D
+#define DT_RELASZ 8 /* Total size of ElfNN_Rela relocations. */=0D
+#define DT_RELAENT 9 /* Size of each ElfNN_Rela relocation entry. */=0D
+#define DT_STRSZ 10 /* Size of string table. */=0D
+#define DT_SYMENT 11 /* Size of each symbol table entry. */=0D
+#define DT_INIT 12 /* Address of initialization function. */=0D
+#define DT_FINI 13 /* Address of finalization function. */=0D
+#define DT_SONAME 14 /* String table offset of shared object=0D
+ name. */=0D
+#define DT_RPATH 15 /* String table offset of library path. [sup] */=0D
+#define DT_SYMBOLIC 16 /* Indicates "symbolic" linking. [sup] */=0D
+#define DT_REL 17 /* Address of ElfNN_Rel relocations. */=0D
+#define DT_RELSZ 18 /* Total size of ElfNN_Rel relocations. */=0D
+#define DT_RELENT 19 /* Size of each ElfNN_Rel relocation. */=0D
+#define DT_PLTREL 20 /* Type of relocation used for PLT. */=0D
+#define DT_DEBUG 21 /* Reserved (not used). */=0D
+#define DT_TEXTREL 22 /* Indicates there may be relocations in=0D
+ non-writable segments. [sup] */=0D
+#define DT_JMPREL 23 /* Address of PLT relocations. */=0D
+#define DT_BIND_NOW 24 /* [sup] */=0D
+#define DT_INIT_ARRAY 25 /* Address of the array of pointers to=0D
+ initialization functions */=0D
+#define DT_FINI_ARRAY 26 /* Address of the array of pointers to=0D
+ termination functions */=0D
+#define DT_INIT_ARRAYSZ 27 /* Size in bytes of the array of=0D
+ initialization functions. */=0D
+#define DT_FINI_ARRAYSZ 28 /* Size in bytes of the array of=0D
+ terminationfunctions. */=0D
+#define DT_RUNPATH 29 /* String table offset of a null-terminated=0D
+ library search path string. */=0D
+#define DT_FLAGS 30 /* Object specific flag values. */=0D
+#define DT_ENCODING 32 /* Values greater than or equal to DT_ENCODING=0D
+ and less than DT_LOOS follow the rules for=0D
+ the interpretation of the d_un union=0D
+ as follows: even =3D=3D 'd_ptr', even =3D=3D 'd_val'=0D
+ or none */=0D
+#define DT_PREINIT_ARRAY 32 /* Address of the array of pointers to=0D
+ pre-initialization functions. */=0D
+#define DT_PREINIT_ARRAYSZ 33 /* Size in bytes of the array of=0D
+ pre-initialization functions. */=0D
+#define DT_MAXPOSTAGS 34 /* number of positive tags */=0D
+#define DT_LOOS 0x6000000d /* First OS-specific */=0D
+#define DT_SUNW_AUXILIARY 0x6000000d /* symbol auxiliary name */=0D
+#define DT_SUNW_RTLDINF 0x6000000e /* ld.so.1 info (private) */=0D
+#define DT_SUNW_FILTER 0x6000000f /* symbol filter name */=0D
+#define DT_SUNW_CAP 0x60000010 /* hardware/software */=0D
+#define DT_HIOS 0x6ffff000 /* Last OS-specific */=0D
+=0D
+/*=0D
+ * DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the=0D
+ * Dyn.d_un.d_val field of the Elf*_Dyn structure.=0D
+ */=0D
+#define DT_VALRNGLO 0x6ffffd00=0D
+#define DT_CHECKSUM 0x6ffffdf8 /* elf checksum */=0D
+#define DT_PLTPADSZ 0x6ffffdf9 /* pltpadding size */=0D
+#define DT_MOVEENT 0x6ffffdfa /* move table entry size */=0D
+#define DT_MOVESZ 0x6ffffdfb /* move table size */=0D
+#define DT_FEATURE_1 0x6ffffdfc /* feature holder */=0D
+#define DT_POSFLAG_1 0x6ffffdfd /* flags for DT_* entries, effecting */=
=0D
+ /* the following DT_* entry. */=0D
+ /* See DF_P1_* definitions */=0D
+#define DT_SYMINSZ 0x6ffffdfe /* syminfo table size (in bytes) */=0D
+#define DT_SYMINENT 0x6ffffdff /* syminfo entry size (in bytes) */=0D
+#define DT_VALRNGHI 0x6ffffdff=0D
+=0D
+/*=0D
+ * DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the=0D
+ * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.=0D
+ *=0D
+ * If any adjustment is made to the ELF object after it has been=0D
+ * built, these entries will need to be adjusted.=0D
+ */=0D
+#define DT_ADDRRNGLO 0x6ffffe00=0D
+#define DT_CONFIG 0x6ffffefa /* configuration information */=0D
+#define DT_DEPAUDIT 0x6ffffefb /* dependency auditing */=0D
+#define DT_AUDIT 0x6ffffefc /* object auditing */=0D
+#define DT_PLTPAD 0x6ffffefd /* pltpadding (sparcv9) */=0D
+#define DT_MOVETAB 0x6ffffefe /* move table */=0D
+#define DT_SYMINFO 0x6ffffeff /* syminfo table */=0D
+#define DT_ADDRRNGHI 0x6ffffeff=0D
+=0D
+#define DT_VERSYM 0x6ffffff0 /* Address of versym section. */=0D
+#define DT_RELACOUNT 0x6ffffff9 /* number of RELATIVE relocations */=0D
+#define DT_RELCOUNT 0x6ffffffa /* number of RELATIVE relocations */=0D
+#define DT_FLAGS_1 0x6ffffffb /* state flags - see DF_1_* defs */=0D
+#define DT_VERDEF 0x6ffffffc /* Address of verdef section. */=0D
+#define DT_VERDEFNUM 0x6ffffffd /* Number of elems in verdef section */=
=0D
+#define DT_VERNEED 0x6ffffffe /* Address of verneed section. */=0D
+#define DT_VERNEEDNUM 0x6fffffff /* Number of elems in verneed section =
*/=0D
+=0D
+#define DT_LOPROC 0x70000000 /* First processor-specific type. */=0D
+#define DT_DEPRECATED_SPARC_REGISTER 0x7000001=0D
+#define DT_AUXILIARY 0x7ffffffd /* shared library auxiliary name */=0D
+#define DT_USED 0x7ffffffe /* ignored - same as needed */=0D
+#define DT_FILTER 0x7fffffff /* shared library filter name */=0D
+#define DT_HIPROC 0x7fffffff /* Last processor-specific type. */=0D
+=0D
+/* Values for DT_FLAGS */=0D
+#define DF_ORIGIN 0x0001 /* Indicates that the object being loaded may=
=0D
+ make reference to the $ORIGIN substitution=0D
+ string */=0D
+#define DF_SYMBOLIC 0x0002 /* Indicates "symbolic" linking. */=0D
+#define DF_TEXTREL 0x0004 /* Indicates there may be relocations in=0D
+ non-writable segments. */=0D
+#define DF_BIND_NOW 0x0008 /* Indicates that the dynamic linker should=
=0D
+ process all relocations for the object=0D
+ containing this entry before transferring=0D
+ control to the program. */=0D
+#define DF_STATIC_TLS 0x0010 /* Indicates that the shared object or=0D
+ executable contains code using a static=0D
+ thread-local storage scheme. */=0D
+=0D
+/* Values for n_type. Used in core files. */=0D
+#define NT_PRSTATUS 1 /* Process status. */=0D
+#define NT_FPREGSET 2 /* Floating point registers. */=0D
+#define NT_PRPSINFO 3 /* Process state info. */=0D
+=0D
+/* Symbol Binding - ELFNN_ST_BIND - st_info */=0D
+#define STB_LOCAL 0 /* Local symbol */=0D
+#define STB_GLOBAL 1 /* Global symbol */=0D
+#define STB_WEAK 2 /* like global - lower precedence */=0D
+#define STB_LOOS 10 /* Reserved range for operating system */=0D
+#define STB_HIOS 12 /* specific semantics. */=0D
+#define STB_LOPROC 13 /* reserved range for processor */=0D
+#define STB_HIPROC 15 /* specific semantics. */=0D
+=0D
+/* Symbol type - ELFNN_ST_TYPE - st_info */=0D
+#define STT_NOTYPE 0 /* Unspecified type. */=0D
+#define STT_OBJECT 1 /* Data object. */=0D
+#define STT_FUNC 2 /* Function. */=0D
+#define STT_SECTION 3 /* Section. */=0D
+#define STT_FILE 4 /* Source file. */=0D
+#define STT_COMMON 5 /* Uninitialized common block. */=0D
+#define STT_TLS 6 /* TLS object. */=0D
+#define STT_NUM 7=0D
+#define STT_LOOS 10 /* Reserved range for operating system */=0D
+#define STT_HIOS 12 /* specific semantics. */=0D
+#define STT_LOPROC 13 /* reserved range for processor */=0D
+#define STT_HIPROC 15 /* specific semantics. */=0D
+=0D
+/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */=0D
+#define STV_DEFAULT 0x0 /* Default visibility (see binding). */=0D
+#define STV_INTERNAL 0x1 /* Special meaning in relocatable objects. */=0D
+#define STV_HIDDEN 0x2 /* Not visible. */=0D
+#define STV_PROTECTED 0x3 /* Visible but not preemptible. */=0D
+=0D
+/* Special symbol table indexes. */=0D
+#define STN_UNDEF 0 /* Undefined symbol index. */=0D
+=0D
+/* Symbol versioning flags. */=0D
+#define VER_DEF_CURRENT 1=0D
+#define VER_DEF_IDX(x) VER_NDX(x)=0D
+=0D
+#define VER_FLG_BASE 0x01=0D
+#define VER_FLG_WEAK 0x02=0D
+=0D
+#define VER_NEED_CURRENT 1=0D
+#define VER_NEED_WEAK (1u << 15)=0D
+#define VER_NEED_HIDDEN VER_NDX_HIDDEN=0D
+#define VER_NEED_IDX(x) VER_NDX(x)=0D
+=0D
+#define VER_NDX_LOCAL 0=0D
+#define VER_NDX_GLOBAL 1=0D
+#define VER_NDX_GIVEN 2=0D
+=0D
+#define VER_NDX_HIDDEN (1u << 15)=0D
+#define VER_NDX(x) ((x) & ~(1u << 15))=0D
+=0D
+#define CA_SUNW_NULL 0=0D
+#define CA_SUNW_HW_1 1 /* first hardware capabilities entry */=0D
+#define CA_SUNW_SF_1 2 /* first software capabilities entry */=0D
+=0D
+/*=0D
+ * Syminfo flag values=0D
+ */=0D
+#define SYMINFO_FLG_DIRECT 0x0001 /* symbol ref has direct association =
*/=0D
+ /* to object containing defn. */=0D
+#define SYMINFO_FLG_PASSTHRU 0x0002 /* ignored - see SYMINFO_FLG_FILTER=
*/=0D
+#define SYMINFO_FLG_COPY 0x0004 /* symbol is a copy-reloc */=0D
+#define SYMINFO_FLG_LAZYLOAD 0x0008 /* object containing defn should be=
*/=0D
+ /* lazily-loaded */=0D
+#define SYMINFO_FLG_DIRECTBIND 0x0010 /* ref should be bound directly t=
o */=0D
+ /* object containing defn. */=0D
+#define SYMINFO_FLG_NOEXTDIRECT 0x0020 /* don't let an external referen=
ce */=0D
+ /* directly bind to this symbol */=0D
+#define SYMINFO_FLG_FILTER 0x0002 /* symbol ref is associated to a */=0D
+#define SYMINFO_FLG_AUXILIARY 0x0040 /* standard or auxiliary filter =
*/=0D
+=0D
+/*=0D
+ * Syminfo.si_boundto values.=0D
+ */=0D
+#define SYMINFO_BT_SELF 0xffff /* symbol bound to self */=0D
+#define SYMINFO_BT_PARENT 0xfffe /* symbol bound to parent */=0D
+#define SYMINFO_BT_NONE 0xfffd /* no special symbol binding */=0D
+#define SYMINFO_BT_EXTERN 0xfffc /* symbol defined as external */=0D
+#define SYMINFO_BT_LOWRESERVE 0xff00 /* beginning of reserved entries *=
/=0D
+=0D
+/*=0D
+ * Syminfo version values.=0D
+ */=0D
+#define SYMINFO_NONE 0 /* Syminfo version */=0D
+#define SYMINFO_CURRENT 1=0D
+#define SYMINFO_NUM 2=0D
+=0D
+/*=0D
+ * Relocation types.=0D
+ *=0D
+ * All machine architectures are defined here to allow tools on one to=0D
+ * handle others.=0D
+ */=0D
+=0D
+#define R_386_NONE 0 /* No relocation. */=0D
+#define R_386_32 1 /* Add symbol value. */=0D
+#define R_386_PC32 2 /* Add PC-relative symbol value. */=0D
+#define R_386_GOT32 3 /* Add PC-relative GOT offset. */=0D
+#define R_386_PLT32 4 /* Add PC-relative PLT offset. */=0D
+#define R_386_COPY 5 /* Copy data from shared object. */=0D
+#define R_386_GLOB_DAT 6 /* Set GOT entry to data address. */=0D
+#define R_386_JMP_SLOT 7 /* Set GOT entry to code address. */=0D
+#define R_386_RELATIVE 8 /* Add load address of shared object. */=0D
+#define R_386_GOTOFF 9 /* Add GOT-relative symbol address. */=0D
+#define R_386_GOTPC 10 /* Add PC-relative GOT table address. */=0D
+#define R_386_TLS_TPOFF 14 /* Negative offset in static TLS block */=
=0D
+#define R_386_TLS_IE 15 /* Absolute address of GOT for -ve static TLS=
*/=0D
+#define R_386_TLS_GOTIE 16 /* GOT entry for negative static TLS block=
*/=0D
+#define R_386_TLS_LE 17 /* Negative offset relative to static TLS */=
=0D
+#define R_386_TLS_GD 18 /* 32 bit offset to GOT (index,off) pair */=0D
+#define R_386_TLS_LDM 19 /* 32 bit offset to GOT (index,zero) pair */=
=0D
+#define R_386_TLS_GD_32 24 /* 32 bit offset to GOT (index,off) pair *=
/=0D
+#define R_386_TLS_GD_PUSH 25 /* pushl instruction for Sun ABI GD sequen=
ce */=0D
+#define R_386_TLS_GD_CALL 26 /* call instruction for Sun ABI GD sequenc=
e */=0D
+#define R_386_TLS_GD_POP 27 /* popl instruction for Sun ABI GD sequence=
*/=0D
+#define R_386_TLS_LDM_32 28 /* 32 bit offset to GOT (index,zero) pair *=
/=0D
+#define R_386_TLS_LDM_PUSH 29 /* pushl instruction for Sun ABI LD seque=
nce */=0D
+#define R_386_TLS_LDM_CALL 30 /* call instruction for Sun ABI LD sequen=
ce */=0D
+#define R_386_TLS_LDM_POP 31 /* popl instruction for Sun ABI LD sequenc=
e */=0D
+#define R_386_TLS_LDO_32 32 /* 32 bit offset from start of TLS block */=
=0D
+#define R_386_TLS_IE_32 33 /* 32 bit offset to GOT static TLS offset =
entry */=0D
+#define R_386_TLS_LE_32 34 /* 32 bit offset within static TLS block *=
/=0D
+#define R_386_TLS_DTPMOD32 35 /* GOT entry containing TLS index */=0D
+#define R_386_TLS_DTPOFF32 36 /* GOT entry containing TLS offset */=0D
+#define R_386_TLS_TPOFF32 37 /* GOT entry of -ve static TLS offset */=0D
+=0D
+/* Null relocation */=0D
+#define R_AARCH64_NONE 256 /* No relocation */=0D
+/* Static AArch64 relocations */=0D
+ /* Static data relocations */=0D
+#define R_AARCH64_ABS64 257 /* S + A */=0D
+#define R_AARCH64_ABS32 258 /* S + A */=0D
+#define R_AARCH64_ABS16 259 /* S + A */=0D
+#define R_AARCH64_PREL64 260 /* S + A - P */=0D
+#define R_AARCH64_PREL32 261 /* S + A - P */=0D
+#define R_AARCH64_PREL16 262 /* S + A - P */=0D
+ /* Group relocations to create a 16, 32, 48, or 64 bit unsigned data valu=
e or address inline */=0D
+#define R_AARCH64_MOVW_UABS_G0 263 /* S + A */=0D
+#define R_AARCH64_MOVW_UABS_G0_NC 264 /* S + A */=0D
+#define R_AARCH64_MOVW_UABS_G1 265 /* S + A */=0D
+#define R_AARCH64_MOVW_UABS_G1_NC 266 /* S + A */=0D
+#define R_AARCH64_MOVW_UABS_G2 267 /* S + A */=0D
+#define R_AARCH64_MOVW_UABS_G2_NC 268 /* S + A */=0D
+#define R_AARCH64_MOVW_UABS_G3 269 /* S + A */=0D
+ /* Group relocations to create a 16, 32, 48, or 64 bit signed data or off=
set value inline */=0D
+#define R_AARCH64_MOVW_SABS_G0 270 /* S + A */=0D
+#define R_AARCH64_MOVW_SABS_G1 271 /* S + A */=0D
+#define R_AARCH64_MOVW_SABS_G2 272 /* S + A */=0D
+ /* Relocations to generate 19, 21 and 33 bit PC-relative addresses */=0D
+#define R_AARCH64_LD_PREL_LO19 273 /* S + A - P */=0D
+#define R_AARCH64_ADR_PREL_LO21 274 /* S + A - P */=0D
+#define R_AARCH64_ADR_PREL_PG_HI21 275 /* Page(S+A) - Page(P) */=0D
+#define R_AARCH64_ADR_PREL_PG_HI21_NC 276 /* Page(S+A) - Page(P) */=0D
+#define R_AARCH64_ADD_ABS_LO12_NC 277 /* S + A */=0D
+#define R_AARCH64_LDST8_ABS_LO12_NC 278 /* S + A */=0D
+#define R_AARCH64_LDST16_ABS_LO12_NC 284 /* S + A */=0D
+#define R_AARCH64_LDST32_ABS_LO12_NC 285 /* S + A */=0D
+#define R_AARCH64_LDST64_ABS_LO12_NC 286 /* S + A */=0D
+#define R_AARCH64_LDST128_ABS_LO12_NC 299 /* S + A */=0D
+ /* Relocations for control-flow instructions - all offsets are a multiple=
of 4 */=0D
+#define R_AARCH64_TSTBR14 279 /* S+A-P */=0D
+#define R_AARCH64_CONDBR19 280 /* S+A-P */=0D
+#define R_AARCH64_JUMP26 282 /* S+A-P */=0D
+#define R_AARCH64_CALL26 283 /* S+A-P */=0D
+ /* Group relocations to create a 16, 32, 48, or 64 bit PC-relative offset=
inline */=0D
+#define R_AARCH64_MOVW_PREL_G0 287 /* S+A-P */=0D
+#define R_AARCH64_MOVW_PREL_G0_NC 288 /* S+A-P */=0D
+#define R_AARCH64_MOVW_PREL_G1 289 /* S+A-P */=0D
+#define R_AARCH64_MOVW_PREL_G1_NC 290 /* S+A-P */=0D
+#define R_AARCH64_MOVW_PREL_G2 291 /* S+A-P */=0D
+#define R_AARCH64_MOVW_PREL_G2_NC 292 /* S+A-P */=0D
+#define R_AARCH64_MOVW_PREL_G3 293 /* S+A-P */=0D
+ /* Group relocations to create a 16, 32, 48, or 64 bit GOT-relative offse=
ts inline */=0D
+#define R_AARCH64_MOVW_GOTOFF_G0 300 /* G(S)-GOT */=0D
+#define R_AARCH64_MOVW_GOTOFF_G0_NC 301 /* G(S)-GOT */=0D
+#define R_AARCH64_MOVW_GOTOFF_G1 302 /* G(S)-GOT */=0D
+#define R_AARCH64_MOVW_GOTOFF_G1_NC 303 /* G(S)-GOT */=0D
+#define R_AARCH64_MOVW_GOTOFF_G2 304 /* G(S)-GOT */=0D
+#define R_AARCH64_MOVW_GOTOFF_G2_NC 305 /* G(S)-GOT */=0D
+#define R_AARCH64_MOVW_GOTOFF_G3 306 /* G(S)-GOT */=0D
+ /* GOT-relative data relocations */=0D
+#define R_AARCH64_GOTREL64 307 /* S+A-GOT */=0D
+#define R_AARCH64_GOTREL32 308 /* S+A-GOT */=0D
+ /* GOT-relative instruction relocations */=0D
+#define R_AARCH64_GOT_LD_PREL19 309 /* G(S)-P */=0D
+#define R_AARCH64_LD64_GOTOFF_LO15 310 /* G(S)-GOT */=0D
+#define R_AARCH64_ADR_GOT_PAGE 311 /* Page(G(S))-Page(P) */=0D
+#define R_AARCH64_LD64_GOT_LO12_NC 312 /* G(S) */=0D
+#define R_AARCH64_LD64_GOTPAGE_LO15 313 /* G(S)-Page(GOT) */=0D
+/* Relocations for thread-local storage */=0D
+ /* General Dynamic TLS relocations */=0D
+#define R_AARCH64_TLSGD_ADR_PREL21 512 /* G(TLSIDX(S+A)) - P */=0D
+#define R_AARCH64_TLSGD_ADR_PAGE21 513 /* Page(G(TLSIDX(S+A))) - Page=
(P) */=0D
+#define R_AARCH64_TLSGD_ADD_LO12_NC 514 /* G(TLSIDX(S+A)) */=0D
+#define R_AARCH64_TLSGD_MOVW_G1 515 /* G(TLSIDX(S+A)) - GOT */=0D
+#define R_AARCH64_TLSGD_MOVW_G0_NC 516 /* G(TLSIDX(S+A)) - GOT */=0D
+ /* Local Dynamic TLS relocations */=0D
+#define R_AARCH64_TLSLD_ADR_PREL21 517 /* G(LDM(S))) - P */=0D
+#define R_AARCH64_TLSLD_ADR_PAGE21 518 /* Page(G(LDM(S)))-Page(P) */=
=0D
+#define R_AARCH64_TLSLD_ADD_LO12_NC 519 /* G(LDM(S)) */=0D
+#define R_AARCH64_TLSLD_MOVW_G1 520 /* G(LDM(S)) - GOT */=0D
+#define R_AARCH64_TLSLD_MOVW_G0_NC 521 /* G(LDM(S)) - GOT */=0D
+#define R_AARCH64_TLSLD_LD_PREL19 522 /* G(LDM(S)) - P */=0D
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G2 523 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G1 524 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G1_NC 525 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G0 526 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC 527 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_ADD_DTPREL_HI12 528 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_ADD_DTPREL_LO12 529 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC 530 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_LDST8_DTPREL_LO12 531 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC 532 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_LDST16_DTPREL_LO12 533 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC 534 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_LDST32_DTPREL_LO12 535 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC 536 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_LDST64_DTPREL_LO12 537 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC 538 /* DTPREL(S+A) */=0D
+ /* Initial Exec TLS relocations */=0D
+#define R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 539 /* G(TPREL(S+A)) - GOT */=
=0D
+#define R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC 540 /* G(TPREL(S+A)) - GOT =
*/=0D
+#define R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 541 /* Page(G(TPREL(S+A))) =
- Page(P) */=0D
+#define R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC 542 /* G(TPREL(S+A)) */=0D
+#define R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 543 /* G(TPREL(S+A)) - P */=
=0D
+ /* Local Exec TLS relocations */=0D
+#define R_AARCH64_TLSLE_MOVW_TPREL_G2 544 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_MOVW_TPREL_G1 545 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_MOVW_TPREL_G1_NC 546 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_MOVW_TPREL_G0 547 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_MOVW_TPREL_G0_NC 548 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_ADD_TPREL_HI12 549 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_ADD_TPREL_LO12 550 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_ADD_TPREL_LO12_NC 551 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_LDST8_TPREL_LO12 552 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC 553 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_LDST16_TPREL_LO12 554 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC 555 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_LDST32_TPREL_LO12 556 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC 557 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_LDST64_TPREL_LO12 558 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC 559 /* TPREL(S+A) */=0D
+/* Dynamic relocations */=0D
+ /* Dynamic relocations */=0D
+#define R_AARCH64_COPY 1024=0D
+#define R_AARCH64_GLOB_DAT 1025 /* S + A */=0D
+#define R_AARCH64_JUMP_SLOT 1026 /* S + A */=0D
+#define R_AARCH64_RELATIVE 1027 /* Delta(S) + A , Delta(P) + A */=0D
+#define R_AARCH64_TLS_DTPREL64 1028 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLS_DTPMOD64 1029 /* LDM(S) */=0D
+#define R_AARCH64_TLS_TPREL64 1030 /* TPREL(S+A) */=0D
+#define R_AARCH64_TLS_DTPREL32 1031 /* DTPREL(S+A) */=0D
+#define R_AARCH64_TLS_DTPMOD32 1032 /* LDM(S) */=0D
+#define R_AARCH64_TLS_TPREL32 1033 /* DTPREL(S+A) */=0D
+=0D
+#define R_ALPHA_NONE 0 /* No reloc */=0D
+#define R_ALPHA_REFLONG 1 /* Direct 32 bit */=0D
+#define R_ALPHA_REFQUAD 2 /* Direct 64 bit */=0D
+#define R_ALPHA_GPREL32 3 /* GP relative 32 bit */=0D
+#define R_ALPHA_LITERAL 4 /* GP relative 16 bit w/optimization */=0D
+#define R_ALPHA_LITUSE 5 /* Optimization hint for LITERAL */=0D
+#define R_ALPHA_GPDISP 6 /* Add displacement to GP */=0D
+#define R_ALPHA_BRADDR 7 /* PC+4 relative 23 bit shifted */=0D
+#define R_ALPHA_HINT 8 /* PC+4 relative 16 bit shifted */=0D
+#define R_ALPHA_SREL16 9 /* PC relative 16 bit */=0D
+#define R_ALPHA_SREL32 10 /* PC relative 32 bit */=0D
+#define R_ALPHA_SREL64 11 /* PC relative 64 bit */=0D
+#define R_ALPHA_OP_PUSH 12 /* OP stack push */=0D
+#define R_ALPHA_OP_STORE 13 /* OP stack pop and store */=0D
+#define R_ALPHA_OP_PSUB 14 /* OP stack subtract */=0D
+#define R_ALPHA_OP_PRSHIFT 15 /* OP stack right shift */=0D
+#define R_ALPHA_GPVALUE 16=0D
+#define R_ALPHA_GPRELHIGH 17=0D
+#define R_ALPHA_GPRELLOW 18=0D
+#define R_ALPHA_IMMED_GP_16 19=0D
+#define R_ALPHA_IMMED_GP_HI32 20=0D
+#define R_ALPHA_IMMED_SCN_HI32 21=0D
+#define R_ALPHA_IMMED_BR_HI32 22=0D
+#define R_ALPHA_IMMED_LO32 23=0D
+#define R_ALPHA_COPY 24 /* Copy symbol at runtime */=0D
+#define R_ALPHA_GLOB_DAT 25 /* Create GOT entry */=0D
+#define R_ALPHA_JMP_SLOT 26 /* Create PLT entry */=0D
+#define R_ALPHA_RELATIVE 27 /* Adjust by program base */=0D
+=0D
+#define R_ARM_NONE 0 /* No relocation. */=0D
+#define R_ARM_PC24 1=0D
+#define R_ARM_ABS32 2=0D
+#define R_ARM_REL32 3=0D
+#define R_ARM_PC13 4=0D
+#define R_ARM_ABS16 5=0D
+#define R_ARM_ABS12 6=0D
+#define R_ARM_THM_ABS5 7=0D
+#define R_ARM_ABS8 8=0D
+#define R_ARM_SBREL32 9=0D
+#define R_ARM_THM_PC22 10=0D
+#define R_ARM_THM_PC8 11=0D
+#define R_ARM_AMP_VCALL9 12=0D
+#define R_ARM_SWI24 13=0D
+#define R_ARM_THM_SWI8 14=0D
+#define R_ARM_XPC25 15=0D
+#define R_ARM_THM_XPC22 16=0D
+#define R_ARM_COPY 20 /* Copy data from shared object. */=0D
+#define R_ARM_GLOB_DAT 21 /* Set GOT entry to data address. */=0D
+#define R_ARM_JUMP_SLOT 22 /* Set GOT entry to code address. */=0D
+#define R_ARM_RELATIVE 23 /* Add load address of shared object. */=0D
+#define R_ARM_GOTOFF 24 /* Add GOT-relative symbol address. */=0D
+#define R_ARM_GOTPC 25 /* Add PC-relative GOT table address. */=0D
+#define R_ARM_GOT32 26 /* Add PC-relative GOT offset. */=0D
+#define R_ARM_PLT32 27 /* Add PC-relative PLT offset. */=0D
+#define R_ARM_CALL 28=0D
+#define R_ARM_JMP24 29=0D
+#define R_ARM_THM_MOVW_ABS_NC 47=0D
+#define R_ARM_THM_MOVT_ABS 48=0D
+=0D
+// Block of PC-relative relocations added to work around gcc putting=0D
+// object relocations in static executables.=0D
+#define R_ARM_THM_JUMP24 30=0D
+#define R_ARM_PREL31 42=0D
+#define R_ARM_MOVW_PREL_NC 45=0D
+#define R_ARM_MOVT_PREL 46=0D
+#define R_ARM_THM_MOVW_PREL_NC 49=0D
+#define R_ARM_THM_MOVT_PREL 50=0D
+#define R_ARM_THM_JMP6 52=0D
+#define R_ARM_THM_ALU_PREL_11_0 53=0D
+#define R_ARM_THM_PC12 54=0D
+#define R_ARM_REL32_NOI 56=0D
+#define R_ARM_ALU_PC_G0_NC 57=0D
+#define R_ARM_ALU_PC_G0 58=0D
+#define R_ARM_ALU_PC_G1_NC 59=0D
+#define R_ARM_ALU_PC_G1 60=0D
+#define R_ARM_ALU_PC_G2 61=0D
+#define R_ARM_LDR_PC_G1 62=0D
+#define R_ARM_LDR_PC_G2 63=0D
+#define R_ARM_LDRS_PC_G0 64=0D
+#define R_ARM_LDRS_PC_G1 65=0D
+#define R_ARM_LDRS_PC_G2 66=0D
+#define R_ARM_LDC_PC_G0 67=0D
+#define R_ARM_LDC_PC_G1 68=0D
+#define R_ARM_LDC_PC_G2 69=0D
+#define R_ARM_GOT_PREL 96=0D
+#define R_ARM_THM_JUMP11 102=0D
+#define R_ARM_THM_JUMP8 103=0D
+#define R_ARM_TLS_GD32 104=0D
+#define R_ARM_TLS_LDM32 105=0D
+#define R_ARM_TLS_IE32 107=0D
+=0D
+#define R_ARM_THM_JUMP19 51=0D
+#define R_ARM_GNU_VTENTRY 100=0D
+#define R_ARM_GNU_VTINHERIT 101=0D
+#define R_ARM_RSBREL32 250=0D
+#define R_ARM_THM_RPC22 251=0D
+#define R_ARM_RREL32 252=0D
+#define R_ARM_RABS32 253=0D
+#define R_ARM_RPC24 254=0D
+#define R_ARM_RBASE 255=0D
+=0D
+#define R_PPC_NONE 0 /* No relocation. */=0D
+#define R_PPC_ADDR32 1=0D
+#define R_PPC_ADDR24 2=0D
+#define R_PPC_ADDR16 3=0D
+#define R_PPC_ADDR16_LO 4=0D
+#define R_PPC_ADDR16_HI 5=0D
+#define R_PPC_ADDR16_HA 6=0D
+#define R_PPC_ADDR14 7=0D
+#define R_PPC_ADDR14_BRTAKEN 8=0D
+#define R_PPC_ADDR14_BRNTAKEN 9=0D
+#define R_PPC_REL24 10=0D
+#define R_PPC_REL14 11=0D
+#define R_PPC_REL14_BRTAKEN 12=0D
+#define R_PPC_REL14_BRNTAKEN 13=0D
+#define R_PPC_GOT16 14=0D
+#define R_PPC_GOT16_LO 15=0D
+#define R_PPC_GOT16_HI 16=0D
+#define R_PPC_GOT16_HA 17=0D
+#define R_PPC_PLTREL24 18=0D
+#define R_PPC_COPY 19=0D
+#define R_PPC_GLOB_DAT 20=0D
+#define R_PPC_JMP_SLOT 21=0D
+#define R_PPC_RELATIVE 22=0D
+#define R_PPC_LOCAL24PC 23=0D
+#define R_PPC_UADDR32 24=0D
+#define R_PPC_UADDR16 25=0D
+#define R_PPC_REL32 26=0D
+#define R_PPC_PLT32 27=0D
+#define R_PPC_PLTREL32 28=0D
+#define R_PPC_PLT16_LO 29=0D
+#define R_PPC_PLT16_HI 30=0D
+#define R_PPC_PLT16_HA 31=0D
+#define R_PPC_SDAREL16 32=0D
+#define R_PPC_SECTOFF 33=0D
+#define R_PPC_SECTOFF_LO 34=0D
+#define R_PPC_SECTOFF_HI 35=0D
+#define R_PPC_SECTOFF_HA 36=0D
+=0D
+/*=0D
+ * TLS relocations=0D
+ */=0D
+#define R_PPC_TLS 67=0D
+#define R_PPC_DTPMOD32 68=0D
+#define R_PPC_TPREL16 69=0D
+#define R_PPC_TPREL16_LO 70=0D
+#define R_PPC_TPREL16_HI 71=0D
+#define R_PPC_TPREL16_HA 72=0D
+#define R_PPC_TPREL32 73=0D
+#define R_PPC_DTPREL16 74=0D
+#define R_PPC_DTPREL16_LO 75=0D
+#define R_PPC_DTPREL16_HI 76=0D
+#define R_PPC_DTPREL16_HA 77=0D
+#define R_PPC_DTPREL32 78=0D
+#define R_PPC_GOT_TLSGD16 79=0D
+#define R_PPC_GOT_TLSGD16_LO 80=0D
+#define R_PPC_GOT_TLSGD16_HI 81=0D
+#define R_PPC_GOT_TLSGD16_HA 82=0D
+#define R_PPC_GOT_TLSLD16 83=0D
+#define R_PPC_GOT_TLSLD16_LO 84=0D
+#define R_PPC_GOT_TLSLD16_HI 85=0D
+#define R_PPC_GOT_TLSLD16_HA 86=0D
+#define R_PPC_GOT_TPREL16 87=0D
+#define R_PPC_GOT_TPREL16_LO 88=0D
+#define R_PPC_GOT_TPREL16_HI 89=0D
+#define R_PPC_GOT_TPREL16_HA 90=0D
+=0D
+/*=0D
+ * The remaining relocs are from the Embedded ELF ABI, and are not in the=
=0D
+ * SVR4 ELF ABI.=0D
+ */=0D
+=0D
+#define R_PPC_EMB_NADDR32 101=0D
+#define R_PPC_EMB_NADDR16 102=0D
+#define R_PPC_EMB_NADDR16_LO 103=0D
+#define R_PPC_EMB_NADDR16_HI 104=0D
+#define R_PPC_EMB_NADDR16_HA 105=0D
+#define R_PPC_EMB_SDAI16 106=0D
+#define R_PPC_EMB_SDA2I16 107=0D
+#define R_PPC_EMB_SDA2REL 108=0D
+#define R_PPC_EMB_SDA21 109=0D
+#define R_PPC_EMB_MRKREF 110=0D
+#define R_PPC_EMB_RELSEC16 111=0D
+#define R_PPC_EMB_RELST_LO 112=0D
+#define R_PPC_EMB_RELST_HI 113=0D
+#define R_PPC_EMB_RELST_HA 114=0D
+#define R_PPC_EMB_BIT_FLD 115=0D
+#define R_PPC_EMB_RELSDA 116=0D
+=0D
+#define R_SPARC_NONE 0=0D
+#define R_SPARC_8 1=0D
+#define R_SPARC_16 2=0D
+#define R_SPARC_32 3=0D
+#define R_SPARC_DISP8 4=0D
+#define R_SPARC_DISP16 5=0D
+#define R_SPARC_DISP32 6=0D
+#define R_SPARC_WDISP30 7=0D
+#define R_SPARC_WDISP22 8=0D
+#define R_SPARC_HI22 9=0D
+#define R_SPARC_22 10=0D
+#define R_SPARC_13 11=0D
+#define R_SPARC_LO10 12=0D
+#define R_SPARC_GOT10 13=0D
+#define R_SPARC_GOT13 14=0D
+#define R_SPARC_GOT22 15=0D
+#define R_SPARC_PC10 16=0D
+#define R_SPARC_PC22 17=0D
+#define R_SPARC_WPLT30 18=0D
+#define R_SPARC_COPY 19=0D
+#define R_SPARC_GLOB_DAT 20=0D
+#define R_SPARC_JMP_SLOT 21=0D
+#define R_SPARC_RELATIVE 22=0D
+#define R_SPARC_UA32 23=0D
+#define R_SPARC_PLT32 24=0D
+#define R_SPARC_HIPLT22 25=0D
+#define R_SPARC_LOPLT10 26=0D
+#define R_SPARC_PCPLT32 27=0D
+#define R_SPARC_PCPLT22 28=0D
+#define R_SPARC_PCPLT10 29=0D
+#define R_SPARC_10 30=0D
+#define R_SPARC_11 31=0D
+#define R_SPARC_64 32=0D
+#define R_SPARC_OLO10 33=0D
+#define R_SPARC_HH22 34=0D
+#define R_SPARC_HM10 35=0D
+#define R_SPARC_LM22 36=0D
+#define R_SPARC_PC_HH22 37=0D
+#define R_SPARC_PC_HM10 38=0D
+#define R_SPARC_PC_LM22 39=0D
+#define R_SPARC_WDISP16 40=0D
+#define R_SPARC_WDISP19 41=0D
+#define R_SPARC_GLOB_JMP 42=0D
+#define R_SPARC_7 43=0D
+#define R_SPARC_5 44=0D
+#define R_SPARC_6 45=0D
+#define R_SPARC_DISP64 46=0D
+#define R_SPARC_PLT64 47=0D
+#define R_SPARC_HIX22 48=0D
+#define R_SPARC_LOX10 49=0D
+#define R_SPARC_H44 50=0D
+#define R_SPARC_M44 51=0D
+#define R_SPARC_L44 52=0D
+#define R_SPARC_REGISTER 53=0D
+#define R_SPARC_UA64 54=0D
+#define R_SPARC_UA16 55=0D
+#define R_SPARC_TLS_GD_HI22 56=0D
+#define R_SPARC_TLS_GD_LO10 57=0D
+#define R_SPARC_TLS_GD_ADD 58=0D
+#define R_SPARC_TLS_GD_CALL 59=0D
+#define R_SPARC_TLS_LDM_HI22 60=0D
+#define R_SPARC_TLS_LDM_LO10 61=0D
+#define R_SPARC_TLS_LDM_ADD 62=0D
+#define R_SPARC_TLS_LDM_CALL 63=0D
+#define R_SPARC_TLS_LDO_HIX22 64=0D
+#define R_SPARC_TLS_LDO_LOX10 65=0D
+#define R_SPARC_TLS_LDO_ADD 66=0D
+#define R_SPARC_TLS_IE_HI22 67=0D
+#define R_SPARC_TLS_IE_LO10 68=0D
+#define R_SPARC_TLS_IE_LD 69=0D
+#define R_SPARC_TLS_IE_LDX 70=0D
+#define R_SPARC_TLS_IE_ADD 71=0D
+#define R_SPARC_TLS_LE_HIX22 72=0D
+#define R_SPARC_TLS_LE_LOX10 73=0D
+#define R_SPARC_TLS_DTPMOD32 74=0D
+#define R_SPARC_TLS_DTPMOD64 75=0D
+#define R_SPARC_TLS_DTPOFF32 76=0D
+#define R_SPARC_TLS_DTPOFF64 77=0D
+#define R_SPARC_TLS_TPOFF32 78=0D
+#define R_SPARC_TLS_TPOFF64 79=0D
+=0D
+#define R_X86_64_NONE 0 /* No relocation. */=0D
+#define R_X86_64_64 1 /* Add 64 bit symbol value. */=0D
+#define R_X86_64_PC32 2 /* PC-relative 32 bit signed sym value. */=0D
+#define R_X86_64_GOT32 3 /* PC-relative 32 bit GOT offset. */=0D
+#define R_X86_64_PLT32 4 /* PC-relative 32 bit PLT offset. */=0D
+#define R_X86_64_COPY 5 /* Copy data from shared object. */=0D
+#define R_X86_64_GLOB_DAT 6 /* Set GOT entry to data address. */=0D
+#define R_X86_64_JMP_SLOT 7 /* Set GOT entry to code address. */=0D
+#define R_X86_64_RELATIVE 8 /* Add load address of shared object. */=0D
+#define R_X86_64_GOTPCREL 9 /* Add 32 bit signed pcrel offset to GOT. *=
/=0D
+#define R_X86_64_32 10 /* Add 32 bit zero extended symbol value */=0D
+#define R_X86_64_32S 11 /* Add 32 bit sign extended symbol value */=0D
+#define R_X86_64_16 12 /* Add 16 bit zero extended symbol value */=0D
+#define R_X86_64_PC16 13 /* Add 16 bit signed extended pc relative sy=
mbol value */=0D
+#define R_X86_64_8 14 /* Add 8 bit zero extended symbol value */=0D
+#define R_X86_64_PC8 15 /* Add 8 bit signed extended pc relative symb=
ol value */=0D
+#define R_X86_64_DTPMOD64 16 /* ID of module containing symbol */=0D
+#define R_X86_64_DTPOFF64 17 /* Offset in TLS block */=0D
+#define R_X86_64_TPOFF64 18 /* Offset in static TLS block */=0D
+#define R_X86_64_TLSGD 19 /* PC relative offset to GD GOT entry */=0D
+#define R_X86_64_TLSLD 20 /* PC relative offset to LD GOT entry */=0D
+#define R_X86_64_DTPOFF32 21 /* Offset in TLS block */=0D
+#define R_X86_64_GOTTPOFF 22 /* PC relative offset to IE GOT entry */=0D
+#define R_X86_64_TPOFF32 23 /* Offset in static TLS block */=0D
+#define R_X86_64_PC64 24 /* PC relative 64 bit */=0D
+#define R_X86_64_GOTOFF64 25 /* 64 bit offset to GOT */=0D
+#define R_X86_64_GOTPC3 26 /* 32 bit signed pc relative offset to GOT *=
/=0D
+#define R_X86_64_GOT64 27 /* 64-bit GOT entry offset */=0D
+#define R_X86_64_GOTPCREL64 28 /* 64-bit PC relative offset to GOT entr=
y */=0D
+#define R_X86_64_GOTPC64 29 /* 64-bit PC relative offset to GOT */=0D
+#define R_X86_64_GOTPLT64 30 /* like GOT64, says PLT entry needed */=0D
+#define R_X86_64_PLTOFF64 31 /* 64-bit GOT relative offset to PLT entry=
*/=0D
+#define R_X86_64_SIZE32 32 /* Size of symbol plus 32-bit addend */=0D
+#define R_X86_64_SIZE64 33 /* Size of symbol plus 64-bit addend */=0D
+#define R_X86_64_GOTPC32_TLSDESC 34 /* GOT offset for TLS descriptor. *=
/=0D
+#define R_X86_64_TLSDESC_CALL 35 /* Marker for call through TLS descrip=
tor. */=0D
+#define R_X86_64_TLSDESC 36 /* TLS descriptor. */=0D
+#define R_X86_64_IRELATIVE 37 /* Adjust indirectly by program base */=0D
+#define R_X86_64_RELATIVE64 38 /* 64-bit adjust by program base */=0D
+#define R_X86_64_GOTPCRELX 41 /* Load from 32 bit signed pc relative of=
fset to GOT entry without REX prefix, relaxable. */=0D
+#define R_X86_64_REX_GOTPCRELX 42 /* Load from 32 bit signed pc relativ=
e offset to GOT entry with REX prefix, relaxable. */=0D
+=0D
+=0D
+#endif /* !_SYS_ELF_COMMON_H_ */=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLib.c b/UefiPayload=
Pkg/PayloadLoaderPeim/ElfLib/ElfLib.c
new file mode 100644
index 0000000000..531b3486d2
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLib.c
@@ -0,0 +1,473 @@
+/** @file=0D
+ ELF library=0D
+=0D
+ Copyright (c) 2019 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include "ElfLibInternal.h"=0D
+=0D
+/**=0D
+ Check if the ELF image is valid.=0D
+=0D
+ @param[in] ImageBase Memory address of an image.=0D
+=0D
+ @retval TRUE if valid.=0D
+=0D
+**/=0D
+BOOLEAN=0D
+IsElfFormat (=0D
+ IN CONST UINT8 *ImageBase=0D
+ )=0D
+{=0D
+ Elf32_Ehdr *Elf32Hdr;=0D
+ Elf64_Ehdr *Elf64Hdr;=0D
+=0D
+ ASSERT (ImageBase !=3D NULL);=0D
+=0D
+ Elf32Hdr =3D (Elf32_Ehdr *)ImageBase;=0D
+=0D
+ //=0D
+ // Start with correct signature "\7fELF"=0D
+ //=0D
+ if ((Elf32Hdr->e_ident[EI_MAG0] !=3D ELFMAG0) ||=0D
+ (Elf32Hdr->e_ident[EI_MAG1] !=3D ELFMAG1) ||=0D
+ (Elf32Hdr->e_ident[EI_MAG1] !=3D ELFMAG1) ||=0D
+ (Elf32Hdr->e_ident[EI_MAG2] !=3D ELFMAG2)=0D
+ ) {=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ //=0D
+ // Support little-endian only=0D
+ //=0D
+ if (Elf32Hdr->e_ident[EI_DATA] !=3D ELFDATA2LSB) {=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ //=0D
+ // Check 32/64-bit architecture=0D
+ //=0D
+ if (Elf32Hdr->e_ident[EI_CLASS] =3D=3D ELFCLASS64) {=0D
+ Elf64Hdr =3D (Elf64_Ehdr *)Elf32Hdr;=0D
+ Elf32Hdr =3D NULL;=0D
+ } else if (Elf32Hdr->e_ident[EI_CLASS] =3D=3D ELFCLASS32) {=0D
+ Elf64Hdr =3D NULL;=0D
+ } else {=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ if (Elf64Hdr !=3D NULL) {=0D
+ //=0D
+ // Support intel architecture only for now=0D
+ //=0D
+ if (Elf64Hdr->e_machine !=3D EM_X86_64) {=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ //=0D
+ // Support ELF types: EXEC (Executable file), DYN (Shared object file=
)=0D
+ //=0D
+ if ((Elf64Hdr->e_type !=3D ET_EXEC) && (Elf64Hdr->e_type !=3D ET_DYN))=
{=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ //=0D
+ // Support current ELF version only=0D
+ //=0D
+ if (Elf64Hdr->e_version !=3D EV_CURRENT) {=0D
+ return FALSE;=0D
+ }=0D
+ } else {=0D
+ //=0D
+ // Support intel architecture only for now=0D
+ //=0D
+ if (Elf32Hdr->e_machine !=3D EM_386) {=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ //=0D
+ // Support ELF types: EXEC (Executable file), DYN (Shared object file=
)=0D
+ //=0D
+ if ((Elf32Hdr->e_type !=3D ET_EXEC) && (Elf32Hdr->e_type !=3D ET_DYN))=
{=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ //=0D
+ // Support current ELF version only=0D
+ //=0D
+ if (Elf32Hdr->e_version !=3D EV_CURRENT) {=0D
+ return FALSE;=0D
+ }=0D
+ }=0D
+ return TRUE;=0D
+}=0D
+=0D
+/**=0D
+ Calculate a ELF file size.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+ @param[out] FileSize Return the file size.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER ElfCt or SecPos is NULL.=0D
+ @retval EFI_NOT_FOUND Could not find the section.=0D
+ @retval EFI_SUCCESS Section posistion was filled successfull=
y.=0D
+**/=0D
+EFI_STATUS=0D
+CalculateElfFileSize (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt,=0D
+ OUT UINTN *FileSize=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINTN FileSize1;=0D
+ UINTN FileSize2;=0D
+ Elf32_Ehdr *Elf32Hdr;=0D
+ Elf64_Ehdr *Elf64Hdr;=0D
+ UINTN Offset;=0D
+ UINTN Size;=0D
+=0D
+ if ((ElfCt =3D=3D NULL) || (FileSize =3D=3D NULL)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ // Use last section as end of file=0D
+ Status =3D GetElfSectionPos (ElfCt, ElfCt->ShNum - 1, &Offset, &Size);=0D
+ if (EFI_ERROR(Status)) {=0D
+ return EFI_UNSUPPORTED;=0D
+ }=0D
+ FileSize1 =3D Offset + Size;=0D
+=0D
+ // Use end of section header as end of file=0D
+ FileSize2 =3D 0;=0D
+ if (ElfCt->EiClass =3D=3D ELFCLASS32) {=0D
+ Elf32Hdr =3D (Elf32_Ehdr *)ElfCt->FileBase;=0D
+ FileSize2 =3D Elf32Hdr->e_shoff + Elf32Hdr->e_shentsize * Elf32Hdr->e_=
shnum;=0D
+ } else if (ElfCt->EiClass =3D=3D ELFCLASS64) {=0D
+ Elf64Hdr =3D (Elf64_Ehdr *)ElfCt->FileBase;=0D
+ FileSize2 =3D (UINTN)(Elf64Hdr->e_shoff + Elf64Hdr->e_shentsize * Elf6=
4Hdr->e_shnum);=0D
+ }=0D
+=0D
+ *FileSize =3D MAX(FileSize1, FileSize2);=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Get a ELF program segment loading info.=0D
+=0D
+ @param[in] ImageBase Image base.=0D
+ @param[in] EiClass ELF class.=0D
+ @param[in] Index ELF segment index.=0D
+ @param[out] SegInfo The pointer to the segment info.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER ElfCt or SecPos is NULL.=0D
+ @retval EFI_NOT_FOUND Could not find the section.=0D
+ @retval EFI_SUCCESS Section posistion was filled successfull=
y.=0D
+**/=0D
+EFI_STATUS=0D
+GetElfSegmentInfo (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 EiClass,=0D
+ IN UINT32 Index,=0D
+ OUT SEGMENT_INFO *SegInfo=0D
+ )=0D
+{=0D
+ Elf32_Phdr *Elf32Phdr;=0D
+ Elf64_Phdr *Elf64Phdr;=0D
+=0D
+ if ((ImageBase =3D=3D NULL) || (SegInfo =3D=3D NULL)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ if (EiClass =3D=3D ELFCLASS32) {=0D
+ Elf32Phdr =3D GetElf32SegmentByIndex (ImageBase, Index);=0D
+ if (Elf32Phdr !=3D NULL) {=0D
+ SegInfo->PtType =3D Elf32Phdr->p_type;=0D
+ SegInfo->Offset =3D Elf32Phdr->p_offset;=0D
+ SegInfo->Length =3D Elf32Phdr->p_filesz;=0D
+ SegInfo->MemLen =3D Elf32Phdr->p_memsz;=0D
+ SegInfo->MemAddr =3D Elf32Phdr->p_paddr;=0D
+ SegInfo->Alignment =3D Elf32Phdr->p_align;=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+ } else if (EiClass =3D=3D ELFCLASS64) {=0D
+ Elf64Phdr =3D GetElf64SegmentByIndex (ImageBase, Index);=0D
+ if (Elf64Phdr !=3D NULL) {=0D
+ SegInfo->PtType =3D Elf64Phdr->p_type;=0D
+ SegInfo->Offset =3D (UINTN)Elf64Phdr->p_offset;=0D
+ SegInfo->Length =3D (UINTN)Elf64Phdr->p_filesz;=0D
+ SegInfo->MemLen =3D (UINTN)Elf64Phdr->p_memsz;=0D
+ SegInfo->MemAddr =3D (UINTN)Elf64Phdr->p_paddr;=0D
+ SegInfo->Alignment =3D (UINTN)Elf64Phdr->p_align;=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+ }=0D
+=0D
+ return EFI_NOT_FOUND;=0D
+}=0D
+=0D
+/**=0D
+ Parse the ELF image info.=0D
+=0D
+ On return, all fields in ElfCt are updated except ImageAddress.=0D
+=0D
+ @param[in] ImageBase Memory address of an image.=0D
+ @param[out] ElfCt The EFL image context pointer.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER Input parameters are not valid.=0D
+ @retval EFI_UNSUPPORTED Unsupported binary type.=0D
+ @retval EFI_LOAD_ERROR ELF binary loading error.=0D
+ @retval EFI_SUCCESS ELF binary is loaded successfully.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+ParseElfImage (=0D
+ IN VOID *ImageBase,=0D
+ OUT ELF_IMAGE_CONTEXT *ElfCt=0D
+ )=0D
+{=0D
+ Elf32_Ehdr *Elf32Hdr;=0D
+ Elf64_Ehdr *Elf64Hdr;=0D
+ Elf32_Shdr *Elf32Shdr;=0D
+ Elf64_Shdr *Elf64Shdr;=0D
+ EFI_STATUS Status;=0D
+ UINT32 Index;=0D
+ SEGMENT_INFO SegInfo;=0D
+ UINTN End;=0D
+ UINTN Base;=0D
+=0D
+ if (ElfCt =3D=3D NULL) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ ZeroMem (ElfCt, sizeof(ELF_IMAGE_CONTEXT));=0D
+=0D
+ if (ImageBase =3D=3D NULL) {=0D
+ return (ElfCt->ParseStatus =3D EFI_INVALID_PARAMETER);=0D
+ }=0D
+=0D
+ ElfCt->FileBase =3D (UINT8 *)ImageBase;=0D
+ if (!IsElfFormat (ElfCt->FileBase)) {=0D
+ return (ElfCt->ParseStatus =3D EFI_UNSUPPORTED);=0D
+ }=0D
+=0D
+ Elf32Hdr =3D (Elf32_Ehdr *)ElfCt->FileBase;=0D
+ ElfCt->EiClass =3D Elf32Hdr->e_ident[EI_CLASS];=0D
+ if (ElfCt->EiClass =3D=3D ELFCLASS32) {=0D
+ if ((Elf32Hdr->e_type !=3D ET_EXEC) && (Elf32Hdr->e_type !=3D ET_DYN))=
{=0D
+ return (ElfCt->ParseStatus =3D EFI_UNSUPPORTED);=0D
+ }=0D
+ Elf32Shdr =3D (Elf32_Shdr *)GetElf32SectionByIndex (ElfCt->FileBase, E=
lf32Hdr->e_shstrndx);=0D
+ if (Elf32Shdr =3D=3D NULL) {=0D
+ return (ElfCt->ParseStatus =3D EFI_UNSUPPORTED);=0D
+ }=0D
+ ElfCt->EntryPoint =3D (UINTN)Elf32Hdr->e_entry;=0D
+ ElfCt->ShNum =3D Elf32Hdr->e_shnum;=0D
+ ElfCt->PhNum =3D Elf32Hdr->e_phnum;=0D
+ ElfCt->ShStrLen =3D Elf32Shdr->sh_size;=0D
+ ElfCt->ShStrOff =3D Elf32Shdr->sh_offset;=0D
+ } else {=0D
+ Elf64Hdr =3D (Elf64_Ehdr *)Elf32Hdr;=0D
+ if ((Elf64Hdr->e_type !=3D ET_EXEC) && (Elf64Hdr->e_type !=3D ET_DYN))=
{=0D
+ return (ElfCt->ParseStatus =3D EFI_UNSUPPORTED);=0D
+ }=0D
+ Elf64Shdr =3D (Elf64_Shdr *)GetElf64SectionByIndex (ElfCt->FileBase, E=
lf64Hdr->e_shstrndx);=0D
+ if (Elf64Shdr =3D=3D NULL) {=0D
+ return (ElfCt->ParseStatus =3D EFI_UNSUPPORTED);=0D
+ }=0D
+ ElfCt->EntryPoint =3D (UINTN)Elf64Hdr->e_entry;=0D
+ ElfCt->ShNum =3D Elf64Hdr->e_shnum;=0D
+ ElfCt->PhNum =3D Elf64Hdr->e_phnum;=0D
+ ElfCt->ShStrLen =3D (UINT32)Elf64Shdr->sh_size;=0D
+ ElfCt->ShStrOff =3D (UINT32)Elf64Shdr->sh_offset;=0D
+ }=0D
+=0D
+ //=0D
+ // Get the preferred image base and required memory size when loaded to =
new location.=0D
+ //=0D
+ End =3D 0;=0D
+ Base =3D MAX_UINT32;=0D
+ ElfCt->ReloadRequired =3D FALSE;=0D
+ for (Index =3D 0; Index < ElfCt->PhNum; Index++) {=0D
+ Status =3D GetElfSegmentInfo (ElfCt->FileBase, ElfCt->EiClass, Index, =
&SegInfo);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ if (SegInfo.PtType !=3D PT_LOAD) {=0D
+ continue;=0D
+ }=0D
+=0D
+ if (SegInfo.MemLen !=3D SegInfo.Length) {=0D
+ //=0D
+ // Not enough space to execute at current location.=0D
+ //=0D
+ ElfCt->ReloadRequired =3D TRUE;=0D
+ }=0D
+=0D
+ if (Base > (SegInfo.MemAddr & ~(EFI_PAGE_SIZE - 1))) {=0D
+ Base =3D SegInfo.MemAddr & ~(EFI_PAGE_SIZE - 1);=0D
+ }=0D
+ if (End < ALIGN_VALUE (SegInfo.MemAddr + SegInfo.MemLen, EFI_PAGE_SIZE=
) - 1) {=0D
+ End =3D ALIGN_VALUE (SegInfo.MemAddr + SegInfo.MemLen, EFI_PAGE_SIZE=
) - 1;=0D
+ }=0D
+ }=0D
+ //=0D
+ // 0 - MAX_UINT32 + 1 equals to 0.=0D
+ //=0D
+ ElfCt->ImageSize =3D End - Base + 1;=0D
+ ElfCt->PreferredImageAddress =3D (VOID *) Base;=0D
+=0D
+ CalculateElfFileSize (ElfCt, &ElfCt->FileSize);=0D
+ return (ElfCt->ParseStatus =3D EFI_SUCCESS);;=0D
+}=0D
+=0D
+/**=0D
+ Load the ELF image to Context.ImageAddress.=0D
+=0D
+ Context should be initialized by ParseElfImage().=0D
+ Caller should set Context.ImageAddress to a proper value, either pointin=
g to=0D
+ a new allocated memory whose size equal to Context.ImageSize, or pointin=
g=0D
+ to Context.PreferredImageAddress.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER Input parameters are not valid.=0D
+ @retval EFI_UNSUPPORTED Unsupported binary type.=0D
+ @retval EFI_LOAD_ERROR ELF binary loading error.=0D
+ @retval EFI_SUCCESS ELF binary is loaded successfully.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LoadElfImage (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+=0D
+ if (ElfCt =3D=3D NULL) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ if (EFI_ERROR (ElfCt->ParseStatus)) {=0D
+ return ElfCt->ParseStatus;=0D
+ }=0D
+=0D
+ if (ElfCt->ImageAddress =3D=3D NULL) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ Status =3D EFI_UNSUPPORTED;=0D
+ if (ElfCt->EiClass =3D=3D ELFCLASS32) {=0D
+ Status =3D LoadElf32Image (ElfCt);=0D
+ } else if (ElfCt->EiClass =3D=3D ELFCLASS64) {=0D
+ Status =3D LoadElf64Image (ElfCt);=0D
+ }=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+=0D
+/**=0D
+ Get a ELF section name from its index.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+ @param[in] SectionIndex ELF section index.=0D
+ @param[out] SectionName The pointer to the section name.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER ElfCt or SecName is NULL.=0D
+ @retval EFI_NOT_FOUND Could not find the section.=0D
+ @retval EFI_SUCCESS Section name was filled successfully.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+GetElfSectionName (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt,=0D
+ IN UINT32 SectionIndex,=0D
+ OUT CHAR8 **SectionName=0D
+ )=0D
+{=0D
+ Elf32_Shdr *Elf32Shdr;=0D
+ Elf64_Shdr *Elf64Shdr;=0D
+ CHAR8 *Name;=0D
+=0D
+ if ((ElfCt =3D=3D NULL) || (SectionName =3D=3D NULL)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ if (EFI_ERROR (ElfCt->ParseStatus)) {=0D
+ return ElfCt->ParseStatus;=0D
+ }=0D
+=0D
+ Name =3D NULL;=0D
+ if (ElfCt->EiClass =3D=3D ELFCLASS32) {=0D
+ Elf32Shdr =3D GetElf32SectionByIndex (ElfCt->FileBase, SectionIndex);=
=0D
+ if ((Elf32Shdr !=3D NULL) && (Elf32Shdr->sh_name < ElfCt->ShStrLen)) {=
=0D
+ Name =3D (CHAR8 *)(ElfCt->FileBase + ElfCt->ShStrOff + Elf32Shdr->sh=
_name);=0D
+ }=0D
+ } else if (ElfCt->EiClass =3D=3D ELFCLASS64) {=0D
+ Elf64Shdr =3D GetElf64SectionByIndex (ElfCt->FileBase, SectionIndex);=
=0D
+ if ((Elf64Shdr !=3D NULL) && (Elf64Shdr->sh_name < ElfCt->ShStrLen)) {=
=0D
+ Name =3D (CHAR8 *)(ElfCt->FileBase + ElfCt->ShStrOff + Elf64Shdr->sh=
_name);=0D
+ }=0D
+ }=0D
+=0D
+ if (Name =3D=3D NULL) {=0D
+ return EFI_NOT_FOUND;=0D
+ }=0D
+=0D
+ *SectionName =3D Name;=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+=0D
+/**=0D
+ Get the offset and size of x-th ELF section.=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+ @param[in] Index ELF section index.=0D
+ @param[out] Offset Return the offset of the specific sectio=
n.=0D
+ @param[out] Size Return the size of the specific section.=
=0D
+=0D
+ @retval EFI_INVALID_PARAMETER ImageBase, Offset or Size is NULL.=0D
+ @retval EFI_INVALID_PARAMETER EiClass doesn't equal to ELFCLASS32 or E=
LFCLASS64.=0D
+ @retval EFI_NOT_FOUND Could not find the section.=0D
+ @retval EFI_SUCCESS Offset and Size are returned.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+GetElfSectionPos (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt,=0D
+ IN UINT32 Index,=0D
+ OUT UINTN *Offset,=0D
+ OUT UINTN *Size=0D
+ )=0D
+{=0D
+ Elf32_Shdr *Elf32Shdr;=0D
+ Elf64_Shdr *Elf64Shdr;=0D
+=0D
+ if ((ElfCt =3D=3D NULL) || (Offset =3D=3D NULL) || (Size =3D=3D NULL)) {=
=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ if (EFI_ERROR (ElfCt->ParseStatus)) {=0D
+ return ElfCt->ParseStatus;=0D
+ }=0D
+=0D
+ if (ElfCt->EiClass =3D=3D ELFCLASS32) {=0D
+ Elf32Shdr =3D GetElf32SectionByIndex (ElfCt->FileBase, Index);=0D
+ if (Elf32Shdr !=3D NULL) {=0D
+ *Offset =3D (UINTN)Elf32Shdr->sh_offset;=0D
+ *Size =3D (UINTN)Elf32Shdr->sh_size;=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+ } else if (ElfCt->EiClass =3D=3D ELFCLASS64) {=0D
+ Elf64Shdr =3D GetElf64SectionByIndex (ElfCt->FileBase, Index);=0D
+ if (Elf64Shdr !=3D NULL) {=0D
+ *Offset =3D (UINTN)Elf64Shdr->sh_offset;=0D
+ *Size =3D (UINTN)Elf64Shdr->sh_size;=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+ }=0D
+=0D
+ return EFI_NOT_FOUND;=0D
+}=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLibInternal.h b/Uef=
iPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLibInternal.h
new file mode 100644
index 0000000000..3c782807e2
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLibInternal.h
@@ -0,0 +1,109 @@
+/** @file=0D
+ ELF library=0D
+=0D
+ Copyright (c) 2019 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef EFI_LIB_INTERNAL_H_=0D
+#define EFI_LIB_INTERNAL_H_=0D
+=0D
+#include <Library/BaseLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/BaseMemoryLib.h>=0D
+#include "ElfLib.h"=0D
+#include "ElfCommon.h"=0D
+#include "Elf32.h"=0D
+#include "Elf64.h"=0D
+=0D
+#define ELF_NEXT_ENTRY(EntryType, Current, EntrySize) \=0D
+ ((EntryType *) ((UINT8 *)Current + EntrySize))=0D
+=0D
+=0D
+/**=0D
+ Return the section header specified by Index.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Index The section index.=0D
+=0D
+ @return Pointer to the section header.=0D
+**/=0D
+Elf32_Shdr *=0D
+GetElf32SectionByIndex (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Index=0D
+ );=0D
+=0D
+/**=0D
+ Return the section header specified by Index.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Index The section index.=0D
+=0D
+ @return Pointer to the section header.=0D
+**/=0D
+Elf64_Shdr *=0D
+GetElf64SectionByIndex (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Index=0D
+ );=0D
+=0D
+/**=0D
+ Return the segment header specified by Index.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Index The segment index.=0D
+=0D
+ @return Pointer to the segment header.=0D
+**/=0D
+Elf32_Phdr *=0D
+GetElf32SegmentByIndex (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Index=0D
+ );=0D
+=0D
+/**=0D
+ Return the segment header specified by Index.=0D
+=0D
+ @param ImageBase The image base.=0D
+ @param Index The segment index.=0D
+=0D
+ @return Pointer to the segment header.=0D
+**/=0D
+Elf64_Phdr *=0D
+GetElf64SegmentByIndex (=0D
+ IN UINT8 *ImageBase,=0D
+ IN UINT32 Index=0D
+ );=0D
+=0D
+/**=0D
+ Load ELF image which has 32-bit architecture=0D
+=0D
+ @param[in] ElfCt ELF image context pointer.=0D
+=0D
+ @retval EFI_SUCCESS ELF binary is loaded successfully.=0D
+ @retval Others Loading ELF binary fails.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+LoadElf32Image (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ );=0D
+=0D
+/**=0D
+ Load ELF image which has 64-bit architecture=0D
+=0D
+ @param[in] ImageBase Memory address of an image.=0D
+ @param[out] EntryPoint The entry point of loaded ELF image.=0D
+=0D
+ @retval EFI_SUCCESS ELF binary is loaded successfully.=0D
+ @retval Others Loading ELF binary fails.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+LoadElf64Image (=0D
+ IN ELF_IMAGE_CONTEXT *ElfCt=0D
+ );=0D
+=0D
+#endif=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c b/UefiPay=
loadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c
new file mode 100644
index 0000000000..c619470dbb
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c
@@ -0,0 +1,187 @@
+/** @file=0D
+ ELF Load Image Support=0D
+=0D
+Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>=0D
+SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include <PiPei.h>=0D
+#include <UniversalPayload/UniversalPayload.h>=0D
+#include <UniversalPayload/ExtraData.h>=0D
+=0D
+#include <Ppi/LoadFile.h>=0D
+=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/HobLib.h>=0D
+#include <Library/PeiServicesLib.h>=0D
+#include <Library/MemoryAllocationLib.h>=0D
+#include <Library/BaseMemoryLib.h>=0D
+=0D
+#include "ElfLib.h"=0D
+=0D
+/**=0D
+ The wrapper function of PeiLoadImageLoadImage().=0D
+=0D
+ @param This - Pointer to EFI_PEI_LOAD_FILE_PPI.=0D
+ @param FileHandle - Pointer to the FFS file header of the image.=0D
+ @param ImageAddressArg - Pointer to PE/TE image.=0D
+ @param ImageSizeArg - Size of PE/TE image.=0D
+ @param EntryPoint - Pointer to entry point of specified image file =
for output.=0D
+ @param AuthenticationState - Pointer to attestation authentication state=
of image.=0D
+=0D
+ @return Status of PeiLoadImageLoadImage().=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+PeiLoadFileLoadPayload (=0D
+ IN CONST EFI_PEI_LOAD_FILE_PPI *This,=0D
+ IN EFI_PEI_FILE_HANDLE FileHandle,=0D
+ OUT EFI_PHYSICAL_ADDRESS *ImageAddressArg, OPTIONAL=0D
+ OUT UINT64 *ImageSizeArg, OPTIONAL=0D
+ OUT EFI_PHYSICAL_ADDRESS *EntryPoint,=0D
+ OUT UINT32 *AuthenticationState=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ VOID *Elf;=0D
+ UNIVERSAL_PAYLOAD_EXTRA_DATA *ExtraData;=0D
+ ELF_IMAGE_CONTEXT Context;=0D
+ UNIVERSAL_PAYLOAD_INFO_HEADER *PldInfo;=0D
+ UINT32 Index;=0D
+ UINT16 ExtraDataIndex;=0D
+ CHAR8 *SectionName;=0D
+ UINTN Offset;=0D
+ UINTN Size;=0D
+ UINT32 ExtraDataCount;=0D
+ UINTN Instance;=0D
+=0D
+ //=0D
+ // ELF is added to file as RAW section for EDKII bootloader.=0D
+ // But RAW section might be added by build tool before the ELF RAW secti=
on when alignment is specified for ELF RAW section.=0D
+ // Below loop skips the RAW section that doesn't contain valid ELF image=
.=0D
+ //=0D
+ Instance =3D 0;=0D
+ do {=0D
+ Status =3D PeiServicesFfsFindSectionData3 (EFI_SECTION_RAW, Instance++=
, FileHandle, &Elf, AuthenticationState);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ ZeroMem (&Context, sizeof (Context));=0D
+ Status =3D ParseElfImage (Elf, &Context);=0D
+ } while (EFI_ERROR (Status));=0D
+=0D
+ DEBUG ((=0D
+ DEBUG_INFO, "Payload File Size: 0x%08X, Mem Size: 0x%08x, Reload: %d\n=
",=0D
+ Context.FileSize, Context.ImageSize, Context.ReloadRequired=0D
+ ));=0D
+=0D
+ //=0D
+ // Get UNIVERSAL_PAYLOAD_INFO_HEADER and number of additional PLD sectio=
ns.=0D
+ //=0D
+ PldInfo =3D NULL;=0D
+ ExtraDataCount =3D 0;=0D
+ for (Index =3D 0; Index < Context.ShNum; Index++) {=0D
+ Status =3D GetElfSectionName (&Context, Index, &SectionName);=0D
+ if (EFI_ERROR(Status)) {=0D
+ continue;=0D
+ }=0D
+ DEBUG ((DEBUG_INFO, "Payload Section[%d]: %a\n", Index, SectionName));=
=0D
+ if (AsciiStrCmp(SectionName, UNIVERSAL_PAYLOAD_INFO_SEC_NAME) =3D=3D 0=
) {=0D
+ Status =3D GetElfSectionPos (&Context, Index, &Offset, &Size);=0D
+ if (!EFI_ERROR(Status)) {=0D
+ PldInfo =3D (UNIVERSAL_PAYLOAD_INFO_HEADER *)(Context.FileBase + O=
ffset);=0D
+ }=0D
+ } else if (AsciiStrnCmp(SectionName, UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_=
PREFIX, UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX_LENGTH) =3D=3D 0) {=0D
+ Status =3D GetElfSectionPos (&Context, Index, &Offset, &Size);=0D
+ if (!EFI_ERROR (Status)) {=0D
+ ExtraDataCount++;=0D
+ }=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // Report the additional PLD sections through HOB.=0D
+ //=0D
+ ExtraData =3D BuildGuidHob (=0D
+ &gUniversalPayloadExtraDataGuid,=0D
+ sizeof (UNIVERSAL_PAYLOAD_EXTRA_DATA) + ExtraDataCount * si=
zeof (UNIVERSAL_PAYLOAD_EXTRA_DATA_ENTRY)=0D
+ );=0D
+ ExtraData->Count =3D ExtraDataCount;=0D
+ if (ExtraDataCount !=3D 0) {=0D
+ for (ExtraDataIndex =3D 0, Index =3D 0; Index < Context.ShNum; Index++=
) {=0D
+ Status =3D GetElfSectionName (&Context, Index, &SectionName);=0D
+ if (EFI_ERROR(Status)) {=0D
+ continue;=0D
+ }=0D
+ if (AsciiStrnCmp(SectionName, UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFI=
X, UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX_LENGTH) =3D=3D 0) {=0D
+ Status =3D GetElfSectionPos (&Context, Index, &Offset, &Size);=0D
+ if (!EFI_ERROR (Status)) {=0D
+ ASSERT (ExtraDataIndex < ExtraDataCount);=0D
+ AsciiStrCpyS (=0D
+ ExtraData->Entry[ExtraDataIndex].Identifier,=0D
+ sizeof(ExtraData->Entry[ExtraDataIndex].Identifier),=0D
+ SectionName + UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX_LENGTH=0D
+ );=0D
+ ExtraData->Entry[ExtraDataIndex].Base =3D (UINTN)(Context.FileBa=
se + Offset);=0D
+ ExtraData->Entry[ExtraDataIndex].Size =3D Size;=0D
+ ExtraDataIndex++;=0D
+ }=0D
+ }=0D
+ }=0D
+ }=0D
+=0D
+ if (Context.ReloadRequired || Context.PreferredImageAddress !=3D Context=
.FileBase) {=0D
+ Context.ImageAddress =3D AllocatePages (EFI_SIZE_TO_PAGES (Context.Ima=
geSize));=0D
+ } else {=0D
+ Context.ImageAddress =3D Context.FileBase;=0D
+ }=0D
+=0D
+ //=0D
+ // Load ELF into the required base=0D
+ //=0D
+ Status =3D LoadElfImage (&Context);=0D
+ if (!EFI_ERROR(Status)) {=0D
+ *ImageAddressArg =3D (UINTN) Context.ImageAddress;=0D
+ *EntryPoint =3D Context.EntryPoint;=0D
+ *ImageSizeArg =3D Context.ImageSize;=0D
+ }=0D
+ return Status;=0D
+}=0D
+=0D
+=0D
+EFI_PEI_LOAD_FILE_PPI mPeiLoadFilePpi =3D {=0D
+ PeiLoadFileLoadPayload=0D
+};=0D
+=0D
+=0D
+EFI_PEI_PPI_DESCRIPTOR gPpiLoadFilePpiList =3D {=0D
+ (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),=0D
+ &gEfiPeiLoadFilePpiGuid,=0D
+ &mPeiLoadFilePpi=0D
+};=0D
+/**=0D
+=0D
+ Install Pei Load File PPI.=0D
+=0D
+ @param FileHandle Handle of the file being invoked.=0D
+ @param PeiServices Describes the list of possible PEI Services.=0D
+=0D
+ @retval EFI_SUCESS The entry point executes successfully.=0D
+ @retval Others Some error occurs during the execution of this funct=
ion.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+InitializePayloadLoaderPeim (=0D
+ IN EFI_PEI_FILE_HANDLE FileHandle,=0D
+ IN CONST EFI_PEI_SERVICES **PeiServices=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ Status =3D PeiServicesInstallPpi (&gPpiLoadFilePpiList);=0D
+=0D
+ return Status;=0D
+}=0D
diff --git a/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf b/UefiP=
ayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf
new file mode 100644
index 0000000000..73f76064a0
--- /dev/null
+++ b/UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf
@@ -0,0 +1,59 @@
+## @file=0D
+# Produce LoadFile PPI for payload loading.=0D
+#=0D
+# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>=0D
+#=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ INF_VERSION =3D 0x00010005=0D
+ BASE_NAME =3D PayloadLoaderPeim=0D
+ FILE_GUID =3D D071A3B4-3EC1-40C5-BEF8-D0BD4A2446F0=
=0D
+ MODULE_TYPE =3D PEIM=0D
+ VERSION_STRING =3D 1.0=0D
+=0D
+ ENTRY_POINT =3D InitializePayloadLoaderPeim=0D
+=0D
+#=0D
+# The following information is for reference only and not required by the =
build tools.=0D
+#=0D
+# VALID_ARCHITECTURES =3D IA32 X64=0D
+#=0D
+=0D
+[Sources]=0D
+ PayloadLoaderPeim.c=0D
+ ElfLib.h=0D
+ ElfLib/ElfLibInternal.h=0D
+ ElfLib/ElfCommon.h=0D
+ ElfLib/Elf32.h=0D
+ ElfLib/Elf64.h=0D
+ ElfLib/ElfLibInternal.h=0D
+ ElfLib/ElfLib.c=0D
+ ElfLib/Elf32Lib.c=0D
+ ElfLib/Elf64Lib.c=0D
+=0D
+[Packages]=0D
+ MdePkg/MdePkg.dec=0D
+ MdeModulePkg/MdeModulePkg.dec=0D
+ UefiPayloadPkg/UefiPayloadPkg.dec=0D
+=0D
+[LibraryClasses]=0D
+ PcdLib=0D
+ MemoryAllocationLib=0D
+ BaseMemoryLib=0D
+ PeiServicesLib=0D
+ HobLib=0D
+ BaseLib=0D
+ PeimEntryPoint=0D
+ DebugLib=0D
+=0D
+[Ppis]=0D
+ gEfiPeiLoadFilePpiGuid ## PRODUCES=0D
+=0D
+[Guids]=0D
+ gUniversalPayloadExtraDataGuid ## PRODUCES=0D
+=0D
+[Depex]=0D
+ TRUE=0D
--=20
2.31.1.windows.1


[PATCH v3 1/3] MdeModulePkg/UniversalPayload: Add definition for extra info in payload

Ni, Ray
 

The payload is in ELF format per the universal payload spec.
UNIVERSAL_PAYLOAD_INFO_HEADER is stored in the ELF payload as a separate
section named ".upld_info".

Extra data needed by payload is stored in sections whose name starts
with ".upld.".

Signed-off-by: Ray Ni <ray.ni@intel.com>
Cc: Maurice Ma <maurice.ma@intel.com>
Cc: Guo Dong <guo.dong@intel.com>
Reviewed-by: Hao A Wu <hao.a.wu@intel.com>
---
.../Include/UniversalPayload/ExtraData.h | 28 +++++++++++++++++++
.../UniversalPayload/UniversalPayload.h | 24 ++++++++++++++++
MdeModulePkg/MdeModulePkg.dec | 3 ++
3 files changed, 55 insertions(+)
create mode 100644 MdeModulePkg/Include/UniversalPayload/ExtraData.h

diff --git a/MdeModulePkg/Include/UniversalPayload/ExtraData.h b/MdeModuleP=
kg/Include/UniversalPayload/ExtraData.h
new file mode 100644
index 0000000000..146ec845f6
--- /dev/null
+++ b/MdeModulePkg/Include/UniversalPayload/ExtraData.h
@@ -0,0 +1,28 @@
+/** @file=0D
+=0D
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+#ifndef EXTRA_DATA_H_=0D
+#define EXTRA_DATA_H_=0D
+=0D
+extern GUID gUniversalPayloadExtraDataGuid;=0D
+=0D
+#pragma pack(1)=0D
+=0D
+typedef struct {=0D
+ CHAR8 Identifier[16];=0D
+ EFI_PHYSICAL_ADDRESS Base;=0D
+ UINT64 Size;=0D
+} UNIVERSAL_PAYLOAD_EXTRA_DATA_ENTRY;=0D
+=0D
+typedef struct {=0D
+ UNIVERSAL_PAYLOAD_GENERIC_HEADER PldHeader;=0D
+ UINT32 Count;=0D
+ UNIVERSAL_PAYLOAD_EXTRA_DATA_ENTRY Entry[0];=0D
+} UNIVERSAL_PAYLOAD_EXTRA_DATA;=0D
+=0D
+#pragma pack()=0D
+=0D
+#endif=0D
diff --git a/MdeModulePkg/Include/UniversalPayload/UniversalPayload.h b/Mde=
ModulePkg/Include/UniversalPayload/UniversalPayload.h
index e661306a9b..bc8a3e0cf8 100644
--- a/MdeModulePkg/Include/UniversalPayload/UniversalPayload.h
+++ b/MdeModulePkg/Include/UniversalPayload/UniversalPayload.h
@@ -11,8 +11,32 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
#ifndef UNIVERSAL_PAYLOAD_H_=0D
#define UNIVERSAL_PAYLOAD_H_=0D
=0D
+/**=0D
+ Main entry point to Universal Payload.=0D
+=0D
+ @param HobList Pointer to the beginning of the HOB List from boot loade=
r.=0D
+**/=0D
+typedef VOID (EFIAPI *UNIVERSAL_PAYLOAD_ENTRY) (VOID *HobList);=0D
+=0D
+#define UNIVERSAL_PAYLOAD_IDENTIFIER SIGNATURE_32('U', '=
P', 'L', 'D')=0D
+#define UNIVERSAL_PAYLOAD_INFO_SEC_NAME ".upld_info"=0D
+#define UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX ".upld."=0D
+#define UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX_LENGTH (sizeof (UNIVERSAL_=
PAYLOAD_EXTRA_SEC_NAME_PREFIX) - 1)=0D
+=0D
#pragma pack(1)=0D
=0D
+typedef struct {=0D
+ UINT32 Identifier;=0D
+ UINT32 HeaderLength;=0D
+ UINT16 SpecRevision;=0D
+ UINT8 Reserved[2];=0D
+ UINT32 Revision;=0D
+ UINT32 Attribute;=0D
+ UINT32 Capability;=0D
+ CHAR8 ProducerId[16];=0D
+ CHAR8 ImageId[16];=0D
+} UNIVERSAL_PAYLOAD_INFO_HEADER;=0D
+=0D
typedef struct {=0D
UINT8 Revision;=0D
UINT8 Reserved;=0D
diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec
index 8c0885955b..10602a8f79 100644
--- a/MdeModulePkg/MdeModulePkg.dec
+++ b/MdeModulePkg/MdeModulePkg.dec
@@ -419,6 +419,9 @@ [Guids]
## Include/UniversalPayload/AcpiTable.h=0D
gUniversalPayloadAcpiTableGuid =3D { 0x9f9a9506, 0x5597, 0x4515, { 0xba,=
0xb6, 0x8b, 0xcd, 0xe7, 0x84, 0xba, 0x87 } }=0D
=0D
+ ## Include/UniversalPayload/ExtraData.h=0D
+ gUniversalPayloadExtraDataGuid =3D {0x15a5baf6, 0x1c91, 0x467d, {0x9d, 0=
xfb, 0x31, 0x9d, 0x17, 0x8d, 0x4b, 0xb4}}=0D
+=0D
[Ppis]=0D
## Include/Ppi/AtaController.h=0D
gPeiAtaControllerPpiGuid =3D { 0xa45e60d1, 0xc719, 0x44aa, { 0xb0,=
0x7a, 0xaa, 0x77, 0x7f, 0x85, 0x90, 0x6d }}=0D
--=20
2.31.1.windows.1


[PATCH v3 0/3] Add PayloadLoaderPeim which can load ELF payload

Ni, Ray
 

v3:
Change PLD_ to UNIVERSAL_PAYLOAD_ based on Mike's comments.

v2:
Separate the patch set from the patch that adds CLANGDWARF toolchain.
Add missing function header commments.
Change DEBUG_ERROR to DEBUG_INFO for information debug message.


Ray Ni (3):
MdeModulePkg/UniversalPayload: Add definition for extra info in
payload
UefiPayloadPkg: Add PayloadLoaderPeim which can load ELF payload
PeiCore: Remove assertion when failing to load PE image

MdeModulePkg/Core/Pei/Image/Image.c | 5 +-
.../Include/UniversalPayload/ExtraData.h | 28 +
.../UniversalPayload/UniversalPayload.h | 24 +
MdeModulePkg/MdeModulePkg.dec | 3 +
UefiPayloadPkg/PayloadLoaderPeim/ElfLib.h | 122 +++
.../PayloadLoaderPeim/ElfLib/Elf32.h | 252 +++++
.../PayloadLoaderPeim/ElfLib/Elf32Lib.c | 451 ++++++++
.../PayloadLoaderPeim/ElfLib/Elf64.h | 254 +++++
.../PayloadLoaderPeim/ElfLib/Elf64Lib.c | 460 ++++++++
.../PayloadLoaderPeim/ElfLib/ElfCommon.h | 983 ++++++++++++++++++
.../PayloadLoaderPeim/ElfLib/ElfLib.c | 473 +++++++++
.../PayloadLoaderPeim/ElfLib/ElfLibInternal.h | 109 ++
.../PayloadLoaderPeim/PayloadLoaderPeim.c | 187 ++++
.../PayloadLoaderPeim/PayloadLoaderPeim.inf | 59 ++
14 files changed, 3406 insertions(+), 4 deletions(-)
create mode 100644 MdeModulePkg/Include/UniversalPayload/ExtraData.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf32Lib.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/Elf64Lib.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfCommon.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLib.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/ElfLib/ElfLibInternal.h
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.c
create mode 100644 UefiPayloadPkg/PayloadLoaderPeim/PayloadLoaderPeim.inf

--
2.31.1.windows.1


Re: [PATCH 1/1] BaseTools GenFw: Keep read only alloc section as text section when convert ELF

Bob Feng
 

Hi Liming,

There are some warning reported from PatchCheck.py, would you update the commit message?

Thanks,
Bob

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Bob Feng
Sent: Tuesday, June 15, 2021 2:49 PM
To: Liming Gao <gaoliming@byosoft.com.cn>; devel@edk2.groups.io
Cc: Ni, Ray <ray.ni@intel.com>
Subject: Re: [edk2-devel] [PATCH 1/1] BaseTools GenFw: Keep read only alloc section as text section when convert ELF

Reviewed-by: Bob Feng <bob.c.feng@intel.com>

-----Original Message-----
From: Liming Gao <gaoliming@byosoft.com.cn>
Sent: Wednesday, June 9, 2021 6:06 PM
To: devel@edk2.groups.io
Cc: Feng, Bob C <bob.c.feng@intel.com>; Ni, Ray <ray.ni@intel.com>
Subject: [PATCH 1/1] BaseTools GenFw: Keep read only alloc section as text section when convert ELF

This is the fix of the regression issue at c6b872c6.
Based on ELF spec, readonly alloc section is .rodata section. It is requried.
This fix is to add back original check logic for ELF section. Now, the readonly alloc section and execute alloc section are regarded as .text section.

Signed-off-by: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Bob Feng <bob.c.feng@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
---
With this fix, previous fix commit ec1cffd9 is not required. But, the checker added by commit ec1cffd9 is correct for ACPI data conversion. So, I don't plan to revert it.

BaseTools/Source/C/GenFw/Elf32Convert.c | 3 ++- BaseTools/Source/C/GenFw/Elf64Convert.c | 3 ++-
2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/BaseTools/Source/C/GenFw/Elf32Convert.c b/BaseTools/Source/C/GenFw/Elf32Convert.c
index 314f8233234d..d917a444c82d 100644
--- a/BaseTools/Source/C/GenFw/Elf32Convert.c
+++ b/BaseTools/Source/C/GenFw/Elf32Convert.c
@@ -238,7 +238,8 @@ IsTextShdr (
Elf_Shdr *Shdr
)
{
- return (BOOLEAN) ((Shdr->sh_flags & (SHF_EXECINSTR | SHF_ALLOC)) == (SHF_EXECINSTR | SHF_ALLOC));
+ return (BOOLEAN) (((Shdr->sh_flags & (SHF_EXECINSTR | SHF_ALLOC)) == (SHF_EXECINSTR | SHF_ALLOC)) ||
+ ((Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) ==
+ SHF_ALLOC));
}

STATIC
diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c b/BaseTools/Source/C/GenFw/Elf64Convert.c
index 8b09db7b690b..33031ec8f6e7 100644
--- a/BaseTools/Source/C/GenFw/Elf64Convert.c
+++ b/BaseTools/Source/C/GenFw/Elf64Convert.c
@@ -246,7 +246,8 @@ IsTextShdr (
Elf_Shdr *Shdr
)
{
- return (BOOLEAN) ((Shdr->sh_flags & (SHF_EXECINSTR | SHF_ALLOC)) == (SHF_EXECINSTR | SHF_ALLOC));
+ return (BOOLEAN) (((Shdr->sh_flags & (SHF_EXECINSTR | SHF_ALLOC)) == (SHF_EXECINSTR | SHF_ALLOC)) ||
+ ((Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) ==
+ SHF_ALLOC));
}

STATIC
--
2.27.0.windows.1


SIMPLE_TEXT_OUTPUT_PROTOCOL and Video Resolution

David F.
 

Hello,

I've found that most implementation of UEFI don't automatically change
the resolution when setting the mode with STOP (Simple Text Output
Protocol) . You can use GOP to change it after the mode but that
causes other problems. For example, using surface pro 7 in this case,
with 4K screen. The default text mode is 342x96 which puts it in
2736x1824 mode which you'd expect and the text is tiny. But now you
set the mode to 0 which is 80x25 and it actually sets the mode to
2736x1824 if not already in that resolution and uses a 80x25 area in
the center of the screen, still tiny text you can hardly read. If you
then say you want GOP in 640x480 mode (which is available as GOP mode
1 on this system, it will make the font larger but you can't see
anything because it's still offset to the middle of the 2736x1824 area
and you're only seeing the 640x480 upper left of that area on the
screen. Likewise if you have it in 342x96 so it's fully in the upper
left corner of the screen and change the mode to say 800x600
(available as GOP mode 2 on this system) it will make the text
readable but the text can go off the screen in both directions because
it's still 342x96 when the 100x31 STOP mode would be the correct one
(which happens to be mode 2 on this system).

Shouldn't setting the STOP mode handle adjusting the resolution since
that's the main reason you want to change the mode so the size shown
on the screen changes to something you can read.

Any tricks? I've tried a bunch of things, resetting the controller,
using the Reset() protocol function, and other things but nothing
works. As soon as you use STOP to set the mode, it is back to high
resolution and using an area centered in the screen and changing the
resolution after that leaves it in the area centered in the high res
screen and not in the upper left area.

Thanks.


Re: [PATCH] UefiPayloadPkg/UefiPayloadEntry: Improve bootloader memrange parsing

Patrick Rudolph
 

Hi Guo,
The PciHostBridgeDxe expects the PCI Aperature and MMCONF to be marked
as EfiMemoryMappedIO,
however as the bootloader provides an e820 compatible memory map, it's
actually marked as
EfiReservedMemoryType. The PciHostBridgeDxe asserts on this incorrect
memory type.
This is what the patch tries to fix by marking MMIO (between TOLUD and
4GiB) as EfiMemoryMappedIO.

I don't think that the mentioned patch (UefiPayloadPkg: UefiPayload
retrieve PCI root bridge
from Guid Hob) would change that, as the same memory ranges are still
being incorrectly marked
reserved by UefiPayloadEntry.

Even with TOLUD guessing not working the OS wouldn't see a difference
as EfiMemoryMappedIO and
EfiReservedMemoryType both appear as reserved to the OS, so it's still
the same memory from OS point of view.
In case TOLUD is estimated too high, MMIO would be marked as Reserved,
so it's the same situation as now and
DXE drivers might fail.
In case TOLUD is estimated too low, Reserved DRAM would be marked as
MMIO, however I can't think of a DXE
that would actually care, it would skip the region as it would be
marked reserved.

Thanks,
Patrick

On Wed, Jun 16, 2021 at 12:20 AM Dong, Guo <guo.dong@intel.com> wrote:


Could you provide more info on the issues in fixed by this patch?
There is a UEFI payload patch (under code review) to support the bootloader to provide a HOB
on the PCI resources, this way the UEFI payload doesn't need collect resources again by parsing
all the PCI devices. Not sure if that patch (UefiPayloadPkg: UefiPayload retrieve PCI root bridge
from Guid Hob) could avoid the issues.

In this patch, as it mentioned some information (system memory or MMIO) is missing in the
bootloader E820 style table. Guessing the TOLUD might work in most cases, but may fail since
the assumptions.

I saw this patch fixed the memory type for ACPI memory. I think we could have this fix if the
TOLUD guessing could be avoided.

Thanks,
Guo

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Patrick
Rudolph
Sent: Tuesday, June 15, 2021 6:23 AM
To: devel@edk2.groups.io
Cc: Ma, Maurice <maurice.ma@intel.com>; Dong, Guo
<guo.dong@intel.com>; You, Benjamin <benjamin.you@intel.com>
Subject: [edk2-devel] [PATCH] UefiPayloadPkg/UefiPayloadEntry: Improve
bootloader memrange parsing

Currently several DXE crash due to invalid memory resource settings.
coreboot and slimbootloader provide an e820 compatible memory map,
which doesn't work well with EDK2 as the e820 spec is missing MMIO regions.
In e820 'reserved' could either mean "DRAM used by boot firmware" or
"MMIO
in use and not detectable by OS".

Guess Top of lower usable DRAM (TOLUD) by walking memory ranges and
then
mark everything reserved below TOLUD as DRAM and everything reserved
above
TOLUD as MMIO.

This fixes several assertions seen in PciHostBridgeDxe.

Signed-off-by: Patrick Rudolph <patrick.rudolph@9elements.com>
---
.../UefiPayloadEntry/UefiPayloadEntry.c | 187 +++++++++++++++++-
.../UefiPayloadEntry/UefiPayloadEntry.h | 10 +
2 files changed, 194 insertions(+), 3 deletions(-)

diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
index 805f5448d9..d20e1a0862 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
+++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
@@ -7,10 +7,162 @@


#include "UefiPayloadEntry.h"



+STATIC UINT32 TopOfLowerUsableDram = 0;

+

/**

Callback function to build resource descriptor HOB



This function build a HOB based on the memory map entry info.

+ It creates only EFI_RESOURCE_MEMORY_MAPPED_IO and
EFI_RESOURCE_MEMORY_RESERVED

+ resources.

+

+ @param MemoryMapEntry Memory map entry info got from
bootloader.

+ @param Params A pointer to ACPI_BOARD_INFO.

+

+ @retval RETURN_SUCCESS Successfully build a HOB.

+ @retval EFI_INVALID_PARAMETER Invalid parameter provided.

+**/

+EFI_STATUS

+MemInfoCallbackMMIO (

+ IN MEMROY_MAP_ENTRY *MemoryMapEntry,

+ IN VOID *Params

+ )

+{

+ EFI_PHYSICAL_ADDRESS Base;

+ EFI_RESOURCE_TYPE Type;

+ UINT64 Size;

+ EFI_RESOURCE_ATTRIBUTE_TYPE Attribue;

+ ACPI_BOARD_INFO *AcpiBoardInfo;

+

+ AcpiBoardInfo = (ACPI_BOARD_INFO *)Params;

+ if (AcpiBoardInfo == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ //

+ // Skip types already handled in MemInfoCallback

+ //

+ if (MemoryMapEntry->Type == E820_RAM || MemoryMapEntry->Type ==
E820_ACPI) {

+ return RETURN_SUCCESS;

+ }

+

+ if (MemoryMapEntry->Base == AcpiBoardInfo->PcieBaseAddress) {

+ //

+ // MMCONF is always MMIO

+ //

+ Type = EFI_RESOURCE_MEMORY_MAPPED_IO;

+ } else if (MemoryMapEntry->Base < TopOfLowerUsableDram) {

+ //

+ // It's in DRAM and thus must be reserved

+ //

+ Type = EFI_RESOURCE_MEMORY_RESERVED;

+ } else if (MemoryMapEntry->Base < 0x100000000ULL &&

+ MemoryMapEntry->Base >= TopOfLowerUsableDram) {

+ //

+ // It's not in DRAM, must be MMIO

+ //

+ Type = EFI_RESOURCE_MEMORY_MAPPED_IO;

+ } else {

+ Type = EFI_RESOURCE_MEMORY_RESERVED;

+ }

+

+ Base = MemoryMapEntry->Base;

+ Size = MemoryMapEntry->Size;

+

+ Attribue = EFI_RESOURCE_ATTRIBUTE_PRESENT |

+ EFI_RESOURCE_ATTRIBUTE_INITIALIZED |

+ EFI_RESOURCE_ATTRIBUTE_TESTED |

+ EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE |

+ EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE |

+ EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |

+ EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE;

+

+ BuildResourceDescriptorHob (Type, Attribue,
(EFI_PHYSICAL_ADDRESS)Base, Size);

+ DEBUG ((DEBUG_INFO , "buildhob: base = 0x%lx, size = 0x%lx, type =
0x%x\n", Base, Size, Type));

+

+ if (MemoryMapEntry->Type == E820_NVS) {

+ BuildMemoryAllocationHob (Base, Size, EfiACPIMemoryNVS);

+ } else if (MemoryMapEntry->Type == E820_UNUSABLE ||

+ MemoryMapEntry->Type == E820_DISABLED) {

+ BuildMemoryAllocationHob (Base, Size, EfiUnusableMemory);

+ } else if (MemoryMapEntry->Type == E820_PMEM) {

+ BuildMemoryAllocationHob (Base, Size, EfiPersistentMemory);

+ }

+

+ return RETURN_SUCCESS;

+}

+

+

+/**

+ Callback function to find TOLUD (Top of Lower Usable DRAM)

+

+ Estimate where TOLUD (Top of Lower Usable DRAM) resides. The exact
position

+ would require platform specific code.

+

+ @param MemoryMapEntry Memory map entry info got from
bootloader.

+ @param Params Not used for now.

+

+ @retval RETURN_SUCCESS Successfully updated
TopOfLowerUsableDram.

+**/

+EFI_STATUS

+FindToludCallback (

+ IN MEMROY_MAP_ENTRY *MemoryMapEntry,

+ IN VOID *Params

+ )

+{

+ //

+ // This code assumes that the memory map on this x86 machine below
4GiB is continous

+ // until TOLUD. In addition it assumes that the bootloader provided
memory tables have

+ // no "holes" and thus the first memory range not covered by e820 marks
the end of

+ // usable DRAM. In addition it's assumed that every reserved memory
region touching

+ // usable RAM is also covering DRAM, everything else that is marked
reserved thus must be

+ // MMIO not detectable by bootloader/OS

+ //

+

+ //

+ // Skip memory types not RAM or reserved

+ //

+ if (MemoryMapEntry->Type == E820_NVS || MemoryMapEntry->Type ==
E820_UNUSABLE ||

+ MemoryMapEntry->Type == E820_DISABLED || MemoryMapEntry->Type
== E820_PMEM) {

+ return RETURN_SUCCESS;

+ }

+

+ //

+ // Skip resources above 4GiB

+ //

+ if (MemoryMapEntry->Base >= 0x100000000ULL) {

+ return RETURN_SUCCESS;

+ }

+

+ if ((MemoryMapEntry->Type == E820_RAM) ||

+ (MemoryMapEntry->Type == E820_ACPI)) {

+ //

+ // It's usable DRAM. Update TOLUD.

+ //

+ if (TopOfLowerUsableDram < (MemoryMapEntry->Base +
MemoryMapEntry->Size)) {

+ TopOfLowerUsableDram = MemoryMapEntry->Base +
MemoryMapEntry->Size;

+ }

+ } else {

+ //

+ // It might be reserved DRAM or MMIO.

+ //

+ // If it touches usable DRAM at Base assume it's DRAM as well,

+ // as it could be bootloader installed tables, TSEG, GTT, ...

+ //

+ if (TopOfLowerUsableDram == MemoryMapEntry->Base) {

+ TopOfLowerUsableDram = MemoryMapEntry->Base +
MemoryMapEntry->Size;

+ }

+ }

+

+ return RETURN_SUCCESS;

+}

+

+

+/**

+ Callback function to build resource descriptor HOB

+

+ This function build a HOB based on the memory map entry info.

+ Only add EFI_RESOURCE_SYSTEM_MEMORY.



@param MemoryMapEntry Memory map entry info got from
bootloader.

@param Params Not used for now.

@@ -28,7 +180,15 @@ MemInfoCallback (
UINT64 Size;

EFI_RESOURCE_ATTRIBUTE_TYPE Attribue;



- Type = (MemoryMapEntry->Type == 1) ?
EFI_RESOURCE_SYSTEM_MEMORY : EFI_RESOURCE_MEMORY_RESERVED;

+ //

+ // Skip everything not known to be usable DRAM.

+ // It will be added later.

+ //

+ if (MemoryMapEntry->Type != E820_RAM && MemoryMapEntry->Type !=
E820_ACPI) {

+ return RETURN_SUCCESS;

+ }

+

+ Type = EFI_RESOURCE_SYSTEM_MEMORY;

Base = MemoryMapEntry->Base;

Size = MemoryMapEntry->Size;



@@ -40,7 +200,7 @@ MemInfoCallback (
EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |

EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE;



- if (Base >= BASE_4GB ) {

+ if (Base >= BASE_4GB) {

// Remove tested attribute to avoid DXE core to dispatch driver to memory
above 4GB

Attribue &= ~EFI_RESOURCE_ATTRIBUTE_TESTED;

}

@@ -48,6 +208,10 @@ MemInfoCallback (
BuildResourceDescriptorHob (Type, Attribue,
(EFI_PHYSICAL_ADDRESS)Base, Size);

DEBUG ((DEBUG_INFO , "buildhob: base = 0x%lx, size = 0x%lx, type =
0x%x\n", Base, Size, Type));



+ if (MemoryMapEntry->Type == E820_ACPI) {

+ BuildMemoryAllocationHob (Base, Size, EfiACPIReclaimMemory);

+ }

+

return RETURN_SUCCESS;

}



@@ -236,7 +400,16 @@ BuildHobFromBl (
EFI_PEI_GRAPHICS_DEVICE_INFO_HOB *NewGfxDeviceInfo;



//

- // Parse memory info and build memory HOBs

+ // First find TOLUD

+ //

+ Status = ParseMemoryInfo (FindToludCallback, NULL);

+ if (EFI_ERROR(Status)) {

+ return Status;

+ }

+ DEBUG ((DEBUG_INFO , "Assuming TOLUD = 0x%x\n",
TopOfLowerUsableDram));

+

+ //

+ // Parse memory info and build memory HOBs for Usable RAM

//

Status = ParseMemoryInfo (MemInfoCallback, NULL);

if (EFI_ERROR(Status)) {

@@ -289,6 +462,14 @@ BuildHobFromBl (
DEBUG ((DEBUG_INFO, "Create acpi board info guid hob\n"));

}



+ //

+ // Parse memory info and build memory HOBs for reserved DRAM and
MMIO

+ //

+ Status = ParseMemoryInfo (MemInfoCallbackMMIO, &AcpiBoardInfo);

+ if (EFI_ERROR(Status)) {

+ return Status;

+ }

+

//

// Parse platform specific information.

//

diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
index 2c84d6ed53..35ea23d202 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
+++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
@@ -38,6 +38,16 @@
#define GET_OCCUPIED_SIZE(ActualSize, Alignment) \

((ActualSize) + (((Alignment) - ((ActualSize) & ((Alignment) - 1))) &
((Alignment) - 1)))



+

+#define E820_RAM 1

+#define E820_RESERVED 2

+#define E820_ACPI 3

+#define E820_NVS 4

+#define E820_UNUSABLE 5

+#define E820_DISABLED 6

+#define E820_PMEM 7

+#define E820_UNDEFINED 8

+

/**

Auto-generated function that calls the library constructors for all of the
module's

dependent libraries.

--
2.30.2



-=-=-=-=-=-=
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#76517): https://edk2.groups.io/g/devel/message/76517
Mute This Topic: https://groups.io/mt/83555387/1781375
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [guo.dong@intel.com]
-=-=-=-=-=-=


[edk2][PATCH V1 1/1] ArmPkg: introduce FF-A interface support in MM_COMMUNICATE

Sayanta Pattanayak
 

From: Aditya Angadi <aditya.angadi@arm.com>

With the introduction of Firmware Framework for Arm platforms (FF-A),
normal world and secure world endpoints can use FF-A interface for
communication with each other. In this patch, FFA_MSG_SEND_DIRECT_REQ
and FFA_VERSION interfaces are introduced. This change adds an option
to either use the existing SMC interface or the introduced FF-A
interface based on the value of PcdFfaEnable.

Signed-off-by: Aditya Angadi <aditya.angadi@arm.com>
Signed-off-by: Sayanta Pattanayak <sayanta.pattanayak@arm.com>
---
ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf | 3 +
ArmPkg/Include/IndustryStandard/ArmFfaSvc.h | 2 +
ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.c | 73 +++++++++++++=
+++----
3 files changed, 63 insertions(+), 15 deletions(-)

diff --git a/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf b/ArmP=
kg/Drivers/MmCommunicationDxe/MmCommunication.inf
index 05b6de73ff34..da8462755a6f 100644
--- a/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf
+++ b/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf
@@ -52,5 +52,8 @@
gArmTokenSpaceGuid.PcdMmBufferBase
gArmTokenSpaceGuid.PcdMmBufferSize
=20
+[FeaturePcd.AARCH64]
+ gArmTokenSpaceGuid.PcdFfaEnable
+
[Depex]
gEfiCpuArchProtocolGuid
diff --git a/ArmPkg/Include/IndustryStandard/ArmFfaSvc.h b/ArmPkg/Include=
/IndustryStandard/ArmFfaSvc.h
index 65b8343ade61..5a300a7295db 100644
--- a/ArmPkg/Include/IndustryStandard/ArmFfaSvc.h
+++ b/ArmPkg/Include/IndustryStandard/ArmFfaSvc.h
@@ -19,6 +19,8 @@
#define ARM_SVC_ID_FFA_VERSION_AARCH32 0x84000063
#define ARM_SVC_ID_FFA_MSG_SEND_DIRECT_REQ_AARCH64 0xC400006F
#define ARM_SVC_ID_FFA_MSG_SEND_DIRECT_RESP_AARCH64 0xC4000070
+#define ARM_SVC_ID_FFA_SUCCESS_AARCH64 0xC4000061
+#define ARM_SVC_ID_FFA_SUCCESS_AARCH32 0x84000060
=20
#define SPM_MAJOR_VERSION_FFA 1
#define SPM_MINOR_VERSION_FFA 0
diff --git a/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.c b/ArmPkg=
/Drivers/MmCommunicationDxe/MmCommunication.c
index b1e309580988..ff15903473ad 100644
--- a/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.c
+++ b/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.c
@@ -18,6 +18,7 @@
=20
#include <Protocol/MmCommunication2.h>
=20
+#include <IndustryStandard/ArmFfaSvc.h>
#include <IndustryStandard/ArmStdSmc.h>
=20
#include "MmCommunicate.h"
@@ -73,6 +74,7 @@ MmCommunication2Communicate (
ARM_SMC_ARGS CommunicateSmcArgs;
EFI_STATUS Status;
UINTN BufferSize;
+ UINTN Ret;
=20
Status =3D EFI_ACCESS_DENIED;
BufferSize =3D 0;
@@ -124,26 +126,55 @@ MmCommunication2Communicate (
return EFI_BAD_BUFFER_SIZE;
}
=20
- // SMC Function ID
- CommunicateSmcArgs.Arg0 =3D ARM_SMC_ID_MM_COMMUNICATE_AARCH64;
-
- // Cookie
- CommunicateSmcArgs.Arg1 =3D 0;
-
// Copy Communication Payload
CopyMem ((VOID *)mNsCommBuffMemRegion.VirtualBase, CommBufferVirtual, =
BufferSize);
=20
- // comm_buffer_address (64-bit physical address)
- CommunicateSmcArgs.Arg2 =3D (UINTN)mNsCommBuffMemRegion.PhysicalBase;
+ // Use the FF-A interface if enabled.
+ if (FeaturePcdGet (PcdFfaEnable)) {
+ // FF-A Interface ID for direct message communication
+ CommunicateSmcArgs.Arg0 =3D ARM_SVC_ID_FFA_MSG_SEND_DIRECT_REQ_AARCH=
64;
=20
- // comm_size_address (not used, indicated by setting to zero)
- CommunicateSmcArgs.Arg3 =3D 0;
+ // FF-A Destination EndPoint ID, not used as of now
+ CommunicateSmcArgs.Arg1 =3D 0x0;
+
+ // Reserved for future use(MBZ)
+ CommunicateSmcArgs.Arg2 =3D 0x0;
+
+ // Arg3 onwards are the IMPLEMENTATION DEFINED FF-A parameters
+ // SMC Function ID
+ CommunicateSmcArgs.Arg3 =3D ARM_SMC_ID_MM_COMMUNICATE_AARCH64;
+
+ // Cookie
+ CommunicateSmcArgs.Arg4 =3D 0x0;
+
+ // comm_buffer_address (64-bit physical address)
+ CommunicateSmcArgs.Arg5 =3D (UINTN)mNsCommBuffMemRegion.PhysicalBase=
;
+
+ // comm_size_address (not used, indicated by setting to zero)
+ CommunicateSmcArgs.Arg6 =3D 0;
+ } else {
+ // SMC Function ID
+ CommunicateSmcArgs.Arg0 =3D ARM_SMC_ID_MM_COMMUNICATE_AARCH64;
+
+ // Cookie
+ CommunicateSmcArgs.Arg1 =3D 0;
+
+ // comm_buffer_address (64-bit physical address)
+ CommunicateSmcArgs.Arg2 =3D (UINTN)mNsCommBuffMemRegion.PhysicalBase=
;
+
+ // comm_size_address (not used, indicated by setting to zero)
+ CommunicateSmcArgs.Arg3 =3D 0;
+ }
=20
// Call the Standalone MM environment.
ArmCallSmc (&CommunicateSmcArgs);
=20
- switch (CommunicateSmcArgs.Arg0) {
- case ARM_SMC_MM_RET_SUCCESS:
+ Ret =3D CommunicateSmcArgs.Arg0;
+
+ if ((FeaturePcdGet (PcdFfaEnable) &&
+ (Ret =3D=3D ARM_SVC_ID_FFA_SUCCESS_AARCH64)) ||
+ (Ret =3D=3D ARM_SMC_MM_RET_SUCCESS))
+ {
ZeroMem (CommBufferVirtual, BufferSize);
// On successful return, the size of data being returned is inferred=
from
// MessageLength + Header.
@@ -158,8 +189,14 @@ MmCommunication2Communicate (
BufferSize
);
Status =3D EFI_SUCCESS;
- break;
+ return Status;
+ }
=20
+ if (FeaturePcdGet (PcdFfaEnable))
+ Ret =3D CommunicateSmcArgs.Arg2;
+
+ // Error Codes are same for FF-A and SMC interface
+ switch (Ret) {
case ARM_SMC_MM_RET_INVALID_PARAMS:
Status =3D EFI_INVALID_PARAMETER;
break;
@@ -233,8 +270,14 @@ GetMmCompatibility ()
UINT32 MmVersion;
ARM_SMC_ARGS MmVersionArgs;
=20
- // MM_VERSION uses SMC32 calling conventions
- MmVersionArgs.Arg0 =3D ARM_SMC_ID_MM_VERSION_AARCH32;
+ if (FeaturePcdGet (PcdFfaEnable)) {
+ MmVersionArgs.Arg0 =3D ARM_SVC_ID_FFA_VERSION_AARCH32;
+ MmVersionArgs.Arg1 =3D MM_CALLER_MAJOR_VER << MM_MAJOR_VER_SHIFT;
+ MmVersionArgs.Arg1 |=3D MM_CALLER_MINOR_VER;
+ } else {
+ // MM_VERSION uses SMC32 calling conventions
+ MmVersionArgs.Arg0 =3D ARM_SMC_ID_MM_VERSION_AARCH32;
+ }
=20
ArmCallSmc (&MmVersionArgs);
=20
--=20
2.17.1


Re: [Patch] StandaloneMmPkg: Fixed communicating from TF-A failed issue

Omkar Anand Kulkarni
 

On 6/10/21 6:44 AM, Ming Huang via groups.io wrote:
On 6/9/21 3:10 PM, Ard Biesheuvel wrote:
On Tue, 8 Jun 2021 at 16:21, Ming Huang <huangming@linux.alibaba.com>
wrote:

TF-A: TrustedFirmware-a
SPM: Secure Partition Manager(MM)

For AArch64, when SPM enable in TF-A, TF-A may communicate to MM
with
buffer address (PLAT_SPM_BUF_BASE). The address is different from
PcdMmBufferBase which use in edk2.
Then why do we have PcdMmBufferBase?
ArmPkg use this Pcd for the base address of non-secure communication
buffer.


Is it possible to set PcdMmBufferBase to the correct value?
The secure communication may interrupt the non-secure communication. if
we use the same address (PcdMmBufferBase and PLAT_SPM_BUF_BASE), the
date in communication buffer may be corrupted.

Best Regards,
Ming
In case where an interrupt handler executing from EL3 makes a call into StandaloneMM, the handler in EL3 makes an spm call into StandaloneMM using PLAT_SPM_BUF_BASE buffer base address. This PLAT_SPM_BUF_BASE is a shared buffer between EL3 and S-EL0. This is where the following check fails and leads to spm call failure. So this change would help resolve this issue.

- Omkar



Checking address will let TF-A communicate failed to MM. So remove
below checking code:
if (NsCommBufferAddr < mNsCommBuffer.PhysicalStart) {
return EFI_ACCESS_DENIED;
}

Signed-off-by: Ming Huang <huangming@linux.alibaba.com>
---
StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/EventHandle.c |
4
----
1 file changed, 4 deletions(-)

diff --git
a/StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/EventHandle.c
b/StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/EventHandle.c
index 63fbe26642..fe98d3181d 100644
---
a/StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/EventHandle.c
+++
b/StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/EventHandle.c
@@ -103,10 +103,6 @@ PiMmStandaloneArmTfCpuDriverEntry (
return EFI_INVALID_PARAMETER;
}

- if (NsCommBufferAddr < mNsCommBuffer.PhysicalStart) {
- return EFI_ACCESS_DENIED;
- }
-
if ((NsCommBufferAddr + sizeof (EFI_MM_COMMUNICATE_HEADER)) >=
(mNsCommBuffer.PhysicalStart + mNsCommBuffer.PhysicalSize)) {
return EFI_INVALID_PARAMETER;
--
2.17.1



[PATCH v5] 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 | 1497 +++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++
IntelFsp2Pkg/Tools/{ =3D> ConfigEditor}/FspDscBsf2Yaml.py | 370 +++++++++=
+++++++++++++++++++--------------------------------------------------------=
--------------------------------------------------
IntelFsp2Pkg/Tools/ConfigEditor/FspGenCfgData.py | 2593 +++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++++
IntelFsp2Pkg/Tools/ConfigEditor/GenYamlCfg.py | 2244 +++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++++++++++++++++++++++++++++
IntelFsp2Pkg/Tools/ConfigEditor/SingleSign.py | 324 +++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++
6 files changed, 7237 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..178c518d30
--- /dev/null
+++ b/IntelFsp2Pkg/Tools/ConfigEditor/ConfigEditor.py
@@ -0,0 +1,1497 @@
+# @ 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
+from FspDscBsf2Yaml import bsf_to_dsc, dsc_to_yaml=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/FspDscBsf2Yaml.py b/IntelFsp2Pkg/Tools/Conf=
igEditor/FspDscBsf2Yaml.py
similarity index 58%
rename from IntelFsp2Pkg/Tools/FspDscBsf2Yaml.py
rename to IntelFsp2Pkg/Tools/ConfigEditor/FspDscBsf2Yaml.py
index d2ca7145ae..f9b2503414 100644
--- a/IntelFsp2Pkg/Tools/FspDscBsf2Yaml.py
+++ b/IntelFsp2Pkg/Tools/ConfigEditor/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/ConfigEditor/FspGenCfgData.py b/IntelFsp2Pk=
g/Tools/ConfigEditor/FspGenCfgData.py
new file mode 100644
index 0000000000..decb3f1c5d
--- /dev/null
+++ b/IntelFsp2Pkg/Tools/ConfigEditor/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
diff --git a/IntelFsp2Pkg/Tools/ConfigEditor/GenYamlCfg.py b/IntelFsp2Pkg/T=
ools/ConfigEditor/GenYamlCfg.py
new file mode 100644
index 0000000000..d4587d7ce5
--- /dev/null
+++ b/IntelFsp2Pkg/Tools/ConfigEditor/GenYamlCfg.py
@@ -0,0 +1,2244 @@
+# @ 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
+ 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
+ if bin_data[pos + len(seg[0]):].find(key) >=3D 0:=0D
+ print("Warning: Multiple matches for '%s' "=0D
+ "in binary, the 1st instance will be used !"=0D
+ % seg[0])=0D
+ string =3D ("Warning: Multiple matches for '%s' "=0D
+ "in binary, the 1st instance will be used !" % seg[0])=
=0D
+ messagebox.showwarning('Warning!', string)=0D
+ bin_segs.append([seg[0], pos, seg[2]])=0D
+ else:=0D
+ raise Exception("Could not find '%s' in binary !"=0D
+ % seg[0])=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
--=20
2.28.0.windows.1


Re: [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event with TPL_HIGH_LEVEL

Sunny Wang
 

Yeah, that is a typo. The result with 13 passes was got from testing with this fix. Thanks for catching this, Barton.

Best Regards,
Sunny Wang

-----Original Message-----
From: Gao Jie <gaojie@byosoft.com.cn>
Sent: Wednesday, June 16, 2021 9:15 AM
To: devel@edk2.groups.io; Sunny Wang <Sunny.Wang@arm.com>; Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>; 'Heinrich Schuchardt' <xypron.glpk@gmx.de>
Cc: G Edhaya Chandran <Edhaya.Chandran@arm.com>; 'Michael D Kinney' <michael.d.kinney@intel.com>
Subject: 回复: [edk2-devel] [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event with TPL_HIGH_LEVEL

Hi Sunny,

I believe the result with 13 passes should be tested *with* this fix, right?

I saw reviewed-by/Acked-by from Samer and Heinrich, will get this patch upstreamed soon.

Thanks
Barton

-----邮件原件-----
发件人: devel@edk2.groups.io <devel@edk2.groups.io> 代表 Sunny Wang
发送时间: 2021年6月14日 17:53
收件人: Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>; Heinrich Schuchardt <xypron.glpk@gmx.de>; devel@edk2.groups.io
抄送: G Edhaya Chandran <Edhaya.Chandran@arm.com>; Barton Gao <gaojie@byosoft.com.cn>; Michael D Kinney <michael.d.kinney@intel.com>; Sunny Wang <Sunny.Wang@arm.com>
主题: Re: [edk2-devel] [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event with TPL_HIGH_LEVEL

Thanks for the review, Samer.
Moreover, I just built it and tested it on my ARM system, and confirmed the issue got fixed by this patch.

Without this fix, the result would be 18 tests, and 4 Errors.
CreateEvent_Func: [FAILED]
Passes........... 14
Warnings......... 0
Errors........... 4

Without this fix, the result would be 13 tests, and 0 Errors.
CreateEvent_Func: [PASSED]
Passes........... 13
Warnings......... 0
Errors........... 0

Best Regards,
Sunny Wang

-----Original Message-----
From: Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>
Sent: Monday, June 14, 2021 8:36 AM
To: Heinrich Schuchardt <xypron.glpk@gmx.de>; Sunny Wang <Sunny.Wang@arm.com>; devel@edk2.groups.io
Cc: G Edhaya Chandran <Edhaya.Chandran@arm.com>; Barton Gao <gaojie@byosoft.com.cn>; Michael D Kinney <michael.d.kinney@intel.com>; Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>
Subject: RE: [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event with TPL_HIGH_LEVEL

Reviewed-By: Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>

-----Original Message-----
From: Heinrich Schuchardt <xypron.glpk@gmx.de>
Sent: Friday, June 11, 2021 5:15 AM
To: Sunny Wang <Sunny.Wang@arm.com>; devel@edk2.groups.io
Cc: Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>; G Edhaya
Chandran <Edhaya.Chandran@arm.com>; Barton Gao
<gaojie@byosoft.com.cn>; Michael D Kinney <michael.d.kinney@intel.com>
Subject: Re: [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event
with TPL_HIGH_LEVEL

On 11.06.21 10:35, Sunny Wang wrote:
The commits a9d1fb58 and ae7e5477b555 caused SCT BS.CreateEvent
failures.

Section 7.1 of the UEFI Spec states that TPL_HIGH_LEVEL is designed for
exclusive use by the firmware. The creation of events by UEFI
applications, UEFI drivers, and UEFI OS Loaders should not use this TPL
level.

Therefore, revert TPL_HIGH_LEVEL change in commits a9d1fb58 and
ae7e5477b555 to not create event with TPL_HIGH_LEVEL to be compliant
with UEFI Spec and fix the failures.

For more information, https://edk2.groups.io/g/devel/message/76338

Cc: Samer El-Haj-Mahmoud <samer.el-haj-mahmoud@arm.com>
Cc: G Edhaya Chandran <edhaya.chandran@arm.com>
Cc: Barton Gao <gaojie@byosoft.com.cn>
Cc: Heinrich Schuchardt <xypron.glpk@gmx.de>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Signed-off-by: Sunny Wang <sunny.wang@arm.com>
Acked-by: Heinrich Schuchardt <xypron.glpk@gmx.de>

---
.../EventTimerTaskPriorityServicesBBTestCreateEvent.c | 5 +----
.../EventTimerTaskPriorityServicesBBTestCreateEventEx.c | 4 +---
2 files changed, 2 insertions(+), 7 deletions(-)

diff --git a/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEvent.c b/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEvent.c
index a7e7366e..d5c033f7 100644
--- a/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEvent.c
+++ b/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEvent.c
@@ -2,6 +2,7 @@

Copyright 2006 - 2012 Unified EFI, Inc.<BR>
Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2021, ARM Limited. All rights reserved.

This program and the accompanying materials
are licensed and made available under the terms and conditions of the
BSD License
@@ -190,7 +191,6 @@ BBTestCreateEvent_Conf_Sub1 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_TEST_ASSERTION AssertionType;
@@ -342,7 +342,6 @@ BBTestCreateEvent_Conf_Sub3 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_TEST_ASSERTION AssertionType;
@@ -407,7 +406,6 @@ BBTestCreateEvent_Conf_Sub4 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_TEST_ASSERTION AssertionType;
@@ -482,7 +480,6 @@ BBTestCreateEvent_Func_Sub1 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_TEST_ASSERTION AssertionType;
diff --git a/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEventEx.c b/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEventEx.c
index eb458de5..03b7ae6e 100644
--- a/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEventEx.c
+++ b/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEventEx.c
@@ -2,6 +2,7 @@

Copyright 2006 - 2016 Unified EFI, Inc.<BR>
Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2021, ARM Limited. All rights reserved.

This program and the accompanying materials
are licensed and made available under the terms and conditions of the
BSD License
@@ -228,7 +229,6 @@ BBTestCreateEventEx_Conf_Sub1 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_GUID *EventGroups[] = {
@@ -318,7 +318,6 @@ BBTestCreateEventEx_Conf_Sub2 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_GUID *EventGroups[] = {
@@ -413,7 +412,6 @@ BBTestCreateEventEx_Conf_Sub3 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_GUID *EventGroups[] = {

IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.







IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


Re: [PATCH v1 1/5] EDK2 Code First: PI Specification: EFI_MM_COMMUNICATE_HEADER Update

Wu, Hao A
 

Thanks Kun,

I am a little concerned on whether there will be other missing cases that are not covered by this patch series.

I am also wondering is there any detection can be made to warn the cases that code modification should be made after this structure update.
Otherwise, it will be the burden for the platform owners to review the platform codes following your guide mentioned in this patch.

Hoping others can provide some inputs on this.

Best Regards,
Hao Wu

-----Original Message-----
From: Kun Qin <kuqin12@gmail.com>
Sent: Wednesday, June 16, 2021 4:51 AM
To: Wu, Hao A <hao.a.wu@intel.com>; devel@edk2.groups.io
Cc: Kinney, Michael D <michael.d.kinney@intel.com>; Liming Gao
<gaoliming@byosoft.com.cn>; Liu, Zhiguang <zhiguang.liu@intel.com>;
Andrew Fish <afish@apple.com>; Laszlo Ersek <lersek@redhat.com>; Leif
Lindholm <leif@nuviainc.com>
Subject: Re: [edk2-devel] [PATCH v1 1/5] EDK2 Code First: PI Specification:
EFI_MM_COMMUNICATE_HEADER Update

Hi Hao,

Sorry that I missed comments for this patch earlier. You are correct. I only
inspected SmmLockBoxPeiLib. The PEI instance handled mode switch with
```OFFSET_OF ``` function. But DXE instance still have a few use cases that will
be impacted.

I will update this read me file and add a code change patch for this library in
v2. Thanks for pointing this out.

Regards,
Kun

On 06/11/2021 00:46, Wu, Hao A wrote:
-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Kun
Qin
Sent: Thursday, June 10, 2021 9:43 AM
To: devel@edk2.groups.io
Cc: Kinney, Michael D <michael.d.kinney@intel.com>; Liming Gao
<gaoliming@byosoft.com.cn>; Liu, Zhiguang <zhiguang.liu@intel.com>;
Andrew Fish <afish@apple.com>; Laszlo Ersek <lersek@redhat.com>; Leif
Lindholm <leif@nuviainc.com>
Subject: [edk2-devel] [PATCH v1 1/5] EDK2 Code First: PI Specification:
EFI_MM_COMMUNICATE_HEADER Update

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

This change includes specification update markdown file that
describes the proposed PI Specification v1.7 Errata A in detail and
potential impact to the existing codebase.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Liming Gao <gaoliming@byosoft.com.cn>
Cc: Zhiguang Liu <zhiguang.liu@intel.com>
Cc: Andrew Fish <afish@apple.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Leif Lindholm <leif@nuviainc.com>

Signed-off-by: Kun Qin <kuqin12@gmail.com>
---
BZ3430-SpecChange.md | 88 ++++++++++++++++++++
1 file changed, 88 insertions(+)

diff --git a/BZ3430-SpecChange.md b/BZ3430-SpecChange.md new file
mode
100644 index 000000000000..33a1ffda447b
--- /dev/null
+++ b/BZ3430-SpecChange.md
@@ -0,0 +1,88 @@
+# Title: Change MessageLength Field of
EFI_MM_COMMUNICATE_HEADER
to
+UINT64
+
+## Status: Draft
+
+## Document: UEFI Platform Initialization Specification Version 1.7
+Errata A
+
+## License
+
+SPDX-License-Identifier: CC-BY-4.0
+
+## Submitter: [TianoCore Community](https://www.tianocore.org)
+
+## Summary of the change
+
+Change the `MessageLength` Field of
`EFI_MM_COMMUNICATE_HEADER`
from UINTN to UINT64 to remove architecture dependency:
+
+```c
+typedef struct {
+ EFI_GUID HeaderGuid;
+ UINT64 MessageLength;
+ UINT8 Data[ANYSIZE_ARRAY];
+} EFI_MM_COMMUNICATE_HEADER;
+```
+
+## Benefits of the change
+
+In PI Spec v1.7 Errata A, Vol.4, Sec 5.7 MM Communication Protocol,
+the
MessageLength field of `EFI_MM_COMMUNICATE_HEADER` (also
defined as
`EFI_SMM_COMMUNICATE_HEADER`) is defined as type UINTN.
+
+But this structure, as a generic definition, could be used for both
+PEI and
DXE MM communication. Thus for a system that supports PEI MM launch,
but operates PEI in 32bit mode and MM foundation in 64bit, the
current `EFI_MM_COMMUNICATE_HEADER` definition will cause
structure
parse error due to UINTN used.
+
+## Impact of the change
+
+This change will impact the known structure consumers including:
+
+```bash
+MdeModulePkg/Core/PiSmmCore/PiSmmIpl
+MdeModulePkg/Application/SmiHandlerProfileInfo
+MdeModulePkg/Application/MemoryProfileInfo
+```
+
+For consumers that are not using
`OFFSET_OF(EFI_MM_COMMUNICATE_HEADER, Data)`, but performing
explicit
addition such as the existing
MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileInfo.
c, one will need to change code implementation to match new structure
definition. Otherwise, the code compiled on IA32 architecture will
experience structure field dereference error.
+
+User who currently uses UINTN local variables as place holder of
MessageLength will need to use caution to make cast from UINTN to
UINT64 and vice versa. It is recommended to use `SafeUint64ToUintn`
for such operations when the value is indeterministic.
+
+Note: MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib is
also
consuming this structure, but it handled this size discrepancy
internally. If this

Hello Kun,

Sorry for a question.
I am not sure why the current codes in file SmmLockBoxDxeLib.c will work
properly after the UINTN -> UINT64 change.

For example:
LockBoxGetSmmCommBuffer():
MinimalSizeNeeded = sizeof (EFI_GUID) +
sizeof (UINTN) +
MAX (sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SAVE),
MAX (sizeof
(EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES),
MAX (sizeof
(EFI_SMM_LOCK_BOX_PARAMETER_UPDATE),
MAX (sizeof
(EFI_SMM_LOCK_BOX_PARAMETER_RESTORE),
sizeof
(EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE)))));

SaveLockBox():
UINT8 TempCommBuffer[sizeof(EFI_GUID) + sizeof(UINTN)
+ sizeof(EFI_SMM_LOCK_BOX_PARAMETER_SAVE)];

Is the series missed changes for SmmLockBoxDxeLib or I got something
wrong?

Best Regards,
Hao Wu


potential spec change is not applied, all applicable PEI MM
communicate callers will need to use the same routine as that of
SmmLockBoxPeiLib to invoke a properly populated
EFI_MM_COMMUNICATE_HEADER to be used in X64 MM foundation.
+
+## Detailed description of the change [normative updates]
+
+### Specification Changes
+
+1. In PI Specification v1.7 Errata A: Vol. 4 Page-91, the definition
+of
`EFI_MM_COMMUNICATE_HEADER` should be changed from current:
+
+```c
+typedef struct {
+ EFI_GUID HeaderGuid;
+ UINTN MessageLength;
+ UINT8 Data[ANYSIZE_ARRAY];
+} EFI_MM_COMMUNICATE_HEADER;
+```
+
+to:
+
+```c
+typedef struct {
+ EFI_GUID HeaderGuid;
+ UINT64 MessageLength;
+ UINT8 Data[ANYSIZE_ARRAY];
+} EFI_MM_COMMUNICATE_HEADER;
+```
+
+### Code Changes
+
+1. Remove the explicit calculation of the offset of `Data` in
`EFI_MM_COMMUNICATE_HEADER`. Thus applicable calculations of
`sizeof(EFI_GUID) + sizeof(UINTN)` should be replaced with
`OFFSET_OF(EFI_MM_COMMUNICATE_HEADER, Data)` or similar
alternatives.
These calculations are identified in:
+
+```bash
+MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileInfo.
c
+MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.c
+```
+
+1. Resolve potentially mismatched type between `UINTN` and `UINT64`.
This would occur when `MessageLength` or its derivitive are used for
local calculation with existing `UINTN` typed variables. Code change
regarding this perspective is per case evaluation: if the variables
involved are all deterministic values, and there is no overflow or
underflow risk, a cast operation (from `UINTN` to `UINT64`) can be
safely used. Otherwise, the calculation will be performed in `UINT64`
bitwidth and then convert to `UINTN` using `SafeUint64*` and
`SafeUint64ToUintn`, respectively. These operations are identified in:
+
+```bash
+MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c
+MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileInfo.
c
+MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.c
+```
+
+1. After all above changes applied and specification updated,
`MdePkg/Include/Protocol/MmCommunication.h` will need to be
updated
to match new definition that includes the field type update.
--
2.31.1.windows.1





回复: [edk2-devel] [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event with TPL_HIGH_LEVEL

Gao Jie
 

Hi Sunny,

I believe the result with 13 passes should be tested *with* this fix, right?

I saw reviewed-by/Acked-by from Samer and Heinrich, will get this patch upstreamed soon.

Thanks
Barton

-----邮件原件-----
发件人: devel@edk2.groups.io <devel@edk2.groups.io> 代表 Sunny Wang
发送时间: 2021年6月14日 17:53
收件人: Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>; Heinrich Schuchardt <xypron.glpk@gmx.de>; devel@edk2.groups.io
抄送: G Edhaya Chandran <Edhaya.Chandran@arm.com>; Barton Gao <gaojie@byosoft.com.cn>; Michael D Kinney <michael.d.kinney@intel.com>; Sunny Wang <Sunny.Wang@arm.com>
主题: Re: [edk2-devel] [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event with TPL_HIGH_LEVEL

Thanks for the review, Samer.
Moreover, I just built it and tested it on my ARM system, and confirmed the issue got fixed by this patch.

Without this fix, the result would be 18 tests, and 4 Errors.
CreateEvent_Func: [FAILED]
Passes........... 14
Warnings......... 0
Errors........... 4

Without this fix, the result would be 13 tests, and 0 Errors.
CreateEvent_Func: [PASSED]
Passes........... 13
Warnings......... 0
Errors........... 0

Best Regards,
Sunny Wang

-----Original Message-----
From: Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>
Sent: Monday, June 14, 2021 8:36 AM
To: Heinrich Schuchardt <xypron.glpk@gmx.de>; Sunny Wang <Sunny.Wang@arm.com>; devel@edk2.groups.io
Cc: G Edhaya Chandran <Edhaya.Chandran@arm.com>; Barton Gao <gaojie@byosoft.com.cn>; Michael D Kinney <michael.d.kinney@intel.com>; Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>
Subject: RE: [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event with TPL_HIGH_LEVEL

Reviewed-By: Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>

-----Original Message-----
From: Heinrich Schuchardt <xypron.glpk@gmx.de>
Sent: Friday, June 11, 2021 5:15 AM
To: Sunny Wang <Sunny.Wang@arm.com>; devel@edk2.groups.io
Cc: Samer El-Haj-Mahmoud <Samer.El-Haj-Mahmoud@arm.com>; G Edhaya
Chandran <Edhaya.Chandran@arm.com>; Barton Gao
<gaojie@byosoft.com.cn>; Michael D Kinney <michael.d.kinney@intel.com>
Subject: Re: [edk2-test][PATCH v2 1/1] uefi-sct/SctPkg: Not create event
with TPL_HIGH_LEVEL

On 11.06.21 10:35, Sunny Wang wrote:
The commits a9d1fb58 and ae7e5477b555 caused SCT BS.CreateEvent
failures.

Section 7.1 of the UEFI Spec states that TPL_HIGH_LEVEL is designed for
exclusive use by the firmware. The creation of events by UEFI
applications, UEFI drivers, and UEFI OS Loaders should not use this TPL
level.

Therefore, revert TPL_HIGH_LEVEL change in commits a9d1fb58 and
ae7e5477b555 to not create event with TPL_HIGH_LEVEL to be compliant
with UEFI Spec and fix the failures.

For more information, https://edk2.groups.io/g/devel/message/76338

Cc: Samer El-Haj-Mahmoud <samer.el-haj-mahmoud@arm.com>
Cc: G Edhaya Chandran <edhaya.chandran@arm.com>
Cc: Barton Gao <gaojie@byosoft.com.cn>
Cc: Heinrich Schuchardt <xypron.glpk@gmx.de>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Signed-off-by: Sunny Wang <sunny.wang@arm.com>
Acked-by: Heinrich Schuchardt <xypron.glpk@gmx.de>

---
.../EventTimerTaskPriorityServicesBBTestCreateEvent.c | 5 +----
.../EventTimerTaskPriorityServicesBBTestCreateEventEx.c | 4 +---
2 files changed, 2 insertions(+), 7 deletions(-)

diff --git a/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEvent.c b/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEvent.c
index a7e7366e..d5c033f7 100644
--- a/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEvent.c
+++ b/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEvent.c
@@ -2,6 +2,7 @@

Copyright 2006 - 2012 Unified EFI, Inc.<BR>
Copyright (c) 2010 - 2012, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2021, ARM Limited. All rights reserved.

This program and the accompanying materials
are licensed and made available under the terms and conditions of the
BSD License
@@ -190,7 +191,6 @@ BBTestCreateEvent_Conf_Sub1 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_TEST_ASSERTION AssertionType;
@@ -342,7 +342,6 @@ BBTestCreateEvent_Conf_Sub3 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_TEST_ASSERTION AssertionType;
@@ -407,7 +406,6 @@ BBTestCreateEvent_Conf_Sub4 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_TEST_ASSERTION AssertionType;
@@ -482,7 +480,6 @@ BBTestCreateEvent_Func_Sub1 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_TEST_ASSERTION AssertionType;
diff --git a/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEventEx.c b/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEventEx.c
index eb458de5..03b7ae6e 100644
--- a/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEventEx.c
+++ b/uefi-
sct/SctPkg/TestCase/UEFI/EFI/BootServices/EventTimerTaskPriorityServices/
BlackBoxTest/EventTimerTaskPriorityServicesBBTestCreateEventEx.c
@@ -2,6 +2,7 @@

Copyright 2006 - 2016 Unified EFI, Inc.<BR>
Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.<BR>
+ Copyright (c) 2021, ARM Limited. All rights reserved.

This program and the accompanying materials
are licensed and made available under the terms and conditions of the
BSD License
@@ -228,7 +229,6 @@ BBTestCreateEventEx_Conf_Sub1 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_GUID *EventGroups[] = {
@@ -318,7 +318,6 @@ BBTestCreateEventEx_Conf_Sub2 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_GUID *EventGroups[] = {
@@ -413,7 +412,6 @@ BBTestCreateEventEx_Conf_Sub3 (
EFI_TPL NotifyTpls[] = {
TPL_CALLBACK,
TPL_NOTIFY,
- TPL_HIGH_LEVEL,
0
};
EFI_GUID *EventGroups[] = {

IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


Event: TianoCore Bug Triage - APAC / NAMO - 06/15/2021 #cal-reminder

devel@edk2.groups.io Calendar <noreply@...>
 

Reminder: TianoCore Bug Triage - APAC / NAMO

When:
06/15/2021
6:30pm to 7:30pm
(UTC-07:00) America/Los Angeles

Where:
https://teams.microsoft.com/l/meetup-join/19%3ameeting_OTUyZTg2NjgtNDhlNS00ODVlLTllYTUtYzg1OTNjNjdiZjFh%40thread.v2/0?context=%7b%22Tid%22%3a%2246c98d88-e344-4ed4-8496-4ed7712e255d%22%2c%22Oid%22%3a%22b286b53a-1218-4db3-bfc9-3d4c5aa7669e%22%7d

Organizer: Liming Gao gaoliming@...

View Event

Description:

TianoCore Bug Triage - APAC / NAMO

Hosted by Liming Gao

 

________________________________________________________________________________

Microsoft Teams meeting

Join on your computer or mobile app

Click here to join the meeting

Join with a video conferencing device

teams@...

Video Conference ID: 116 062 094 0

Alternate VTC dialing instructions

Or call in (audio only)

+1 916-245-6934,,77463821#   United States, Sacramento

Phone Conference ID: 774 638 21#

Find a local number | Reset PIN

Learn More | Meeting options


回复: [edk2-devel] [Patch V4 0/9] Create multiple Hobs for Universal Payload

Zhiguang Liu
 

Thank Patrick for verifying.
I will add your Tested-by tag for this patch series.

Thanks
Zhiguang

发件人: Patrick Rudolph <patrick.rudolph@...>
发送时间: 2021年6月15日 20:00
收件人: devel@edk2.groups.io <devel@edk2.groups.io>; Liu, Zhiguang <zhiguang.liu@...>
抄送: gaoliming <gaoliming@...>
主题: Re: [edk2-devel] [Patch V4 0/9] Create multiple Hobs for Universal Payload
 
Tested the patch series on Intel Coffee Lake Platform using latest
coreboot master.
Everything seems to work fine.

Thanks
Patrick

On Thu, Jun 10, 2021 at 11:48 AM Zhiguang Liu <zhiguang.liu@...> wrote:
>
> Liming,
>
> Bugzilla is created at https://bugzilla.tianocore.org/show_bug.cgi?id=3447
>
> Thanks
> Zhiguang
>
> > -----Original Message-----
> > From: gaoliming <gaoliming@...>
> > Sent: Thursday, June 10, 2021 5:14 PM
> > To: devel@edk2.groups.io; Liu, Zhiguang <zhiguang.liu@...>
> > Subject: 回复: [edk2-devel] [Patch V4 0/9] Create multiple Hobs for Universal
> > Payload
> >
> > Zhiguang:
> >   Can you submit one BZ for this new feature? I will add it into edk2 202108
> > stable tag planning.
> >
> > Thanks
> > Liming
> > > -----邮件原件-----
> > > 发件人: devel@edk2.groups.io <devel@edk2.groups.io> 代表 Zhiguang Liu
> > > 发送时间: 2021年6月10日 9:33
> > > 收件人: devel@edk2.groups.io
> > > 主题: [edk2-devel] [Patch V4 0/9] Create multiple Hobs for Universal
> > > Payload
> > >
> > > V1:
> > > This patch set is based on Universal Payload on
> > > https://universalpayload.github.io/documentation/payload-
> > interfaces/index.
> > > html
> > > This patch set introduce one general header, three different hob types
> > > and how Universal Payload consume these hobs.
> > >
> > > V2:
> > > Move all the header files and Guid define to MdeModulePkg Fix code bug
> > > when parsing SmbiosDxe.
> > > Enhance error handling in AcpiTableProtocol.c.
> > > Add AcpiTableDxe.inf in UefiPayload.fdf
> > >
> > > V3:
> > > Avoid duplicated code in SmBiosDxe.c
> > >
> > > V4:
> > > Add link to spec in header files' file comments Avoid using PLD,
> > > because it may be confusing
> > >
> > > All changes can be seen at
> > >
> > https://github.com/LiuZhiguang001/edk2/tree/UniversalPayloadHeaders_v4
> > >
> > > Zhiguang Liu (9):
> > >   MdeModulePkg: Add Universal Payload general definition header file
> > >   MdeModulePkg: Add new structure for the PCI Root Bridge Info Hob
> > >   UefiPayloadPkg: UefiPayload retrieve PCI root bridge from Guid Hob
> > >   MdeModulePkg: Add new structure for the Universal Payload SMBios
> > Table
> > >     Info Hob
> > >   MdeModulePkg/Universal/SmbiosDxe: Scan for existing tables
> > >   UefiPayloadPkg: Creat gPldSmbiosTableGuid Hob
> > >   MdeModulePkg: Add new structure for the Universal Payload ACPI Table
> > >     Info Hob
> > >   MdeModulePkg/ACPI: Install ACPI table from HOB.
> > >   UefiPayloadPkg: Creat gPldAcpiTableGuid Hob
> > >
> > >  MdeModulePkg/Include/UniversalPayload/AcpiTable.h              |
> > > 30 ++++++++++++++++++++++++++++++
> > >  MdeModulePkg/Include/UniversalPayload/PciRootBridges.h         |
> > > 91
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > > +++++++++++++++++++++++++++++
> > >  MdeModulePkg/Include/UniversalPayload/SmbiosTable.h            |
> > > 30 ++++++++++++++++++++++++++++++
> > >  MdeModulePkg/Include/UniversalPayload/UniversalPayload.h       |
> > > 35 +++++++++++++++++++++++++++++++++++
> > >  MdeModulePkg/MdeModulePkg.dec
> > > |  15 +++++++++++++++
> > >  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiSdt.c             |
> > > 92
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > > +++---------------------------
> > >  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTable.h           |
> > > 38 +++++++++++++++++++++++++++++++++++++-
> > >  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf      |   8
> > > +++++---
> > >  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableProtocol.c   | 171
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > > ++++++++++++++++++++++++++++++++++++++++-------
> > >  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c                   |
> > > 293
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > > ++++++++++++++++++++++++++++++++++++++++++++-
> > >  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.h                   |
> > > 65
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > > ++-
> > >  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf                 |
> > > 5 ++++-
> > >  UefiPayloadPkg/BlSupportDxe/BlSupportDxe.c                     |
> > > 28 +---------------------------
> > >  UefiPayloadPkg/BlSupportDxe/BlSupportDxe.h                     |
> > > 5 +----
> > >  UefiPayloadPkg/BlSupportDxe/BlSupportDxe.inf                   |
> > > 4 +---
> > >  UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridge.h        |  40
> > > ++++++++++++++++++++++++++++++++++++++--
> > >  UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridgeLib.c     |  47
> > > ++++++++++++++++++++++++++++++++++++++++++++---
> > >  UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridgeLib.inf   |   8
> > > +++++++-
> > >  UefiPayloadPkg/Library/PciHostBridgeLib/PciHostBridgeSupport.c |  73
> > >
> > ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> > ++++
> > > ++++++++++-
> > >  UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c             |  23
> > > ++++++++++++++++++++++-
> > >  UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h             |   5
> > > +++--
> > >  UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.inf           |   4
> > > +++-
> > >  UefiPayloadPkg/UefiPayloadPkg.dsc                              |
> > > 2 +-
> > >  UefiPayloadPkg/UefiPayloadPkg.fdf                              |
> > > 4 ++++
> > >  24 files changed, 1029 insertions(+), 87 deletions(-)  create mode
> > > 100644 MdeModulePkg/Include/UniversalPayload/AcpiTable.h
> > >  create mode 100644
> > > MdeModulePkg/Include/UniversalPayload/PciRootBridges.h
> > >  create mode 100644
> > > MdeModulePkg/Include/UniversalPayload/SmbiosTable.h
> > >  create mode 100644
> > > MdeModulePkg/Include/UniversalPayload/UniversalPayload.h
> > >
> > > --
> > > 2.30.0.windows.2
> > >
> > >
> > >
> > >
> > >
> >
> >
>
>
>
>
>
>


Re: [PATCH v3 6/8] SecurityPkg: Add new modules to Security package.

Yao, Jiewen
 

Good catch, Jeremiah!

Thank you!

 

From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Jeremiah Cox via groups.io
Sent: Wednesday, June 16, 2021 2:55 AM
To: Grzegorz Bernacki <gjb@...>; devel@edk2.groups.io
Subject: Re: [edk2-devel] [PATCH v3 6/8] SecurityPkg: Add new modules to Security package.

 

"dbt" and "dbx" are swapped in the comments?  Look for groups of 3 underscores ("___") below...

+ ## GUID used to specify section with default ___dbt___ content
+ gDefault___dbx___FileGuid = { 0x5740766a, 0x718e, 0x4dc0, { 0x99, 0x35, 0xc3, 0x6f, 0x7d, 0x3f, 0x88, 0x4f } }
+
+ ## GUID used to specify section with default ___dbx___ content
+ gDefault___dbt___FileGuid = { 0x36c513ee, 0xa338, 0x4976, { 0xa0, 0xfb, 0x6d, 0xdb, 0xa3, 0xda, 0xfe, 0x87 } }


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

Yao, Jiewen
 

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%)



Re: [edk2-platforms][PATCH 0/2] Support for TiogaPass Platform and Override generic PciBus Driver with

Nate DeSimone
 

One final comment, PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe seems a little excessive, I think you can do PurleyOpenBoardPkg/Override/MdeModulePkg/Bus/Pci/PciBusDxe and everyone will understand what it is.

Thanks,
Nate

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Nate DeSimone
Sent: Tuesday, June 15, 2021 2:45 PM
To: devel@edk2.groups.io; Desimone, Nathaniel L <nathaniel.l.desimone@intel.com>; KARPAGAVINAYAGAM, MANICKAVASAKAM <manickavasakamk@ami.com>
Cc: Oram, Isaac W <isaac.w.oram@intel.com>; Felixp@ami.com; DOPPALAPUDI, HARIKRISHNA <harikrishnad@ami.com>; Jha, Manish <manishj@ami.com>; Bobroff, Zachary <zacharyb@ami.com>
Subject: Re: [edk2-devel] [edk2-platforms][PATCH 0/2] Support for TiogaPass Platform and Override generic PciBus Driver with

Also, uefi_2500_800.efi should not be added directly inside of PurleyOpenBoardPkg. You will need to move that to edk2-non-osi. I'm not sure exactly which driver that is, but I have a suspicion that it might make sense to add it to ASpeedGopBinPkg.

Thanks,
Nate

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Nate DeSimone
Sent: Tuesday, June 15, 2021 2:41 PM
To: KARPAGAVINAYAGAM, MANICKAVASAKAM <manickavasakamk@ami.com>; devel@edk2.groups.io
Cc: Oram, Isaac W <isaac.w.oram@intel.com>; Felixp@ami.com; DOPPALAPUDI, HARIKRISHNA <harikrishnad@ami.com>; Jha, Manish <manishj@ami.com>; Bobroff, Zachary <zacharyb@ami.com>; KARPAGAVINAYAGAM, MANICKAVASAKAM <manickavasakamk@ami.com>
Subject: Re: [edk2-devel] [edk2-platforms][PATCH 0/2] Support for TiogaPass Platform and Override generic PciBus Driver with

Hi Manic,

I looked over all of your changes. The code itself looks good. However, there is an issue with the copyright headers that you have placed on the top of many of the files included here. It appears that you added the following:

/** @file

Copyright (c) 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent

**/

//***********************************************************************
//* *
//* Copyright (c) 1985 - 2021, American Megatrends International LLC. *
//* *
//* All rights reserved. *
//* *
//* SPDX-License-Identifier: BSD-2-Clause-Patent *
//* *
//***********************************************************************

Note that the SPDX spec requires that there be only one copyright and license statement per file. The correct way to add your new attribution would be the following:

/** @file

Copyright (c) 2018, Intel Corporation. All rights reserved.<BR> Copyright (c) 2021, American Megatrends International LLC.
SPDX-License-Identifier: BSD-2-Clause-Patent

**/

There are also several files where you modified the file but did not add the new copyright notice. For example AmlOffsetTable.c, BoardAcpiDxeDsdt.c do not have the new copyright added. Please correct this and send a new patch series.

Thanks,
Nate

-----Original Message-----
From: manickavasakam karpagavinayagam <manickavasakamk@ami.com>
Sent: Thursday, June 10, 2021 4:50 PM
To: devel@edk2.groups.io
Cc: Oram, Isaac W <isaac.w.oram@intel.com>; Desimone, Nathaniel L <nathaniel.l.desimone@intel.com>; Felixp@ami.com; DOPPALAPUDI, HARIKRISHNA <harikrishnad@ami.com>; Jha, Manish <manishj@ami.com>; Bobroff, Zachary <zacharyb@ami.com>; KARPAGAVINAYAGAM, MANICKAVASAKAM <manickavasakamk@ami.com>
Subject: [edk2-platforms][PATCH 0/2] Support for TiogaPass Platform and Override generic PciBus Driver with

Add BoardTiogaPass packages to support TiogaPass Platform Overriden generic PciBus Driver with Platform specific instance of PciBus driver To skip SPI controller initialization during PCI enumeration to avoid SET variable assert issue during POST To skip executing a specific MLX card UEFI OPROM


manickavasakam karpagavinayagam (2):
PurleyOpenBoardPkg : Support for TiogaPass Platform
PurleyOpenBoardPkg : Override generic PciBus Driver with Platform
specific instance of PciBus driver.

.../Acpi/BoardAcpiDxe/AmlOffsetTable.c | 452 +-
.../Acpi/BoardAcpiDxe/BoardAcpiDxeDsdt.c | 2 +
.../BoardTiogaPass/CoreDxeInclude.dsc | 168 +
.../BoardTiogaPass/CoreUefiBootInclude.fdf | 82 +
.../BoardTiogaPass/GitEdk2MinTiogaPass.bat | 102 +
.../BasePlatformHookLib/BasePlatformHookLib.c | 397 ++
.../BasePlatformHookLib.inf | 46 +
.../BoardAcpiLib/DxeBoardAcpiTableLib.c | 45 +
.../BoardAcpiLib/DxeBoardAcpiTableLib.inf | 50 +
.../BoardAcpiLib/DxeTiogaPassAcpiTableLib.c | 62 +
.../BoardAcpiLib/SmmBoardAcpiEnableLib.c | 71 +
.../BoardAcpiLib/SmmBoardAcpiEnableLib.inf | 51 +
.../BoardAcpiLib/SmmSiliconAcpiEnableLib.c | 129 +
.../BoardAcpiLib/SmmTiogaPassAcpiEnableLib.c | 46 +
.../Library/BoardInitLib/AllLanesEparam.c | 53 +
.../Library/BoardInitLib/GpioTable.c | 305 +
.../Library/BoardInitLib/IioBifur.c | 79 +
.../BoardInitLib/PeiBoardInitPostMemLib.c | 55 +
.../BoardInitLib/PeiBoardInitPostMemLib.inf | 47 +
.../BoardInitLib/PeiBoardInitPreMemLib.c | 121 +
.../BoardInitLib/PeiBoardInitPreMemLib.inf | 79 +
.../Library/BoardInitLib/PeiTiogaPassDetect.c | 37 +
.../BoardInitLib/PeiTiogaPassInitLib.h | 27 +
.../BoardInitLib/PeiTiogaPassInitPostMemLib.c | 95 +
.../BoardInitLib/PeiTiogaPassInitPreMemLib.c | 647 ++
.../Library/BoardInitLib/UsbOC.c | 55 +
.../Library/PeiReportFvLib/PeiReportFvLib.c | 147 +
.../Library/PeiReportFvLib/PeiReportFvLib.inf | 60 +
.../BoardTiogaPass/OpRoms/uefi_2500_800.efi | Bin 0 -> 36928 bytes
.../BoardTiogaPass/OpenBoardPkg.dsc | 255 +
.../BoardTiogaPass/OpenBoardPkg.fdf | 610 ++
.../BoardTiogaPass/PlatformPkgBuildOption.dsc | 94 +
.../BoardTiogaPass/PlatformPkgConfig.dsc | 68 +
.../BoardTiogaPass/PlatformPkgPcd.dsc | 402 ++
.../BoardTiogaPass/StructureConfig.dsc | 6246 +++++++++++++++++
.../BoardTiogaPass/__init__.py | 0
.../PurleyOpenBoardPkg/BoardTiogaPass/bld.bat | 148 +
.../BoardTiogaPass/build_board.py | 204 +
.../BoardTiogaPass/build_config.cfg | 42 +
.../BoardTiogaPass/logo.txt | 10 +
.../BoardTiogaPass/postbuild.bat | 105 +
.../BoardTiogaPass/prebuild.bat | 221 +
.../Ipmi/Library/IpmiLibKcs/IpmiLibKcs.inf | 6 +-
.../IpmiPlatformHookLib.inf | 2 +-
.../Include/Guid/PchRcVariable.h | 5 +
.../Include/Guid/SetupVariable.h | 14 +-
.../Bus/Pci/PciBusDxe/ComponentName.c | 170 +
.../Bus/Pci/PciBusDxe/ComponentName.h | 146 +
.../MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c | 460 ++
.../MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h | 396 ++
.../Bus/Pci/PciBusDxe/PciBusDxe.inf | 112 +
.../Bus/Pci/PciBusDxe/PciBusDxe.uni | 16 +
.../Bus/Pci/PciBusDxe/PciBusDxeExtra.uni | 14 +
.../Bus/Pci/PciBusDxe/PciCommand.c | 267 +
.../Bus/Pci/PciBusDxe/PciCommand.h | 232 +
.../Bus/Pci/PciBusDxe/PciDeviceSupport.c | 1056 +++
.../Bus/Pci/PciBusDxe/PciDeviceSupport.h | 266 +
.../Bus/Pci/PciBusDxe/PciDriverOverride.c | 188 +
.../Bus/Pci/PciBusDxe/PciDriverOverride.h | 83 +
.../Bus/Pci/PciBusDxe/PciEnumerator.c | 2210 ++++++
.../Bus/Pci/PciBusDxe/PciEnumerator.h | 515 ++
.../Bus/Pci/PciBusDxe/PciEnumeratorSupport.c | 2884 ++++++++ .../Bus/Pci/PciBusDxe/PciEnumeratorSupport.h | 480 ++
.../Bus/Pci/PciBusDxe/PciHotPlugSupport.c | 484 ++
.../Bus/Pci/PciBusDxe/PciHotPlugSupport.h | 205 +
.../MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c | 2087 ++++++
.../MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.h | 660 ++
.../MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c | 1809 +++++
.../MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.h | 179 +
.../Bus/Pci/PciBusDxe/PciOptionRomSupport.c | 775 ++
.../Bus/Pci/PciBusDxe/PciOptionRomSupport.h | 136 +
.../Bus/Pci/PciBusDxe/PciPowerManagement.c | 82 +
.../Bus/Pci/PciBusDxe/PciPowerManagement.h | 28 +
.../Bus/Pci/PciBusDxe/PciResourceSupport.c | 2292 ++++++
.../Bus/Pci/PciBusDxe/PciResourceSupport.h | 456 ++
.../Bus/Pci/PciBusDxe/PciRomTable.c | 135 +
.../Bus/Pci/PciBusDxe/PciRomTable.h | 48 +
Platform/Intel/build.cfg | 1 +
Platform/Intel/build_bios.py | 2 +-
79 files changed, 30584 insertions(+), 232 deletions(-) create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/CoreDxeInclude.dsc
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/CoreUefiBootInclude.fdf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/GitEdk2MinTiogaPass.bat
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BasePlatformHookLib/BasePlatformHookLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BasePlatformHookLib/BasePlatformHookLib.inf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardAcpiLib/DxeBoardAcpiTableLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardAcpiLib/DxeBoardAcpiTableLib.inf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardAcpiLib/DxeTiogaPassAcpiTableLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardAcpiLib/SmmBoardAcpiEnableLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardAcpiLib/SmmBoardAcpiEnableLib.inf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardAcpiLib/SmmSiliconAcpiEnableLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardAcpiLib/SmmTiogaPassAcpiEnableLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/AllLanesEparam.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/GpioTable.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/IioBifur.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/PeiBoardInitPostMemLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/PeiBoardInitPostMemLib.inf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/PeiBoardInitPreMemLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/PeiBoardInitPreMemLib.inf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/PeiTiogaPassDetect.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/PeiTiogaPassInitLib.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/PeiTiogaPassInitPostMemLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/PeiTiogaPassInitPreMemLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/BoardInitLib/UsbOC.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/PeiReportFvLib/PeiReportFvLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/Library/PeiReportFvLib/PeiReportFvLib.inf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/OpRoms/uefi_2500_800.efi
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/OpenBoardPkg.dsc
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/OpenBoardPkg.fdf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/PlatformPkgBuildOption.dsc
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/PlatformPkgConfig.dsc
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/PlatformPkgPcd.dsc
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/StructureConfig.dsc
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/__init__.py
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/bld.bat
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/build_board.py
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/build_config.cfg
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/logo.txt
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/postbuild.bat
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/BoardTiogaPass/prebuild.bat
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.uni
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxeExtra.uni
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.h
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.c
create mode 100644 Platform/Intel/PurleyOpenBoardPkg/Override/edk2/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.h

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


Re: [PATCH] UefiPayloadPkg/UefiPayloadEntry: Improve bootloader memrange parsing

Guo Dong
 

Could you provide more info on the issues in fixed by this patch?
There is a UEFI payload patch (under code review) to support the bootloader to provide a HOB
on the PCI resources, this way the UEFI payload doesn't need collect resources again by parsing
all the PCI devices. Not sure if that patch (UefiPayloadPkg: UefiPayload retrieve PCI root bridge
from Guid Hob) could avoid the issues.

In this patch, as it mentioned some information (system memory or MMIO) is missing in the
bootloader E820 style table. Guessing the TOLUD might work in most cases, but may fail since
the assumptions.

I saw this patch fixed the memory type for ACPI memory. I think we could have this fix if the
TOLUD guessing could be avoided.

Thanks,
Guo

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Patrick
Rudolph
Sent: Tuesday, June 15, 2021 6:23 AM
To: devel@edk2.groups.io
Cc: Ma, Maurice <maurice.ma@intel.com>; Dong, Guo
<guo.dong@intel.com>; You, Benjamin <benjamin.you@intel.com>
Subject: [edk2-devel] [PATCH] UefiPayloadPkg/UefiPayloadEntry: Improve
bootloader memrange parsing

Currently several DXE crash due to invalid memory resource settings.
coreboot and slimbootloader provide an e820 compatible memory map,
which doesn't work well with EDK2 as the e820 spec is missing MMIO regions.
In e820 'reserved' could either mean "DRAM used by boot firmware" or
"MMIO
in use and not detectable by OS".

Guess Top of lower usable DRAM (TOLUD) by walking memory ranges and
then
mark everything reserved below TOLUD as DRAM and everything reserved
above
TOLUD as MMIO.

This fixes several assertions seen in PciHostBridgeDxe.

Signed-off-by: Patrick Rudolph <patrick.rudolph@9elements.com>
---
.../UefiPayloadEntry/UefiPayloadEntry.c | 187 +++++++++++++++++-
.../UefiPayloadEntry/UefiPayloadEntry.h | 10 +
2 files changed, 194 insertions(+), 3 deletions(-)

diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
index 805f5448d9..d20e1a0862 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
+++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
@@ -7,10 +7,162 @@


#include "UefiPayloadEntry.h"



+STATIC UINT32 TopOfLowerUsableDram = 0;

+

/**

Callback function to build resource descriptor HOB



This function build a HOB based on the memory map entry info.

+ It creates only EFI_RESOURCE_MEMORY_MAPPED_IO and
EFI_RESOURCE_MEMORY_RESERVED

+ resources.

+

+ @param MemoryMapEntry Memory map entry info got from
bootloader.

+ @param Params A pointer to ACPI_BOARD_INFO.

+

+ @retval RETURN_SUCCESS Successfully build a HOB.

+ @retval EFI_INVALID_PARAMETER Invalid parameter provided.

+**/

+EFI_STATUS

+MemInfoCallbackMMIO (

+ IN MEMROY_MAP_ENTRY *MemoryMapEntry,

+ IN VOID *Params

+ )

+{

+ EFI_PHYSICAL_ADDRESS Base;

+ EFI_RESOURCE_TYPE Type;

+ UINT64 Size;

+ EFI_RESOURCE_ATTRIBUTE_TYPE Attribue;

+ ACPI_BOARD_INFO *AcpiBoardInfo;

+

+ AcpiBoardInfo = (ACPI_BOARD_INFO *)Params;

+ if (AcpiBoardInfo == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ //

+ // Skip types already handled in MemInfoCallback

+ //

+ if (MemoryMapEntry->Type == E820_RAM || MemoryMapEntry->Type ==
E820_ACPI) {

+ return RETURN_SUCCESS;

+ }

+

+ if (MemoryMapEntry->Base == AcpiBoardInfo->PcieBaseAddress) {

+ //

+ // MMCONF is always MMIO

+ //

+ Type = EFI_RESOURCE_MEMORY_MAPPED_IO;

+ } else if (MemoryMapEntry->Base < TopOfLowerUsableDram) {

+ //

+ // It's in DRAM and thus must be reserved

+ //

+ Type = EFI_RESOURCE_MEMORY_RESERVED;

+ } else if (MemoryMapEntry->Base < 0x100000000ULL &&

+ MemoryMapEntry->Base >= TopOfLowerUsableDram) {

+ //

+ // It's not in DRAM, must be MMIO

+ //

+ Type = EFI_RESOURCE_MEMORY_MAPPED_IO;

+ } else {

+ Type = EFI_RESOURCE_MEMORY_RESERVED;

+ }

+

+ Base = MemoryMapEntry->Base;

+ Size = MemoryMapEntry->Size;

+

+ Attribue = EFI_RESOURCE_ATTRIBUTE_PRESENT |

+ EFI_RESOURCE_ATTRIBUTE_INITIALIZED |

+ EFI_RESOURCE_ATTRIBUTE_TESTED |

+ EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE |

+ EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE |

+ EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |

+ EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE;

+

+ BuildResourceDescriptorHob (Type, Attribue,
(EFI_PHYSICAL_ADDRESS)Base, Size);

+ DEBUG ((DEBUG_INFO , "buildhob: base = 0x%lx, size = 0x%lx, type =
0x%x\n", Base, Size, Type));

+

+ if (MemoryMapEntry->Type == E820_NVS) {

+ BuildMemoryAllocationHob (Base, Size, EfiACPIMemoryNVS);

+ } else if (MemoryMapEntry->Type == E820_UNUSABLE ||

+ MemoryMapEntry->Type == E820_DISABLED) {

+ BuildMemoryAllocationHob (Base, Size, EfiUnusableMemory);

+ } else if (MemoryMapEntry->Type == E820_PMEM) {

+ BuildMemoryAllocationHob (Base, Size, EfiPersistentMemory);

+ }

+

+ return RETURN_SUCCESS;

+}

+

+

+/**

+ Callback function to find TOLUD (Top of Lower Usable DRAM)

+

+ Estimate where TOLUD (Top of Lower Usable DRAM) resides. The exact
position

+ would require platform specific code.

+

+ @param MemoryMapEntry Memory map entry info got from
bootloader.

+ @param Params Not used for now.

+

+ @retval RETURN_SUCCESS Successfully updated
TopOfLowerUsableDram.

+**/

+EFI_STATUS

+FindToludCallback (

+ IN MEMROY_MAP_ENTRY *MemoryMapEntry,

+ IN VOID *Params

+ )

+{

+ //

+ // This code assumes that the memory map on this x86 machine below
4GiB is continous

+ // until TOLUD. In addition it assumes that the bootloader provided
memory tables have

+ // no "holes" and thus the first memory range not covered by e820 marks
the end of

+ // usable DRAM. In addition it's assumed that every reserved memory
region touching

+ // usable RAM is also covering DRAM, everything else that is marked
reserved thus must be

+ // MMIO not detectable by bootloader/OS

+ //

+

+ //

+ // Skip memory types not RAM or reserved

+ //

+ if (MemoryMapEntry->Type == E820_NVS || MemoryMapEntry->Type ==
E820_UNUSABLE ||

+ MemoryMapEntry->Type == E820_DISABLED || MemoryMapEntry->Type
== E820_PMEM) {

+ return RETURN_SUCCESS;

+ }

+

+ //

+ // Skip resources above 4GiB

+ //

+ if (MemoryMapEntry->Base >= 0x100000000ULL) {

+ return RETURN_SUCCESS;

+ }

+

+ if ((MemoryMapEntry->Type == E820_RAM) ||

+ (MemoryMapEntry->Type == E820_ACPI)) {

+ //

+ // It's usable DRAM. Update TOLUD.

+ //

+ if (TopOfLowerUsableDram < (MemoryMapEntry->Base +
MemoryMapEntry->Size)) {

+ TopOfLowerUsableDram = MemoryMapEntry->Base +
MemoryMapEntry->Size;

+ }

+ } else {

+ //

+ // It might be reserved DRAM or MMIO.

+ //

+ // If it touches usable DRAM at Base assume it's DRAM as well,

+ // as it could be bootloader installed tables, TSEG, GTT, ...

+ //

+ if (TopOfLowerUsableDram == MemoryMapEntry->Base) {

+ TopOfLowerUsableDram = MemoryMapEntry->Base +
MemoryMapEntry->Size;

+ }

+ }

+

+ return RETURN_SUCCESS;

+}

+

+

+/**

+ Callback function to build resource descriptor HOB

+

+ This function build a HOB based on the memory map entry info.

+ Only add EFI_RESOURCE_SYSTEM_MEMORY.



@param MemoryMapEntry Memory map entry info got from
bootloader.

@param Params Not used for now.

@@ -28,7 +180,15 @@ MemInfoCallback (
UINT64 Size;

EFI_RESOURCE_ATTRIBUTE_TYPE Attribue;



- Type = (MemoryMapEntry->Type == 1) ?
EFI_RESOURCE_SYSTEM_MEMORY : EFI_RESOURCE_MEMORY_RESERVED;

+ //

+ // Skip everything not known to be usable DRAM.

+ // It will be added later.

+ //

+ if (MemoryMapEntry->Type != E820_RAM && MemoryMapEntry->Type !=
E820_ACPI) {

+ return RETURN_SUCCESS;

+ }

+

+ Type = EFI_RESOURCE_SYSTEM_MEMORY;

Base = MemoryMapEntry->Base;

Size = MemoryMapEntry->Size;



@@ -40,7 +200,7 @@ MemInfoCallback (
EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |

EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE;



- if (Base >= BASE_4GB ) {

+ if (Base >= BASE_4GB) {

// Remove tested attribute to avoid DXE core to dispatch driver to memory
above 4GB

Attribue &= ~EFI_RESOURCE_ATTRIBUTE_TESTED;

}

@@ -48,6 +208,10 @@ MemInfoCallback (
BuildResourceDescriptorHob (Type, Attribue,
(EFI_PHYSICAL_ADDRESS)Base, Size);

DEBUG ((DEBUG_INFO , "buildhob: base = 0x%lx, size = 0x%lx, type =
0x%x\n", Base, Size, Type));



+ if (MemoryMapEntry->Type == E820_ACPI) {

+ BuildMemoryAllocationHob (Base, Size, EfiACPIReclaimMemory);

+ }

+

return RETURN_SUCCESS;

}



@@ -236,7 +400,16 @@ BuildHobFromBl (
EFI_PEI_GRAPHICS_DEVICE_INFO_HOB *NewGfxDeviceInfo;



//

- // Parse memory info and build memory HOBs

+ // First find TOLUD

+ //

+ Status = ParseMemoryInfo (FindToludCallback, NULL);

+ if (EFI_ERROR(Status)) {

+ return Status;

+ }

+ DEBUG ((DEBUG_INFO , "Assuming TOLUD = 0x%x\n",
TopOfLowerUsableDram));

+

+ //

+ // Parse memory info and build memory HOBs for Usable RAM

//

Status = ParseMemoryInfo (MemInfoCallback, NULL);

if (EFI_ERROR(Status)) {

@@ -289,6 +462,14 @@ BuildHobFromBl (
DEBUG ((DEBUG_INFO, "Create acpi board info guid hob\n"));

}



+ //

+ // Parse memory info and build memory HOBs for reserved DRAM and
MMIO

+ //

+ Status = ParseMemoryInfo (MemInfoCallbackMMIO, &AcpiBoardInfo);

+ if (EFI_ERROR(Status)) {

+ return Status;

+ }

+

//

// Parse platform specific information.

//

diff --git a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
index 2c84d6ed53..35ea23d202 100644
--- a/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
+++ b/UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
@@ -38,6 +38,16 @@
#define GET_OCCUPIED_SIZE(ActualSize, Alignment) \

((ActualSize) + (((Alignment) - ((ActualSize) & ((Alignment) - 1))) &
((Alignment) - 1)))



+

+#define E820_RAM 1

+#define E820_RESERVED 2

+#define E820_ACPI 3

+#define E820_NVS 4

+#define E820_UNUSABLE 5

+#define E820_DISABLED 6

+#define E820_PMEM 7

+#define E820_UNDEFINED 8

+

/**

Auto-generated function that calls the library constructors for all of the
module's

dependent libraries.

--
2.30.2



-=-=-=-=-=-=
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#76517): https://edk2.groups.io/g/devel/message/76517
Mute This Topic: https://groups.io/mt/83555387/1781375
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [guo.dong@intel.com]
-=-=-=-=-=-=

6141 - 6160 of 82648