]> git.proxmox.com Git - mirror_edk2.git/blame_incremental - BaseTools/Scripts/BinToPcd.py
BaseTools/BinToPcd: Update for Python 3 compatibility
[mirror_edk2.git] / BaseTools / Scripts / BinToPcd.py
... / ...
CommitLineData
1## @file\r
2# Convert a binary file to a VOID* PCD value or DSC file VOID* PCD statement.\r
3#\r
4# Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>\r
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
21import xdrlib\r
22\r
23#\r
24# Globals for help information\r
25#\r
26__prog__ = 'BinToPcd'\r
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
29\r
30if __name__ == '__main__':\r
31 def ValidateUnsignedInteger (Argument):\r
32 try:\r
33 Value = int (Argument, 0)\r
34 except:\r
35 Message = '{Argument} is not a valid integer value.'.format (Argument = Argument)\r
36 raise argparse.ArgumentTypeError(Message)\r
37 if Value < 0:\r
38 Message = '{Argument} is a negative value.'.format (Argument = Argument)\r
39 raise argparse.ArgumentTypeError(Message)\r
40 return Value\r
41\r
42 def ValidatePcdName (Argument):\r
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
45 raise argparse.ArgumentTypeError(Message)\r
46 return Argument\r
47\r
48 def ValidateGuidName (Argument):\r
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
51 raise argparse.ArgumentTypeError(Message)\r
52 return Argument\r
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
63 Buffer = bytearray(XdrEncoder.get_buffer())\r
64 else:\r
65 #\r
66 # If Xdr flag is not set, then concatenate all the data\r
67 #\r
68 Buffer = b''.join(Buffer)\r
69 #\r
70 # Return a PCD value of the form '{0x01, 0x02, ...}' along with the PCD length in bytes\r
71 #\r
72 return '{' + (', '.join(['0x{Byte:02X}'.format(Byte = Item) for Item in Buffer])) + '}', len (Buffer)\r
73\r
74 #\r
75 # Create command line argument parser object\r
76 #\r
77 parser = argparse.ArgumentParser(prog = __prog__,\r
78 description = __description__ + __copyright__,\r
79 conflict_handler = 'resolve')\r
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
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
91 help = "VPD offset if --type is VPD. UEFI Variable offset if --type is HII. Must be 8-byte aligned.")\r
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
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
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
111 # Read all binary input files\r
112 #\r
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
119 print ('BinToPcd: error: can not read binary input file {File}'.format (File = File))\r
120 sys.exit(1)\r
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
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
134 #\r
135 Pcd = PcdValue\r
136 if args.Verbose:\r
137 print ('BinToPcd: Convert binary file to PCD Value')\r
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
149 Pcd = ' {Name}|{Value}'.format (Name = args.PcdName, Value = PcdValue)\r
150 elif args.MaxSize < PcdSize:\r
151 print ('BinToPcd: error: argument --max-size is smaller than input file.')\r
152 sys.exit(1)\r
153 else:\r
154 Pcd = ' {Name}|{Value}|VOID*|{Size}'.format (Name = args.PcdName, Value = PcdValue, Size = args.MaxSize)\r
155\r
156 if args.Verbose:\r
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
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
168 args.MaxSize = PcdSize\r
169 if args.MaxSize < PcdSize:\r
170 print ('BinToPcd: error: argument --max-size is smaller than input file.')\r
171 sys.exit(1)\r
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
177 Pcd = ' {Name}|*|{Size}|{Value}'.format (Name = args.PcdName, Size = args.MaxSize, Value = PcdValue)\r
178 else:\r
179 #\r
180 # --offset value must be 8-byte aligned\r
181 #\r
182 if (args.Offset % 8) != 0:\r
183 print ('BinToPcd: error: argument --offset must be 8-byte aligned.')\r
184 sys.exit(1)\r
185 #\r
186 # Use the --offset value provided.\r
187 #\r
188 Pcd = ' {Name}|{Offset}|{Size}|{Value}'.format (Name = args.PcdName, Offset = args.Offset, Size = args.MaxSize, Value = PcdValue)\r
189 if args.Verbose:\r
190 print ('BinToPcd: Convert binary file to PCD statement compatible with PCD sections')\r
191 print (' [PcdsDynamicVpd]')\r
192 print (' [PcdsDynamicExVpd]')\r
193 elif args.PcdType == 'HII':\r
194 if args.VariableGuid is None or args.VariableName is None:\r
195 print ('BinToPcd: error: arguments --variable-guid and --variable-name are required for --type HII.')\r
196 sys.exit(1)\r
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
202 #\r
203 # --offset value must be 8-byte aligned\r
204 #\r
205 if (args.Offset % 8) != 0:\r
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
209 if args.Verbose:\r
210 print ('BinToPcd: Convert binary file to PCD statement compatible with PCD sections')\r
211 print (' [PcdsDynamicHii]')\r
212 print (' [PcdsDynamicExHii]')\r
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
225 print (Pcd)\r