VirtualBox

source: vbox/trunk/src/VBox/Devices/EFI/FirmwareNew/UefiPayloadPkg/UniversalPayloadBuild.py@ 101291

Last change on this file since 101291 was 101291, checked in by vboxsync, 14 months ago

EFI/FirmwareNew: Make edk2-stable202308 build on all supported platforms (using gcc at least, msvc not tested yet), bugref:4643

  • Property svn:eol-style set to native
File size: 10.0 KB
Line 
1## @file
2# This file contains the script to build UniversalPayload
3#
4# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
5# SPDX-License-Identifier: BSD-2-Clause-Patent
6##
7
8import argparse
9import subprocess
10import os
11import shutil
12import sys
13from ctypes import *
14from Tools.ElfFv import ReplaceFv
15sys.dont_write_bytecode = True
16
17class UPLD_INFO_HEADER(LittleEndianStructure):
18 _pack_ = 1
19 _fields_ = [
20 ('Identifier', ARRAY(c_char, 4)),
21 ('HeaderLength', c_uint32),
22 ('SpecRevision', c_uint16),
23 ('Reserved', c_uint16),
24 ('Revision', c_uint32),
25 ('Attribute', c_uint32),
26 ('Capability', c_uint32),
27 ('ProducerId', ARRAY(c_char, 16)),
28 ('ImageId', ARRAY(c_char, 16)),
29 ]
30
31 def __init__(self):
32 self.Identifier = b'PLDH'
33 self.HeaderLength = sizeof(UPLD_INFO_HEADER)
34 self.SpecRevision = 0x0070
35 self.Revision = 0x0000010105
36 self.ImageId = b'UEFI'
37 self.ProducerId = b'INTEL'
38
39def BuildUniversalPayload(Args):
40 def RunCommand(cmd):
41 print(cmd)
42 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE'])
43 while True:
44 line = p.stdout.readline()
45 if not line:
46 break
47 print(line.strip().decode(errors='ignore'))
48
49 p.communicate()
50 if p.returncode != 0:
51 print("- Failed - error happened when run command: %s"%cmd)
52 raise Exception("ERROR: when run command: %s"%cmd)
53
54 BuildTarget = Args.Target
55 ToolChain = Args.ToolChain
56 Quiet = "--quiet" if Args.Quiet else ""
57 ElfToolChain = 'CLANGDWARF'
58 BuildDir = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/UefiPayloadPkgX64"))
59 BuildModule = ""
60 BuildArch = ""
61 if Args.Arch == 'X64':
62 BuildArch = "X64"
63 EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ElfToolChain), os.path.normpath("X64/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry/DEBUG/UniversalPayloadEntry.dll"))
64 else:
65 BuildArch = "IA32 -a X64"
66 EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ElfToolChain), os.path.normpath("IA32/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry/DEBUG/UniversalPayloadEntry.dll"))
67
68 if Args.PreBuildUplBinary is not None:
69 EntryOutputDir = os.path.abspath(Args.PreBuildUplBinary)
70 DscPath = os.path.normpath("UefiPayloadPkg/UefiPayloadPkg.dsc")
71 ModuleReportPath = os.path.join(BuildDir, "UefiUniversalPayloadEntry.txt")
72 UpldInfoFile = os.path.join(BuildDir, "UniversalPayloadInfo.bin")
73
74 Pcds = ""
75 if (Args.pcd != None):
76 for PcdItem in Args.pcd:
77 Pcds += " --pcd {}".format (PcdItem)
78
79 Defines = ""
80 if (Args.Macro != None):
81 for MacroItem in Args.Macro:
82 Defines += " -D {}".format (MacroItem)
83
84 #
85 # Building DXE core and DXE drivers as DXEFV.
86 #
87 if Args.BuildEntryOnly == False:
88 PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt")
89 BuildPayload = "build -p {} -b {} -a X64 -t {} -y {} {}".format (DscPath, BuildTarget, ToolChain, PayloadReportPath, Quiet)
90 BuildPayload += Pcds
91 BuildPayload += Defines
92 RunCommand(BuildPayload)
93 #
94 # Building Universal Payload entry.
95 #
96 if Args.PreBuildUplBinary is None:
97 EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf")
98 BuildModule = "build -p {} -b {} -a {} -m {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, EntryModuleInf, ElfToolChain, ModuleReportPath, Quiet)
99 BuildModule += Pcds
100 BuildModule += Defines
101 RunCommand(BuildModule)
102 #
103 # Buid Universal Payload Information Section ".upld_info"
104 #
105 upld_info_hdr = UPLD_INFO_HEADER()
106 upld_info_hdr.SpecRevision = Args.SpecRevision
107 upld_info_hdr.Revision = Args.Revision
108 upld_info_hdr.ProducerId = Args.ProducerId.encode()[:16]
109 upld_info_hdr.ImageId = Args.ImageId.encode()[:16]
110 upld_info_hdr.Attribute |= 1 if BuildTarget == "DEBUG" else 0
111 fp = open(UpldInfoFile, 'wb')
112 fp.write(bytearray(upld_info_hdr))
113 fp.close()
114
115 MultiFvList = []
116 if Args.BuildEntryOnly == False:
117 MultiFvList = [
118 ['uefi_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) ],
119 ['bds_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) ],
120 ['network_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv")) ],
121 ]
122 AddSectionName = '.upld_info'
123 ReplaceFv (EntryOutputDir, UpldInfoFile, AddSectionName, Alignment = 4)
124
125 shutil.copy (EntryOutputDir, os.path.join(BuildDir, 'UniversalPayload.elf'))
126
127 return MultiFvList, os.path.join(BuildDir, 'UniversalPayload.elf')
128
129def main():
130 def ValidateSpecRevision (Argument):
131 try:
132 (MajorStr, MinorStr) = Argument.split('.')
133 except:
134 raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument))
135 #
136 # Spec Revision Bits 15 : 8 - Major Version. Bits 7 : 0 - Minor Version.
137 #
138 if len(MinorStr) > 0 and len(MinorStr) < 3:
139 try:
140 Minor = int(MinorStr, 16) if len(MinorStr) == 2 else (int(MinorStr, 16) << 4)
141 except:
142 raise argparse.ArgumentTypeError ('{} Minor version of SpecRevision is not a valid integer value.'.format (Argument))
143 else:
144 raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument))
145
146 if len(MajorStr) > 0 and len(MajorStr) < 3:
147 try:
148 Major = int(MajorStr, 16)
149 except:
150 raise argparse.ArgumentTypeError ('{} Major version of SpecRevision is not a valid integer value.'.format (Argument))
151 else:
152 raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument))
153
154 return int('0x{0:02x}{1:02x}'.format(Major, Minor), 0)
155
156 def Validate32BitInteger (Argument):
157 try:
158 Value = int (Argument, 0)
159 except:
160 raise argparse.ArgumentTypeError ('{} is not a valid integer value.'.format (Argument))
161 if Value < 0:
162 raise argparse.ArgumentTypeError ('{} is a negative value.'.format (Argument))
163 if Value > 0xffffffff:
164 raise argparse.ArgumentTypeError ('{} is larger than 32-bits.'.format (Argument))
165 return Value
166
167 def ValidateAddFv (Argument):
168 Value = Argument.split ("=")
169 if len (Value) != 2:
170 raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument))
171 if Value[0][-3:] != "_fv":
172 raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument))
173 if Value[1][-3:].lower () != ".fv":
174 raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument))
175 if os.path.exists (Value[1]) == False:
176 raise argparse.ArgumentTypeError ('File {} is not found.'.format (Value[1]))
177 return Value
178
179 parser = argparse.ArgumentParser(description='For building Universal Payload')
180 parser.add_argument('-t', '--ToolChain')
181 parser.add_argument('-b', '--Target', default='DEBUG')
182 parser.add_argument('-a', '--Arch', choices=['IA32', 'X64'], help='Specify the ARCH for payload entry module. Default build X64 image.', default ='X64')
183 parser.add_argument("-D", "--Macro", action="append", default=["UNIVERSAL_PAYLOAD=TRUE"])
184 parser.add_argument('-i', '--ImageId', type=str, help='Specify payload ID (16 bytes maximal).', default ='UEFI')
185 parser.add_argument('-q', '--Quiet', action='store_true', help='Disable all build messages except FATAL ERRORS.')
186 parser.add_argument("-p", "--pcd", action="append")
187 parser.add_argument("-s", "--SpecRevision", type=ValidateSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.')
188 parser.add_argument("-r", "--Revision", type=Validate32BitInteger, default ='0x0000010105', help='Revision of the Payload binary. Major.Minor.Revision.Build')
189 parser.add_argument("-o", "--ProducerId", default ='INTEL', help='A null-terminated OEM-supplied string that identifies the payload producer (16 bytes maximal).')
190 parser.add_argument("-sk", "--SkipBuild", action='store_true', help='Skip UniversalPayload build')
191 parser.add_argument("-af", "--AddFv", type=ValidateAddFv, action='append', help='Add or replace specific FV into payload, Ex: uefi_fv=XXX.fv')
192 command_group = parser.add_mutually_exclusive_group()
193 command_group.add_argument("-e", "--BuildEntryOnly", action='store_true', help='Build UniversalPayload Entry file')
194 command_group.add_argument("-pb", "--PreBuildUplBinary", default=None, help='Specify the UniversalPayload file')
195 args = parser.parse_args()
196
197 MultiFvList = []
198 UniversalPayloadBinary = args.PreBuildUplBinary
199 if (args.SkipBuild == False):
200 MultiFvList, UniversalPayloadBinary = BuildUniversalPayload(args)
201
202 if (args.AddFv != None):
203 for (SectionName, SectionFvFile) in args.AddFv:
204 MultiFvList.append ([SectionName, SectionFvFile])
205
206 if (UniversalPayloadBinary != None):
207 for (SectionName, SectionFvFile) in MultiFvList:
208 if os.path.exists (SectionFvFile) == False:
209 continue
210 print ("Patch {}={} into {}".format (SectionName, SectionFvFile, UniversalPayloadBinary))
211 ReplaceFv (UniversalPayloadBinary, SectionFvFile, '.upld.{}'.format (SectionName))
212
213 print ("\nSuccessfully build Universal Payload")
214
215if __name__ == '__main__':
216 main()
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette