Skip to content

Commit

Permalink
IntelFsp2Pkg: FSP Python scripts to support 3.x.
Browse files Browse the repository at this point in the history
https://bugzilla.tianocore.org/show_bug.cgi?id=1930

Updated FSP Python scripts to support both 2.x and
3.x.

Test:
  . Verified with Python 2.7.12 and 3.6.6.
  . Verified tool result is the same before the change.
  . Both py -2 and py -3 built binary can boot.

Cc: Maurice Ma <[email protected]>
Cc: Nate DeSimone <[email protected]>
Cc: Star Zeng <[email protected]>
Signed-off-by: Chasel Chiu <[email protected]>
Reviewed-by: Star Zeng <[email protected]>
Reviewed-by: Nate DeSimone <[email protected]>
  • Loading branch information
ChaselChiu committed Jul 1, 2019
1 parent 2603fce commit c3f0829
Show file tree
Hide file tree
Showing 3 changed files with 109 additions and 62 deletions.
61 changes: 31 additions & 30 deletions IntelFsp2Pkg/Tools/GenCfgOpt.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## @ GenCfgOpt.py
#
# Copyright (c) 2014 - 2018, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2014 - 2019, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
Expand All @@ -10,6 +10,7 @@
import sys
import struct
from datetime import date
from functools import reduce

# Generated file copyright header

Expand Down Expand Up @@ -90,11 +91,11 @@ def __init__(self):
self.string = ''

def errExit(self, err = ''):
print "ERROR: Express parsing for:"
print " %s" % self.string
print " %s^" % (' ' * self.index)
print ("ERROR: Express parsing for:")
print (" %s" % self.string)
print (" %s^" % (' ' * self.index))
if err:
print "INFO : %s" % err
print ("INFO : %s" % err)
raise SystemExit

def getNonNumber (self, n1, n2):
Expand Down Expand Up @@ -338,15 +339,15 @@ def ParseMacros (self, MacroDefStr):
else:
Error = 0
if self.Debug:
print "INFO : Macro dictionary:"
print ("INFO : Macro dictionary:")
for Each in self._MacroDict:
print " $(%s) = [ %s ]" % (Each , self._MacroDict[Each])
print (" $(%s) = [ %s ]" % (Each , self._MacroDict[Each]))
return Error

def EvaulateIfdef (self, Macro):
Result = Macro in self._MacroDict
if self.Debug:
print "INFO : Eval Ifdef [%s] : %s" % (Macro, Result)
print ("INFO : Eval Ifdef [%s] : %s" % (Macro, Result))
return Result

def ExpandMacros (self, Input):
Expand All @@ -359,7 +360,7 @@ def ExpandMacros (self, Input):
Line = Line.replace(Each, self._MacroDict[Variable])
else:
if self.Debug:
print "WARN : %s is not defined" % Each
print ("WARN : %s is not defined" % Each)
Line = Line.replace(Each, Each[2:-1])
return Line

Expand All @@ -372,7 +373,7 @@ def ExpandPcds (self, Input):
Line = Line.replace(PcdName, self._PcdsDict[PcdName])
else:
if self.Debug:
print "WARN : %s is not defined" % PcdName
print ("WARN : %s is not defined" % PcdName)
return Line

def EvaluateExpress (self, Expr):
Expand All @@ -381,7 +382,7 @@ def EvaluateExpress (self, Expr):
LogExpr = CLogicalExpression()
Result = LogExpr.evaluateExpress (ExpExpr)
if self.Debug:
print "INFO : Eval Express [%s] : %s" % (Expr, Result)
print ("INFO : Eval Express [%s] : %s" % (Expr, Result))
return Result

def FormatListValue(self, ConfigDict):
Expand All @@ -406,7 +407,7 @@ def FormatListValue(self, ConfigDict):
bytearray = []
for each in dataarray:
value = each
for loop in xrange(unit):
for loop in range(int(unit)):
bytearray.append("0x%02X" % (value & 0xFF))
value = value >> 8
newvalue = '{' + ','.join(bytearray) + '}'
Expand Down Expand Up @@ -548,15 +549,15 @@ def ParseDscFile (self, DscFile, FvDir):
if Match:
self._MacroDict[Match.group(1)] = Match.group(2)
if self.Debug:
print "INFO : DEFINE %s = [ %s ]" % (Match.group(1), Match.group(2))
print ("INFO : DEFINE %s = [ %s ]" % (Match.group(1), Match.group(2)))
elif IsPcdSect:
#gSiPkgTokenSpaceGuid.PcdTxtEnable|FALSE
#gSiPkgTokenSpaceGuid.PcdOverclockEnable|TRUE
Match = re.match("^\s*([\w\.]+)\s*\|\s*(\w+)", DscLine)
if Match:
self._PcdsDict[Match.group(1)] = Match.group(2)
if self.Debug:
print "INFO : PCD %s = [ %s ]" % (Match.group(1), Match.group(2))
print ("INFO : PCD %s = [ %s ]" % (Match.group(1), Match.group(2)))
i = 0
while i < len(BuildOptionPcd):
Match = re.match("\s*([\w\.]+)\s*\=\s*(\w+)", BuildOptionPcd[i])
Expand Down Expand Up @@ -774,7 +775,7 @@ def GetBsfBitFields (self, subitem, bytes):
bitsvalue = bitsvalue[::-1]
bitslen = len(bitsvalue)
if start > bitslen or end > bitslen:
print "Invalid bits offset [%d,%d] for %s" % (start, end, subitem['name'])
print ("Invalid bits offset [%d,%d] for %s" % (start, end, subitem['name']))
raise SystemExit
return hex(int(bitsvalue[start:end][::-1], 2))

Expand Down Expand Up @@ -1031,7 +1032,7 @@ def PostProcessBody (self, TextBody):

if Match and Match.group(3) == 'END':
if (StructName != Match.group(1)) or (VariableName != Match.group(2)):
print "Unmatched struct name '%s' and '%s' !" % (StructName, Match.group(1))
print ("Unmatched struct name '%s' and '%s' !" % (StructName, Match.group(1)))
else:
if IsUpdHdrDefined != True or IsUpdHeader != True:
NewTextBody.append ('} %s;\n\n' % StructName)
Expand Down Expand Up @@ -1464,11 +1465,11 @@ def GenerateBsfFile (self, BsfFile):


def Usage():
print "GenCfgOpt Version 0.53"
print "Usage:"
print " GenCfgOpt UPDTXT PlatformDscFile BuildFvDir [-D Macros]"
print " GenCfgOpt HEADER PlatformDscFile BuildFvDir InputHFile [-D Macros]"
print " GenCfgOpt GENBSF PlatformDscFile BuildFvDir BsfOutFile [-D Macros]"
print ("GenCfgOpt Version 0.54")
print ("Usage:")
print (" GenCfgOpt UPDTXT PlatformDscFile BuildFvDir [-D Macros]")
print (" GenCfgOpt HEADER PlatformDscFile BuildFvDir InputHFile [-D Macros]")
print (" GenCfgOpt GENBSF PlatformDscFile BuildFvDir BsfOutFile [-D Macros]")

def Main():
#
Expand All @@ -1489,7 +1490,7 @@ def Main():
else:
DscFile = sys.argv[2]
if not os.path.exists(DscFile):
print "ERROR: Cannot open DSC file '%s' !" % DscFile
print ("ERROR: Cannot open DSC file '%s' !" % DscFile)
return 2

OutFile = ''
Expand All @@ -1501,43 +1502,43 @@ def Main():
Start = 5
if argc > Start:
if GenCfgOpt.ParseMacros(sys.argv[Start:]) != 0:
print "ERROR: Macro parsing failed !"
print ("ERROR: Macro parsing failed !")
return 3

FvDir = sys.argv[3]
if not os.path.exists(FvDir):
os.makedirs(FvDir)

if GenCfgOpt.ParseDscFile(DscFile, FvDir) != 0:
print "ERROR: %s !" % GenCfgOpt.Error
print ("ERROR: %s !" % GenCfgOpt.Error)
return 5

if GenCfgOpt.UpdateSubRegionDefaultValue() != 0:
print "ERROR: %s !" % GenCfgOpt.Error
print ("ERROR: %s !" % GenCfgOpt.Error)
return 7

