]> git.proxmox.com Git - mirror_edk2.git/commitdiff
BaseTools/Scripts: Add BinToPcd utility
authorMichael Kinney <michael.d.kinney@intel.com>
Tue, 8 Nov 2016 22:25:30 +0000 (14:25 -0800)
committerMichael Kinney <michael.d.kinney@intel.com>
Mon, 14 Nov 2016 16:40:41 +0000 (08:40 -0800)
https://bugzilla.tianocore.org/show_bug.cgi?id=228

Add a utility that converts a binary file into a VOID* PCD value
or a full DSC file VOID* PCD statement with support for all the
DSC supported PCD sections.

usage: BinToPcd [-h] [--version] -i INPUTFILE [-o OUTPUTFILE] [-p PCDNAME]
                [-t {VPD,HII}] [-m MAXSIZE] [-f OFFSET] [-n VARIABLENAME]
                [-g VARIABLEGUID] [-v] [-q] [--debug [0-9]]

Convert a binary file to a VOID* PCD value or DSC file VOID* PCD statement.
Copyright (c) 2016, Intel Corporation. All rights reserved.

optional arguments:
  -h, --help        show this help message and exit
  --version         show program's version number and exit
  -i INPUTFILE, --input INPUTFILE
                    Input binary filename
  -o OUTPUTFILE, --output OUTPUTFILE
                    Output filename for PCD value or PCD statement
  -p PCDNAME, --pcd PCDNAME
                    Name of the PCD in the form
                    <PcdTokenSpaceGuidCName>.<PcdCName>
  -t {VPD,HII}, --type {VPD,HII}
                    PCD statement type (HII or VPD). Default is standard.
  -m MAXSIZE, --max-size MAXSIZE
                    Maximum size of the PCD. Ignored with --type HII.
  -f OFFSET, --offset OFFSET
                    VPD offset if --type is VPD. UEFI Variable offset if
                    --type is HII.
  -n VARIABLENAME, --variable-name VARIABLENAME
                    UEFI variable name. Only used with --type HII.
  -g VARIABLEGUID, --variable-guid VARIABLEGUID
                    UEFI variable GUID C name. Only used with --type HII.
  -v, --verbose     Increase output messages
  -q, --quiet       Reduce output messages
  --debug [0-9]     Set debug level

This utility can be used in PCD value mode to convert a binary
file into a string that can then be copied into the PCD value field
of a VOID* PCD.  The following is an example of PCD value mode on
an 8 byte test.bin file.

  BinToPcd.py -i test.bin

  {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x0d, 0x0a}

The DSC file VOID* PCD statement mode can be used to generate a
complete PCD statement for the PCD section types that a DSC file
supports:

  [PcdsFixedAtBuild]
  [PcdsPatchableInModule]
  [PcdsDynamicDefault]
  [PcdsDynamicExDefault]
  [PcdsDynamicVpd]
  [PcdsDynamicExVpd]
  [PcdsDynamicHii]
  [PcdsDynamicExHii]

The PCD statement mode is useful when combined with a !include
statement in a DSC file.  BinToPcd.py can be used to convert a
binary file to a PCD statement in an output file, and that output
file can be included into a DSC file in the matching PCD section
to set the value of the PCD to the value from the binary file
without having to copy the value into the DSC file.  Updates can be
made to the included file without editing the DSC file.  Some
example use cases are the setting the public key PCDs such as:

  gEfiSecurityPkgTokenSpaceGuid.PcdRsa2048Sha256PublicKeyBuffer
  gEfiSecurityPkgTokenSpaceGuid.PcdPkcs7CertBuffer

The following example converts a public key binary file to a
[PcdsFixedAtBuild] compatible PCD statement:

  BinToPcd.py -i PublicKey.bin -o PublicKey.pcd
    --pcd gEfiSecurityPkgTokenSpaceGuid.PcdPkcs7CertBufferkenSpaceGuid

The PublicKey.pcd output file contains a single line:

  gEfiSecurityPkgTokenSpaceGuid.PcdPkcs7CertBuffer|{0x48, ...}

A DSC file can be updated to include the PublicKey.pcd file:

  [PcdsFixedAtBuild]
  !include PublicKey.pcd

Value examples
===============
  BinToPcd.py -i test.bin
    {0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x0d, 0x0a}

Normal examples:
=================
  BinToPcd.py -i test.bin -p Guid.Token
    Guid.Token|{0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x0d, 0x0a}

  BinToPcd.py -i test.bin -p Guid.Token -m 20
    Guid.Token|{0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x0d, 0x0a}|VOID*|20

