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 |
|
---|
8 | import argparse
|
---|
9 | import subprocess
|
---|
10 | import os
|
---|
11 | import shutil
|
---|
12 | import sys
|
---|
13 | import pathlib
|
---|
14 | from ctypes import *
|
---|
15 |
|
---|
16 | sys.dont_write_bytecode = True
|
---|
17 |
|
---|
18 | class 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 |
|
---|
29 | class 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 |
|
---|
51 | def 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 |
|
---|
77 | def 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 |
|
---|
88 | def 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 |
|
---|
100 | def 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 |
|
---|
114 | def BuildUniversalPayload(Args):
|
---|
115 | BuildTarget = Args.Target
|
---|
116 | ToolChain = Args.ToolChain
|
---|
117 | Quiet = "--quiet" if Args.Quiet else ""
|
---|
118 |
|
---|
119 | if Args.Fit == True:
|
---|
120 | PayloadEntryToolChain = ToolChain
|
---|
121 | Args.Macro.append("UNIVERSAL_PAYLOAD_FORMAT=FIT")
|
---|
122 | UpldEntryFile = "FitUniversalPayloadEntry"
|
---|
123 | else:
|
---|
124 | PayloadEntryToolChain = 'CLANGDWARF'
|
---|
125 | Args.Macro.append("UNIVERSAL_PAYLOAD_FORMAT=ELF")
|
---|
126 | UpldEntryFile = "UniversalPayloadEntry"
|
---|
127 |
|
---|
128 | BuildDir = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/UefiPayloadPkg{}").format (Args.Arch))
|
---|
129 | if Args.Arch == 'X64':
|
---|
130 | BuildArch = "X64"
|
---|
131 | FitArch = "x86_64"
|
---|
132 | elif Args.Arch == 'IA32':
|
---|
133 | BuildArch = "IA32 -a X64"
|
---|
134 | FitArch = "x86"
|
---|
135 | elif Args.Arch == 'RISCV64':
|
---|
136 | BuildArch = "RISCV64"
|
---|
137 | FitArch = "RISCV64"
|
---|
138 | else:
|
---|
139 | print("Incorrect arch option provided")
|
---|
140 |
|
---|
141 | EntryOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, PayloadEntryToolChain), os.path.normpath("{}/UefiPayloadPkg/UefiPayloadEntry/{}/DEBUG/{}.dll".format (Args.Arch, UpldEntryFile, UpldEntryFile)))
|
---|
142 | EntryModuleInf = os.path.normpath("UefiPayloadPkg/UefiPayloadEntry/{}.inf".format (UpldEntryFile))
|
---|
143 | DscPath = os.path.normpath("UefiPayloadPkg/UefiPayloadPkg.dsc")
|
---|
144 | DxeFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv"))
|
---|
145 | BdsFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv"))
|
---|
146 | NetworkFvOutputDir = os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv"))
|
---|
147 | PayloadReportPath = os.path.join(BuildDir, "UefiUniversalPayload.txt")
|
---|
148 | ModuleReportPath = os.path.join(BuildDir, "UefiUniversalPayloadEntry.txt")
|
---|
149 | UpldInfoFile = os.path.join(BuildDir, "UniversalPayloadInfo.bin")
|
---|
150 |
|
---|
151 | Pcds = ""
|
---|
152 | if (Args.pcd != None):
|
---|
153 | for PcdItem in Args.pcd:
|
---|
154 | Pcds += " --pcd {}".format (PcdItem)
|
---|
155 |
|
---|
156 | Defines = ""
|
---|
157 | Defines += " -D BUILD_ARCH={}".format(Args.Arch)
|
---|
158 | if (Args.Macro != None):
|
---|
159 | for MacroItem in Args.Macro:
|
---|
160 | Defines += " -D {}".format (MacroItem)
|
---|
161 |
|
---|
162 | #
|
---|
163 | # Building DXE core and DXE drivers as DXEFV.
|
---|
164 | #
|
---|
165 | if Args.BuildEntryOnly == False:
|
---|
166 | BuildPayload = "build -p {} -b {} -a {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, ToolChain, PayloadReportPath, Quiet)
|
---|
167 | BuildPayload += Pcds
|
---|
168 | BuildPayload += Defines
|
---|
169 | RunCommand(BuildPayload)
|
---|
170 | #
|
---|
171 | # Building Universal Payload entry.
|
---|
172 | #
|
---|
173 | if Args.PreBuildUplBinary is None:
|
---|
174 | BuildModule = "build -p {} -b {} -a {} -m {} -t {} -y {} {}".format (DscPath, BuildTarget, BuildArch, EntryModuleInf, PayloadEntryToolChain, ModuleReportPath, Quiet)
|
---|
175 | BuildModule += Pcds
|
---|
176 | BuildModule += Defines
|
---|
177 | RunCommand(BuildModule)
|
---|
178 |
|
---|
179 | if Args.PreBuildUplBinary is not None:
|
---|
180 | if Args.Fit == False:
|
---|
181 | EntryOutputDir = os.path.join(BuildDir, "UniversalPayload.elf")
|
---|
182 | else:
|
---|
183 | EntryOutputDir = os.path.join(BuildDir, "UniversalPayload.fit")
|
---|
184 | shutil.copy (os.path.abspath(Args.PreBuildUplBinary), EntryOutputDir)
|
---|
185 |
|
---|
186 | #
|
---|
187 | # Build Universal Payload Information Section ".upld_info"
|
---|
188 | #
|
---|
189 | if Args.Fit == False:
|
---|
190 | upld_info_hdr = UPLD_INFO_HEADER()
|
---|
191 | upld_info_hdr.SpecRevision = Args.SpecRevision
|
---|
192 | upld_info_hdr.Revision = Args.Revision
|
---|
193 | upld_info_hdr.ProducerId = Args.ProducerId.encode()[:16]
|
---|
194 | upld_info_hdr.ImageId = Args.ImageId.encode()[:16]
|
---|
195 | upld_info_hdr.Attribute |= 1 if BuildTarget == "DEBUG" else 0
|
---|
196 | fp = open(UpldInfoFile, 'wb')
|
---|
197 | fp.write(bytearray(upld_info_hdr))
|
---|
198 | fp.close()
|
---|
199 |
|
---|
200 | if Args.BuildEntryOnly == False:
|
---|
201 | import Tools.ElfFv as ElfFv
|
---|
202 | ElfFv.ReplaceFv (EntryOutputDir, UpldInfoFile, '.upld_info', Alignment = 4)
|
---|
203 | if Args.PreBuildUplBinary is None:
|
---|
204 | if Args.Fit == False:
|
---|
205 | shutil.copy (EntryOutputDir, os.path.join(BuildDir, 'UniversalPayload.elf'))
|
---|
206 | else:
|
---|
207 | shutil.copy (EntryOutputDir, os.path.join(BuildDir, 'UniversalPayload.fit'))
|
---|
208 |
|
---|
209 | MultiFvList = []
|
---|
210 | if Args.BuildEntryOnly == False:
|
---|
211 | MultiFvList = [
|
---|
212 | ['uefi_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/DXEFV.Fv")) ],
|
---|
213 | ['bds_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/BDSFV.Fv")) ],
|
---|
214 | ['network_fv', os.path.join(BuildDir, "{}_{}".format (BuildTarget, ToolChain), os.path.normpath("FV/NETWORKFV.Fv"))],
|
---|
215 | ]
|
---|
216 |
|
---|
217 |
|
---|
218 | if Args.Fit == True:
|
---|
219 | import Tools.MkFitImage as MkFitImage
|
---|
220 | import pefile
|
---|
221 | fit_image_info_header = MkFitImage.FIT_IMAGE_INFO_HEADER()
|
---|
222 | fit_image_info_header.Description = 'Uefi Universal Payload'
|
---|
223 | fit_image_info_header.UplVersion = Args.SpecRevision
|
---|
224 | fit_image_info_header.Type = 'flat-binary'
|
---|
225 | fit_image_info_header.Arch = FitArch
|
---|
226 | fit_image_info_header.Compression = 'none'
|
---|
227 | fit_image_info_header.Revision = Args.Revision
|
---|
228 | fit_image_info_header.BuildType = Args.Target.lower()
|
---|
229 | fit_image_info_header.Capabilities = None
|
---|
230 | fit_image_info_header.Producer = Args.ProducerId.lower()
|
---|
231 | fit_image_info_header.ImageId = Args.ImageId.lower()
|
---|
232 | fit_image_info_header.Binary = os.path.join(BuildDir, 'UniversalPayload.fit')
|
---|
233 | fit_image_info_header.TargetPath = os.path.join(BuildDir, 'UniversalPayload.fit')
|
---|
234 | fit_image_info_header.UefifvPath = DxeFvOutputDir
|
---|
235 | fit_image_info_header.BdsfvPath = BdsFvOutputDir
|
---|
236 | fit_image_info_header.NetworkfvPath = NetworkFvOutputDir
|
---|
237 | fit_image_info_header.DataOffset = 0x1000
|
---|
238 | fit_image_info_header.LoadAddr = Args.LoadAddress
|
---|
239 | fit_image_info_header.Project = 'tianocore'
|
---|
240 |
|
---|
241 | TargetRebaseFile = fit_image_info_header.Binary.replace (pathlib.Path(fit_image_info_header.Binary).suffix, ".pecoff")
|
---|
242 | TargetRebaseEntryFile = fit_image_info_header.Binary.replace (pathlib.Path(fit_image_info_header.Binary).suffix, ".entry")
|
---|
243 |
|
---|
244 |
|
---|
245 | #
|
---|
246 | # Rebase PECOFF to load address
|
---|
247 | #
|
---|
248 | RunCommand (
|
---|
249 | "GenFw -e SEC -o {} {}".format (
|
---|
250 | TargetRebaseFile,
|
---|
251 | fit_image_info_header.Binary
|
---|
252 | ))
|
---|
253 | RunCommand (
|
---|
254 | "GenFw --rebase 0x{:02X} -o {} {} ".format (
|
---|
255 | fit_image_info_header.LoadAddr + fit_image_info_header.DataOffset,
|
---|
256 | TargetRebaseFile,
|
---|
257 | TargetRebaseFile,
|
---|
258 | ))
|
---|
259 |
|
---|
260 | #
|
---|
261 | # Open PECOFF relocation table binary.
|
---|
262 | #
|
---|
263 | RelocBinary = b''
|
---|
264 | PeCoff = pefile.PE (TargetRebaseFile)
|
---|
265 | for reloc in PeCoff.DIRECTORY_ENTRY_BASERELOC:
|
---|
266 | for entry in reloc.entries:
|
---|
267 | if (entry.type == 0):
|
---|
268 | continue
|
---|
269 | Type = entry.type
|
---|
270 | Offset = entry.rva + fit_image_info_header.DataOffset
|
---|
271 | RelocBinary += Type.to_bytes (8, 'little') + Offset.to_bytes (8, 'little')
|
---|
272 | RelocBinary += b'\x00' * (0x1000 - (len(RelocBinary) % 0x1000))
|
---|
273 |
|
---|
274 | #
|
---|
275 | # Output UniversalPayload.entry
|
---|
276 | #
|
---|
277 | TempBinary = open (TargetRebaseFile, 'rb')
|
---|
278 | TianoBinary = TempBinary.read ()
|
---|
279 | TempBinary.close ()
|
---|
280 |
|
---|
281 | TianoEntryBinary = TianoBinary + RelocBinary
|
---|
282 | TianoEntryBinary += (b'\x00' * (0x1000 - (len(TianoBinary) % 0x1000)))
|
---|
283 | TianoEntryBinarySize = len (TianoEntryBinary)
|
---|
284 |
|
---|
285 | TempBinary = open(TargetRebaseEntryFile, "wb")
|
---|
286 | TempBinary.truncate()
|
---|
287 | TempBinary.write(TianoEntryBinary)
|
---|
288 | TempBinary.close()
|
---|
289 |
|
---|
290 | #
|
---|
291 | # Calculate entry and update relocation table start address and data-size.
|
---|
292 | #
|
---|
293 | fit_image_info_header.Entry = PeCoff.OPTIONAL_HEADER.ImageBase + PeCoff.OPTIONAL_HEADER.AddressOfEntryPoint
|
---|
294 | fit_image_info_header.RelocStart = fit_image_info_header.DataOffset + len(TianoBinary)
|
---|
295 | fit_image_info_header.DataSize = TianoEntryBinarySize
|
---|
296 | fit_image_info_header.Binary = TargetRebaseEntryFile
|
---|
297 |
|
---|
298 | if MkFitImage.MakeFitImage(fit_image_info_header, Args.Arch) is True:
|
---|
299 | print('\nSuccessfully build Fit Image')
|
---|
300 | else:
|
---|
301 | sys.exit(1)
|
---|
302 | return MultiFvList, os.path.join(BuildDir, 'UniversalPayload.fit')
|
---|
303 | else:
|
---|
304 | return MultiFvList, os.path.join(BuildDir, 'UniversalPayload.elf')
|
---|
305 |
|
---|
306 | def main():
|
---|
307 | parser = argparse.ArgumentParser(description='For building Universal Payload')
|
---|
308 | parser.add_argument('-t', '--ToolChain')
|
---|
309 | parser.add_argument('-b', '--Target', default='DEBUG')
|
---|
310 | parser.add_argument('-a', '--Arch', choices=['IA32', 'X64', 'RISCV64'], help='Specify the ARCH for payload entry module. Default build X64 image.', default ='X64')
|
---|
311 | parser.add_argument("-D", "--Macro", action="append", default=["UNIVERSAL_PAYLOAD=TRUE"])
|
---|
312 | parser.add_argument('-i', '--ImageId', type=str, help='Specify payload ID (16 bytes maximal).', default ='UEFI')
|
---|
313 | parser.add_argument('-q', '--Quiet', action='store_true', help='Disable all build messages except FATAL ERRORS.')
|
---|
314 | parser.add_argument("-p", "--pcd", action="append")
|
---|
315 | parser.add_argument("-s", "--SpecRevision", type=ValidateSpecRevision, default ='0.7', help='Indicates compliance with a revision of this specification in the BCD format.')
|
---|
316 | parser.add_argument("-r", "--Revision", type=Validate32BitInteger, default ='0x0000010105', help='Revision of the Payload binary. Major.Minor.Revision.Build')
|
---|
317 | parser.add_argument("-o", "--ProducerId", default ='INTEL', help='A null-terminated OEM-supplied string that identifies the payload producer (16 bytes maximal).')
|
---|
318 | parser.add_argument("-e", "--BuildEntryOnly", action='store_true', help='Build UniversalPayload Entry file')
|
---|
319 | parser.add_argument("-pb", "--PreBuildUplBinary", default=None, help='Specify the UniversalPayload file')
|
---|
320 | parser.add_argument("-sk", "--SkipBuild", action='store_true', help='Skip UniversalPayload build')
|
---|
321 | parser.add_argument("-af", "--AddFv", type=ValidateAddFv, action='append', help='Add or replace specific FV into payload, Ex: uefi_fv=XXX.fv')
|
---|
322 | parser.add_argument("-f", "--Fit", action='store_true', help='Build UniversalPayload file as UniversalPayload.fit', default=False)
|
---|
323 | parser.add_argument('-l', "--LoadAddress", type=int, help='Specify payload load address', default =0x000800000)
|
---|
324 |
|
---|
325 | args = parser.parse_args()
|
---|
326 |
|
---|
327 |
|
---|
328 | MultiFvList = []
|
---|
329 | UniversalPayloadBinary = args.PreBuildUplBinary
|
---|
330 | if (args.SkipBuild == False):
|
---|
331 | MultiFvList, UniversalPayloadBinary = BuildUniversalPayload(args)
|
---|
332 |
|
---|
333 | if (args.AddFv != None):
|
---|
334 | for (SectionName, SectionFvFile) in args.AddFv:
|
---|
335 | MultiFvList.append ([SectionName, SectionFvFile])
|
---|
336 |
|
---|
337 | def ReplaceFv (UplBinary, SectionFvFile, SectionName, Arch):
|
---|
338 | print (bcolors.OKGREEN + "Patch {}={} into {}".format (SectionName, SectionFvFile, UplBinary) + bcolors.ENDC)
|
---|
339 | if (args.Fit == False):
|
---|
340 | import Tools.ElfFv as ElfFv
|
---|
341 | return ElfFv.ReplaceFv (UplBinary, SectionFvFile, '.upld.{}'.format (SectionName))
|
---|
342 | else:
|
---|
343 | import Tools.MkFitImage as MkFitImage
|
---|
344 | return MkFitImage.ReplaceFv (UplBinary, SectionFvFile, SectionName, Arch)
|
---|
345 |
|
---|
346 | if (UniversalPayloadBinary != None):
|
---|
347 | for (SectionName, SectionFvFile) in MultiFvList:
|
---|
348 | if os.path.exists (SectionFvFile) == False:
|
---|
349 | continue
|
---|
350 | if (args.Fit == False):
|
---|
351 | status = ReplaceFv (UniversalPayloadBinary, SectionFvFile, SectionName, args.Arch)
|
---|
352 | else:
|
---|
353 | status = ReplaceFv (UniversalPayloadBinary, SectionFvFile, SectionName.replace ("_", "-"), args.Arch)
|
---|
354 | if status != 0:
|
---|
355 | print (bcolors.FAIL + "[Fail] Patch {}={}".format (SectionName, SectionFvFile) + bcolors.ENDC)
|
---|
356 | return status
|
---|
357 |
|
---|
358 | print ("\nSuccessfully build Universal Payload")
|
---|
359 |
|
---|
360 | if __name__ == '__main__':
|
---|
361 | main()
|
---|