if sys.argv[1] == "UPDTXT":
Ret = GenCfgOpt.CreateSplitUpdTxt(OutFile)
if Ret != 0:
# No change is detected
if Ret == 256:
print "INFO: %s !" % (GenCfgOpt.Error)
print ("INFO: %s !" % (GenCfgOpt.Error))
else :
print "ERROR: %s !" % (GenCfgOpt.Error)
print ("ERROR: %s !" % (GenCfgOpt.Error))
return Ret
elif sys.argv[1] == "HEADER":
if GenCfgOpt.CreateHeaderFile(OutFile) != 0:
print "ERROR: %s !" % GenCfgOpt.Error
print ("ERROR: %s !" % GenCfgOpt.Error)
return 8
elif sys.argv[1] == "GENBSF":
if GenCfgOpt.GenerateBsfFile(OutFile) != 0:
print "ERROR: %s !" % GenCfgOpt.Error
print ("ERROR: %s !" % GenCfgOpt.Error)
return 9
else:
if argc < 5:
Usage()
return 1
print "ERROR: Unknown command '%s' !" % sys.argv[1]
print ("ERROR: Unknown command '%s' !" % sys.argv[1])
Usage()
return 1
return 0
Expand Down
36 changes: 23 additions & 13 deletions IntelFsp2Pkg/Tools/PatchFv.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## @ PatchFv.py
#
# Copyright (c) 2014 - 2018, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2014 - 2019, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
Expand All @@ -25,7 +25,10 @@ def readDataFromFile (binfile, offset, len=1):
if (offval & 0x80000000):
offval = fsize - (0xFFFFFFFF - offval + 1)
fd.seek(offval)
bytearray = [ord(b) for b in fd.read(len)]
if sys.version_info[0] < 3:
bytearray = [ord(b) for b in fd.read(len)]
else:
bytearray = [b for b in fd.read(len)]
value = 0
idx = len - 1
while idx >= 0:
Expand All @@ -45,7 +48,7 @@ def IsFspHeaderValid (binfile):
fd = open (binfile, "rb")
bindat = fd.read(0x200) # only read first 0x200 bytes
fd.close()
HeaderList = ['FSPH' , 'FSPP' , 'FSPE'] # Check 'FSPH', 'FSPP', and 'FSPE' in the FSP header
HeaderList = [b'FSPH' , b'FSPP' , b'FSPE'] # Check 'FSPH', 'FSPP', and 'FSPE' in the FSP header
OffsetList = []
for each in HeaderList:
if each in bindat:
Expand All @@ -55,7 +58,10 @@ def IsFspHeaderValid (binfile):
OffsetList.append(idx)
if not OffsetList[0] or not OffsetList[1]: # If 'FSPH' or 'FSPP' is missing, it will return false
return False
Revision = ord(bindat[OffsetList[0] + 0x0B])
if sys.version_info[0] < 3:
Revision = ord(bindat[OffsetList[0] + 0x0B])
else:
Revision = bindat[OffsetList[0] + 0x0B]
#
# if revision is bigger than 1, it means it is FSP v1.1 or greater revision, which must contain 'FSPE'.
#
Expand Down Expand Up @@ -86,7 +92,10 @@ def patchDataInFile (binfile, offset, value, len=1):
value = value >> 8
idx = idx + 1
fd.seek(offval)
fd.write("".join(chr(b) for b in bytearray))
if sys.version_info[0] < 3:
fd.write("".join(chr(b) for b in bytearray))
else:
fd.write(bytes(bytearray))
fd.close()
return len

Expand Down Expand Up @@ -791,7 +800,7 @@ def getGuidOff(self, value):
# retval ret
#
def getSymbols(self, value):
if self.dictSymbolAddress.has_key(value):
if value in self.dictSymbolAddress:
# Module:Function
ret = int (self.dictSymbolAddress[value], 16)
else:
Expand Down Expand Up @@ -827,8 +836,9 @@ def evaluate(self, expression, isOffset):
#
# Print out the usage
#
def usage():
print "Usage: \n\tPatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch \"Offset, Value\""
def Usage():
print ("PatchFv Version 0.50")
print ("Usage: \n\tPatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch \"Offset, Value\"")

def main():
#
Expand All @@ -847,7 +857,7 @@ def main():
# If it fails to create dictionaries, then return an error.
#
if symTables.createDicts(sys.argv[1], sys.argv[2]) != 0:
print "ERROR: Failed to create symbol dictionary!!"
print ("ERROR: Failed to create symbol dictionary!!")
return 2

#
Expand Down Expand Up @@ -907,7 +917,7 @@ def main():
if ret:
raise Exception ("Patch failed for offset 0x%08X" % offset)
else:
print "Patched offset 0x%08X:[%08X] with value 0x%08X # %s" % (offset, oldvalue, value, comment)
print ("Patched offset 0x%08X:[%08X] with value 0x%08X # %s" % (offset, oldvalue, value, comment))

elif command == "COPY":
#
Expand All @@ -928,13 +938,13 @@ def main():
if ret:
raise Exception ("Copy failed from offset 0x%08X to offset 0x%08X!" % (src, dest))
else :
print "Copied %d bytes from offset 0x%08X ~ offset 0x%08X # %s" % (clen, src, dest, comment)
print ("Copied %d bytes from offset 0x%08X ~ offset 0x%08X # %s" % (clen, src, dest, comment))
else:
raise Exception ("Unknown command %s!" % command)
return 0

except Exception as (ex):
print "ERROR: %s" % ex
except Exception as ex:
print ("ERROR: %s" % ex)
return 1

if __name__ == '__main__':
Expand Down
Loading

0 comments on commit c3f0829

Please sign in to comment.