From 95ef765839a8d0de52095e3dec3584fc347b94b2 Mon Sep 17 00:00:00 2001 From: BruceX Wang Date: Wed, 26 Apr 2023 14:32:01 +0800 Subject: UefiPayloadPkg: Clang dependency removal REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4426 Use Python to replace llvm-objcopy in UniversalPayloadBuild.py. 1. AddSection32() and AddSection64(): Make a section named
with the contents of . 2. RemoveSection32() and RemoveSection64(): Remove
. 3. ReplaceFv (): remove the section before add the section if the file exists. Cc: Guo Dong Cc: Ray Ni Cc: Sean Rhodes Cc: James Lu Signed-off-by: BruceX Wang Reviewed-by: Gua Guo --- UefiPayloadPkg/Tools/ElfFv.py | 809 ++++++++++++++++++++++++++++++++ UefiPayloadPkg/Tools/__init__.py | 6 + UefiPayloadPkg/UefiPayloadPkg.ci.yaml | 1 + UefiPayloadPkg/UniversalPayloadBuild.py | 232 +++++---- 4 files changed, 923 insertions(+), 125 deletions(-) create mode 100644 UefiPayloadPkg/Tools/ElfFv.py create mode 100644 UefiPayloadPkg/Tools/__init__.py (limited to 'UefiPayloadPkg') diff --git a/UefiPayloadPkg/Tools/ElfFv.py b/UefiPayloadPkg/Tools/ElfFv.py new file mode 100644 index 0000000..a3d5bf0 --- /dev/null +++ b/UefiPayloadPkg/Tools/ElfFv.py @@ -0,0 +1,809 @@ +## @file +# OBJCOPY parser, it's used to replace FV +# +# Copyright (c) 2023, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import argparse +from ctypes import * +import struct + +class ElfSectionHeader64: + def __init__(self, sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link, sh_info, sh_addralign, sh_entsize): + self.sh_name = sh_name + self.sh_type = sh_type + self.sh_flags = sh_flags + self.sh_addr = sh_addr + self.sh_offset = sh_offset + self.sh_size = sh_size + self.sh_link = sh_link + self.sh_info = sh_info + self.sh_addralign = sh_addralign + self.sh_entsize = sh_entsize + + def pack(self): + return struct.pack(' RemoveNameOffset): + unpacked_header.sh_name -= RemoveNameOffset + # Modify size of name string section entry in section entry. + if (Index == StringIndexNumber): + unpacked_header.sh_size -= len (SectionName) + # added section + else : + if (Index == StringIndexNumber): + unpacked_header.sh_size += len (SectionName) + NewSHentry = ElfSectionHeader64 ( + unpacked_header.sh_name, + unpacked_header.sh_type, + unpacked_header.sh_flags, + unpacked_header.sh_addr, + unpacked_header.sh_offset, + unpacked_header.sh_size, + unpacked_header.sh_link, + unpacked_header.sh_info, + unpacked_header.sh_addralign, + unpacked_header.sh_entsize).pack() + return NewSHentry + +def AddSectionHeader32(SHentry, NewUPLEntrylen, SectionHeaderEntrySize, Index, RemoveNameOffset, SectionName, StringIndexNumber): + SHentry = bytearray(SHentry) + unpacked_header = ElfSectionHeader32.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + if (Index != 0): + NewSHentry = SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)] + unpacked_header.sh_offset = NewUPLEntrylen + # Modify offset of name in section entry + # if RemoveNameOffset != 0 that is remove function. + if (RemoveNameOffset != 0): + if (unpacked_header.sh_name > RemoveNameOffset): + unpacked_header.sh_name -= RemoveNameOffset + # Modify size of name string section entry in section entry. + if (Index == StringIndexNumber): + unpacked_header.sh_size -= len (SectionName) + # added section + else : + if (Index == StringIndexNumber): + unpacked_header.sh_size += len (SectionName) + NewSHentry = ElfSectionHeader32 ( + unpacked_header.sh_name, + unpacked_header.sh_type, + unpacked_header.sh_flags, + unpacked_header.sh_addr, + unpacked_header.sh_offset, + unpacked_header.sh_size, + unpacked_header.sh_link, + unpacked_header.sh_info, + unpacked_header.sh_addralign, + unpacked_header.sh_entsize).pack() + return NewSHentry + +def ModifyPHSegmentOffset64(NewUPLEntry, ElfHeaderOffset, PHSegmentName): + # Modify offset and address of program header tables. + elf_header = ElfHeader64(NewUPLEntry[:64]) + SHentry = NewUPLEntry[ElfHeaderOffset:] + # Elf program header tables start from 0x40 in 64-bits objects + PHentry = NewUPLEntry[64: 64 + (elf_header.e_phnum * elf_header.e_phentsize)] + PHdrs = [] + SHdrs = [] + for i in range(elf_header.e_shnum): + SHData = SHentry[(i * elf_header.e_shentsize): (i * elf_header.e_shentsize) + elf_header.e_shentsize] + unpacked_SectionHeader = ElfSectionHeader64.unpack(SHData) + SHdrs.append(unpacked_SectionHeader) + for i in range(elf_header.e_phnum): + PHData = PHentry[(i * elf_header.e_phentsize): (i * elf_header.e_phentsize) + elf_header.e_phentsize] + unpacked_ProgramHeader = Elf64_Phdr(PHData) + PHdrs.append(unpacked_ProgramHeader) + if (PHSegmentName == '.text'): + PHdrs[0].p_offset = SHdrs[1].sh_offset + PHdrs[0].p_paddr = SHdrs[1].sh_addr + PHdrs[4].p_offset = SHdrs[1].sh_offset + PHdrs[4].p_paddr = SHdrs[1].sh_addr + elif (PHSegmentName == '.dynamic'): + PHdrs[1].p_offset = SHdrs[2].sh_offset + PHdrs[1].p_paddr = SHdrs[2].sh_addr + PHdrs[3].p_offset = SHdrs[2].sh_offset + PHdrs[3].p_paddr = SHdrs[2].sh_addr + elif (PHSegmentName == '.data'): + PHdrs[2].p_offset = SHdrs[3].sh_offset + PHdrs[2].p_paddr = SHdrs[3].sh_addr + packed_PHData = b'' + for phdr in PHdrs: + packed_PHData += phdr.pack() + NewUPLEntry = bytearray(NewUPLEntry) + NewUPLEntry[64: 64 + (elf_header.e_phnum * elf_header.e_phentsize)] = packed_PHData + return NewUPLEntry + +def ModifyPHSegmentOffset32(NewUPLEntry, ElfHeaderOffset, PHSegmentName): + # Modify offset and address of program header tables. + # Elf header is stored at 0x0-0x34 in 32-bits objects + elf_header = ElfHeader32(NewUPLEntry[:52]) + SHentry = NewUPLEntry[ElfHeaderOffset:] + # Elf program header tables start from 0x34 in 32-bits objects + PHentry = NewUPLEntry[52: 52 + (elf_header.e_phnum * elf_header.e_phentsize)] + PHdrs = [] + SHdrs = [] + for i in range(elf_header.e_shnum): + SHData = SHentry[(i * elf_header.e_shentsize): (i * elf_header.e_shentsize) + elf_header.e_shentsize] + unpacked_SectionHeader = ElfSectionHeader32.unpack(SHData) + SHdrs.append(unpacked_SectionHeader) + for i in range(elf_header.e_phnum): + PHData = PHentry[(i * elf_header.e_phentsize): (i * elf_header.e_phentsize) + elf_header.e_phentsize] + unpacked_ProgramHeader = Elf32_Phdr(PHData) + PHdrs.append(unpacked_ProgramHeader) + if (PHSegmentName == '.text'): + PHdrs[0].p_offset = SHdrs[1].sh_offset + PHdrs[0].p_paddr = SHdrs[1].sh_addr + PHdrs[0].p_vaddr = SHdrs[1].sh_addr + PHdrs[2].p_offset = SHdrs[1].sh_offset + PHdrs[2].p_paddr = SHdrs[1].sh_addr + PHdrs[0].p_vaddr = SHdrs[1].sh_addr + elif (PHSegmentName == '.data'): + PHdrs[1].p_offset = SHdrs[2].sh_offset + PHdrs[1].p_paddr = SHdrs[2].sh_addr + PHdrs[1].p_vaddr = SHdrs[2].sh_addr + packed_PHData = b'' + for phdr in PHdrs: + packed_PHData += phdr.pack() + NewUPLEntry = bytearray(NewUPLEntry) + NewUPLEntry[52: 52 + (elf_header.e_phnum * elf_header.e_phentsize)] = packed_PHData + return NewUPLEntry + +def RemoveSection64(UniversalPayloadEntry, RemoveSectionName): + # If elf is 64-bit objects. + # Get offsets as follows: + # 1. Section name which will remove in section name string. + # 2. Section which will remove. + # 3. Section header which will remove. + with open(UniversalPayloadEntry,'rb') as f: + UPLEntry = f.read() + RemoveSectionNameOffset, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntry, RemoveSectionName) + if (RemoveSectionNameOffset == -1): + raise argparse.ArgumentTypeError ('Section: {} not found.'.format (RemoveSectionNameOffset)) + # Read section header entry + SHentry = UPLEntry[ElfHeaderOffset:] + # find deleted fv section offset. + # Elf header is stored at 0x0-0x40 in 64-bits objects + elf_header = ElfHeader64(UPLEntry[:64]) + Counter = 0 + RemoveIndex = 0 + RemoveNameOffset = 0 + for Index in range(0, elf_header.e_shnum): + # Read Index of section header. + unpacked_SectionHeader = ElfSectionHeader64.unpack(SHentry[(Index * elf_header.e_shentsize):((Index * elf_header.e_shentsize) + elf_header.e_shentsize)]) + # Find offset of section name which is removed. + if (unpacked_SectionHeader.sh_name == RemoveSectionNameOffset): + RemoveIndex = Counter + Counter += 1 + else: + Counter += 1 + # Elf header is recombined. + # Elf header and program header table in front of first section are reserved. + # Elf header size is 0x40 with 64-bit object. + ElfHeaderSize = 64 + ElfHandPH = ElfHeaderSize + (elf_header.e_phnum * elf_header.e_phentsize) + NewUPLEntry = UPLEntry[:ElfHandPH] + # Keep Section header and program header table, RemoveSection64() only recombined section and section header. + NewUPLEntry = bytearray(NewUPLEntry) + # Sections is recombined. + # 1. name of deleted section is removed in name string section. + # 2. deleted section is removed in dll file. + # 3. re-align sections before and after deleted section. + NewUPLEntrylen = [] + for Index in range(0, (SectionHeaderEntryNumber)): + unpacked_SectionHeader = ElfSectionHeader64.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntrylen.append(len(NewUPLEntry)) + if (Index == 0): + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + if (SectionHeaderEntryNumber > 2): + unpacked_NextSectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section in front of removed section + elif (Index + 1 == RemoveIndex): + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Read section address alignment + # If section that will be removed in .dll is not first and last one . + # Address alignment, section will align with alignment of section after deleted section. + # Check next and the section after next are not end of section. + if ((Index + 2) < (SectionHeaderEntryNumber - 1)): + unpacked_Next2SectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 2) * SectionHeaderEntrySize):(((Index + 2) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_Next2SectionHeader.sh_addralign) + else: + # It is align 8 bytes if next section or the section after next is last one. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + # section is Deleted section + elif (Index == RemoveIndex): + # Don't add removed section to elf. + # Find offset of section name. + RemoveNameOffset = unpacked_SectionHeader.sh_name + # section is name string section. + elif (Index == StringIndexNumber): + # StringIndex is String Index section + StringIndex = UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Remove name of removed section in name string section. + # Section header isn't exist if RemoveSectionNameOffset equal to -1. + StringIndex = bytearray(StringIndex) + RemoveSectionName = bytearray(RemoveSectionName, encoding='utf-8') + RemoveSectionName = RemoveSectionName + bytes('\0', encoding='utf-8') + StringIndex = StringIndex.replace(RemoveSectionName,b'') + NewUPLEntry += StringIndex + # other sections. + else: + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + if (Index < (SectionHeaderEntryNumber - 1)): + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + else: + # If section is last one. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + SectionHeaderOffset = len(NewUPLEntry) + # Add section header + for Number in range(0, (SectionHeaderEntryNumber)): + if (Number != RemoveIndex): + NewSHentry = AddSectionHeader64(SHentry, NewUPLEntrylen[Number], SectionHeaderEntrySize, Number, RemoveNameOffset, RemoveSectionName, StringIndexNumber) + NewUPLEntry += NewSHentry + # Modify number of sections and offset of section header in Elf header. + elf_header.e_shoff = SectionHeaderOffset + elf_header.e_shnum -= 1 + NewUPLEntry = elf_header.pack() + NewUPLEntry[64:] + # write to Elf. + with open(UniversalPayloadEntry,'wb') as f: + f.write(NewUPLEntry) + +def RemoveSection32(UniversalPayloadEntry, RemoveSectionName): + # If elf is 32-bit objects. + # Get offsets as follows: + # 1. Section name which will remove in section name string. + # 2. Section which will remove. + # 3. Section header which will remove. + with open(UniversalPayloadEntry,'rb') as f: + UPLEntry = f.read() + RemoveSectionNameOffset, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, EI_CLASS = FindSection(UPLEntry, RemoveSectionName) + if (RemoveSectionNameOffset == -1): + raise argparse.ArgumentTypeError ('Section: {} not found.'.format (RemoveSectionNameOffset)) + # Read section header entry + SHentry = UPLEntry[ElfHeaderOffset:] + # find deleted fv section offset. + # Elf header is stored at 0x0-0x34 in 32-bits objects + elf_header = ElfHeader32(UPLEntry[:52]) + Counter = 0 + RemoveIndex = 0 + RemoveNameOffset = 0 + for Index in range(0, elf_header.e_shnum): + # Read Index of section header. + unpacked_SectionHeader = ElfSectionHeader32.unpack(SHentry[(Index * elf_header.e_shentsize):((Index * elf_header.e_shentsize) + elf_header.e_shentsize)]) + # Find offset of section name which is removed. + if (unpacked_SectionHeader.sh_name == RemoveSectionNameOffset): + RemoveIndex = Counter + Counter += 1 + else: + Counter += 1 + # Elf header is recombined. + # Elf header and program header table in front of first section are reserved. + # Elf header size is 0x34 with 32-bit object. + ElfHeaderSize = 52 + ElfHandPH = ElfHeaderSize + (elf_header.e_phnum * elf_header.e_phentsize) + NewUPLEntry = UPLEntry[:ElfHandPH] + # Keep Section header and program header table, RemoveSection32() only recombined section and section header. + NewUPLEntry = bytearray(NewUPLEntry) + # Sections is recombined. + # 1. name of deleted section is removed in name string section. + # 2. deleted section is removed in dll file. + # 3. re-align sections before and after deleted section. + NewUPLEntrylen = [] + for Index in range(0, (SectionHeaderEntryNumber)): + unpacked_SectionHeader = ElfSectionHeader32.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntrylen.append(len(NewUPLEntry)) + if (Index == 0): + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + if (SectionHeaderEntryNumber > 2): + unpacked_NextSectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section in front of removed section + elif (Index + 1 == RemoveIndex): + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Read section address alignment + # If section that will be removed in .dll is not first and last one . + # Address alignment, section will align with alignment of section after deleted section. + # Check next and the section after next are not end of section. + if ((Index + 2) < (SectionHeaderEntryNumber - 1)): + unpacked_Next2SectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 2) * SectionHeaderEntrySize):(((Index + 2) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_Next2SectionHeader.sh_addralign) + else: + # It is align 8 bytes if next section or the section after next is last one. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + # section is Deleted section + elif (Index == RemoveIndex): + # Don't add removed section to elf. + # Find offset of section name. + RemoveNameOffset = unpacked_SectionHeader.sh_name + # section is name string section. + elif (Index == StringIndexNumber): + # StringIndex is String Index section + StringIndex = UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Remove name of removed section in name string section. + # Section header isn't exist if RemoveSectionNameOffset equal to -1. + StringIndex = bytearray(StringIndex) + RemoveSectionName = bytearray(RemoveSectionName, encoding='utf-8') + RemoveSectionName = RemoveSectionName + bytes('\0', encoding='utf-8') + StringIndex = StringIndex.replace(RemoveSectionName,b'') + NewUPLEntry += StringIndex + # other sections. + else: + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + if (Index < (SectionHeaderEntryNumber - 1)): + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + else: + # If section is last one. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + SectionHeaderOffset = len(NewUPLEntry) + # Add section header + for Number in range(0, (SectionHeaderEntryNumber)): + if (Number != RemoveIndex): + NewSHentry = AddSectionHeader32(SHentry, NewUPLEntrylen[Number], SectionHeaderEntrySize, Number, RemoveNameOffset, RemoveSectionName, StringIndexNumber) + NewUPLEntry += NewSHentry + # Modify number of sections and offset of section header in Elf header. + elf_header.e_shoff = SectionHeaderOffset + elf_header.e_shnum -= 1 + NewUPLEntry = elf_header.pack() + NewUPLEntry[52:] + # write to Elf. + with open(UniversalPayloadEntry,'wb') as f: + f.write(NewUPLEntry) + +def AddSection64(UniversalPayloadEntry, AddSectionName, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, StringIndexNumber, FileBinary, Alignment): + with open(UniversalPayloadEntry,'rb+') as f: + UPLEntry = f.read() + fFileBinary = open(FileBinary, 'rb') + Binary_File = fFileBinary.read() + ElfHeaderOffset, SectionHeaderEntryNumber, StringIndexNumber, _, _, SectionHeaderEntrySize, _, _ = ElfHeaderParser(UPLEntry) + # Read section header entry + SHentry = UPLEntry[ElfHeaderOffset:] + # Elf header is recombined. + # Elf header and program header table in front of first section are reserved. + # Elf header is stored at 0x0-0x40 in 64-bits objects + elf_header = ElfHeader64(UPLEntry[:64]) + # Elf header size is 0x40 with 64-bit object. + ElfHeaderSize = 64 + ElfHandPH = ElfHeaderSize + (elf_header.e_phnum * elf_header.e_phentsize) + NewUPLEntry = UPLEntry[:ElfHandPH] + # Keep Section header and program header table, AddSection64() only recombined section and section header. + NewUPLEntry = bytearray(NewUPLEntry) + # Sections is recombined. + # 1. name of added section is added in name string section. + # 2. added section is added in dll file. + # 3. re-align sections before and after added section. + NewUPLEntrylen = [] + StringIndexValue = 0 + for Index in range(0, SectionHeaderEntryNumber): + NewUPLEntrylen.append(len(NewUPLEntry)) + unpacked_SectionHeader = ElfSectionHeader64.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + # Sections is recombined. + if (Index == 0): + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + if (SectionHeaderEntryNumber > 2): + unpacked_NextSectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section is last one. + elif (Index == (SectionHeaderEntryNumber - 1)): + # Add new section at the end. + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + NewUPLEntry = SectionAlignment(NewUPLEntry, Alignment) + LastUPLEntrylen = len(NewUPLEntry) + NewUPLEntry += Binary_File + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + # section is name string section. + elif (Index == StringIndexNumber): + # StringIndex is String Index section + StringIndex = UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Read name of added Section after StringIndex is transform into string. + StringIndex = bytearray(StringIndex) + StringIndexValue = len(StringIndex) + AddSectionName = bytearray(AddSectionName, encoding='utf-8') + bytes('\0', encoding='utf-8') + StringIndex += AddSectionName + NewUPLEntry += StringIndex + # section after name string section but not last one. + elif ((Index > StringIndexNumber) and (Index < (SectionHeaderEntryNumber - 1))): + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + unpacked_NextSectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section before name string section. + else: + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + if (Index < (SectionHeaderEntryNumber - 1)): + unpacked_NextSectionHeader = ElfSectionHeader64.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + SectionHeaderOffset = len(NewUPLEntry) + RemoveNameOffset = 0 + # Add section header + for Number in range(0, (SectionHeaderEntryNumber)): + NewSHentry = AddSectionHeader64(SHentry, NewUPLEntrylen[Number], SectionHeaderEntrySize, Number, RemoveNameOffset, AddSectionName, StringIndexNumber) + NewUPLEntry += NewSHentry + NewUPLEntry += bytearray(AddNewSectionEntry64(LastUPLEntrylen, StringIndexValue, len(Binary_File), Alignment)) + # Modify number of sections and offset of section header in Elf header. + # Modify offset in in Elf header. + elf_header.e_shoff = SectionHeaderOffset + elf_header.e_shnum += 1 + elf_header = elf_header.pack() + UPLEntryBin = elf_header + NewUPLEntry[64:] + # Modify offsets and address of program header table in elf. + PHSegmentName = '.text' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset64(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + # Modify offsets and address of program header table in elf. + PHSegmentName = '.dynamic' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset64(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + # Modify offsets and address of program header table in elf. + PHSegmentName = '.data' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset64(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + fFileBinary.close() + return UPLEntryBin + +def AddSection32(UniversalPayloadEntry, AddSectionName, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, StringIndexNumber, FileBinary, Alignment): + with open(UniversalPayloadEntry,'rb+') as f: + # Read Elf and binary which will be write to elf. + UPLEntry = f.read() + fFileBinary = open(FileBinary, 'rb') + Binary_File = fFileBinary.read() + ElfHeaderOffset, SectionHeaderEntryNumber, StringIndexNumber, _, _, SectionHeaderEntrySize, _, _ = ElfHeaderParser(UPLEntry) + # Read section header entry + SHentry = UPLEntry[ElfHeaderOffset:] + # Elf header is recombined. + # Elf header and program header table in front of first section are reserved. + # Elf header is stored at 0x0-0x34 in 32-bits objects + elf_header = ElfHeader32(UPLEntry[:52]) + # Elf header size is 0x34 with 32-bit object. + ElfHeaderSize = 52 + ElfHandPH = ElfHeaderSize + (elf_header.e_phnum * elf_header.e_phentsize) + NewUPLEntry = UPLEntry[:ElfHandPH] + # Keep Section header and program header table, AddSection64() only recombined section and section header. + NewUPLEntry = bytearray(NewUPLEntry) + # Sections is recombined. + # 1. name of added section is added in name string section. + # 2. added section is added in dll file. + # 3. re-align sections before and after added section. + NewUPLEntrylen = [] + StringIndexValue = 0 + for Index in range(0, SectionHeaderEntryNumber): + NewUPLEntrylen.append(len(NewUPLEntry)) + unpacked_SectionHeader = ElfSectionHeader32.unpack(SHentry[(Index * SectionHeaderEntrySize):((Index * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + # Sections is recombined. + if (Index == 0): + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + if (SectionHeaderEntryNumber > 2): + unpacked_NextSectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section is last one. + elif (Index == (SectionHeaderEntryNumber - 1)): + # Add new section at the end. + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + NewUPLEntry = SectionAlignment(NewUPLEntry, Alignment) + LastUPLEntrylen = len(NewUPLEntry) + NewUPLEntry += Binary_File + # Address alignment, section will align with alignment of next section. + AlignmentIndex = 8 + NewUPLEntry = SectionAlignment(NewUPLEntry, AlignmentIndex) + # section is name string section. + elif (Index == StringIndexNumber): + # StringIndex is String Index section + StringIndex = UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Read name of added Section after StringIndex is transform into string. + StringIndex = bytearray(StringIndex) + StringIndexValue = len(StringIndex) + AddSectionName = bytearray(AddSectionName, encoding='utf-8') + bytes('\0', encoding='utf-8') + StringIndex += AddSectionName + NewUPLEntry += StringIndex + # section after name string section but not last one. + elif ((Index > StringIndexNumber) and (Index < (SectionHeaderEntryNumber - 1))): + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + unpacked_NextSectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + # Section before name string section. + else: + NewUPLEntry += UPLEntry[unpacked_SectionHeader.sh_offset:(unpacked_SectionHeader.sh_offset + unpacked_SectionHeader.sh_size)] + # Address alignment, section will align with alignment of next section. + if (Index < (SectionHeaderEntryNumber - 1)): + unpacked_NextSectionHeader = ElfSectionHeader32.unpack(SHentry[((Index + 1) * SectionHeaderEntrySize):(((Index + 1) * SectionHeaderEntrySize) + SectionHeaderEntrySize)]) + NewUPLEntry = SectionAlignment(NewUPLEntry, unpacked_NextSectionHeader.sh_addralign) + SectionHeaderOffset = len(NewUPLEntry) + RemoveNameOffset = 0 + # Add section header + for Number in range(0, (SectionHeaderEntryNumber)): + NewSHentry = AddSectionHeader32(SHentry, NewUPLEntrylen[Number], SectionHeaderEntrySize, Number, RemoveNameOffset, AddSectionName, StringIndexNumber) + NewUPLEntry += NewSHentry + NewUPLEntry += bytearray(AddNewSectionEntry32(LastUPLEntrylen, StringIndexValue, len(Binary_File), Alignment)) + # Modify number of sections and offset of section header in Elf header. + # Modify offset in in Elf header. + elf_header.e_shoff = SectionHeaderOffset + elf_header.e_shnum += 1 + PHTableSize = elf_header.e_phentsize + elf_header = elf_header.pack() + UPLEntryBin = elf_header + NewUPLEntry[52:] + # Modify offsets and address of program header table in elf. + PHSegmentName = '.text' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset32(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + # Modify offsets and address of program header table in elf. Its are stored at 0x08-0x0F and 0x10-0x17 + PHSegmentName = '.data' + _, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, _ = FindSection(UPLEntryBin, PHSegmentName) + UPLEntryBin = ModifyPHSegmentOffset32(UPLEntryBin, ElfHeaderOffset, PHSegmentName) + fFileBinary.close() + return UPLEntryBin + +def ReplaceFv (UniversalPayloadEntry, FileBinary, AddSectionName, Alignment = 16): + with open(UniversalPayloadEntry,'rb+') as f: + UPLEntry = f.read() + SectionNameOffset, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, _, StringIndexNumber, EI_CLASS = FindSection(UPLEntry, AddSectionName) + # If elf is 64-bit objects. + if (EI_CLASS == 2): + # Remove section if it exists. + if (SectionNameOffset != -1): + RemoveSection64(UniversalPayloadEntry, AddSectionName) + # Add section. + NewUPLEntry = AddSection64(UniversalPayloadEntry, AddSectionName, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, StringIndexNumber, FileBinary, Alignment) + # If elf is 32-bit objects. + else: + # Remove section if it exists. + if (SectionNameOffset != -1): + RemoveSection32(UniversalPayloadEntry, AddSectionName) + # Add section. + NewUPLEntry = AddSection32(UniversalPayloadEntry, AddSectionName, ElfHeaderOffset, SectionHeaderEntrySize, SectionHeaderEntryNumber, StringIndexNumber, FileBinary, Alignment) + with open(UniversalPayloadEntry,'wb') as f: + f.write(NewUPLEntry) + return 0 diff --git a/UefiPayloadPkg/Tools/__init__.py b/UefiPayloadPkg/Tools/__init__.py new file mode 100644 index 0000000..c754125 --- /dev/null +++ b/UefiPayloadPkg/Tools/__init__.py @@ -0,0 +1,6 @@ +## @file +# This file is used to replace FV. +# +# Copyright (c) 2023, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## diff --git a/UefiPayloadPkg/UefiPayloadPkg.ci.yaml b/UefiPayloadPkg/UefiPayloadPkg.ci.yaml index 909379e..278f271 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.ci.yaml +++ b/UefiPayloadPkg/UefiPayloadPkg.ci.yaml @@ -18,6 +18,7 @@ ], ## Both file path and directory path are accepted. "IgnoreFiles": [ + "Tools/", "Include/Coreboot.h", "Library/CbParseLib/CbParseLib.c", "PayloadLoaderPeim/ElfLib/ElfCommon.h", diff --git a/UefiPayloadPkg/UniversalPayloadBuild.py b/UefiPayloadPkg/UniversalPayloadBuild.py index 83e0de9..416946a 100644 --- a/UefiPayloadPkg/UniversalPayloadBuild.py +++ b/UefiPayloadPkg/UniversalPayloadBuild.py @@ -11,7 +11,7 @@ import os import shutil import sys from ctypes import * - +from Tools.ElfFv import ReplaceFv sys.dont_write_bytecode = True class UPLD_INFO_HEADER(LittleEndianStructure): @@ -36,106 +36,56 @@ class UPLD_INFO_HEADER(LittleEndianStructure): self.ImageId = b'UEFI' self.ProducerId = b'INTEL' -def GenSpecRevision (Argument): - try: - (MajorStr, MinorStr) = Argument.split('.') - except: - raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) - # - # Spec Revision Bits 15 : 8 - Major Version. Bits 7 : 0 - Minor Version. - # - if len(MinorStr) > 0 and len(MinorStr) < 3: - try: - Minor = int(MinorStr, 16) if len(MinorStr) == 2 else (int(MinorStr, 16) << 4) - except: - raise argparse.ArgumentTypeError ('{} Minor version of SpecRevision is not a valid integer value.'.format (Argument)) - else: - raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) +def BuildUniversalPayload(Args): + def RunCommand(cmd): + print(cmd) + p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE']) + while True: + line = p.stdout.readline() + if not line: + break + print(line.strip().decode(errors='ignore')) + + p.communicate() + if p.returncode != 0: + print("- Failed - error happened when run command: %s"%cmd) + raise Exception("ERROR: when run command: %s"%cmd) - if len(MajorStr) > 0 and len(MajorStr) < 3: - try: - Major = int(MajorStr, 16) - except: - raise argparse.ArgumentTypeError ('{} Major version of SpecRevision is not a valid integer value.'.format (Argument)) - else: - raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) - - return int('0x{0:02x}{1:02x}'.format(Major, Minor), 0) - -def Validate32BitInteger (Argument): - try: - Value = int (Argument, 0) - except: - raise argparse.ArgumentTypeError ('{} is not a valid integer value.'.format (Argument)) - if Value < 0: - raise argparse.ArgumentTypeError ('{} is a negative value.'.format (Argument)) - if Value > 0xffffffff: - raise argparse.ArgumentTypeError ('{} is larger than 32-bits.'.format (Argument)) - return Value - -def RunCommand(cmd): - print(cmd) - p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE']) - while True: - line = p.stdout.readline() - if not line: - break - print(line.strip().decode(errors='ignore')) - - p.communicate() - if p.returncode != 0: - print("- Failed - error happened when run command: %s"%cmd) - raise Exception("ERROR: when run command: %s"%cmd) - -def BuildUniversalPayload(Args, MacroList): BuildTarget = Args.Target ToolChain = Args.ToolChain Quiet = "--quiet" if Args.Quiet else "" ElfToolChain = 'CLANGDWARF' BuildDir = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/UefiPayloadPkgX64")) + BuildModule = "" + BuildArch = "" if Args.Arch == 'X64': BuildArch = "X64" - ObjCopyFlag = "elf64-x86-64" EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ElfToolChain), os.path.normpath("X64/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry/DEBUG/UniversalPayloadEntry.dll")) else: BuildArch = "IA32 -a X64" - ObjCopyFlag = "elf32-i386" EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ElfToolChain), os.path.normpath("IA32/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry/DEBUG/UniversalPayloadEntry.dll")) if Args.PreBuildUplBinary is not None: EntryOutputDir = os.path.abspath(Args.PreBuildUplBinary) - EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf") DscPath = os.path.normpath("UefiPayloadPkg/UefiPayloadPkg.dsc") - DxeFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) - BdsFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) - NetworkFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv")) - PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt") ModuleReportPath = os.path.join(BuildDir, "UefiUniversalPayloadEntry.txt") UpldInfoFile = os.path.join(BuildDir, "UniversalPayloadInfo.bin") - if "CLANG_BIN" in os.environ: - LlvmObjcopyPath = os.path.join(os.environ["CLANG_BIN"], "llvm-objcopy") - else: - LlvmObjcopyPath = "llvm-objcopy" - try: - RunCommand('"%s" --version'%LlvmObjcopyPath) - except: - print("- Failed - Please check if LLVM is installed or if CLANG_BIN is set correctly") - sys.exit(1) - Pcds = "" if (Args.pcd != None): for PcdItem in Args.pcd: Pcds += " --pcd {}".format (PcdItem) Defines = "" - for key in MacroList: - Defines +=" -D {0}={1}".format(key, MacroList[key]) + if (Args.Macro != None): + for MacroItem in Args.Macro: + Defines += " -D {}".format (MacroItem) # # Building DXE core and DXE drivers as DXEFV. # if Args.BuildEntryOnly == False: + PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt") BuildPayload = "build -p {} -b {} -a X64 -t {} -y {} {}".format (DscPath, BuildTarget, ToolChain, PayloadReportPath, Quiet) BuildPayload += Pcds BuildPayload += Defines @@ -144,6 +94,7 @@ def BuildUniversalPayload(Args, MacroList): # Building Universal Payload entry. # if Args.PreBuildUplBinary is None: + EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf") BuildModule = "build -p {} -b {} -a {} -m {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, EntryModuleInf, ElfToolChain, ModuleReportPath, Quiet) BuildModule += Pcds BuildModule += Defines @@ -151,59 +102,80 @@ def BuildUniversalPayload(Args, MacroList): # # Buid Universal Payload Information Section ".upld_info" # - upld_info_hdr = UPLD_INFO_HEADER() + upld_info_hdr = UPLD_INFO_HEADER() upld_info_hdr.SpecRevision = Args.SpecRevision - upld_info_hdr.Revision = Args.Revision - upld_info_hdr.ProducerId = Args.ProducerId.encode()[:16] - upld_info_hdr.ImageId = Args.ImageId.encode()[:16] - upld_info_hdr.Attribute |= 1 if BuildTarget == "DEBUG" else 0 + upld_info_hdr.Revision = Args.Revision + upld_info_hdr.ProducerId = Args.ProducerId.encode()[:16] + upld_info_hdr.ImageId = Args.ImageId.encode()[:16] + upld_info_hdr.Attribute |= 1 if BuildTarget == "DEBUG" else 0 fp = open(UpldInfoFile, 'wb') fp.write(bytearray(upld_info_hdr)) fp.close() + MultiFvList = [] if Args.BuildEntryOnly == False: - # - # Copy the DXEFV as a section in elf format Universal Payload entry. - # - remove_section = '"{}" -I {} -O {} --remove-section .upld_info --remove-section .upld.uefi_fv --remove-section .upld.bds_fv {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - EntryOutputDir - ) - add_section = '"{}" -I {} -O {} --add-section .upld_info={} --add-section .upld.uefi_fv={} --add-section .upld.bds_fv={} {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - UpldInfoFile, - DxeFvOutputDir, - BdsFvOutputDir, - EntryOutputDir - ) - set_section = '"{}" -I {} -O {} --set-section-alignment .upld_info=4 --set-section-alignment .upld.uefi_fv=16 --set-section-alignment .upld.bds_fv=16 {}'.format ( - LlvmObjcopyPath, - ObjCopyFlag, - ObjCopyFlag, - EntryOutputDir - ) - # - # Append network fv to sections if exists - # - if os.path.isfile(NetworkFvOutputDir): - index = remove_section.find(EntryOutputDir) - remove_section = remove_section[:index] + '--remove-section .upld.network_fv ' + remove_section[index:] - index = add_section.find(EntryOutputDir) - add_section = add_section[:index] + '--add-section .upld.network_fv=' + NetworkFvOutputDir + ' ' + add_section[index:] - index = set_section.find(EntryOutputDir) - set_section = set_section[:index] + '--set-section-alignment .upld.network_fv=16 ' + set_section[index:] - - RunCommand(remove_section) - RunCommand(add_section) - RunCommand(set_section) + MultiFvList = [ + ['uefi_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) ], + ['bds_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) ], + ['network_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv")) ], + ] + AddSectionName = '.upld_info' + ReplaceFv (EntryOutputDir, UpldInfoFile, AddSectionName, Alignment = 4) shutil.copy (EntryOutputDir, os.path.join(BuildDir, 'UniversalPayload.elf')) + return MultiFvList, os.path.join(BuildDir, 'UniversalPayload.elf') + def main(): + def ValidateSpecRevision (Argument): + try: + (MajorStr, MinorStr) = Argument.split('.') + except: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + # + # Spec Revision Bits 15 : 8 - Major Version. Bits 7 : 0 - Minor Version. + # + if len(MinorStr) > 0 and len(MinorStr) < 3: + try: + Minor = int(MinorStr, 16) if len(MinorStr) == 2 else (int(MinorStr, 16) << 4) + except: + raise argparse.ArgumentTypeError ('{} Minor version of SpecRevision is not a valid integer value.'.format (Argument)) + else: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + + if len(MajorStr) > 0 and len(MajorStr) < 3: + try: + Major = int(MajorStr, 16) + except: + raise argparse.ArgumentTypeError ('{} Major version of SpecRevision is not a valid integer value.'.format (Argument)) + else: + raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument)) + + return int('0x{0:02x}{1:02x}'.format(Major, Minor), 0) + + def Validate32BitInteger (Argument): + try: + Value = int (Argument, 0) + except: + raise argparse.ArgumentTypeError ('{} is not a valid integer value.'.format (Argument)) + if Value < 0: + raise argparse.ArgumentTypeError ('{} is a negative value.'.format (Argument)) + if Value > 0xffffffff: + raise argparse.ArgumentTypeError ('{} is larger than 32-bits.'.format (Argument)) + return Value + + def ValidateAddFv (Argument): + Value = Argument.split ("=") + if len (Value) != 2: + raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument)) + if Value[0][-3:] != "_fv": + raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument)) + if Value[1][-3:].lower () != ".fv": + raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument)) + if os.path.exists (Value[1]) == False: + raise argparse.ArgumentTypeError ('File {} is not found.'.format (Value[1])) + return Value + parser = argparse.ArgumentParser(description='For building Universal Payload') parser.add_argument('-t', '--ToolChain') parser.add_argument('-b', '--Target', default='DEBUG') @@ -212,22 +184,32 @@ def main(): parser.add_argument('-i', '--ImageId', type=str, help='Specify payload ID (16 bytes maximal).', default ='UEFI') parser.add_argument('-q', '--Quiet', action='store_true', help='Disable all build messages except FATAL ERRORS.') parser.add_argument("-p", "--pcd", action="append") - parser.add_argument("-s", "--SpecRevision", type=GenSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.') + parser.add_argument("-s", "--SpecRevision", type=ValidateSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.') parser.add_argument("-r", "--Revision", type=Validate32BitInteger, default ='0x0000010105', help='Revision of the Payload binary. Major.Minor.Revision.Build') parser.add_argument("-o", "--ProducerId", default ='INTEL', help='A null-terminated OEM-supplied string that identifies the payload producer (16 bytes maximal).') parser.add_argument("-e", "--BuildEntryOnly", action='store_true', help='Build UniversalPayload Entry file') parser.add_argument("-pb", "--PreBuildUplBinary", default=None, help='Specify the UniversalPayload file') - MacroList = {} + parser.add_argument("-sk", "--SkipBuild", action='store_true', help='Skip UniversalPayload build') + parser.add_argument("-af", "--AddFv", type=ValidateAddFv, action='append', help='Add or replace specific FV into payload, Ex: uefi_fv=XXX.fv') args = parser.parse_args() - if args.Macro is not None: - for Argument in args.Macro: - if Argument.count('=') != 1: - print("Unknown variable passed in: %s"%Argument) - raise Exception("ERROR: Unknown variable passed in: %s"%Argument) - tokens = Argument.strip().split('=') - MacroList[tokens[0].upper()] = tokens[1] - BuildUniversalPayload(args, MacroList) - print ("Successfully build Universal Payload") + + MultiFvList = [] + UniversalPayloadBinary = args.PreBuildUplBinary + if (args.SkipBuild == False): + MultiFvList, UniversalPayloadBinary = BuildUniversalPayload(args) + + if (args.AddFv != None): + for (SectionName, SectionFvFile) in args.AddFv: + MultiFvList.append ([SectionName, SectionFvFile]) + + if (UniversalPayloadBinary != None): + for (SectionName, SectionFvFile) in MultiFvList: + if os.path.exists (SectionFvFile) == False: + continue + print ("Patch {}={} into {}".format (SectionName, SectionFvFile, UniversalPayloadBinary)) + ReplaceFv (UniversalPayloadBinary, SectionFvFile, '.upld.{}'.format (SectionName)) + + print ("\nSuccessfully build Universal Payload") if __name__ == '__main__': main() -- cgit v1.1