]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Scripts/BinToPcd.py
BaseTools/BinToPcd: Fix Python 2.7.x compatibility issue
[mirror_edk2.git] / BaseTools / Scripts / BinToPcd.py
index f2485a27fa3391acc7844fb362ae505519c7de87..25b74f60049335d57f0878ed69e40fe0c6f0c5d9 100644 (file)
@@ -14,6 +14,7 @@
 '''\r
 BinToPcd\r
 '''\r
 '''\r
 BinToPcd\r
 '''\r
+from __future__ import print_function\r
 \r
 import sys\r
 import argparse\r
 \r
 import sys\r
 import argparse\r
@@ -24,194 +25,202 @@ import xdrlib
 # Globals for help information\r
 #\r
 __prog__        = 'BinToPcd'\r
 # Globals for help information\r
 #\r
 __prog__        = 'BinToPcd'\r
-__version__     = '%s Version %s' % (__prog__, '0.91 ')\r
 __copyright__   = 'Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.'\r
 __description__ = 'Convert one or more binary files to a VOID* PCD value or DSC file VOID* PCD statement.\n'\r
 \r
 if __name__ == '__main__':\r
 __copyright__   = 'Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.'\r
 __description__ = 'Convert one or more binary files to a VOID* PCD value or DSC file VOID* PCD statement.\n'\r
 \r
 if __name__ == '__main__':\r
-  def ValidateUnsignedInteger (Argument):\r
-    try:\r
-      Value = int (Argument, 0)\r
-    except:\r
-      Message = '%s is not a valid integer value.' % (Argument)\r
-      raise argparse.ArgumentTypeError(Message)\r
-    if Value < 0:\r
-      Message = '%s is a negative value.' % (Argument)\r
-      raise argparse.ArgumentTypeError(Message)\r
-    return Value\r
+    def ValidateUnsignedInteger (Argument):\r
+        try:\r
+            Value = int (Argument, 0)\r
+        except:\r
+            Message = '{Argument} is not a valid integer value.'.format (Argument = Argument)\r
+            raise argparse.ArgumentTypeError (Message)\r
+        if Value < 0:\r
+            Message = '{Argument} is a negative value.'.format (Argument = Argument)\r
+            raise argparse.ArgumentTypeError (Message)\r
+        return Value\r
 \r
 \r
-  def ValidatePcdName (Argument):\r
-    if re.split('[a-zA-Z\_][a-zA-Z0-9\_]*\.[a-zA-Z\_][a-zA-Z0-9\_]*', Argument) <> ['','']:\r
-      Message = '%s is not in the form <PcdTokenSpaceGuidCName>.<PcdCName>' % (Argument)\r
-      raise argparse.ArgumentTypeError(Message)\r
-    return Argument\r
+    def ValidatePcdName (Argument):\r
+        if re.split ('[a-zA-Z\_][a-zA-Z0-9\_]*\.[a-zA-Z\_][a-zA-Z0-9\_]*', Argument) != ['', '']:\r
+            Message = '{Argument} is not in the form <PcdTokenSpaceGuidCName>.<PcdCName>'.format (Argument = Argument)\r
+            raise argparse.ArgumentTypeError (Message)\r
+        return Argument\r
 \r
 \r
-  def ValidateGuidName (Argument):\r
-    if re.split('[a-zA-Z\_][a-zA-Z0-9\_]*', Argument) <> ['','']:\r
-      Message = '%s is not a valid GUID C name' % (Argument)\r
-      raise argparse.ArgumentTypeError(Message)\r
-    return Argument\r
+    def ValidateGuidName (Argument):\r
+        if re.split ('[a-zA-Z\_][a-zA-Z0-9\_]*', Argument) != ['', '']:\r
+            Message = '{Argument} is not a valid GUID C name'.format (Argument = Argument)\r
+            raise argparse.ArgumentTypeError (Message)\r
+        return Argument\r
+\r
+    def ByteArray (Buffer, Xdr = False):\r
+        if Xdr:\r
+            #\r
+            # If Xdr flag is set then encode data using the Variable-Length Opaque\r
+            # Data format of RFC 4506 External Data Representation Standard (XDR).\r
+            #\r
+            XdrEncoder = xdrlib.Packer ()\r
+            for Item in Buffer:\r
+                XdrEncoder.pack_bytes (Item)\r
+            Buffer = bytearray (XdrEncoder.get_buffer ())\r
+        else:\r
+            #\r
+            # If Xdr flag is not set, then concatenate all the data\r
+            #\r
+            Buffer = bytearray (b''.join (Buffer))\r
+        #\r
+        # Return a PCD value of the form '{0x01, 0x02, ...}' along with the PCD length in bytes\r
+        #\r
+        return '{' + (', '.join (['0x{Byte:02X}'.format (Byte = Item) for Item in Buffer])) + '}', len (Buffer)\r
 \r
 \r
