VirtualBox

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

Last change on this file was 108794, checked in by vboxsync, 2 weeks ago

Devices/EFI/FirmwareNew: Merge edk2-stable202502 from the vendor branch and make it build for the important platforms, bugref:4643

  • Property svn:eol-style set to native
File size: 16.5 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
13import pathlib
14from ctypes import *
15
16sys.dont_write_bytecode = True
17
18class bcolors:
19 HEADER = '\033[95m'
20 OKBLUE = '\033[94m'
21 OKCYAN = '\033[96m'
22 OKGREEN = '\033[92m'
23 WARNING = '\033[93m'
24 FAIL = '\033[91m'
25 ENDC = '\033[0m'
26 BOLD = '\033[1m'
27 UNDERLINE = '\033[4m'
28
29class UPLD_INFO_HEADER(LittleEndianStructure):
30 _pack_ = 1
31 _fields_ = [
32 ('Identifier', ARRAY(c_char, 4)),
33 ('HeaderLength', c_uint32),
34 ('SpecRevision', c_uint16),
35 ('Reserved', c_uint16),
36 ('Revision', c_uint32),
37 ('Attribute', c_uint32),
38 ('Capability', c_uint32),
39 ('ProducerId', ARRAY(c_char, 16)),
40 ('ImageId', ARRAY(c_char, 16)),
41 ]
42
43 def __init__(self):
44 self.Identifier = b'PLDH'
45 self.HeaderLength = sizeof(UPLD_INFO_HEADER)
46 self.SpecRevision = 0x0070
47 self.Revision = 0x0000010105
48 self.ImageId = b'UEFI'
49 self.ProducerId = b'INTEL'
50
51def ValidateSpecRevision (Argument):
52 try:
53 (MajorStr, MinorStr) = Argument.split('.')
54 except:
55 raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument))
56 #
57 # Spec Revision Bits 15 : 8 - Major Version. Bits 7 : 0 - Minor Version.
58 #
59 if len(MinorStr) > 0 and len(MinorStr) < 3:
60 try:
61 Minor = int(MinorStr, 16) if len(MinorStr) == 2 else (int(MinorStr, 16) << 4)
62 except:
63 raise argparse.ArgumentTypeError ('{} Minor version of SpecRevision is not a valid integer value.'.format (Argument))
64 else:
65 raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument))
66
67 if len(MajorStr) > 0 and len(MajorStr) < 3:
68 try:
69 Major = int(MajorStr, 16)
70 except:
71 raise argparse.ArgumentTypeError ('{} Major version of SpecRevision is not a valid integer value.'.format (Argument))
72 else:
73 raise argparse.ArgumentTypeError ('{} is not a valid SpecRevision format (Major[8-bits].Minor[8-bits]).'.format (Argument))
74
75 return int('0x{0:02x}{1:02x}'.format(Major, Minor), 0)
76
77def Validate32BitInteger (Argument):
78 try:
79 Value = int (Argument, 0)
80 except:
81 raise argparse.ArgumentTypeError ('{} is not a valid integer value.'.format (Argument))
82 if Value < 0:
83 raise argparse.ArgumentTypeError ('{} is a negative value.'.format (Argument))
84 if Value > 0xffffffff:
85 raise argparse.ArgumentTypeError ('{} is larger than 32-bits.'.format (Argument))
86 return Value
87
88def ValidateAddFv (Argument):
89 Value = Argument.split ("=")
90 if len (Value) != 2:
91 raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument))
92 if Value[0][-3:] != "_fv":
93 raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument))
94 if Value[1][-3:].lower () != ".fv":
95 raise argparse.ArgumentTypeError ('{} is incorrect format with "xxx_fv=xxx.fv"'.format (Argument))
96 if os.path.exists (Value[1]) == False:
97 raise argparse.ArgumentTypeError ('File {} is not found.'.format (Value[1]))
98 return Value
99
100def RunCommand(cmd):
101 print(cmd)
102 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE'])
103 while True:
104 line = p.stdout.readline()
105 if not line:
106 break
107 print(line.strip().decode(errors='ignore'))
108
109 p.communicate()
110 if p.returncode != 0:
111 print("- Failed - error happened when run command: %s"%cmd)
112 raise Exception("ERROR: when run command: %s"%cmd)
113
114def BuildUniversalPayload(Args):
115 DscPath = os.path.normpath(Args.DscPath)
116 print("Building FIT for DSC file %s"%DscPath)
117 BuildTarget = Args.Target
118 ToolChain = Args.ToolChain
119 Quiet = "--quiet" if Args.Quiet else ""
120
121 if Args.Fit == True:
122 PayloadEntryToolChain = ToolChain
123 Args.Macro.append("UNIVERSAL_PAYLOAD_FORMAT=FIT")
124 UpldEntryFile = "FitUniversalPayloadEntry"
125 else:
126 PayloadEntryToolChain = 'CLANGDWARF'
127 Args.Macro.append("UNIVERSAL_PAYLOAD_FORMAT=ELF")
128 UpldEntryFile = "UniversalPayloadEntry"
129
130 BuildDir = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/UefiPayloadPkg{}").format (Args.Arch))
131 if Args.Arch == 'X64':
132 BuildArch = "X64"
133 FitArch = "x86_64"
134 elif Args.Arch == 'IA32':
135 BuildArch = "IA32 -a X64"
136 FitArch = "x86"
137 elif Args.Arch == 'RISCV64':
138 BuildArch = "RISCV64"
139 FitArch = "RISCV64"
140 else:
141 print("Incorrect arch option provided")
142
143 EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, PayloadEntryToolChain), os.path.normpath("{}/UefiPayloadPkg/UefiPayloadEntry/{}/DEBUG/{}.dll".format (Args.Arch, UpldEntryFile, UpldEntryFile)))
144 EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/{}.inf".format (UpldEntryFile))
145 DxeFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv"))
146 BdsFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv"))
147 SecFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/SECFV.Fv"))
148 NetworkFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv"))
149 PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt")
150 ModuleReportPath = os.path.join(BuildDir, "UefiUniversalPayloadEntry.txt")
151 UpldInfoFile = os.path.join(BuildDir, "UniversalPayloadInfo.bin")
152
153 Pcds = ""
154 if (Args.pcd != None):
155 for PcdItem in Args.pcd:
156 Pcds += " --pcd {}".format (PcdItem)
157
158 Defines = ""
159 Defines += " -D BUILD_ARCH={}".format(Args.Arch)
160 if (Args.Macro != None):
161 for MacroItem in Args.Macro:
162 Defines += " -D {}".format (MacroItem)
163
164 #
165 # Building DXE core and DXE drivers as DXEFV.
166 #
167 if Args.BuildEntryOnly == False:
168 BuildPayload = "build -p {} -b {} -a {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, ToolChain, PayloadReportPath, Quiet)
169 BuildPayload += Pcds
170 BuildPayload += Defines
171 RunCommand(BuildPayload)
172 #
173 # Building Universal Payload entry.
174 #
175 if Args.PreBuildUplBinary is None:
176 BuildModule = "build -p {} -b {} -a {} -m {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, EntryModuleInf, PayloadEntryToolChain, ModuleReportPath, Quiet)
177 BuildModule += Pcds
178 BuildModule += Defines
179 RunCommand(BuildModule)
180
181 if Args.PreBuildUplBinary is not None:
182 if Args.Fit == False:
183 EntryOutputDir = os.path.join(BuildDir, "UniversalPayload.elf")
184 else:
185 EntryOutputDir = os.path.join(BuildDir, "UniversalPayload.fit")
186 shutil.copy (os.path.abspath(Args.PreBuildUplBinary), EntryOutputDir)
187
188 #
189 # Build Universal Payload Information Section ".upld_info"
190 #
191 if Args.Fit == False:
192 upld_info_hdr = UPLD_INFO_HEADER()
193 upld_info_hdr.SpecRevision = Args.SpecRevision
194 upld_info_hdr.Revision = Args.Revision
195 upld_info_hdr.ProducerId = Args.ProducerId.encode()[:16]
196 upld_info_hdr.ImageId = Args.ImageId.encode()[:16]
197 upld_info_hdr.Attribute |= 1 if BuildTarget == "DEBUG" else 0
198 fp = open(UpldInfoFile, 'wb')
199 fp.write(bytearray(upld_info_hdr))
200 fp.close()
201
202 if Args.BuildEntryOnly == False:
203 import Tools.ElfFv as ElfFv
204 ElfFv.ReplaceFv (EntryOutputDir, UpldInfoFile, '.upld_info', Alignment = 4)
205 if Args.PreBuildUplBinary is None:
206 if Args.Fit == False:
207 shutil.copy (EntryOutputDir, os.path.join(BuildDir, 'UniversalPayload.elf'))
208 else:
209 shutil.copy (EntryOutputDir, os.path.join(BuildDir, 'UniversalPayload.fit'))
210
211 MultiFvList = []
212 if Args.BuildEntryOnly == False:
213 MultiFvList = [
214 ['uefi_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) ],
215 ['bds_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) ],
216 ['sec_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/SECFV.Fv")) ],
217 ['network_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv"))],
218 ]
219
220
221 if Args.Fit == True:
222 import Tools.MkFitImage as MkFitImage
223 import pefile
224 fit_image_info_header = MkFitImage.FIT_IMAGE_INFO_HEADER()
225 fit_image_info_header.Description = 'Uefi Universal Payload'
226 fit_image_info_header.UplVersion = Args.SpecRevision
227 fit_image_info_header.Type = 'flat-binary'
228 fit_image_info_header.Arch = FitArch
229 fit_image_info_header.Compression = 'none'
230 fit_image_info_header.Revision = Args.Revision
231 fit_image_info_header.BuildType = Args.Target.lower()
232 fit_image_info_header.Capabilities = None
233 fit_image_info_header.Producer = Args.ProducerId.lower()
234 fit_image_info_header.ImageId = Args.ImageId.lower()
235 fit_image_info_header.Binary = os.path.join(BuildDir, 'UniversalPayload.fit')
236 fit_image_info_header.TargetPath = os.path.join(BuildDir, 'UniversalPayload.fit')
237 fit_image_info_header.UefifvPath = DxeFvOutputDir
238 fit_image_info_header.BdsfvPath = BdsFvOutputDir
239 fit_image_info_header.SecfvPath = SecFvOutputDir
240 fit_image_info_header.NetworkfvPath = NetworkFvOutputDir
241 fit_image_info_header.DataOffset = 0x1000
242 fit_image_info_header.LoadAddr = Args.LoadAddress
243 fit_image_info_header.Project = 'tianocore'
244
245 TargetRebaseFile = fit_image_info_header.Binary.replace (pathlib.Path(fit_image_info_header.Binary).suffix, ".pecoff")
246 TargetRebaseEntryFile = fit_image_info_header.Binary.replace (pathlib.Path(fit_image_info_header.Binary).suffix, ".entry")
247
248
249 #
250 # Rebase PECOFF to load address
251 #
252 RunCommand (
253 "GenFw -e SEC -o {} {}".format (
254 TargetRebaseFile,
255 fit_image_info_header.Binary
256 ))
257 RunCommand (
258 "GenFw --rebase 0x{:02X} -o {} {} ".format (
259 fit_image_info_header.LoadAddr + fit_image_info_header.DataOffset,
260 TargetRebaseFile,
261 TargetRebaseFile,
262 ))
263
264 #
265 # Open PECOFF relocation table binary.
266 #
267 RelocBinary = b''
268 PeCoff = pefile.PE (TargetRebaseFile)
269 if hasattr(PeCoff, 'DIRECTORY_ENTRY_BASERELOC'):
270 for reloc in PeCoff.DIRECTORY_ENTRY_BASERELOC:
271 for entry in reloc.entries:
272 if (entry.type == 0):
273 continue
274 Type = entry.type
275 Offset = entry.rva + fit_image_info_header.DataOffset
276 RelocBinary += Offset.to_bytes (8, 'little') + Type.to_bytes (8, 'little')
277 RelocBinary += b'\x00' * (0x1000 - (len(RelocBinary) % 0x1000))
278
279 #
280 # Output UniversalPayload.entry
281 #
282 TempBinary = open (TargetRebaseFile, 'rb')
283 TianoBinary = TempBinary.read ()
284 TempBinary.close ()
285
286 TianoEntryBinary = TianoBinary + RelocBinary
287 TianoEntryBinary += (b'\x00' * (0x1000 - (len(TianoBinary) % 0x1000)))
288 TianoEntryBinarySize = len (TianoEntryBinary)
289
290 TempBinary = open(TargetRebaseEntryFile, "wb")
291 TempBinary.truncate()
292 TempBinary.write(TianoEntryBinary)
293 TempBinary.close()
294
295 #
296 # Calculate entry and update relocation table start address and data-size.
297 #
298 fit_image_info_header.Entry = PeCoff.OPTIONAL_HEADER.ImageBase + PeCoff.OPTIONAL_HEADER.AddressOfEntryPoint
299 fit_image_info_header.RelocStart = fit_image_info_header.DataOffset + len(TianoBinary)
300 fit_image_info_header.DataSize = TianoEntryBinarySize
301 fit_image_info_header.Binary = TargetRebaseEntryFile
302
303 if MkFitImage.MakeFitImage(fit_image_info_header, Args.Arch) is True:
304 print('\nSuccessfully build Fit Image')
305 else:
306 sys.exit(1)
307 return MultiFvList, os.path.join(BuildDir, 'UniversalPayload.fit')
308 else:
309 return MultiFvList, os.path.join(BuildDir, 'UniversalPayload.elf')
310
311def main():
312 parser = argparse.ArgumentParser(description='For building Universal Payload')
313 parser.add_argument('-t', '--ToolChain')
314 parser.add_argument('-b', '--Target', default='DEBUG')
315 parser.add_argument('-a', '--Arch', choices=['IA32', 'X64', 'RISCV64'], help='Specify the ARCH for payload entry module. Default build X64 image.', default ='X64')
316 parser.add_argument("-D", "--Macro", action="append", default=["UNIVERSAL_PAYLOAD=TRUE"])
317 parser.add_argument('-i', '--ImageId', type=str, help='Specify payload ID (16 bytes maximal).', default ='UEFI')
318 parser.add_argument('-q', '--Quiet', action='store_true', help='Disable all build messages except FATAL ERRORS.')
319 parser.add_argument("-p", "--pcd", action="append")
320 parser.add_argument("-s", "--SpecRevision", type=ValidateSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.')
321 parser.add_argument("-r", "--Revision", type=Validate32BitInteger, default ='0x0000010105', help='Revision of the Payload binary. Major.Minor.Revision.Build')
322 parser.add_argument("-o", "--ProducerId", default ='INTEL', help='A null-terminated OEM-supplied string that identifies the payload producer (16 bytes maximal).')
323 parser.add_argument("-e", "--BuildEntryOnly", action='store_true', help='Build UniversalPayload Entry file')
324 parser.add_argument("-pb", "--PreBuildUplBinary", default=None, help='Specify the UniversalPayload file')
325 parser.add_argument("-sk", "--SkipBuild", action='store_true', help='Skip UniversalPayload build')
326 parser.add_argument("-af", "--AddFv", type=ValidateAddFv, action='append', help='Add or replace specific FV into payload, Ex: uefi_fv=XXX.fv')
327 parser.add_argument("-f", "--Fit", action='store_true', help='Build UniversalPayload file as UniversalPayload.fit', default=False)
328 parser.add_argument('-l', "--LoadAddress", type=int, help='Specify payload load address', default =0x000800000)
329 parser.add_argument('-c', '--DscPath', type=str, default="UefiPayloadPkg/UefiPayloadPkg.dsc", help='Path to the DSC file')
330
331 args = parser.parse_args()
332
333
334 MultiFvList = []
335 UniversalPayloadBinary = args.PreBuildUplBinary
336 if (args.SkipBuild == False):
337 MultiFvList, UniversalPayloadBinary = BuildUniversalPayload(args)
338
339 if (args.AddFv != None):
340 for (SectionName, SectionFvFile) in args.AddFv:
341 MultiFvList.append ([SectionName, SectionFvFile])
342
343 def ReplaceFv (UplBinary, SectionFvFile, SectionName, Arch):
344 print (bcolors.OKGREEN + "Patch {}={} into {}".format (SectionName, SectionFvFile, UplBinary) + bcolors.ENDC)
345 if (args.Fit == False):
346 import Tools.ElfFv as ElfFv
347 return ElfFv.ReplaceFv (UplBinary, SectionFvFile, '.upld.{}'.format (SectionName))
348 else:
349 import Tools.MkFitImage as MkFitImage
350 return MkFitImage.ReplaceFv (UplBinary, SectionFvFile, SectionName, Arch)
351
352 if (UniversalPayloadBinary != None):
353 for (SectionName, SectionFvFile) in MultiFvList:
354 if os.path.exists (SectionFvFile) == False:
355 continue
356 if (args.Fit == False):
357 status = ReplaceFv (UniversalPayloadBinary, SectionFvFile, SectionName, args.Arch)
358 else:
359 status = ReplaceFv (UniversalPayloadBinary, SectionFvFile, SectionName.replace ("_", "-"), args.Arch)
360 if status != 0:
361 print (bcolors.FAIL + "[Fail] Patch {}={}".format (SectionName, SectionFvFile) + bcolors.ENDC)
362 return status
363
364 print ("\nSuccessfully build Universal Payload")
365
366if __name__ == '__main__':
367 main()
Note: See TracBrowser for help on using the repository browser.

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