BaseTools/BinToPcd: Clarify error message for --type HII
[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 __version__ = '%s Version %s' % (__prog__, '0.91 ')
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 = '%s is not a valid integer value.' % (Argument)
37 raise argparse.ArgumentTypeError(Message)
38 if Value < 0:
39 Message = '%s is a negative value.' % (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 = '%s is not in the form <PcdTokenSpaceGuidCName>.<PcdCName>' % (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 = '%s is not a valid GUID C name' % (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 = XdrEncoder.get_buffer()
65 else:
66 #
67 # If Xdr flag is not set, then concatenate all the data
68 #
69 Buffer = ''.join(Buffer)
70 #
71 # Return a PCD value of the form '{0x01, 0x02, ...}' along with the PCD length in bytes
72 #
73 return '{%s}' % (', '.join(['0x%02x' % (ord(Item)) for Item in Buffer])), len (Buffer)
74
75 #
76 # Create command line argument parser object
77 #
78 parser = argparse.ArgumentParser(prog = __prog__, version = __version__,
79 description = __description__ + __copyright__,
80 conflict_handler = 'resolve')
81 parser.add_argument("-i", "--input", dest = 'InputFile', type = argparse.FileType('rb'), action='append', required = True,
82 help = "Input binary filename. Multiple input files are combined into a single PCD.")
83 parser.add_argument("-o", "--output", dest = 'OutputFile', type = argparse.FileType('wb'),
84 help = "Output filename for PCD value or PCD statement")
85 parser.add_argument("-p", "--pcd", dest = 'PcdName', type = ValidatePcdName,
86 help = "Name of the PCD in the form <PcdTokenSpaceGuidCName>.<PcdCName>")
87 parser.add_argument("-t", "--type", dest = 'PcdType', default = None, choices = ['VPD','HII'],
88 help = "PCD statement type (HII or VPD). Default is standard.")
89 parser.add_argument("-m", "--max-size", dest = 'MaxSize', type = ValidateUnsignedInteger,
90 help = "Maximum size of the PCD. Ignored with --type HII.")
91 parser.add_argument("-f", "--offset", dest = 'Offset', type = ValidateUnsignedInteger,
92 help = "VPD offset if --type is VPD. UEFI Variable offset if --type is HII.")
93 parser.add_argument("-n", "--variable-name", dest = 'VariableName',
94 help = "UEFI variable name. Only used with --type HII.")
95 parser.add_argument("-g", "--variable-guid", type = ValidateGuidName, dest = 'VariableGuid',
96 help = "UEFI variable GUID C name. Only used with --type HII.")
97 parser.add_argument("-x", "--xdr", dest = 'Xdr', action = "store_true",
98 help = "Encode PCD using the Variable-Length Opaque Data format of RFC 4506 External Data Representation Standard (XDR)")
99 parser.add_argument("-v", "--verbose", dest = 'Verbose', action = "store_true",
100 help = "Increase output messages")
101 parser.add_argument("-q", "--quiet", dest = 'Quiet', action = "store_true",
102 help = "Reduce output messages")
103 parser.add_argument("--debug", dest = 'Debug', type = int, metavar = '[0-9]', choices = range(0,10), default = 0,
104 help = "Set debug level")
105
106 #
107 # Parse command line arguments
108 #
109 args = parser.parse_args()
110
111 #
112 # Read all binary input files
113 #
114 Buffer = []
115 for File in args.InputFile:
116 try:
117 Buffer.append(File.read())
118 File.close()
119 except:
120 print 'BinToPcd: error: can not read binary input file', File
121 sys.exit()
122
123 #
124 # Convert PCD to an encoded string of hex values and determine the size of
125 # the encoded PCD in bytes.
126 #
127 PcdValue, PcdSize = ByteArray (Buffer, args.Xdr)
128
129 #
130 # Convert binary buffer to a DSC file PCD statement
131 #
132 if args.PcdName is None:
133 #
134 # If PcdName is None, then only a PCD value is being requested.
135 #
136 Pcd = PcdValue
137 if args.Verbose:
138 print 'BinToPcd: Convert binary file to PCD Value'
139 elif args.PcdType is None:
140 #
141 # If --type is neither VPD nor HII, then use PCD statement syntax that is
142 # compatible with [PcdsFixedAtBuild], [PcdsPatchableInModule],
143 # [PcdsDynamicDefault], and [PcdsDynamicExDefault].
144 #
145 if args.MaxSize is None:
146 #
147 # If --max-size is not provided, then do not generate the syntax that
148 # includes the maximum size.
149 #
150 Pcd = ' %s|%s' % (args.PcdName, PcdValue)
151 elif args.MaxSize < PcdSize:
152 print 'BinToPcd: error: argument --max-size is smaller than input file.'
153 sys.exit()
154 else:
155 Pcd = ' %s|%s|VOID*|%d' % (args.PcdName, PcdValue, args.MaxSize)
156
157 if args.Verbose:
158 print 'BinToPcd: Convert binary file to PCD statement compatible with PCD sections:'
159 print ' [PcdsFixedAtBuild]'
160 print ' [PcdsPatchableInModule]'
161 print ' [PcdsDynamicDefault]'
162 print ' [PcdsDynamicExDefault]'
163 elif args.PcdType == 'VPD':
164 if args.MaxSize is None:
165 #
166 # If --max-size is not provided, then set maximum size to the size of the
167 # binary input file
168 #
169 args.MaxSize = PcdSize
170 if args.MaxSize < PcdSize:
171 print 'BinToPcd: error: argument --max-size is smaller than input file.'
172 sys.exit()
173 if args.Offset is None:
174 #
175 # if --offset is not provided, then set offset field to '*' so build
176 # tools will compute offset of PCD in VPD region.
177 #
178 Pcd = ' %s|*|%d|%s' % (args.PcdName, args.MaxSize, PcdValue)
179 else:
180 #
181 # Use the --offset value provided.
182 #
183 Pcd = ' %s|%d|%d|%s' % (args.PcdName, args.Offset, args.MaxSize, PcdValue)
184 if args.Verbose:
185 print 'BinToPcd: Convert binary file to PCD statement compatible with PCD sections'
186 print ' [PcdsDynamicVpd]'
187 print ' [PcdsDynamicExVpd]'
188 elif args.PcdType == 'HII':
189 if args.VariableGuid is None or args.VariableName is None:
190 print 'BinToPcd: error: arguments --variable-guid and --variable-name are required for --type HII.'
191 sys.exit()
192 if args.Offset is None:
193 #
194 # Use UEFI Variable offset of 0 if --offset is not provided
195 #
196 args.Offset = 0
197 Pcd = ' %s|L"%s"|%s|%d|%s' % (args.PcdName, args.VariableName, args.VariableGuid, args.Offset, PcdValue)
198 if args.Verbose:
199 print 'BinToPcd: Convert binary file to PCD statement compatible with PCD sections'
200 print ' [PcdsDynamicHii]'
201 print ' [PcdsDynamicExHii]'
202
203 #
204 # Write PCD value or PCD statement to the output file
205 #
206 try:
207 args.OutputFile.write (Pcd)
208 args.OutputFile.close ()
209 except:
210 #
211 # If output file is not specified or it can not be written, then write the
212 # PCD value or PCD statement to the console
213 #
214 print Pcd