VirtualBox

source: vbox/trunk/src/VBox/Devices/EFI/Firmware/BaseTools/Scripts/BinToPcd.py

Last change on this file was 108794, checked in by vboxsync, 7 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: 9.8 KB
Line 
1## @file
2# Convert a binary file to a VOID* PCD value or DSC file VOID* PCD statement.
3#
4# Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
5# SPDX-License-Identifier: BSD-2-Clause-Patent
6#
7
8'''
9BinToPcd
10'''
11from __future__ import print_function
12
13import argparse
14import io
15import math
16import re
17import struct
18import sys
19
20#
21# Globals for help information
22#
23__prog__ = 'BinToPcd'
24__copyright__ = 'Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.'
25__description__ = 'Convert one or more binary files to a VOID* PCD value or DSC file VOID* PCD statement.\n'
26
27if __name__ == '__main__':
28 def ValidateUnsignedInteger (Argument):
29 try:
30 Value = int (Argument, 0)
31 except:
32 Message = '{Argument} is not a valid integer value.'.format (Argument = Argument)
33 raise argparse.ArgumentTypeError (Message)
34 if Value < 0:
35 Message = '{Argument} is a negative value.'.format (Argument = Argument)
36 raise argparse.ArgumentTypeError (Message)
37 return Value
38
39 def ValidatePcdName (Argument):
40 if re.split (r'[a-zA-Z\_][a-zA-Z0-9\_]*\.[a-zA-Z\_][a-zA-Z0-9\_]*', Argument) != ['', '']:
41 Message = '{Argument} is not in the form <PcdTokenSpaceGuidCName>.<PcdCName>'.format (Argument = Argument)
42 raise argparse.ArgumentTypeError (Message)
43 return Argument
44
45 def ValidateGuidName (Argument):
46 if re.split (r'[a-zA-Z\_][a-zA-Z0-9\_]*', Argument) != ['', '']:
47 Message = '{Argument} is not a valid GUID C name'.format (Argument = Argument)
48 raise argparse.ArgumentTypeError (Message)
49 return Argument
50
51 def XdrPackBuffer (buffer):
52 packed_bytes = io.BytesIO()
53 for unpacked_bytes in buffer:
54 n = len(unpacked_bytes)
55 packed_bytes.write(struct.pack('>L',n))
56 data = unpacked_bytes[:n]
57 n = math.ceil(n/4)*4
58 data = data + (n - len(data)) * b'\0'
59 packed_bytes.write(data)
60 return packed_bytes.getvalue()
61
62 def ByteArray (Buffer, Xdr = False):
63 if Xdr:
64 #
65 # If Xdr flag is set then encode data using the Variable-Length Opaque
66 # Data format of RFC 4506 External Data Representation Standard (XDR).
67 #
68 Buffer = bytearray (XdrPackBuffer (Buffer))
69 else:
70 #
71 # If Xdr flag is not set, then concatenate all the data
72 #
73 Buffer = bytearray (b''.join (Buffer))
74 #
75 # Return a PCD value of the form '{0x01, 0x02, ...}' along with the PCD length in bytes
76 #
77 return '{' + (', '.join (['0x{Byte:02X}'.format (Byte = Item) for Item in Buffer])) + '}', len (Buffer)
78
79 #
80 # Create command line argument parser object
81 #
82 parser = argparse.ArgumentParser (prog = __prog__,
83 description = __description__ + __copyright__,
84 conflict_handler = 'resolve')
85 parser.add_argument ("-i", "--input", dest = 'InputFile', type = argparse.FileType ('rb'), action='append', required = True,
86 help = "Input binary filename. Multiple input files are combined into a single PCD.")
87 parser.add_argument ("-o", "--output", dest = 'OutputFile', type = argparse.FileType ('w'),
88 help = "Output filename for PCD value or PCD statement")
89 parser.add_argument ("-p", "--pcd", dest = 'PcdName', type = ValidatePcdName,
90 help = "Name of the PCD in the form <PcdTokenSpaceGuidCName>.<PcdCName>")
91 parser.add_argument ("-t", "--type", dest = 'PcdType', default = None, choices = ['VPD', 'HII'],
92 help = "PCD statement type (HII or VPD). Default is standard.")
93 parser.add_argument ("-m", "--max-size", dest = 'MaxSize', type = ValidateUnsignedInteger,
94 help = "Maximum size of the PCD. Ignored with --type HII.")
95 parser.add_argument ("-f", "--offset", dest = 'Offset', type = ValidateUnsignedInteger,
96 help = "VPD offset if --type is VPD. UEFI Variable offset if --type is HII. Must be 8-byte aligned.")
97 parser.add_argument ("-n", "--variable-name", dest = 'VariableName',
98 help = "UEFI variable name. Only used with --type HII.")
99 parser.add_argument ("-g", "--variable-guid", type = ValidateGuidName, dest = 'VariableGuid',
100 help = "UEFI variable GUID C name. Only used with --type HII.")
101 parser.add_argument ("-x", "--xdr", dest = 'Xdr', action = "store_true",
102 help = "Encode PCD using the Variable-Length Opaque Data format of RFC 4506 External Data Representation Standard (XDR)")
103 parser.add_argument ("-v", "--verbose", dest = 'Verbose', action = "store_true",
104 help = "Increase output messages")
105 parser.add_argument ("-q", "--quiet", dest = 'Quiet', action = "store_true",
106 help = "Reduce output messages")
107 parser.add_argument ("--debug", dest = 'Debug', type = int, metavar = '[0-9]', choices = range (0, 10), default = 0,
108 help = "Set debug level")
109
110 #
111 # Parse command line arguments
112 #
113 args = parser.parse_args ()
114
115 #
116 # Read all binary input files
117 #
118 Buffer = []
119 for File in args.InputFile:
120 try:
121 Buffer.append (File.read ())
122 File.close ()
123 except:
124 print ('BinToPcd: error: can not read binary input file {File}'.format (File = File))
125 sys.exit (1)
126
127 #
128 # Convert PCD to an encoded string of hex values and determine the size of
129 # the encoded PCD in bytes.
130 #
131 PcdValue, PcdSize = ByteArray (Buffer, args.Xdr)
132
133 #
134 # Convert binary buffer to a DSC file PCD statement
135 #
136 if args.PcdName is None:
137 #
138 # If PcdName is None, then only a PCD value is being requested.
139 #
140 Pcd = PcdValue
141 if args.Verbose:
142 print ('BinToPcd: Convert binary file to PCD Value')
143 elif args.PcdType is None:
144 #
145 # If --type is neither VPD nor HII, then use PCD statement syntax that is
146 # compatible with [PcdsFixedAtBuild], [PcdsPatchableInModule],
147 # [PcdsDynamicDefault], and [PcdsDynamicExDefault].
148 #
149 if args.MaxSize is None:
150 #
151 # If --max-size is not provided, then do not generate the syntax that
152 # includes the maximum size.
153 #
154 Pcd = ' {Name}|{Value}'.format (Name = args.PcdName, Value = PcdValue)
155 elif args.MaxSize < PcdSize:
156 print ('BinToPcd: error: argument --max-size is smaller than input file.')
157 sys.exit (1)
158 else:
159 Pcd = ' {Name}|{Value}|VOID*|{Size}'.format (Name = args.PcdName, Value = PcdValue, Size = args.MaxSize)
160
161 if args.Verbose:
162 print ('BinToPcd: Convert binary file to PCD statement compatible with PCD sections:')
163 print (' [PcdsFixedAtBuild]')
164 print (' [PcdsPatchableInModule]')
165 print (' [PcdsDynamicDefault]')
166 print (' [PcdsDynamicExDefault]')
167 elif args.PcdType == 'VPD':
168 if args.MaxSize is None:
169 #
170 # If --max-size is not provided, then set maximum size to the size of the
171 # binary input file
172 #
173 args.MaxSize = PcdSize
174 if args.MaxSize < PcdSize:
175 print ('BinToPcd: error: argument --max-size is smaller than input file.')
176 sys.exit (1)
177 if args.Offset is None:
178 #
179 # if --offset is not provided, then set offset field to '*' so build
180 # tools will compute offset of PCD in VPD region.
181 #
182 Pcd = ' {Name}|*|{Size}|{Value}'.format (Name = args.PcdName, Size = args.MaxSize, Value = PcdValue)
183 else:
184 #
185 # --offset value must be 8-byte aligned
186 #
187 if (args.Offset % 8) != 0:
188 print ('BinToPcd: error: argument --offset must be 8-byte aligned.')
189 sys.exit (1)
190 #
191 # Use the --offset value provided.
192 #
193 Pcd = ' {Name}|{Offset}|{Size}|{Value}'.format (Name = args.PcdName, Offset = args.Offset, Size = args.MaxSize, Value = PcdValue)
194 if args.Verbose:
195 print ('BinToPcd: Convert binary file to PCD statement compatible with PCD sections')
196 print (' [PcdsDynamicVpd]')
197 print (' [PcdsDynamicExVpd]')
198 elif args.PcdType == 'HII':
199 if args.VariableGuid is None or args.VariableName is None:
200 print ('BinToPcd: error: arguments --variable-guid and --variable-name are required for --type HII.')
201 sys.exit (1)
202 if args.Offset is None:
203 #
204 # Use UEFI Variable offset of 0 if --offset is not provided
205 #
206 args.Offset = 0
207 #
208 # --offset value must be 8-byte aligned
209 #
210 if (args.Offset % 8) != 0:
211 print ('BinToPcd: error: argument --offset must be 8-byte aligned.')
212 sys.exit (1)
213 Pcd = ' {Name}|L"{VarName}"|{VarGuid}|{Offset}|{Value}'.format (Name = args.PcdName, VarName = args.VariableName, VarGuid = args.VariableGuid, Offset = args.Offset, Value = PcdValue)
214 if args.Verbose:
215 print ('BinToPcd: Convert binary file to PCD statement compatible with PCD sections')
216 print (' [PcdsDynamicHii]')
217 print (' [PcdsDynamicExHii]')
218
219 #
220 # Write PCD value or PCD statement to the output file
221 #
222 try:
223 args.OutputFile.write (Pcd)
224 args.OutputFile.close ()
225 except:
226 #
227 # If output file is not specified or it can not be written, then write the
228 # PCD value or PCD statement to the console
229 #
230 print (Pcd)
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