-  def ByteArray (Buffer, Xdr = False):\r
-    if Xdr:\r
-      #\r
-      # If Xdr flag is set then encode data using the Variable-Length Opaque\r
-      # Data format of RFC 4506 External Data Representation Standard (XDR).\r
-      #\r
-      XdrEncoder = xdrlib.Packer()\r
-      for Item in Buffer:\r
-        XdrEncoder.pack_bytes(Item)\r
-      Buffer = XdrEncoder.get_buffer()\r
-    else:\r
-      #\r
-      # If Xdr flag is not set, then concatenate all the data\r
-      #\r
-      Buffer = ''.join(Buffer)\r
     #\r
     #\r
-    # Return a PCD value of the form '{0x01, 0x02, ...}' along with the PCD length in bytes\r
+    # Create command line argument parser object\r
     #\r
     #\r
-    return '{%s}' % (', '.join(['0x%02x' % (ord(Item)) for Item in Buffer])), len (Buffer)\r
-\r
-  #\r
-  # Create command line argument parser object\r
-  #\r
-  parser = argparse.ArgumentParser(prog = __prog__, version = __version__,\r
-                                   description = __description__ + __copyright__,\r
-                                   conflict_handler = 'resolve')\r
-  parser.add_argument("-i", "--input", dest = 'InputFile', type = argparse.FileType('rb'), action='append', required = True,\r
-                      help = "Input binary filename.  Multiple input files are combined into a single PCD.")\r
-  parser.add_argument("-o", "--output", dest = 'OutputFile', type = argparse.FileType('wb'),\r
-                      help = "Output filename for PCD value or PCD statement")\r
-  parser.add_argument("-p", "--pcd", dest = 'PcdName', type = ValidatePcdName,\r
-                      help = "Name of the PCD in the form <PcdTokenSpaceGuidCName>.<PcdCName>")\r
-  parser.add_argument("-t", "--type", dest = 'PcdType', default = None, choices = ['VPD','HII'],\r
-                      help = "PCD statement type (HII or VPD).  Default is standard.")\r
-  parser.add_argument("-m", "--max-size", dest = 'MaxSize', type = ValidateUnsignedInteger,\r
-                      help = "Maximum size of the PCD.  Ignored with --type HII.")\r
-  parser.add_argument("-f", "--offset", dest = 'Offset', type = ValidateUnsignedInteger,\r
-                      help = "VPD offset if --type is VPD.  UEFI Variable offset if --type is HII.")\r
-  parser.add_argument("-n", "--variable-name", dest = 'VariableName',\r
-                      help = "UEFI variable name.  Only used with --type HII.")\r
-  parser.add_argument("-g", "--variable-guid", type = ValidateGuidName, dest = 'VariableGuid',\r
-                      help = "UEFI variable GUID C name.  Only used with --type HII.")\r
-  parser.add_argument("-x", "--xdr", dest = 'Xdr', action = "store_true",\r
-                      help = "Encode PCD using the Variable-Length Opaque Data format of RFC 4506 External Data Representation Standard (XDR)")\r
-  parser.add_argument("-v", "--verbose", dest = 'Verbose', action = "store_true",\r
-                      help = "Increase output messages")\r
-  parser.add_argument("-q", "--quiet", dest = 'Quiet', action = "store_true",\r
-                      help = "Reduce output messages")\r
-  parser.add_argument("--debug", dest = 'Debug', type = int, metavar = '[0-9]', choices = range(0,10), default = 0,\r
-                      help = "Set debug level")\r
+    parser = argparse.ArgumentParser (prog = __prog__,\r
+                                      description = __description__ + __copyright__,\r
+                                      conflict_handler = 'resolve')\r
+    parser.add_argument ("-i", "--input", dest = 'InputFile', type = argparse.FileType ('rb'), action='append', required = True,\r
+                         help = "Input binary filename.  Multiple input files are combined into a single PCD.")\r
+    parser.add_argument ("-o", "--output", dest = 'OutputFile', type = argparse.FileType ('wb'),\r
+                         help = "Output filename for PCD value or PCD statement")\r
+    parser.add_argument ("-p", "--pcd", dest = 'PcdName', type = ValidatePcdName,\r
+                         help = "Name of the PCD in the form <PcdTokenSpaceGuidCName>.<PcdCName>")\r
+    parser.add_argument ("-t", "--type", dest = 'PcdType', default = None, choices = ['VPD', 'HII'],\r
+                         help = "PCD statement type (HII or VPD).  Default is standard.")\r
+    parser.add_argument ("-m", "--max-size", dest = 'MaxSize', type = ValidateUnsignedInteger,\r
+                         help = "Maximum size of the PCD.  Ignored with --type HII.")\r
+    parser.add_argument ("-f", "--offset", dest = 'Offset', type = ValidateUnsignedInteger,\r
+                         help = "VPD offset if --type is VPD.  UEFI Variable offset if --type is HII.  Must be 8-byte aligned.")\r
+    parser.add_argument ("-n", "--variable-name", dest = 'VariableName',\r
+                         help = "UEFI variable name.  Only used with --type HII.")\r
+    parser.add_argument ("-g", "--variable-guid", type = ValidateGuidName, dest = 'VariableGuid',\r
+                         help = "UEFI variable GUID C name.  Only used with --type HII.")\r
+    parser.add_argument ("-x", "--xdr", dest = 'Xdr', action = "store_true",\r
+                         help = "Encode PCD using the Variable-Length Opaque Data format of RFC 4506 External Data Representation Standard (XDR)")\r
+    parser.add_argument ("-v", "--verbose", dest = 'Verbose', action = "store_true",\r
+                         help = "Increase output messages")\r
+    parser.add_argument ("-q", "--quiet", dest = 'Quiet', action = "store_true",\r
+                         help = "Reduce output messages")\r
+    parser.add_argument ("--debug", dest = 'Debug', type = int, metavar = '[0-9]', choices = range (0, 10), default = 0,\r
+                         help = "Set debug level")\r
 \r
 \r
