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