BinToPcd.py 9.7 KB

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