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