VPD examples:
=============
  BinToPcd.py -i test.bin -p Guid.Token -t VPD
    Guid.Name|*|8|{0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x0d, 0x0a}

  BinToPcd.py -i test.bin -p Guid.Token -t VPD -f 20
    Guid.Name|20|8|{0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x0d, 0x0a}

  BinToPcd.py -i test.bin -p Guid.Token -t VPD -m 10
    Guid.Name|*|10|{0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x0d, 0x0a}

  BinToPcd.py -i test.bin -p Guid.Token -t VPD -f 20 -m 10
    Guid.Name|20|10|{0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x0d, 0x0a}

HII examples:
=============
  BinToPcd.py -i test.bin -p Guid.Token -t HII -g VarGuid -n VarName
    Guid.Name|L"VarName"|VarGuid|0|{0x48, 0x65, 0x6c, 0x6c}

  BinToPcd.py -i test.bin -p Guid.Token -t HII -g VarGuid -n VarName -f 8
    Guid.Name|L"VarName"|VarGuid|8|{0x48, 0x65, 0x6c, 0x6c}

Cc: Yonghong Zhu <yonghong.zhu@intel.com>
Cc: Liming Gao <liming.gao@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Michael Kinney <michael.d.kinney@intel.com>
Reviewed-by: Liming Gao <liming.gao@intel.com>
Reviewed-by: Yonghong Zhu <yonghong.zhu@intel.com>
BaseTools/Scripts/BinToPcd.py [new file with mode: 0644]

diff --git a/BaseTools/Scripts/BinToPcd.py b/BaseTools/Scripts/BinToPcd.py
new file mode 100644 (file)
index 0000000..68a7ac6
--- /dev/null
@@ -0,0 +1,192 @@
+## @file\r
+# Convert a binary file to a VOID* PCD value or DSC file VOID* PCD statement.\r
+#\r
+# Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>\r
+# This program and the accompanying materials\r
+# are licensed and made available under the terms and conditions of the BSD License\r
+# which accompanies this distribution.  The full text of the license may be found at\r
+# http://opensource.org/licenses/bsd-license.php\r
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+#\r
+\r
+'''\r
+BinToPcd\r
+'''\r
+\r
+import sys\r
+import argparse\r
+import re\r
+\r
+#\r
+# Globals for help information\r
+#\r
+__prog__        = 'BinToPcd'\r
+__version__     = '%s Version %s' % (__prog__, '0.9 ')\r
+__copyright__   = 'Copyright (c) 2016, Intel Corporation. All rights reserved.'\r
+__description__ = 'Convert a binary file 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
+\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
+\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
+    \r
+  def ByteArray (Buffer):\r
+    #\r
+    # Append byte array of values of the form '{0x01, 0x02, ...}'\r
+    #\r
+    return '{%s}' % (', '.join(['0x%02x' % (ord(Item)) for Item in 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'),\r
+                      help = "Input binary filename", required = True)\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("-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
+  # Parse command line arguments\r
+  #\r
+  args = parser.parse_args()\r
+\r
+  #\r
+  # Read binary input file\r
+  #\r
+  try:\r
+    Buffer = args.InputFile.read()\r
+    args.InputFile.close()\r
+  except:\r
+    print 'BinToPcd: error: can not read binary input file'\r
+    sys.exit()\r
+\r
+  #\r
+  # Convert binary buffer to a DSC file PCD statement\r
+  #\r
+  if args.PcdName is None:\r
+    #\r
+    # If PcdName is None, then only a PCD value is being requested.\r
+    Pcd = ByteArray (Buffer)\r
+    if args.Verbose:\r
+      print 'PcdToBin: 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 = '  %s|%s' % (args.PcdName, ByteArray (Buffer))\r
+    elif args.MaxSize < len(Buffer):\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, ByteArray (Buffer), args.MaxSize)\r
+      args.MaxSize = len(Buffer)\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 = len(Buffer)\r
+    if args.MaxSize < len(Buffer):\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, ByteArray (Buffer))\r
+    else:\r
+      #\r
+      # Use the --offset value provided.\r
+      #\r
+      Pcd = '  %s|%d|%d|%s' % (args.PcdName, args.Offset, args.MaxSize, ByteArray (Buffer))\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, ByteArray (Buffer))\r
+    if args.Verbose:\r
+      print 'PcdToBin: Convert binary file to PCD statement compatible with PCD sections'\r
+      print '    [PcdsDynamicHii]'\r
+      print '    [PcdsDynamicExHii]'\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
+    # 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