-  #\r
-  # Parse command line arguments\r
-  #\r
-  args = parser.parse_args()\r
-\r
-  #\r
-  # Read all binary input files\r
-  #\r
-  Buffer = []\r
-  for File in args.InputFile:\r
-    try:\r
-      Buffer.append(File.read())\r
-      File.close()\r
-    except:\r
-      print 'BinToPcd: error: can not read binary input file', File\r
-      sys.exit()\r
+    #\r
+    # Parse command line arguments\r
+    #\r
+    args = parser.parse_args ()\r
 \r
 \r
-  #\r
-  # Convert PCD to an encoded string of hex values and determine the size of\r
-  # the encoded PCD in bytes.\r
-  #\r
-  PcdValue, PcdSize = ByteArray (Buffer, args.Xdr)\r
+    #\r
+    # Read all binary input files\r
+    #\r
+    Buffer = []\r
+    for File in args.InputFile:\r
+        try:\r
+            Buffer.append (File.read ())\r
+            File.close ()\r
+        except:\r
+            print ('BinToPcd: error: can not read binary input file {File}'.format (File = File))\r
+            sys.exit (1)\r
 \r
 \r
-  #\r
-  # Convert binary buffer to a DSC file PCD statement\r
-  #\r
-  if args.PcdName is None:\r
     #\r
     #\r
-    # If PcdName is None, then only a PCD value is being requested.\r
+    # Convert PCD to an encoded string of hex values and determine the size of\r
+    # the encoded PCD in bytes.\r
     #\r
     #\r
-    Pcd = PcdValue\r
-    if args.Verbose:\r
-      print 'PcdToBin: Convert binary file to PCD Value'\r
-  elif args.PcdType is None:\r
+    PcdValue, PcdSize = ByteArray (Buffer, args.Xdr)\r
+\r
     #\r
     #\r
-    # If --type is neither VPD nor HII, then use PCD statement syntax that is\r
-    # compatible with [PcdsFixedAtBuild], [PcdsPatchableInModule],\r
-    # [PcdsDynamicDefault], and [PcdsDynamicExDefault].\r
+    # Convert binary buffer to a DSC file PCD statement\r
     #\r
     #\r
-    if args.MaxSize is None:\r
-      #\r
-      # If --max-size is not provided, then do not generate the syntax that\r
-      # includes the maximum size.\r
-      #\r
-      Pcd = '  %s|%s' % (args.PcdName, PcdValue)\r
-    elif args.MaxSize < PcdSize:\r
-      print 'BinToPcd: error: argument --max-size is smaller than input file.'\r
-      sys.exit()\r
-    else:\r
-      Pcd = '  %s|%s|VOID*|%d' % (args.PcdName, PcdValue, args.MaxSize)\r
+    if args.PcdName is None:\r
+        #\r
+        # If PcdName is None, then only a PCD value is being requested.\r
+        #\r
+        Pcd = PcdValue\r
+        if args.Verbose:\r
+            print ('BinToPcd: Convert binary file to PCD Value')\r
+    elif args.PcdType is None:\r
+        #\r
+        # If --type is neither VPD nor HII, then use PCD statement syntax that is\r
+        # compatible with [PcdsFixedAtBuild], [PcdsPatchableInModule],\r
+        # [PcdsDynamicDefault], and [PcdsDynamicExDefault].\r
+        #\r
+        if args.MaxSize is None:\r
+            #\r
+            # If --max-size is not provided, then do not generate the syntax that\r
+            # includes the maximum size.\r
+            #\r
+            Pcd = '  {Name}|{Value}'.format (Name = args.PcdName, Value = PcdValue)\r
+        elif args.MaxSize < PcdSize:\r
+            print ('BinToPcd: error: argument --max-size is smaller than input file.')\r
+            sys.exit (1)\r
+        else:\r
+            Pcd = '  {Name}|{Value}|VOID*|{Size}'.format (Name = args.PcdName, Value = PcdValue, Size = args.MaxSize)\r
 \r
 \r
-    if args.Verbose:\r
-      print 'PcdToBin: Convert binary file to PCD statement compatible with PCD sections:'\r
-      print '    [PcdsFixedAtBuild]'\r
-      print '    [PcdsPatchableInModule]'\r
-      print '    [PcdsDynamicDefault]'\r
-      print '    [PcdsDynamicExDefault]'\r
-  elif args.PcdType == 'VPD':\r
-    if args.MaxSize is None:\r
-      #\r
-      # If --max-size is not provided, then set maximum size to the size of the\r
-      # binary input file\r
-      #\r
-      args.MaxSize = PcdSize\r
-    if args.MaxSize < PcdSize:\r
-      print 'BinToPcd: error: argument --max-size is smaller than input file.'\r
-      sys.exit()\r
-    if args.Offset is None:\r
-      #\r
-      # if --offset is not provided, then set offset field to '*' so build\r
-      # tools will compute offset of PCD in VPD region.\r
-      #\r
-      Pcd = '  %s|*|%d|%s' % (args.PcdName, args.MaxSize, PcdValue)\r
-    else:\r
-      #\r
-      # Use the --offset value provided.\r
-      #\r
-      Pcd = '  %s|%d|%d|%s' % (args.PcdName, args.Offset, args.MaxSize, PcdValue)\r
-    if args.Verbose:\r
-      print 'PcdToBin: Convert binary file to PCD statement compatible with PCD sections'\r
-      print '    [PcdsDynamicVpd]'\r
-      print '    [PcdsDynamicExVpd]'\r
-  elif args.PcdType == 'HII':\r
-    if args.VariableGuid is None:\r
-      print 'BinToPcd: error: argument --variable-guid is required for --type HII.'\r
-      sys.exit()\r
-    if args.VariableName is None:\r
-      print 'BinToPcd: error: argument --variable-name is required for --type HII.'\r
-      sys.exit()\r
-    if args.Offset is None:\r
-      #\r
-      # Use UEFI Variable offset of 0 if --offset is not provided\r
-      #\r
-      args.Offset = 0\r
-    Pcd = '  %s|L"%s"|%s|%d|%s' % (args.PcdName, args.VariableName, args.VariableGuid, args.Offset, PcdValue)\r
-    if args.Verbose:\r
-      print 'PcdToBin: Convert binary file to PCD statement compatible with PCD sections'\r
-      print '    [PcdsDynamicHii]'\r
-      print '    [PcdsDynamicExHii]'\r
+        if args.Verbose:\r
+            print ('BinToPcd: Convert binary file to PCD statement compatible with PCD sections:')\r
+            print ('    [PcdsFixedAtBuild]')\r
+            print ('    [PcdsPatchableInModule]')\r
+            print ('    [PcdsDynamicDefault]')\r
+            print ('    [PcdsDynamicExDefault]')\r
+    elif args.PcdType == 'VPD':\r
+        if args.MaxSize is None:\r
+            #\r
+            # If --max-size is not provided, then set maximum size to the size of the\r
+            # binary input file\r
+            #\r
+            args.MaxSize = PcdSize\r
+        if args.MaxSize < PcdSize:\r
+            print ('BinToPcd: error: argument --max-size is smaller than input file.')\r
+            sys.exit (1)\r
+        if args.Offset is None:\r
+            #\r
+            # if --offset is not provided, then set offset field to '*' so build\r
+            # tools will compute offset of PCD in VPD region.\r
+            #\r
+            Pcd = '  {Name}|*|{Size}|{Value}'.format (Name = args.PcdName, Size = args.MaxSize, Value = PcdValue)\r
+        else:\r
+            #\r
+            # --offset value must be 8-byte aligned\r
+            #\r
+            if (args.Offset % 8) != 0:\r
+                print ('BinToPcd: error: argument --offset must be 8-byte aligned.')\r
+                sys.exit (1)\r
+            #\r
+            # Use the --offset value provided.\r
+            #\r
+            Pcd = '  {Name}|{Offset}|{Size}|{Value}'.format (Name = args.PcdName, Offset = args.Offset, Size = args.MaxSize, Value = PcdValue)\r
+        if args.Verbose:\r
+            print ('BinToPcd: Convert binary file to PCD statement compatible with PCD sections')\r
+            print ('    [PcdsDynamicVpd]')\r
+            print ('    [PcdsDynamicExVpd]')\r
+    elif args.PcdType == 'HII':\r
+        if args.VariableGuid is None or args.VariableName is None:\r
+            print ('BinToPcd: error: arguments --variable-guid and --variable-name are required for --type HII.')\r
+            sys.exit (1)\r
+        if args.Offset is None:\r
+            #\r
+            # Use UEFI Variable offset of 0 if --offset is not provided\r
+            #\r
+            args.Offset = 0\r
+        #\r
+        # --offset value must be 8-byte aligned\r
+        #\r
+        if (args.Offset % 8) != 0:\r
+            print ('BinToPcd: error: argument --offset must be 8-byte aligned.')\r
+            sys.exit (1)\r
+        Pcd = '  {Name}|L"{VarName}"|{VarGuid}|{Offset}|{Value}'.format (Name = args.PcdName, VarName = args.VariableName, VarGuid = args.VariableGuid, Offset = args.Offset, Value = PcdValue)\r
+        if args.Verbose:\r
+            print ('BinToPcd: Convert binary file to PCD statement compatible with PCD sections')\r
+            print ('    [PcdsDynamicHii]')\r
+            print ('    [PcdsDynamicExHii]')\r
 \r
 \r
-  #\r
-  # Write PCD value or PCD statement to the output file\r
-  #\r
-  try:\r
-    args.OutputFile.write (Pcd)\r
-    args.OutputFile.close ()\r
-  except:\r
     #\r
     #\r
-    # If output file is not specified or it can not be written, then write the\r
-    # PCD value or PCD statement to the console\r
+    # Write PCD value or PCD statement to the output file\r
     #\r
     #\r
-    print Pcd\r
+    try:\r
+        args.OutputFile.write (Pcd)\r
+        args.OutputFile.close ()\r
+    except:\r
+        #\r
+        # If output file is not specified or it can not be written, then write the\r
+        # PCD value or PCD statement to the console\r
+        #\r
+        print (Pcd)\r