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