VirtualBox

source: vbox/trunk/src/VBox/Devices/EFI/Firmware/BaseTools/Scripts/BinToPcd.py@ 105681

最後變更 在這個檔案從105681是 101291,由 vboxsync 提交於 14 月 前

EFI/FirmwareNew: Make edk2-stable202308 build on all supported platforms (using gcc at least, msvc not tested yet), bugref:4643

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette