BaseTools/GenFds: cleanup GenFds

1) remove wildcard imports and use explicit imports
2) refactor to use shared variables from Common/DataType
3) rename to not shadow imports
4) don't assign a variable in a loop (just do final assignment)
5) remove spaces, parens, unused or commented out code, etc.
6) merge unnecessary parent classes into child
7) refactor to share DXE and PEI apriori GUIDs from one place
  this includes changes to Build and EOT files
8) for PEP8, dont use __ for custom methods.

Cc: Yonghong Zhu <yonghong.zhu@intel.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Bob C Feng <bob.c.feng@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Jaben Carsey <jaben.carsey@intel.com>
Reviewed-by: Yonghong Zhu <yonghong.zhu@intel.com>
This commit is contained in:
Carsey, Jaben 2018-10-24 01:29:19 +08:00 committed by Yonghong Zhu
parent 0019375fbc
commit 9e47e6f908
24 changed files with 2186 additions and 2021 deletions

View File

@ -37,50 +37,6 @@ class FDClassObject:
self.RegionList = [] self.RegionList = []
self.vtfRawDict = {} self.vtfRawDict = {}
## FV data in FDF
#
#
class FvClassObject:
## The constructor
#
# @param self The object pointer
#
def __init__(self):
self.UiFvName = None
self.CreateFileName = None
# 3-tuple list (blockSize, numBlocks, pcd)
self.BlockSizeList = []
# DefineVarDict[var] = value
self.DefineVarDict = {}
# SetVarDict[var] = value
self.SetVarDict = {}
self.FvAlignment = None
# FvAttributeDict[attribute] = TRUE/FALSE (1/0)
self.FvAttributeDict = {}
self.FvNameGuid = None
self.FvNameString = None
self.AprioriSectionList = []
self.FfsList = []
self.BsBaseAddress = None
self.RtBaseAddress = None
## Region data in FDF
#
#
class RegionClassObject:
## The constructor
#
# @param self The object pointer
#
def __init__(self):
self.Offset = None # The begin position of the Region
self.Size = None # The Size of the Region
self.PcdOffset = None
self.PcdSize = None
self.SetVarDict = {}
self.RegionType = None
self.RegionDataList = []
## FFS data in FDF ## FFS data in FDF
# #
# #
@ -112,7 +68,6 @@ class FileStatementClassObject (FfsClassObject) :
self.FvName = None self.FvName = None
self.FdName = None self.FdName = None
self.DefineVarDict = {} self.DefineVarDict = {}
self.AprioriSection = None
self.KeepReloc = None self.KeepReloc = None
## INF statement data in FDF ## INF statement data in FDF
@ -134,19 +89,6 @@ class FfsInfStatementClassObject(FfsClassObject):
self.KeepReloc = None self.KeepReloc = None
self.UseArch = None self.UseArch = None
## APRIORI section data in FDF
#
#
class AprioriSectionClassObject:
## The constructor
#
# @param self The object pointer
#
def __init__(self):
# DefineVarDict[var] = value
self.DefineVarDict = {}
self.FfsList = []
## section data in FDF ## section data in FDF
# #
# #
@ -363,21 +305,6 @@ class CapsuleClassObject :
self.CapsuleDataList = [] self.CapsuleDataList = []
self.FmpPayloadList = [] self.FmpPayloadList = []
## VTF data in FDF
#
#
class VtfClassObject :
## The constructor
#
# @param self The object pointer
#
def __init__(self):
self.KeyArch = None
self.ArchList = None
self.UiName = None
self.ResetBin = None
self.ComponentStatementList = []
## VTF component data in FDF ## VTF component data in FDF
# #
# #

View File

@ -36,10 +36,9 @@ import struct
import uuid import uuid
import copy import copy
import codecs import codecs
from GenFds.AprioriSection import DXE_APRIORI_GUID, PEI_APRIORI_GUID
gGuidStringFormat = "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X" gGuidStringFormat = "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X"
gPeiAprioriFileNameGuid = '1b45cc0a-156a-428a-af62-49864da0e6e6'
gAprioriGuid = 'fc510ee7-ffdc-11d4-bd41-0080c73c8881'
gIndention = -4 gIndention = -4
class Image(array): class Image(array):
@ -402,10 +401,10 @@ class FirmwareVolume(Image):
if Ffs.Type == 0x05: if Ffs.Type == 0x05:
FfsDxeCoreGuid = FfsID FfsDxeCoreGuid = FfsID
continue continue
if Ffs.Guid.lower() == gPeiAprioriFileNameGuid: if Ffs.Guid.lower() == PEI_APRIORI_GUID.lower():
FfsPeiPrioriGuid = FfsID FfsPeiPrioriGuid = FfsID
continue continue
if Ffs.Guid.lower() == gAprioriGuid: if Ffs.Guid.lower() == DXE_APRIORI_GUID.lower():
FfsDxePrioriGuid = FfsID FfsDxePrioriGuid = FfsID
continue continue
@ -1084,6 +1083,371 @@ class Ffs(Image):
State = property(_GetState, _SetState) State = property(_GetState, _SetState)
_FfsGuid = "8C8CE578-8A3D-4F1C-9935-896185C32DD3"
_GUID_ = struct.Struct("16x 1I2H8B")
_LENGTH_ = struct.Struct("16x 16x 1Q")
_SIG_ = struct.Struct("16x 16x 8x 1I")
_ATTR_ = struct.Struct("16x 16x 8x 4x 1I")
_HLEN_ = struct.Struct("16x 16x 8x 4x 4x 1H")
_CHECKSUM_ = struct.Struct("16x 16x 8x 4x 4x 2x 1H")
def __init__(self, Name=''):
Image.__init__(self)
self.Name = Name
self.FfsDict = sdict()
self.OrderedFfsDict = sdict()
self.UnDispatchedFfsDict = sdict()
self.ProtocolList = sdict()
def CheckArchProtocol(self):
for Item in EotGlobalData.gArchProtocolGuids:
if Item.lower() not in EotGlobalData.gProtocolList:
return False
return True
def ParseDepex(self, Depex, Type):
List = None
if Type == 'Ppi':
List = EotGlobalData.gPpiList
if Type == 'Protocol':
List = EotGlobalData.gProtocolList
DepexStack = []
DepexList = []
DepexString = ''
FileDepex = None
CouldBeLoaded = True
for Index in range(0, len(Depex.Expression)):
Item = Depex.Expression[Index]
if Item == 0x00:
Index = Index + 1
Guid = gGuidStringFormat % Depex.Expression[Index]
if Guid in self.OrderedFfsDict and Depex.Expression[Index + 1] == 0x08:
return (True, 'BEFORE %s' % Guid, [Guid, 'BEFORE'])
elif Item == 0x01:
Index = Index + 1
Guid = gGuidStringFormat % Depex.Expression[Index]
if Guid in self.OrderedFfsDict and Depex.Expression[Index + 1] == 0x08:
return (True, 'AFTER %s' % Guid, [Guid, 'AFTER'])
elif Item == 0x02:
Index = Index + 1
Guid = gGuidStringFormat % Depex.Expression[Index]
if Guid.lower() in List:
DepexStack.append(True)
DepexList.append(Guid)
else:
DepexStack.append(False)
DepexList.append(Guid)
continue
elif Item == 0x03 or Item == 0x04:
DepexStack.append(eval(str(DepexStack.pop()) + ' ' + Depex._OPCODE_STRING_[Item].lower() + ' ' + str(DepexStack.pop())))
DepexList.append(str(DepexList.pop()) + ' ' + Depex._OPCODE_STRING_[Item].upper() + ' ' + str(DepexList.pop()))
elif Item == 0x05:
DepexStack.append(eval(Depex._OPCODE_STRING_[Item].lower() + ' ' + str(DepexStack.pop())))
DepexList.append(Depex._OPCODE_STRING_[Item].lower() + ' ' + str(DepexList.pop()))
elif Item == 0x06:
DepexStack.append(True)
DepexList.append('TRUE')
DepexString = DepexString + 'TRUE' + ' '
elif Item == 0x07:
DepexStack.append(False)
DepexList.append('False')
DepexString = DepexString + 'FALSE' + ' '
elif Item == 0x08:
if Index != len(Depex.Expression) - 1:
CouldBeLoaded = False
else:
CouldBeLoaded = DepexStack.pop()
else:
CouldBeLoaded = False
if DepexList != []:
DepexString = DepexList[0].strip()
return (CouldBeLoaded, DepexString, FileDepex)
def Dispatch(self, Db = None):
if Db is None:
return False
self.UnDispatchedFfsDict = copy.copy(self.FfsDict)
# Find PeiCore, DexCore, PeiPriori, DxePriori first
FfsSecCoreGuid = None
FfsPeiCoreGuid = None
FfsDxeCoreGuid = None
FfsPeiPrioriGuid = None
FfsDxePrioriGuid = None
for FfsID in self.UnDispatchedFfsDict:
Ffs = self.UnDispatchedFfsDict[FfsID]
if Ffs.Type == 0x03:
FfsSecCoreGuid = FfsID
continue
if Ffs.Type == 0x04:
FfsPeiCoreGuid = FfsID
continue
if Ffs.Type == 0x05:
FfsDxeCoreGuid = FfsID
continue
if Ffs.Guid.lower() == PEI_APRIORI_GUID.lower():
FfsPeiPrioriGuid = FfsID
continue
if Ffs.Guid.lower() == DXE_APRIORI_GUID.lower():
FfsDxePrioriGuid = FfsID
continue
# Parse SEC_CORE first
if FfsSecCoreGuid is not None:
self.OrderedFfsDict[FfsSecCoreGuid] = self.UnDispatchedFfsDict.pop(FfsSecCoreGuid)
self.LoadPpi(Db, FfsSecCoreGuid)
# Parse PEI first
if FfsPeiCoreGuid is not None:
self.OrderedFfsDict[FfsPeiCoreGuid] = self.UnDispatchedFfsDict.pop(FfsPeiCoreGuid)
self.LoadPpi(Db, FfsPeiCoreGuid)
if FfsPeiPrioriGuid is not None:
# Load PEIM described in priori file
FfsPeiPriori = self.UnDispatchedFfsDict.pop(FfsPeiPrioriGuid)
if len(FfsPeiPriori.Sections) == 1:
Section = FfsPeiPriori.Sections.popitem()[1]
if Section.Type == 0x19:
GuidStruct = struct.Struct('1I2H8B')
Start = 4
while len(Section) > Start:
Guid = GuidStruct.unpack_from(Section[Start : Start + 16])
GuidString = gGuidStringFormat % Guid
Start = Start + 16
if GuidString in self.UnDispatchedFfsDict:
self.OrderedFfsDict[GuidString] = self.UnDispatchedFfsDict.pop(GuidString)
self.LoadPpi(Db, GuidString)
self.DisPatchPei(Db)
# Parse DXE then
if FfsDxeCoreGuid is not None:
self.OrderedFfsDict[FfsDxeCoreGuid] = self.UnDispatchedFfsDict.pop(FfsDxeCoreGuid)
self.LoadProtocol(Db, FfsDxeCoreGuid)
if FfsDxePrioriGuid is not None:
# Load PEIM described in priori file
FfsDxePriori = self.UnDispatchedFfsDict.pop(FfsDxePrioriGuid)
if len(FfsDxePriori.Sections) == 1:
Section = FfsDxePriori.Sections.popitem()[1]
if Section.Type == 0x19:
GuidStruct = struct.Struct('1I2H8B')
Start = 4
while len(Section) > Start:
Guid = GuidStruct.unpack_from(Section[Start : Start + 16])
GuidString = gGuidStringFormat % Guid
Start = Start + 16
if GuidString in self.UnDispatchedFfsDict:
self.OrderedFfsDict[GuidString] = self.UnDispatchedFfsDict.pop(GuidString)
self.LoadProtocol(Db, GuidString)
self.DisPatchDxe(Db)
def LoadProtocol(self, Db, ModuleGuid):
SqlCommand = """select GuidValue from Report
where SourceFileFullPath in
(select Value1 from Inf where BelongsToFile =
(select BelongsToFile from Inf
where Value1 = 'FILE_GUID' and Value2 like '%s' and Model = %s)
and Model = %s)
and ItemType = 'Protocol' and ItemMode = 'Produced'""" \
% (ModuleGuid, 5001, 3007)
RecordSet = Db.TblReport.Exec(SqlCommand)
for Record in RecordSet:
SqlCommand = """select Value2 from Inf where BelongsToFile =
(select DISTINCT BelongsToFile from Inf
where Value1 =
(select SourceFileFullPath from Report
where GuidValue like '%s' and ItemMode = 'Callback'))
and Value1 = 'FILE_GUID'""" % Record[0]
CallBackSet = Db.TblReport.Exec(SqlCommand)
if CallBackSet != []:
EotGlobalData.gProtocolList[Record[0].lower()] = ModuleGuid
else:
EotGlobalData.gProtocolList[Record[0].lower()] = ModuleGuid
def LoadPpi(self, Db, ModuleGuid):
SqlCommand = """select GuidValue from Report
where SourceFileFullPath in
(select Value1 from Inf where BelongsToFile =
(select BelongsToFile from Inf
where Value1 = 'FILE_GUID' and Value2 like '%s' and Model = %s)
and Model = %s)
and ItemType = 'Ppi' and ItemMode = 'Produced'""" \
% (ModuleGuid, 5001, 3007)
RecordSet = Db.TblReport.Exec(SqlCommand)
for Record in RecordSet:
EotGlobalData.gPpiList[Record[0].lower()] = ModuleGuid
def DisPatchDxe(self, Db):
IsInstalled = False
ScheduleList = sdict()
for FfsID in self.UnDispatchedFfsDict:
CouldBeLoaded = False
DepexString = ''
FileDepex = None
Ffs = self.UnDispatchedFfsDict[FfsID]
if Ffs.Type == 0x07:
# Get Depex
IsFoundDepex = False
for Section in Ffs.Sections.values():
# Find Depex
if Section.Type == 0x13:
IsFoundDepex = True
CouldBeLoaded, DepexString, FileDepex = self.ParseDepex(Section._SubImages[4], 'Protocol')
break
if Section.Type == 0x01:
CompressSections = Section._SubImages[4]
for CompressSection in CompressSections.Sections:
if CompressSection.Type == 0x13:
IsFoundDepex = True
CouldBeLoaded, DepexString, FileDepex = self.ParseDepex(CompressSection._SubImages[4], 'Protocol')
break
if CompressSection.Type == 0x02:
NewSections = CompressSection._SubImages[4]
for NewSection in NewSections.Sections:
if NewSection.Type == 0x13:
IsFoundDepex = True
CouldBeLoaded, DepexString, FileDepex = self.ParseDepex(NewSection._SubImages[4], 'Protocol')
break
# Not find Depex
if not IsFoundDepex:
CouldBeLoaded = self.CheckArchProtocol()
DepexString = ''
FileDepex = None
# Append New Ffs
if CouldBeLoaded:
IsInstalled = True
NewFfs = self.UnDispatchedFfsDict.pop(FfsID)
NewFfs.Depex = DepexString
if FileDepex is not None:
ScheduleList.insert(FileDepex[1], FfsID, NewFfs, FileDepex[0])
else:
ScheduleList[FfsID] = NewFfs
else:
self.UnDispatchedFfsDict[FfsID].Depex = DepexString
for FfsID in ScheduleList:
NewFfs = ScheduleList.pop(FfsID)
FfsName = 'UnKnown'
self.OrderedFfsDict[FfsID] = NewFfs
self.LoadProtocol(Db, FfsID)
SqlCommand = """select Value2 from Inf
where BelongsToFile = (select BelongsToFile from Inf where Value1 = 'FILE_GUID' and lower(Value2) = lower('%s') and Model = %s)
and Model = %s and Value1='BASE_NAME'""" % (FfsID, 5001, 5001)
RecordSet = Db.TblReport.Exec(SqlCommand)
if RecordSet != []:
FfsName = RecordSet[0][0]
if IsInstalled:
self.DisPatchDxe(Db)
def DisPatchPei(self, Db):
IsInstalled = False
for FfsID in self.UnDispatchedFfsDict:
CouldBeLoaded = True
DepexString = ''
FileDepex = None
Ffs = self.UnDispatchedFfsDict[FfsID]
if Ffs.Type == 0x06 or Ffs.Type == 0x08:
# Get Depex
for Section in Ffs.Sections.values():
if Section.Type == 0x1B:
CouldBeLoaded, DepexString, FileDepex = self.ParseDepex(Section._SubImages[4], 'Ppi')
break
if Section.Type == 0x01:
CompressSections = Section._SubImages[4]
for CompressSection in CompressSections.Sections:
if CompressSection.Type == 0x1B:
CouldBeLoaded, DepexString, FileDepex = self.ParseDepex(CompressSection._SubImages[4], 'Ppi')
break
if CompressSection.Type == 0x02:
NewSections = CompressSection._SubImages[4]
for NewSection in NewSections.Sections:
if NewSection.Type == 0x1B:
CouldBeLoaded, DepexString, FileDepex = self.ParseDepex(NewSection._SubImages[4], 'Ppi')
break
# Append New Ffs
if CouldBeLoaded:
IsInstalled = True
NewFfs = self.UnDispatchedFfsDict.pop(FfsID)
NewFfs.Depex = DepexString
self.OrderedFfsDict[FfsID] = NewFfs
self.LoadPpi(Db, FfsID)
else:
self.UnDispatchedFfsDict[FfsID].Depex = DepexString
if IsInstalled:
self.DisPatchPei(Db)
def __str__(self):
global gIndention
gIndention += 4
FvInfo = '\n' + ' ' * gIndention
FvInfo += "[FV:%s] file_system=%s size=%x checksum=%s\n" % (self.Name, self.FileSystemGuid, self.Size, self.Checksum)
FfsInfo = "\n".join([str(self.FfsDict[FfsId]) for FfsId in self.FfsDict])
gIndention -= 4
return FvInfo + FfsInfo
def _Unpack(self):
Size = self._LENGTH_.unpack_from(self._BUF_, self._OFF_)[0]
self.empty()
self.extend(self._BUF_[self._OFF_:self._OFF_+Size])
# traverse the FFS
EndOfFv = Size
FfsStartAddress = self.HeaderSize
LastFfsObj = None
while FfsStartAddress < EndOfFv:
FfsObj = Ffs()
FfsObj.frombuffer(self, FfsStartAddress)
FfsId = repr(FfsObj)
if ((self.Attributes & 0x00000800) != 0 and len(FfsObj) == 0xFFFFFF) \
or ((self.Attributes & 0x00000800) == 0 and len(FfsObj) == 0):
if LastFfsObj is not None:
LastFfsObj.FreeSpace = EndOfFv - LastFfsObj._OFF_ - len(LastFfsObj)
else:
if FfsId in self.FfsDict:
EdkLogger.error("FV", 0, "Duplicate GUID in FFS",
ExtraData="\t%s @ %s\n\t%s @ %s" \
% (FfsObj.Guid, FfsObj.Offset,
self.FfsDict[FfsId].Guid, self.FfsDict[FfsId].Offset))
self.FfsDict[FfsId] = FfsObj
if LastFfsObj is not None:
LastFfsObj.FreeSpace = FfsStartAddress - LastFfsObj._OFF_ - len(LastFfsObj)
FfsStartAddress += len(FfsObj)
#
# align to next 8-byte aligned address: A = (A + 8 - 1) & (~(8 - 1))
# The next FFS must be at the latest next 8-byte aligned address
#
FfsStartAddress = (FfsStartAddress + 7) & (~7)
LastFfsObj = FfsObj
def _GetAttributes(self):
return self.GetField(self._ATTR_, 0)[0]
def _GetSize(self):
return self.GetField(self._LENGTH_, 0)[0]
def _GetChecksum(self):
return self.GetField(self._CHECKSUM_, 0)[0]
def _GetHeaderLength(self):
return self.GetField(self._HLEN_, 0)[0]
def _GetFileSystemGuid(self):
return gGuidStringFormat % self.GetField(self._GUID_, 0)
Attributes = property(_GetAttributes)
Size = property(_GetSize)
Checksum = property(_GetChecksum)
HeaderSize = property(_GetHeaderLength)
FileSystemGuid = property(_GetFileSystemGuid)
## MultipleFv() class ## MultipleFv() class
# #
# A class for Multiple FV # A class for Multiple FV

View File

@ -16,28 +16,31 @@
# Import Modules # Import Modules
# #
from __future__ import absolute_import from __future__ import absolute_import
from struct import * from struct import pack
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
from io import BytesIO from io import BytesIO
from . import FfsFileStatement from .FfsFileStatement import FileStatement
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
from CommonDataClass.FdfClass import AprioriSectionClassObject from Common.StringUtils import NormPath
from Common.StringUtils import *
from Common.Misc import SaveFileOnChange, PathClass from Common.Misc import SaveFileOnChange, PathClass
from Common import EdkLogger from Common.EdkLogger import error as EdkLoggerError
from Common.BuildToolError import * from Common.BuildToolError import RESOURCE_NOT_AVAILABLE
from Common.DataType import TAB_COMMON from Common.DataType import TAB_COMMON
DXE_APRIORI_GUID = "FC510EE7-FFDC-11D4-BD41-0080C73C8881"
PEI_APRIORI_GUID = "1B45CC0A-156A-428A-AF62-49864DA0E6E6"
## process APRIORI file data and generate PEI/DXE APRIORI file ## process APRIORI file data and generate PEI/DXE APRIORI file
# #
# #
class AprioriSection (AprioriSectionClassObject): class AprioriSection (object):
## The constructor ## The constructor
# #
# @param self The object pointer # @param self The object pointer
# #
def __init__(self): def __init__(self):
AprioriSectionClassObject.__init__(self) self.DefineVarDict = {}
self.FfsList = []
self.AprioriType = "" self.AprioriType = ""
## GenFfs() method ## GenFfs() method
@ -50,16 +53,16 @@ class AprioriSection (AprioriSectionClassObject):
# @retval string Generated file name # @retval string Generated file name
# #
def GenFfs (self, FvName, Dict = {}, IsMakefile = False): def GenFfs (self, FvName, Dict = {}, IsMakefile = False):
DXE_GUID = "FC510EE7-FFDC-11D4-BD41-0080C73C8881"
PEI_GUID = "1B45CC0A-156A-428A-AF62-49864DA0E6E6"
Buffer = BytesIO('') Buffer = BytesIO('')
AprioriFileGuid = DXE_GUID
if self.AprioriType == "PEI": if self.AprioriType == "PEI":
AprioriFileGuid = PEI_GUID AprioriFileGuid = PEI_APRIORI_GUID
else:
AprioriFileGuid = DXE_APRIORI_GUID
OutputAprFilePath = os.path.join (GenFdsGlobalVariable.WorkSpaceDir, \ OutputAprFilePath = os.path.join (GenFdsGlobalVariable.WorkSpaceDir, \
GenFdsGlobalVariable.FfsDir,\ GenFdsGlobalVariable.FfsDir,\
AprioriFileGuid + FvName) AprioriFileGuid + FvName)
if not os.path.exists(OutputAprFilePath) : if not os.path.exists(OutputAprFilePath):
os.makedirs(OutputAprFilePath) os.makedirs(OutputAprFilePath)
OutputAprFileName = os.path.join( OutputAprFilePath, \ OutputAprFileName = os.path.join( OutputAprFilePath, \
@ -69,33 +72,30 @@ class AprioriSection (AprioriSectionClassObject):
Dict.update(self.DefineVarDict) Dict.update(self.DefineVarDict)
InfFileName = None InfFileName = None
for FfsObj in self.FfsList : for FfsObj in self.FfsList:
Guid = "" Guid = ""
if isinstance(FfsObj, FfsFileStatement.FileStatement): if isinstance(FfsObj, FileStatement):
Guid = FfsObj.NameGuid Guid = FfsObj.NameGuid
else: else:
InfFileName = NormPath(FfsObj.InfFileName) InfFileName = NormPath(FfsObj.InfFileName)
Arch = FfsObj.GetCurrentArch() Arch = FfsObj.GetCurrentArch()
if Arch is not None: if Arch:
Dict['$(ARCH)'] = Arch Dict['$(ARCH)'] = Arch
InfFileName = GenFdsGlobalVariable.MacroExtend(InfFileName, Dict, Arch) InfFileName = GenFdsGlobalVariable.MacroExtend(InfFileName, Dict, Arch)
if Arch is not None: if Arch:
Inf = GenFdsGlobalVariable.WorkSpace.BuildObject[PathClass(InfFileName, GenFdsGlobalVariable.WorkSpaceDir), Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] Inf = GenFdsGlobalVariable.WorkSpace.BuildObject[PathClass(InfFileName, GenFdsGlobalVariable.WorkSpaceDir), Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
Guid = Inf.Guid Guid = Inf.Guid
else: else:
Inf = GenFdsGlobalVariable.WorkSpace.BuildObject[PathClass(InfFileName, GenFdsGlobalVariable.WorkSpaceDir), TAB_COMMON, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] Inf = GenFdsGlobalVariable.WorkSpace.BuildObject[PathClass(InfFileName, GenFdsGlobalVariable.WorkSpaceDir), TAB_COMMON, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
Guid = Inf.Guid Guid = Inf.Guid
self.BinFileList = Inf.Module.Binaries if not Inf.Module.Binaries:
if self.BinFileList == []: EdkLoggerError("GenFds", RESOURCE_NOT_AVAILABLE,
EdkLogger.error("GenFds", RESOURCE_NOT_AVAILABLE,
"INF %s not found in build ARCH %s!" \ "INF %s not found in build ARCH %s!" \
% (InfFileName, GenFdsGlobalVariable.ArchList)) % (InfFileName, GenFdsGlobalVariable.ArchList))
GuidPart = Guid.split('-') GuidPart = Guid.split('-')
Buffer.write(pack('I', long(GuidPart[0], 16))) Buffer.write(pack('I', long(GuidPart[0], 16)))
Buffer.write(pack('H', int(GuidPart[1], 16))) Buffer.write(pack('H', int(GuidPart[1], 16)))
@ -123,4 +123,3 @@ class AprioriSection (AprioriSectionClassObject):
'EFI_FV_FILETYPE_FREEFORM', AprioriFileGuid, MakefilePath=MakefilePath) 'EFI_FV_FILETYPE_FREEFORM', AprioriFileGuid, MakefilePath=MakefilePath)
return AprFfsFileName return AprFfsFileName

View File

@ -16,22 +16,18 @@
# Import Modules # Import Modules
# #
from __future__ import absolute_import from __future__ import absolute_import
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable, FindExtendTool
from .GenFdsGlobalVariable import FindExtendTool
from CommonDataClass.FdfClass import CapsuleClassObject from CommonDataClass.FdfClass import CapsuleClassObject
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
import subprocess
from io import BytesIO from io import BytesIO
from Common.Misc import SaveFileOnChange from Common.Misc import SaveFileOnChange, PackRegistryFormatGuid
from Common.Misc import PackRegistryFormatGuid
import uuid import uuid
from struct import pack from struct import pack
from Common import EdkLogger from Common import EdkLogger
from Common.BuildToolError import * from Common.BuildToolError import GENFDS_ERROR
from Common.DataType import TAB_LINE_BREAK
WIN_CERT_REVISION = 0x0200
T_CHAR_LF = '\n'
WIN_CERT_REVISION = 0x0200
WIN_CERT_TYPE_EFI_GUID = 0x0EF1 WIN_CERT_TYPE_EFI_GUID = 0x0EF1
EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}') EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}')
EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-4977-9420-844712a735bf}') EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-4977-9420-844712a735bf}')
@ -39,7 +35,7 @@ EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-4977-9420-844712a7
## create inf file describes what goes into capsule and call GenFv to generate capsule ## create inf file describes what goes into capsule and call GenFv to generate capsule
# #
# #
class Capsule (CapsuleClassObject) : class Capsule (CapsuleClassObject):
## The constructor ## The constructor
# #
# @param self The object pointer # @param self The object pointer
@ -210,16 +206,16 @@ class Capsule (CapsuleClassObject) :
return self.GenFmpCapsule() return self.GenFmpCapsule()
CapInfFile = self.GenCapInf() CapInfFile = self.GenCapInf()
CapInfFile.writelines("[files]" + T_CHAR_LF) CapInfFile.writelines("[files]" + TAB_LINE_BREAK)
CapFileList = [] CapFileList = []
for CapsuleDataObj in self.CapsuleDataList : for CapsuleDataObj in self.CapsuleDataList:
CapsuleDataObj.CapsuleName = self.CapsuleName CapsuleDataObj.CapsuleName = self.CapsuleName
FileName = CapsuleDataObj.GenCapsuleSubItem() FileName = CapsuleDataObj.GenCapsuleSubItem()
CapsuleDataObj.CapsuleName = None CapsuleDataObj.CapsuleName = None
CapFileList.append(FileName) CapFileList.append(FileName)
CapInfFile.writelines("EFI_FILE_NAME = " + \ CapInfFile.writelines("EFI_FILE_NAME = " + \
FileName + \ FileName + \
T_CHAR_LF) TAB_LINE_BREAK)
SaveFileOnChange(self.CapInfFileName, CapInfFile.getvalue(), False) SaveFileOnChange(self.CapInfFileName, CapInfFile.getvalue(), False)
CapInfFile.close() CapInfFile.close()
# #
@ -249,13 +245,13 @@ class Capsule (CapsuleClassObject) :
self.UiCapsuleName + "_Cap" + '.inf') self.UiCapsuleName + "_Cap" + '.inf')
CapInfFile = BytesIO() #open (self.CapInfFileName , 'w+') CapInfFile = BytesIO() #open (self.CapInfFileName , 'w+')
CapInfFile.writelines("[options]" + T_CHAR_LF) CapInfFile.writelines("[options]" + TAB_LINE_BREAK)
for Item in self.TokensDict: for Item in self.TokensDict:
CapInfFile.writelines("EFI_" + \ CapInfFile.writelines("EFI_" + \
Item + \ Item + \
' = ' + \ ' = ' + \
self.TokensDict[Item] + \ self.TokensDict[Item] + \
T_CHAR_LF) TAB_LINE_BREAK)
return CapInfFile return CapInfFile

View File

@ -16,7 +16,6 @@
# Import Modules # Import Modules
# #
from __future__ import absolute_import from __future__ import absolute_import
from . import Ffs
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
from io import BytesIO from io import BytesIO
from struct import pack from struct import pack

View File

@ -16,7 +16,7 @@
# Import Modules # Import Modules
# #
from __future__ import absolute_import from __future__ import absolute_import
from .Ffs import Ffs from .Ffs import SectionSuffix
from . import Section from . import Section
import subprocess import subprocess
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
@ -86,7 +86,7 @@ class CompressSection (CompressSectionClassObject) :
ModuleName + \ ModuleName + \
SUP_MODULE_SEC + \ SUP_MODULE_SEC + \
SecNum + \ SecNum + \
Ffs.SectionSuffix['COMPRESS'] SectionSuffix['COMPRESS']
OutputFile = os.path.normpath(OutputFile) OutputFile = os.path.normpath(OutputFile)
DummyFile = OutputFile + '.dummy' DummyFile = OutputFile + '.dummy'
GenFdsGlobalVariable.GenerateSection(DummyFile, SectFiles, InputAlign=SectAlign, IsMakefile=IsMakefile) GenFdsGlobalVariable.GenerateSection(DummyFile, SectFiles, InputAlign=SectAlign, IsMakefile=IsMakefile)

View File

@ -19,7 +19,7 @@ from __future__ import absolute_import
from . import Section from . import Section
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
import subprocess import subprocess
from .Ffs import Ffs from .Ffs import SectionSuffix
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
from CommonDataClass.FdfClass import DataSectionClassObject from CommonDataClass.FdfClass import DataSectionClassObject
from Common.Misc import PeImageClass from Common.Misc import PeImageClass
@ -121,7 +121,7 @@ class DataSection (DataSectionClassObject):
) )
self.SectFileName = TeFile self.SectFileName = TeFile
OutputFile = os.path.join (OutputPath, ModuleName + SUP_MODULE_SEC + SecNum + Ffs.SectionSuffix.get(self.SecType)) OutputFile = os.path.join (OutputPath, ModuleName + SUP_MODULE_SEC + SecNum + SectionSuffix.get(self.SecType))
OutputFile = os.path.normpath(OutputFile) OutputFile = os.path.normpath(OutputFile)
GenFdsGlobalVariable.GenerateSection(OutputFile, [self.SectFileName], Section.Section.SectionType.get(self.SecType), IsMakefile = IsMakefile) GenFdsGlobalVariable.GenerateSection(OutputFile, [self.SectFileName], Section.Section.SectionType.get(self.SecType), IsMakefile = IsMakefile)
FileList = [OutputFile] FileList = [OutputFile]

View File

@ -18,8 +18,6 @@
from __future__ import absolute_import from __future__ import absolute_import
from . import Section from . import Section
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
import subprocess
from .Ffs import Ffs
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
from CommonDataClass.FdfClass import DepexSectionClassObject from CommonDataClass.FdfClass import DepexSectionClassObject
from AutoGen.GenDepex import DependencyExpression from AutoGen.GenDepex import DependencyExpression
@ -46,9 +44,8 @@ class DepexSection (DepexSectionClassObject):
GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.TargetName,
GenFdsGlobalVariable.ToolChainTag) GenFdsGlobalVariable.ToolChainTag)
for Inf in GenFdsGlobalVariable.FdfParser.Profile.InfList: for Inf in GenFdsGlobalVariable.FdfParser.Profile.InfList:
ModuleFile = PathClass(Inf, GenFdsGlobalVariable.WorkSpaceDir)
ModuleData = GenFdsGlobalVariable.WorkSpace.BuildObject[ ModuleData = GenFdsGlobalVariable.WorkSpace.BuildObject[
ModuleFile, PathClass(Inf, GenFdsGlobalVariable.WorkSpaceDir),
Arch, Arch,
GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.TargetName,
GenFdsGlobalVariable.ToolChainTag GenFdsGlobalVariable.ToolChainTag

View File

@ -20,7 +20,7 @@ from struct import *
from . import Section from . import Section
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
import subprocess import subprocess
from .Ffs import Ffs from .Ffs import SectionSuffix
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
from CommonDataClass.FdfClass import EfiSectionClassObject from CommonDataClass.FdfClass import EfiSectionClassObject
from Common import EdkLogger from Common import EdkLogger
@ -124,7 +124,7 @@ class EfiSection (EfiSectionClassObject):
BuildNumTuple = tuple() BuildNumTuple = tuple()
Num = SecNum Num = SecNum
OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType)) OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + SectionSuffix.get(SectionType))
GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION', GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',
#Ui=StringData, #Ui=StringData,
Ver=BuildNum, Ver=BuildNum,
@ -135,7 +135,7 @@ class EfiSection (EfiSectionClassObject):
for File in FileList: for File in FileList:
Index = Index + 1 Index = Index + 1
Num = '%s.%d' %(SecNum, Index) Num = '%s.%d' %(SecNum, Index)
OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType)) OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + Num + SectionSuffix.get(SectionType))
f = open(File, 'r') f = open(File, 'r')
VerString = f.read() VerString = f.read()
f.close() f.close()
@ -164,7 +164,7 @@ class EfiSection (EfiSectionClassObject):
else: else:
EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s miss Version Section value" %InfFileName) EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s miss Version Section value" %InfFileName)
Num = SecNum Num = SecNum
OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType)) OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + SectionSuffix.get(SectionType))
GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION', GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',
#Ui=VerString, #Ui=VerString,
Ver=BuildNum, Ver=BuildNum,
@ -185,7 +185,7 @@ class EfiSection (EfiSectionClassObject):
Num = SecNum Num = SecNum
if IsMakefile and StringData == ModuleNameStr: if IsMakefile and StringData == ModuleNameStr:
StringData = "$(MODULE_NAME)" StringData = "$(MODULE_NAME)"
OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType)) OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + SectionSuffix.get(SectionType))
GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE', GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE',
Ui=StringData, IsMakefile=IsMakefile) Ui=StringData, IsMakefile=IsMakefile)
OutputFileList.append(OutputFile) OutputFileList.append(OutputFile)
@ -194,7 +194,7 @@ class EfiSection (EfiSectionClassObject):
for File in FileList: for File in FileList:
Index = Index + 1 Index = Index + 1
Num = '%s.%d' %(SecNum, Index) Num = '%s.%d' %(SecNum, Index)
OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType)) OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + Num + SectionSuffix.get(SectionType))
f = open(File, 'r') f = open(File, 'r')
UiString = f.read() UiString = f.read()
f.close() f.close()
@ -218,7 +218,7 @@ class EfiSection (EfiSectionClassObject):
Num = SecNum Num = SecNum
if IsMakefile and StringData == ModuleNameStr: if IsMakefile and StringData == ModuleNameStr:
StringData = "$(MODULE_NAME)" StringData = "$(MODULE_NAME)"
OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType)) OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + SectionSuffix.get(SectionType))
GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE', GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE',
Ui=StringData, IsMakefile=IsMakefile) Ui=StringData, IsMakefile=IsMakefile)
OutputFileList.append(OutputFile) OutputFileList.append(OutputFile)
@ -239,7 +239,7 @@ class EfiSection (EfiSectionClassObject):
""" Copy Map file to FFS output path """ """ Copy Map file to FFS output path """
Index = Index + 1 Index = Index + 1
Num = '%s.%d' %(SecNum, Index) Num = '%s.%d' %(SecNum, Index)
OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType)) OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + Num + SectionSuffix.get(SectionType))
File = GenFdsGlobalVariable.MacroExtend(File, Dict) File = GenFdsGlobalVariable.MacroExtend(File, Dict)
#Get PE Section alignment when align is set to AUTO #Get PE Section alignment when align is set to AUTO

File diff suppressed because it is too large Load Diff

View File

@ -15,53 +15,41 @@
## ##
# Import Modules # Import Modules
# #
from CommonDataClass.FdfClass import FDClassObject
from Common.DataType import * from Common.DataType import *
## generate FFS # mapping between FILE type in FDF and file type for GenFfs
# FdfFvFileTypeToFileType = {
# SUP_MODULE_SEC : 'EFI_FV_FILETYPE_SECURITY_CORE',
class Ffs(FDClassObject): SUP_MODULE_PEI_CORE : 'EFI_FV_FILETYPE_PEI_CORE',
# mapping between FILE type in FDF and file type for GenFfs SUP_MODULE_PEIM : 'EFI_FV_FILETYPE_PEIM',
FdfFvFileTypeToFileType = { SUP_MODULE_DXE_CORE : 'EFI_FV_FILETYPE_DXE_CORE',
SUP_MODULE_SEC : 'EFI_FV_FILETYPE_SECURITY_CORE', 'FREEFORM' : 'EFI_FV_FILETYPE_FREEFORM',
SUP_MODULE_PEI_CORE : 'EFI_FV_FILETYPE_PEI_CORE', 'DRIVER' : 'EFI_FV_FILETYPE_DRIVER',
SUP_MODULE_PEIM : 'EFI_FV_FILETYPE_PEIM', 'APPLICATION' : 'EFI_FV_FILETYPE_APPLICATION',
SUP_MODULE_DXE_CORE : 'EFI_FV_FILETYPE_DXE_CORE', 'FV_IMAGE' : 'EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE',
'FREEFORM' : 'EFI_FV_FILETYPE_FREEFORM', 'RAW' : 'EFI_FV_FILETYPE_RAW',
'DRIVER' : 'EFI_FV_FILETYPE_DRIVER', 'PEI_DXE_COMBO' : 'EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER',
'APPLICATION' : 'EFI_FV_FILETYPE_APPLICATION', 'SMM' : 'EFI_FV_FILETYPE_SMM',
'FV_IMAGE' : 'EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE', SUP_MODULE_SMM_CORE : 'EFI_FV_FILETYPE_SMM_CORE',
'RAW' : 'EFI_FV_FILETYPE_RAW', SUP_MODULE_MM_STANDALONE : 'EFI_FV_FILETYPE_MM_STANDALONE',
'PEI_DXE_COMBO' : 'EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER', SUP_MODULE_MM_CORE_STANDALONE : 'EFI_FV_FILETYPE_MM_CORE_STANDALONE'
'SMM' : 'EFI_FV_FILETYPE_SMM', }
SUP_MODULE_SMM_CORE : 'EFI_FV_FILETYPE_SMM_CORE',
SUP_MODULE_MM_STANDALONE : 'EFI_FV_FILETYPE_MM_STANDALONE',
SUP_MODULE_MM_CORE_STANDALONE : 'EFI_FV_FILETYPE_MM_CORE_STANDALONE'
}
# mapping between section type in FDF and file suffix # mapping between section type in FDF and file suffix
SectionSuffix = { SectionSuffix = {
BINARY_FILE_TYPE_PE32 : '.pe32', BINARY_FILE_TYPE_PE32 : '.pe32',
BINARY_FILE_TYPE_PIC : '.pic', BINARY_FILE_TYPE_PIC : '.pic',
BINARY_FILE_TYPE_TE : '.te', BINARY_FILE_TYPE_TE : '.te',
BINARY_FILE_TYPE_DXE_DEPEX : '.dpx', BINARY_FILE_TYPE_DXE_DEPEX : '.dpx',
'VERSION' : '.ver', 'VERSION' : '.ver',
BINARY_FILE_TYPE_UI : '.ui', BINARY_FILE_TYPE_UI : '.ui',
'COMPAT16' : '.com16', 'COMPAT16' : '.com16',
'RAW' : '.raw', 'RAW' : '.raw',
'FREEFORM_SUBTYPE_GUID': '.guid', 'FREEFORM_SUBTYPE_GUID': '.guid',
'SUBTYPE_GUID' : '.guid', 'SUBTYPE_GUID' : '.guid',
'FV_IMAGE' : 'fv.sec', 'FV_IMAGE' : 'fv.sec',
'COMPRESS' : '.com', 'COMPRESS' : '.com',
'GUIDED' : '.guided', 'GUIDED' : '.guided',
BINARY_FILE_TYPE_PEI_DEPEX : '.dpx', BINARY_FILE_TYPE_PEI_DEPEX : '.dpx',
BINARY_FILE_TYPE_SMM_DEPEX : '.dpx' BINARY_FILE_TYPE_SMM_DEPEX : '.dpx'
} }
## The constructor
#
# @param self The object pointer
#
def __init__(self):
FfsClassObject.__init__(self)

View File

@ -16,26 +16,22 @@
# Import Modules # Import Modules
# #
from __future__ import absolute_import from __future__ import absolute_import
from . import Ffs
from . import Rule
import Common.LongFilePathOs as os
from io import BytesIO from io import BytesIO
import subprocess from struct import pack
from .GenFdsGlobalVariable import GenFdsGlobalVariable
from CommonDataClass.FdfClass import FileStatementClassObject from CommonDataClass.FdfClass import FileStatementClassObject
from Common import EdkLogger from Common import EdkLogger
from Common.BuildToolError import * from Common.BuildToolError import GENFDS_ERROR
from Common.Misc import GuidStructureByteArrayToGuidString from Common.Misc import GuidStructureByteArrayToGuidString, SaveFileOnChange
import Common.LongFilePathOs as os
from .GuidSection import GuidSection from .GuidSection import GuidSection
from .FvImageSection import FvImageSection from .FvImageSection import FvImageSection
from Common.Misc import SaveFileOnChange from .Ffs import FdfFvFileTypeToFileType
from struct import * from .GenFdsGlobalVariable import GenFdsGlobalVariable
## generate FFS from FILE ## generate FFS from FILE
# #
# #
class FileStatement (FileStatementClassObject) : class FileStatement (FileStatementClassObject):
## The constructor ## The constructor
# #
# @param self The object pointer # @param self The object pointer
@ -60,7 +56,7 @@ class FileStatement (FileStatementClassObject) :
# #
def GenFfs(self, Dict = {}, FvChildAddr=[], FvParentAddr=None, IsMakefile=False, FvName=None): def GenFfs(self, Dict = {}, FvChildAddr=[], FvParentAddr=None, IsMakefile=False, FvName=None):
if self.NameGuid is not None and self.NameGuid.startswith('PCD('): if self.NameGuid and self.NameGuid.startswith('PCD('):
PcdValue = GenFdsGlobalVariable.GetPcdValue(self.NameGuid) PcdValue = GenFdsGlobalVariable.GetPcdValue(self.NameGuid)
if len(PcdValue) == 0: if len(PcdValue) == 0:
EdkLogger.error("GenFds", GENFDS_ERROR, '%s NOT defined.' \ EdkLogger.error("GenFds", GENFDS_ERROR, '%s NOT defined.' \
@ -82,7 +78,7 @@ class FileStatement (FileStatementClassObject) :
Dict.update(self.DefineVarDict) Dict.update(self.DefineVarDict)
SectionAlignments = None SectionAlignments = None
if self.FvName is not None : if self.FvName:
Buffer = BytesIO('') Buffer = BytesIO('')
if self.FvName.upper() not in GenFdsGlobalVariable.FdfParser.Profile.FvDict: if self.FvName.upper() not in GenFdsGlobalVariable.FdfParser.Profile.FvDict:
EdkLogger.error("GenFds", GENFDS_ERROR, "FV (%s) is NOT described in FDF file!" % (self.FvName)) EdkLogger.error("GenFds", GENFDS_ERROR, "FV (%s) is NOT described in FDF file!" % (self.FvName))
@ -90,14 +86,14 @@ class FileStatement (FileStatementClassObject) :
FileName = Fv.AddToBuffer(Buffer) FileName = Fv.AddToBuffer(Buffer)
SectionFiles = [FileName] SectionFiles = [FileName]
elif self.FdName is not None: elif self.FdName:
if self.FdName.upper() not in GenFdsGlobalVariable.FdfParser.Profile.FdDict: if self.FdName.upper() not in GenFdsGlobalVariable.FdfParser.Profile.FdDict:
EdkLogger.error("GenFds", GENFDS_ERROR, "FD (%s) is NOT described in FDF file!" % (self.FdName)) EdkLogger.error("GenFds", GENFDS_ERROR, "FD (%s) is NOT described in FDF file!" % (self.FdName))
Fd = GenFdsGlobalVariable.FdfParser.Profile.FdDict.get(self.FdName.upper()) Fd = GenFdsGlobalVariable.FdfParser.Profile.FdDict.get(self.FdName.upper())
FileName = Fd.GenFd() FileName = Fd.GenFd()
SectionFiles = [FileName] SectionFiles = [FileName]
elif self.FileName is not None: elif self.FileName:
if hasattr(self, 'FvFileType') and self.FvFileType == 'RAW': if hasattr(self, 'FvFileType') and self.FvFileType == 'RAW':
if isinstance(self.FileName, list) and isinstance(self.SubAlignment, list) and len(self.FileName) == len(self.SubAlignment): if isinstance(self.FileName, list) and isinstance(self.SubAlignment, list) and len(self.FileName) == len(self.SubAlignment):
FileContent = '' FileContent = ''
@ -111,7 +107,7 @@ class FileStatement (FileStatementClassObject) :
Content = f.read() Content = f.read()
f.close() f.close()
AlignValue = 1 AlignValue = 1
if self.SubAlignment[Index] is not None: if self.SubAlignment[Index]:
AlignValue = GenFdsGlobalVariable.GetAlignment(self.SubAlignment[Index]) AlignValue = GenFdsGlobalVariable.GetAlignment(self.SubAlignment[Index])
if AlignValue > MaxAlignValue: if AlignValue > MaxAlignValue:
MaxAlignIndex = Index MaxAlignIndex = Index
@ -143,7 +139,7 @@ class FileStatement (FileStatementClassObject) :
SectionFiles = [] SectionFiles = []
Index = 0 Index = 0
SectionAlignments = [] SectionAlignments = []
for section in self.SectionList : for section in self.SectionList:
Index = Index + 1 Index = Index + 1
SecIndex = '%d' %Index SecIndex = '%d' %Index
# process the inside FvImage from FvSection or GuidSection # process the inside FvImage from FvSection or GuidSection
@ -152,7 +148,7 @@ class FileStatement (FileStatementClassObject) :
section.FvAddr = FvChildAddr.pop(0) section.FvAddr = FvChildAddr.pop(0)
elif isinstance(section, GuidSection): elif isinstance(section, GuidSection):
section.FvAddr = FvChildAddr section.FvAddr = FvChildAddr
if FvParentAddr is not None and isinstance(section, GuidSection): if FvParentAddr and isinstance(section, GuidSection):
section.FvParentAddr = FvParentAddr section.FvParentAddr = FvParentAddr
if self.KeepReloc == False: if self.KeepReloc == False:
@ -168,7 +164,7 @@ class FileStatement (FileStatementClassObject) :
# #
FfsFileOutput = os.path.join(OutputDir, self.NameGuid + '.ffs') FfsFileOutput = os.path.join(OutputDir, self.NameGuid + '.ffs')
GenFdsGlobalVariable.GenerateFfs(FfsFileOutput, SectionFiles, GenFdsGlobalVariable.GenerateFfs(FfsFileOutput, SectionFiles,
Ffs.Ffs.FdfFvFileTypeToFileType.get(self.FvFileType), FdfFvFileTypeToFileType.get(self.FvFileType),
self.NameGuid, self.NameGuid,
Fixed=self.Fixed, Fixed=self.Fixed,
CheckSum=self.CheckSum, CheckSum=self.CheckSum,
@ -177,6 +173,3 @@ class FileStatement (FileStatementClassObject) :
) )
return FfsFileOutput return FfsFileOutput

View File

@ -22,7 +22,7 @@ import Common.LongFilePathOs as os
from io import BytesIO from io import BytesIO
from struct import * from struct import *
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
from . import Ffs from .Ffs import SectionSuffix,FdfFvFileTypeToFileType
import subprocess import subprocess
import sys import sys
from . import Section from . import Section
@ -760,7 +760,7 @@ class FfsInfStatement(FfsInfStatementClassObject):
SecNum = '%d' %Index SecNum = '%d' %Index
GenSecOutputFile= self.__ExtendMacro__(Rule.NameGuid) + \ GenSecOutputFile= self.__ExtendMacro__(Rule.NameGuid) + \
Ffs.Ffs.SectionSuffix[SectionType] + SUP_MODULE_SEC + SecNum SectionSuffix[SectionType] + SUP_MODULE_SEC + SecNum
Index = Index + 1 Index = Index + 1
OutputFile = os.path.join(self.OutputPath, GenSecOutputFile) OutputFile = os.path.join(self.OutputPath, GenSecOutputFile)
File = GenFdsGlobalVariable.MacroExtend(File, Dict, self.CurrentArch) File = GenFdsGlobalVariable.MacroExtend(File, Dict, self.CurrentArch)
@ -803,7 +803,7 @@ class FfsInfStatement(FfsInfStatementClassObject):
else: else:
SecNum = '%d' %Index SecNum = '%d' %Index
GenSecOutputFile= self.__ExtendMacro__(Rule.NameGuid) + \ GenSecOutputFile= self.__ExtendMacro__(Rule.NameGuid) + \
Ffs.Ffs.SectionSuffix[SectionType] + SUP_MODULE_SEC + SecNum SectionSuffix[SectionType] + SUP_MODULE_SEC + SecNum
OutputFile = os.path.join(self.OutputPath, GenSecOutputFile) OutputFile = os.path.join(self.OutputPath, GenSecOutputFile)
GenSecInputFile = GenFdsGlobalVariable.MacroExtend(GenSecInputFile, Dict, self.CurrentArch) GenSecInputFile = GenFdsGlobalVariable.MacroExtend(GenSecInputFile, Dict, self.CurrentArch)
@ -882,7 +882,7 @@ class FfsInfStatement(FfsInfStatementClassObject):
self.ModuleGuid = RegistryGuidStr self.ModuleGuid = RegistryGuidStr
GenFdsGlobalVariable.GenerateFfs(FfsOutput, InputSection, GenFdsGlobalVariable.GenerateFfs(FfsOutput, InputSection,
Ffs.Ffs.FdfFvFileTypeToFileType[Rule.FvFileType], FdfFvFileTypeToFileType[Rule.FvFileType],
self.ModuleGuid, Fixed=Rule.Fixed, self.ModuleGuid, Fixed=Rule.Fixed,
CheckSum=Rule.CheckSum, Align=Rule.Alignment, CheckSum=Rule.CheckSum, Align=Rule.Alignment,
SectionAlign=SectionAlignments, SectionAlign=SectionAlignments,
@ -1055,7 +1055,7 @@ class FfsInfStatement(FfsInfStatementClassObject):
FfsOutput = os.path.join( self.OutputPath, self.ModuleGuid + '.ffs') FfsOutput = os.path.join( self.OutputPath, self.ModuleGuid + '.ffs')
GenFdsGlobalVariable.GenerateFfs(FfsOutput, InputFile, GenFdsGlobalVariable.GenerateFfs(FfsOutput, InputFile,
Ffs.Ffs.FdfFvFileTypeToFileType[Rule.FvFileType], FdfFvFileTypeToFileType[Rule.FvFileType],
self.ModuleGuid, Fixed=Rule.Fixed, self.ModuleGuid, Fixed=Rule.Fixed,
CheckSum=Rule.CheckSum, Align=Rule.Alignment, CheckSum=Rule.CheckSum, Align=Rule.Alignment,
SectionAlign=Alignments, SectionAlign=Alignments,

View File

@ -1,4 +1,3 @@
from __future__ import absolute_import
## @file ## @file
# process FV generation # process FV generation
# #
@ -16,16 +15,13 @@ from __future__ import absolute_import
## ##
# Import Modules # Import Modules
# #
from __future__ import absolute_import
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
import subprocess import subprocess
from io import BytesIO from io import BytesIO
from struct import * from struct import *
from . import Ffs
from . import AprioriSection
from . import FfsFileStatement from . import FfsFileStatement
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
from CommonDataClass.FdfClass import FvClassObject
from Common.Misc import SaveFileOnChange, PackGUID from Common.Misc import SaveFileOnChange, PackGUID
from Common.LongFilePathSupport import CopyLongFilePath from Common.LongFilePathSupport import CopyLongFilePath
from Common.LongFilePathSupport import OpenLongFilePath as open from Common.LongFilePathSupport import OpenLongFilePath as open
@ -36,13 +32,25 @@ FV_UI_EXT_ENTY_GUID = 'A67DF1FA-8DE8-4E98-AF09-4BDF2EFFBC7C'
## generate FV ## generate FV
# #
# #
class FV (FvClassObject): class FV (object):
## The constructor ## The constructor
# #
# @param self The object pointer # @param self The object pointer
# #
def __init__(self): def __init__(self):
FvClassObject.__init__(self) self.UiFvName = None
self.CreateFileName = None
self.BlockSizeList = []
self.DefineVarDict = {}
self.SetVarDict = {}
self.FvAlignment = None
self.FvAttributeDict = {}
self.FvNameGuid = None
self.FvNameString = None
self.AprioriSectionList = []
self.FfsList = []
self.BsBaseAddress = None
self.RtBaseAddress = None
self.FvInfFile = None self.FvInfFile = None
self.FvAddressFile = None self.FvAddressFile = None
self.BaseAddress = None self.BaseAddress = None
@ -68,7 +76,7 @@ class FV (FvClassObject):
# @param MacroDict macro value pair # @param MacroDict macro value pair
# @retval string Generated FV file path # @retval string Generated FV file path
# #
def AddToBuffer (self, Buffer, BaseAddress=None, BlockSize= None, BlockNum=None, ErasePloarity='1', VtfDict=None, MacroDict = {}, Flag=False) : def AddToBuffer (self, Buffer, BaseAddress=None, BlockSize= None, BlockNum=None, ErasePloarity='1', VtfDict=None, MacroDict = {}, Flag=False):
if BaseAddress is None and self.UiFvName.upper() + 'fv' in GenFdsGlobalVariable.ImageBinDict: if BaseAddress is None and self.UiFvName.upper() + 'fv' in GenFdsGlobalVariable.ImageBinDict:
return GenFdsGlobalVariable.ImageBinDict[self.UiFvName.upper() + 'fv'] return GenFdsGlobalVariable.ImageBinDict[self.UiFvName.upper() + 'fv']
@ -96,7 +104,7 @@ class FV (FvClassObject):
if self.FvBaseAddress is not None: if self.FvBaseAddress is not None:
BaseAddress = self.FvBaseAddress BaseAddress = self.FvBaseAddress
if not Flag: if not Flag:
self.__InitializeInf__(BaseAddress, BlockSize, BlockNum, ErasePloarity, VtfDict) self._InitializeInf(BaseAddress, BlockSize, BlockNum, ErasePloarity, VtfDict)
# #
# First Process the Apriori section # First Process the Apriori section
# #
@ -114,7 +122,7 @@ class FV (FvClassObject):
TAB_LINE_BREAK) TAB_LINE_BREAK)
# Process Modules in FfsList # Process Modules in FfsList
for FfsFile in self.FfsList : for FfsFile in self.FfsList:
if Flag: if Flag:
if isinstance(FfsFile, FfsFileStatement.FileStatement): if isinstance(FfsFile, FfsFileStatement.FileStatement):
continue continue
@ -177,7 +185,7 @@ class FV (FvClassObject):
if FvChildAddr != []: if FvChildAddr != []:
# Update Ffs again # Update Ffs again
for FfsFile in self.FfsList : for FfsFile in self.FfsList:
FileName = FfsFile.GenFfs(MacroDict, FvChildAddr, BaseAddress, IsMakefile=Flag, FvName=self.UiFvName) FileName = FfsFile.GenFfs(MacroDict, FvChildAddr, BaseAddress, IsMakefile=Flag, FvName=self.UiFvName)
if GenFdsGlobalVariable.LargeFileInFvFlags[-1]: if GenFdsGlobalVariable.LargeFileInFvFlags[-1]:
@ -252,7 +260,7 @@ class FV (FvClassObject):
return True return True
return False return False
## __InitializeInf__() ## _InitializeInf()
# #
# Initilize the inf file to create FV # Initilize the inf file to create FV
# #
@ -263,7 +271,7 @@ class FV (FvClassObject):
# @param ErasePolarity Flash erase polarity # @param ErasePolarity Flash erase polarity
# @param VtfDict VTF objects # @param VtfDict VTF objects
# #
def __InitializeInf__ (self, BaseAddress = None, BlockSize= None, BlockNum = None, ErasePloarity='1', VtfDict=None) : def _InitializeInf (self, BaseAddress = None, BlockSize= None, BlockNum = None, ErasePloarity='1', VtfDict=None):
# #
# Create FV inf file # Create FV inf file
# #
@ -275,7 +283,7 @@ class FV (FvClassObject):
# Add [Options] # Add [Options]
# #
self.FvInfFile.writelines("[options]" + TAB_LINE_BREAK) self.FvInfFile.writelines("[options]" + TAB_LINE_BREAK)
if BaseAddress is not None : if BaseAddress is not None:
self.FvInfFile.writelines("EFI_BASE_ADDRESS = " + \ self.FvInfFile.writelines("EFI_BASE_ADDRESS = " + \
BaseAddress + \ BaseAddress + \
TAB_LINE_BREAK) TAB_LINE_BREAK)
@ -294,7 +302,7 @@ class FV (FvClassObject):
#set default block size is 1 #set default block size is 1
self.FvInfFile.writelines("EFI_BLOCK_SIZE = 0x1" + TAB_LINE_BREAK) self.FvInfFile.writelines("EFI_BLOCK_SIZE = 0x1" + TAB_LINE_BREAK)
for BlockSize in self.BlockSizeList : for BlockSize in self.BlockSizeList:
if BlockSize[0] is not None: if BlockSize[0] is not None:
self.FvInfFile.writelines("EFI_BLOCK_SIZE = " + \ self.FvInfFile.writelines("EFI_BLOCK_SIZE = " + \
'0x%X' %BlockSize[0] + \ '0x%X' %BlockSize[0] + \
@ -320,9 +328,9 @@ class FV (FvClassObject):
' %s' %ErasePloarity + \ ' %s' %ErasePloarity + \
TAB_LINE_BREAK) TAB_LINE_BREAK)
if not (self.FvAttributeDict is None): if not (self.FvAttributeDict is None):
for FvAttribute in self.FvAttributeDict.keys() : for FvAttribute in self.FvAttributeDict.keys():
if FvAttribute == "FvUsedSizeEnable": if FvAttribute == "FvUsedSizeEnable":
if self.FvAttributeDict[FvAttribute].upper() in ('TRUE', '1') : if self.FvAttributeDict[FvAttribute].upper() in ('TRUE', '1'):
self.UsedSizeEnable = True self.UsedSizeEnable = True
continue continue
self.FvInfFile.writelines("EFI_" + \ self.FvInfFile.writelines("EFI_" + \
@ -365,8 +373,8 @@ class FV (FvClassObject):
Guid = FV_UI_EXT_ENTY_GUID.split('-') Guid = FV_UI_EXT_ENTY_GUID.split('-')
# #
# Layout: # Layout:
# EFI_FIRMWARE_VOLUME_EXT_ENTRY : size 4 # EFI_FIRMWARE_VOLUME_EXT_ENTRY: size 4
# GUID : size 16 # GUID: size 16
# FV UI name # FV UI name
# #
Buffer += (pack('HH', (FvUiLen + 16 + 4), 0x0002) Buffer += (pack('HH', (FvUiLen + 16 + 4), 0x0002)
@ -422,7 +430,6 @@ class FV (FvClassObject):
FvExtHeaderFileName + \ FvExtHeaderFileName + \
TAB_LINE_BREAK) TAB_LINE_BREAK)
# #
# Add [Files] # Add [Files]
# #

View File

@ -18,7 +18,7 @@
from __future__ import absolute_import from __future__ import absolute_import
from . import Section from . import Section
from io import BytesIO from io import BytesIO
from .Ffs import Ffs from .Ffs import SectionSuffix
import subprocess import subprocess
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
@ -76,7 +76,7 @@ class FvImageSection(FvImageSectionClassObject):
if FvAlignmentValue > MaxFvAlignment: if FvAlignmentValue > MaxFvAlignment:
MaxFvAlignment = FvAlignmentValue MaxFvAlignment = FvAlignmentValue
OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + Num + Ffs.SectionSuffix.get("FV_IMAGE")) OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + Num + SectionSuffix.get("FV_IMAGE"))
GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileName], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', IsMakefile=IsMakefile) GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileName], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', IsMakefile=IsMakefile)
OutputFileList.append(OutputFile) OutputFileList.append(OutputFile)
@ -146,7 +146,7 @@ class FvImageSection(FvImageSectionClassObject):
# #
# Prepare the parameter of GenSection # Prepare the parameter of GenSection
# #
OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + SecNum + Ffs.SectionSuffix.get("FV_IMAGE")) OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + SecNum + SectionSuffix.get("FV_IMAGE"))
GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileName], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', IsMakefile=IsMakefile) GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileName], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', IsMakefile=IsMakefile)
OutputFileList.append(OutputFile) OutputFileList.append(OutputFile)

View File

@ -17,34 +17,30 @@
# #
from __future__ import print_function from __future__ import print_function
from __future__ import absolute_import from __future__ import absolute_import
from re import compile
from optparse import OptionParser from optparse import OptionParser
import sys from sys import exit
import Common.LongFilePathOs as os from glob import glob
import linecache from struct import unpack
from . import FdfParser from linecache import getlines
import Common.BuildToolError as BuildToolError
from .GenFdsGlobalVariable import GenFdsGlobalVariable
from Workspace.WorkspaceDatabase import WorkspaceDatabase
from Workspace.BuildClassObject import PcdClassObject
from . import RuleComplexFile
from .EfiSection import EfiSection
from io import BytesIO from io import BytesIO
import Common.TargetTxtClassObject as TargetTxtClassObject
import Common.ToolDefClassObject as ToolDefClassObject import Common.LongFilePathOs as os
from Common.TargetTxtClassObject import TargetTxtClassObject
from Common.DataType import * from Common.DataType import *
import Common.GlobalData as GlobalData import Common.GlobalData as GlobalData
from Common import EdkLogger from Common import EdkLogger
from Common.StringUtils import * from Common.StringUtils import NormPath
from Common.Misc import DirCache, PathClass from Common.Misc import DirCache, PathClass, GuidStructureStringToGuidString
from Common.Misc import SaveFileOnChange from Common.Misc import SaveFileOnChange, ClearDuplicatedInf
from Common.Misc import ClearDuplicatedInf
from Common.Misc import GuidStructureStringToGuidString
from Common.BuildVersion import gBUILD_VERSION from Common.BuildVersion import gBUILD_VERSION
from Common.MultipleWorkspace import MultipleWorkspace as mws from Common.MultipleWorkspace import MultipleWorkspace as mws
from . import FfsFileStatement from Common.BuildToolError import FatalError, GENFDS_ERROR, CODE_ERROR, FORMAT_INVALID, RESOURCE_NOT_AVAILABLE, FILE_NOT_FOUND, OPTION_MISSING, FORMAT_NOT_SUPPORTED,OPTION_VALUE_INVALID
import glob from Workspace.WorkspaceDatabase import WorkspaceDatabase
from struct import unpack
from Common.GlobalData import gGuidPattern from .FdfParser import FdfParser, Warning
from .GenFdsGlobalVariable import GenFdsGlobalVariable
from .FfsFileStatement import FileStatement
## Version and Copyright ## Version and Copyright
versionNumber = "1.0" + ' ' + gBUILD_VERSION versionNumber = "1.0" + ' ' + gBUILD_VERSION
@ -71,22 +67,22 @@ def main():
EdkLogger.Initialize() EdkLogger.Initialize()
try: try:
if Options.verbose is not None: if Options.verbose:
EdkLogger.SetLevel(EdkLogger.VERBOSE) EdkLogger.SetLevel(EdkLogger.VERBOSE)
GenFdsGlobalVariable.VerboseMode = True GenFdsGlobalVariable.VerboseMode = True
if Options.FixedAddress is not None: if Options.FixedAddress:
GenFdsGlobalVariable.FixedLoadAddress = True GenFdsGlobalVariable.FixedLoadAddress = True
if Options.quiet is not None: if Options.quiet:
EdkLogger.SetLevel(EdkLogger.QUIET) EdkLogger.SetLevel(EdkLogger.QUIET)
if Options.debug is not None: if Options.debug:
EdkLogger.SetLevel(Options.debug + 1) EdkLogger.SetLevel(Options.debug + 1)
GenFdsGlobalVariable.DebugLevel = Options.debug GenFdsGlobalVariable.DebugLevel = Options.debug
else: else:
EdkLogger.SetLevel(EdkLogger.INFO) EdkLogger.SetLevel(EdkLogger.INFO)
if (Options.Workspace is None): if not Options.Workspace:
EdkLogger.error("GenFds", OPTION_MISSING, "WORKSPACE not defined", EdkLogger.error("GenFds", OPTION_MISSING, "WORKSPACE not defined",
ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.") ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.")
elif not os.path.exists(Options.Workspace): elif not os.path.exists(Options.Workspace):
@ -97,7 +93,7 @@ def main():
GenFdsGlobalVariable.WorkSpaceDir = Workspace GenFdsGlobalVariable.WorkSpaceDir = Workspace
if 'EDK_SOURCE' in os.environ: if 'EDK_SOURCE' in os.environ:
GenFdsGlobalVariable.EdkSourceDir = os.path.normcase(os.environ['EDK_SOURCE']) GenFdsGlobalVariable.EdkSourceDir = os.path.normcase(os.environ['EDK_SOURCE'])
if (Options.debug): if Options.debug:
GenFdsGlobalVariable.VerboseLogger("Using Workspace:" + Workspace) GenFdsGlobalVariable.VerboseLogger("Using Workspace:" + Workspace)
if Options.GenfdsMultiThread: if Options.GenfdsMultiThread:
GenFdsGlobalVariable.EnableGenfdsMultiThread = True GenFdsGlobalVariable.EnableGenfdsMultiThread = True
@ -107,7 +103,7 @@ def main():
PackagesPath = os.getenv("PACKAGES_PATH") PackagesPath = os.getenv("PACKAGES_PATH")
mws.setWs(GenFdsGlobalVariable.WorkSpaceDir, PackagesPath) mws.setWs(GenFdsGlobalVariable.WorkSpaceDir, PackagesPath)
if (Options.filename): if Options.filename:
FdfFilename = Options.filename FdfFilename = Options.filename
FdfFilename = GenFdsGlobalVariable.ReplaceWorkspaceMacro(FdfFilename) FdfFilename = GenFdsGlobalVariable.ReplaceWorkspaceMacro(FdfFilename)
@ -123,13 +119,13 @@ def main():
else: else:
EdkLogger.error("GenFds", OPTION_MISSING, "Missing FDF filename") EdkLogger.error("GenFds", OPTION_MISSING, "Missing FDF filename")
if (Options.BuildTarget): if Options.BuildTarget:
GenFdsGlobalVariable.TargetName = Options.BuildTarget GenFdsGlobalVariable.TargetName = Options.BuildTarget
if (Options.ToolChain): if Options.ToolChain:
GenFdsGlobalVariable.ToolChainTag = Options.ToolChain GenFdsGlobalVariable.ToolChainTag = Options.ToolChain
if (Options.activePlatform): if Options.activePlatform:
ActivePlatform = Options.activePlatform ActivePlatform = Options.activePlatform
ActivePlatform = GenFdsGlobalVariable.ReplaceWorkspaceMacro(ActivePlatform) ActivePlatform = GenFdsGlobalVariable.ReplaceWorkspaceMacro(ActivePlatform)
@ -139,15 +135,15 @@ def main():
if not os.path.isabs (ActivePlatform): if not os.path.isabs (ActivePlatform):
ActivePlatform = mws.join(GenFdsGlobalVariable.WorkSpaceDir, ActivePlatform) ActivePlatform = mws.join(GenFdsGlobalVariable.WorkSpaceDir, ActivePlatform)
if not os.path.exists(ActivePlatform) : if not os.path.exists(ActivePlatform):
EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!") EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!")
else: else:
EdkLogger.error("GenFds", OPTION_MISSING, "Missing active platform") EdkLogger.error("GenFds", OPTION_MISSING, "Missing active platform")
GlobalData.BuildOptionPcd = Options.OptionPcd if Options.OptionPcd else {} GlobalData.BuildOptionPcd = Options.OptionPcd if Options.OptionPcd else {}
GenFdsGlobalVariable.ActivePlatform = PathClass(NormPath(ActivePlatform)) GenFdsGlobalVariable.ActivePlatform = PathClass(NormPath(ActivePlatform))
if (Options.ConfDirectory): if Options.ConfDirectory:
# Get alternate Conf location, if it is absolute, then just use the absolute directory name # Get alternate Conf location, if it is absolute, then just use the absolute directory name
ConfDirectoryPath = os.path.normpath(Options.ConfDirectory) ConfDirectoryPath = os.path.normpath(Options.ConfDirectory)
if ConfDirectoryPath.startswith('"'): if ConfDirectoryPath.startswith('"'):
@ -169,7 +165,7 @@ def main():
GlobalData.gConfDirectory = GenFdsGlobalVariable.ConfDir GlobalData.gConfDirectory = GenFdsGlobalVariable.ConfDir
BuildConfigurationFile = os.path.normpath(os.path.join(ConfDirectoryPath, "target.txt")) BuildConfigurationFile = os.path.normpath(os.path.join(ConfDirectoryPath, "target.txt"))
if os.path.isfile(BuildConfigurationFile) == True: if os.path.isfile(BuildConfigurationFile) == True:
TargetTxt = TargetTxtClassObject.TargetTxtClassObject() TargetTxt = TargetTxtClassObject()
TargetTxt.LoadTargetTxtFile(BuildConfigurationFile) TargetTxt.LoadTargetTxtFile(BuildConfigurationFile)
# if no build target given in command line, get it from target.txt # if no build target given in command line, get it from target.txt
if not GenFdsGlobalVariable.TargetName: if not GenFdsGlobalVariable.TargetName:
@ -237,10 +233,9 @@ def main():
GlobalData.gAllFiles = DirCache(Workspace) GlobalData.gAllFiles = DirCache(Workspace)
GlobalData.gWorkspace = Workspace GlobalData.gWorkspace = Workspace
if (Options.archList) : if Options.archList:
ArchList = Options.archList.split(',') ArchList = Options.archList.split(',')
else: else:
# EdkLogger.error("GenFds", OPTION_MISSING, "Missing build ARCH")
ArchList = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, TAB_COMMON, Options.BuildTarget, Options.ToolChain].SupArchList ArchList = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, TAB_COMMON, Options.BuildTarget, Options.ToolChain].SupArchList
TargetArchList = set(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, TAB_COMMON, Options.BuildTarget, Options.ToolChain].SupArchList) & set(ArchList) TargetArchList = set(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, TAB_COMMON, Options.BuildTarget, Options.ToolChain].SupArchList) & set(ArchList)
@ -249,9 +244,11 @@ def main():
for Arch in ArchList: for Arch in ArchList:
GenFdsGlobalVariable.OutputDirFromDscDict[Arch] = NormPath(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].OutputDirectory) GenFdsGlobalVariable.OutputDirFromDscDict[Arch] = NormPath(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].OutputDirectory)
GenFdsGlobalVariable.PlatformName = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].PlatformName
if (Options.outputDir): # assign platform name based on last entry in ArchList
GenFdsGlobalVariable.PlatformName = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, ArchList[-1], Options.BuildTarget, Options.ToolChain].PlatformName
if Options.outputDir:
OutputDirFromCommandLine = GenFdsGlobalVariable.ReplaceWorkspaceMacro(Options.outputDir) OutputDirFromCommandLine = GenFdsGlobalVariable.ReplaceWorkspaceMacro(Options.outputDir)
if not os.path.isabs (OutputDirFromCommandLine): if not os.path.isabs (OutputDirFromCommandLine):
OutputDirFromCommandLine = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, OutputDirFromCommandLine) OutputDirFromCommandLine = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, OutputDirFromCommandLine)
@ -274,27 +271,27 @@ def main():
GenFdsGlobalVariable.OutputDirDict[Key] = OutputDir GenFdsGlobalVariable.OutputDirDict[Key] = OutputDir
""" Parse Fdf file, has to place after build Workspace as FDF may contain macros from DSC file """ """ Parse Fdf file, has to place after build Workspace as FDF may contain macros from DSC file """
FdfParserObj = FdfParser.FdfParser(FdfFilename) FdfParserObj = FdfParser(FdfFilename)
FdfParserObj.ParseFile() FdfParserObj.ParseFile()
if FdfParserObj.CycleReferenceCheck(): if FdfParserObj.CycleReferenceCheck():
EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Cycle Reference Detected in FDF file") EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Cycle Reference Detected in FDF file")
if (Options.uiFdName) : if Options.uiFdName:
if Options.uiFdName.upper() in FdfParserObj.Profile.FdDict: if Options.uiFdName.upper() in FdfParserObj.Profile.FdDict:
GenFds.OnlyGenerateThisFd = Options.uiFdName GenFds.OnlyGenerateThisFd = Options.uiFdName
else: else:
EdkLogger.error("GenFds", OPTION_VALUE_INVALID, EdkLogger.error("GenFds", OPTION_VALUE_INVALID,
"No such an FD in FDF file: %s" % Options.uiFdName) "No such an FD in FDF file: %s" % Options.uiFdName)
if (Options.uiFvName) : if Options.uiFvName:
if Options.uiFvName.upper() in FdfParserObj.Profile.FvDict: if Options.uiFvName.upper() in FdfParserObj.Profile.FvDict:
GenFds.OnlyGenerateThisFv = Options.uiFvName GenFds.OnlyGenerateThisFv = Options.uiFvName
else: else:
EdkLogger.error("GenFds", OPTION_VALUE_INVALID, EdkLogger.error("GenFds", OPTION_VALUE_INVALID,
"No such an FV in FDF file: %s" % Options.uiFvName) "No such an FV in FDF file: %s" % Options.uiFvName)
if (Options.uiCapName) : if Options.uiCapName:
if Options.uiCapName.upper() in FdfParserObj.Profile.CapsuleDict: if Options.uiCapName.upper() in FdfParserObj.Profile.CapsuleDict:
GenFds.OnlyGenerateThisCap = Options.uiCapName GenFds.OnlyGenerateThisCap = Options.uiCapName
else: else:
@ -302,7 +299,7 @@ def main():
"No such a Capsule in FDF file: %s" % Options.uiCapName) "No such a Capsule in FDF file: %s" % Options.uiCapName)
GenFdsGlobalVariable.WorkSpace = BuildWorkSpace GenFdsGlobalVariable.WorkSpace = BuildWorkSpace
if ArchList is not None: if ArchList:
GenFdsGlobalVariable.ArchList = ArchList GenFdsGlobalVariable.ArchList = ArchList
# Dsc Build Data will handle Pcd Settings from CommandLine. # Dsc Build Data will handle Pcd Settings from CommandLine.
@ -313,10 +310,8 @@ def main():
# Record the FV Region info that may specific in the FD # Record the FV Region info that may specific in the FD
if FdfParserObj.Profile.FvDict and FdfParserObj.Profile.FdDict: if FdfParserObj.Profile.FvDict and FdfParserObj.Profile.FdDict:
for Fv in FdfParserObj.Profile.FvDict: for FvObj in FdfParserObj.Profile.FvDict.values():
FvObj = FdfParserObj.Profile.FvDict[Fv] for FdObj in FdfParserObj.Profile.FdDict.values():
for Fd in FdfParserObj.Profile.FdDict:
FdObj = FdfParserObj.Profile.FdDict[Fd]
for RegionObj in FdObj.RegionList: for RegionObj in FdObj.RegionList:
if RegionObj.RegionType != BINARY_FILE_TYPE_FV: if RegionObj.RegionType != BINARY_FILE_TYPE_FV:
continue continue
@ -338,7 +333,7 @@ def main():
"""Display FV space info.""" """Display FV space info."""
GenFds.DisplayFvSpaceInfo(FdfParserObj) GenFds.DisplayFvSpaceInfo(FdfParserObj)
except FdfParser.Warning as X: except Warning as X:
EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError=False) EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError=False)
ReturnCode = FORMAT_INVALID ReturnCode = FORMAT_INVALID
except FatalError as X: except FatalError as X:
@ -374,7 +369,6 @@ def SingleCheckCallback(option, opt_str, value, parser):
# Using standard Python module optparse to parse command line option of this tool. # Using standard Python module optparse to parse command line option of this tool.
# #
# @retval Opt A optparse.Values object containing the parsed options # @retval Opt A optparse.Values object containing the parsed options
# @retval Args Target of build command
# #
def myOptionParser(): def myOptionParser():
usage = "%prog [options] -f input_file -a arch_list -b build_target -p active_platform -t tool_chain_tag -D \"MacroName [= MacroValue]\"" usage = "%prog [options] -f input_file -a arch_list -b build_target -p active_platform -t tool_chain_tag -D \"MacroName [= MacroValue]\""
@ -404,7 +398,7 @@ def myOptionParser():
Parser.add_option("--pcd", action="append", dest="OptionPcd", help="Set PCD value by command line. Format: \"PcdName=Value\" ") Parser.add_option("--pcd", action="append", dest="OptionPcd", help="Set PCD value by command line. Format: \"PcdName=Value\" ")
Parser.add_option("--genfds-multi-thread", action="store_true", dest="GenfdsMultiThread", default=False, help="Enable GenFds multi thread to generate ffs file.") Parser.add_option("--genfds-multi-thread", action="store_true", dest="GenfdsMultiThread", default=False, help="Enable GenFds multi thread to generate ffs file.")
(Options, args) = Parser.parse_args() Options, _ = Parser.parse_args()
return Options return Options
## The class implementing the EDK2 flash image generation process ## The class implementing the EDK2 flash image generation process
@ -414,7 +408,7 @@ def myOptionParser():
# 2. Call methods of Fd class to generate FD # 2. Call methods of Fd class to generate FD
# 3. Call methods of Fv class to generate FV that not belong to FD # 3. Call methods of Fv class to generate FV that not belong to FD
# #
class GenFds : class GenFds(object):
FdfParsef = None FdfParsef = None
OnlyGenerateThisFd = None OnlyGenerateThisFd = None
OnlyGenerateThisFv = None OnlyGenerateThisFv = None
@ -423,12 +417,13 @@ class GenFds :
## GenFd() ## GenFd()
# #
# @param OutputDir Output directory # @param OutputDir Output directory
# @param FdfParser FDF contents parser # @param FdfParserObject FDF contents parser
# @param Workspace The directory of workspace # @param Workspace The directory of workspace
# @param ArchList The Arch list of platform # @param ArchList The Arch list of platform
# #
def GenFd (OutputDir, FdfParser, WorkSpace, ArchList): @staticmethod
GenFdsGlobalVariable.SetDir ('', FdfParser, WorkSpace, ArchList) def GenFd (OutputDir, FdfParserObject, WorkSpace, ArchList):
GenFdsGlobalVariable.SetDir ('', FdfParserObject, WorkSpace, ArchList)
GenFdsGlobalVariable.VerboseLogger(" Generate all Fd images and their required FV and Capsule images!") GenFdsGlobalVariable.VerboseLogger(" Generate all Fd images and their required FV and Capsule images!")
if GenFds.OnlyGenerateThisCap is not None and GenFds.OnlyGenerateThisCap.upper() in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict: if GenFds.OnlyGenerateThisCap is not None and GenFds.OnlyGenerateThisCap.upper() in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict:
@ -470,9 +465,10 @@ class GenFds :
GenFdsGlobalVariable.VerboseLogger("\n Generate all Option ROM!") GenFdsGlobalVariable.VerboseLogger("\n Generate all Option ROM!")
for OptRomObj in GenFdsGlobalVariable.FdfParser.Profile.OptRomDict.values(): for OptRomObj in GenFdsGlobalVariable.FdfParser.Profile.OptRomDict.values():
OptRomObj.AddToBuffer(None) OptRomObj.AddToBuffer(None)
@staticmethod @staticmethod
def GenFfsMakefile(OutputDir, FdfParser, WorkSpace, ArchList, GlobalData): def GenFfsMakefile(OutputDir, FdfParserObject, WorkSpace, ArchList, GlobalData):
GenFdsGlobalVariable.SetEnv(FdfParser, WorkSpace, ArchList, GlobalData) GenFdsGlobalVariable.SetEnv(FdfParserObject, WorkSpace, ArchList, GlobalData)
for FdObj in GenFdsGlobalVariable.FdfParser.Profile.FdDict.values(): for FdObj in GenFdsGlobalVariable.FdfParser.Profile.FdDict.values():
FdObj.GenFd(Flag=True) FdObj.GenFd(Flag=True)
@ -490,6 +486,7 @@ class GenFds :
# @param FvObj Whose block size to get # @param FvObj Whose block size to get
# @retval int Block size value # @retval int Block size value
# #
@staticmethod
def GetFvBlockSize(FvObj): def GetFvBlockSize(FvObj):
DefaultBlockSize = 0x1 DefaultBlockSize = 0x1
FdObj = None FdObj = None
@ -524,16 +521,17 @@ class GenFds :
# @param FvObj Whose block size to get # @param FvObj Whose block size to get
# @retval None # @retval None
# #
def DisplayFvSpaceInfo(FdfParser): @staticmethod
def DisplayFvSpaceInfo(FdfParserObject):
FvSpaceInfoList = [] FvSpaceInfoList = []
MaxFvNameLength = 0 MaxFvNameLength = 0
for FvName in FdfParser.Profile.FvDict: for FvName in FdfParserObject.Profile.FvDict:
if len(FvName) > MaxFvNameLength: if len(FvName) > MaxFvNameLength:
MaxFvNameLength = len(FvName) MaxFvNameLength = len(FvName)
FvSpaceInfoFileName = os.path.join(GenFdsGlobalVariable.FvDir, FvName.upper() + '.Fv.map') FvSpaceInfoFileName = os.path.join(GenFdsGlobalVariable.FvDir, FvName.upper() + '.Fv.map')
if os.path.exists(FvSpaceInfoFileName): if os.path.exists(FvSpaceInfoFileName):
FileLinesList = linecache.getlines(FvSpaceInfoFileName) FileLinesList = getlines(FvSpaceInfoFileName)
TotalFound = False TotalFound = False
Total = '' Total = ''
UsedFound = False UsedFound = False
@ -575,6 +573,7 @@ class GenFds :
# @param DscFile modules from dsc file will be preprocessed # @param DscFile modules from dsc file will be preprocessed
# @retval None # @retval None
# #
@staticmethod
def PreprocessImage(BuildDb, DscFile): def PreprocessImage(BuildDb, DscFile):
PcdDict = BuildDb.BuildObject[DscFile, TAB_COMMON, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Pcds PcdDict = BuildDb.BuildObject[DscFile, TAB_COMMON, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Pcds
PcdValue = '' PcdValue = ''
@ -600,6 +599,7 @@ class GenFds :
ModuleObj = BuildDb.BuildObject[Key, TAB_COMMON, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] ModuleObj = BuildDb.BuildObject[Key, TAB_COMMON, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
print(ModuleObj.BaseName + ' ' + ModuleObj.ModuleType) print(ModuleObj.BaseName + ' ' + ModuleObj.ModuleType)
@staticmethod
def GenerateGuidXRefFile(BuildDb, ArchList, FdfParserObj): def GenerateGuidXRefFile(BuildDb, ArchList, FdfParserObj):
GuidXRefFileName = os.path.join(GenFdsGlobalVariable.FvDir, "Guid.xref") GuidXRefFileName = os.path.join(GenFdsGlobalVariable.FvDir, "Guid.xref")
GuidXRefFile = BytesIO('') GuidXRefFile = BytesIO('')
@ -607,7 +607,6 @@ class GenFds :
GuidDict = {} GuidDict = {}
ModuleList = [] ModuleList = []
FileGuidList = [] FileGuidList = []
GuidPattern = gGuidPattern
for Arch in ArchList: for Arch in ArchList:
PlatformDataBase = BuildDb.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] PlatformDataBase = BuildDb.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
PkgList = GenFdsGlobalVariable.WorkSpace.GetPackageList(GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag) PkgList = GenFdsGlobalVariable.WorkSpace.GetPackageList(GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag)
@ -626,20 +625,16 @@ class GenFds :
continue continue
else: else:
ModuleList.append(Module) ModuleList.append(Module)
GuidMatch = GuidPattern.match(ModuleFile.BaseName) if GlobalData.gGuidPattern.match(ModuleFile.BaseName):
if GuidMatch is not None:
GuidXRefFile.write("%s %s\n" % (ModuleFile.BaseName, Module.BaseName)) GuidXRefFile.write("%s %s\n" % (ModuleFile.BaseName, Module.BaseName))
else: else:
GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName)) GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName))
for key, item in Module.Protocols.items(): GuidDict.update(Module.Protocols)
GuidDict[key] = item GuidDict.update(Module.Guids)
for key, item in Module.Guids.items(): GuidDict.update(Module.Ppis)
GuidDict[key] = item
for key, item in Module.Ppis.items():
GuidDict[key] = item
for FvName in FdfParserObj.Profile.FvDict: for FvName in FdfParserObj.Profile.FvDict:
for FfsObj in FdfParserObj.Profile.FvDict[FvName].FfsList: for FfsObj in FdfParserObj.Profile.FvDict[FvName].FfsList:
if not isinstance(FfsObj, FfsFileStatement.FileStatement): if not isinstance(FfsObj, FileStatement):
InfPath = PathClass(NormPath(mws.join(GenFdsGlobalVariable.WorkSpaceDir, FfsObj.InfFileName))) InfPath = PathClass(NormPath(mws.join(GenFdsGlobalVariable.WorkSpaceDir, FfsObj.InfFileName)))
FdfModule = BuildDb.BuildObject[InfPath, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] FdfModule = BuildDb.BuildObject[InfPath, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
if FdfModule in ModuleList: if FdfModule in ModuleList:
@ -647,12 +642,9 @@ class GenFds :
else: else:
ModuleList.append(FdfModule) ModuleList.append(FdfModule)
GuidXRefFile.write("%s %s\n" % (FdfModule.Guid, FdfModule.BaseName)) GuidXRefFile.write("%s %s\n" % (FdfModule.Guid, FdfModule.BaseName))
for key, item in FdfModule.Protocols.items(): GuidDict.update(FdfModule.Protocols)
GuidDict[key] = item GuidDict.update(FdfModule.Guids)
for key, item in FdfModule.Guids.items(): GuidDict.update(FdfModule.Ppis)
GuidDict[key] = item
for key, item in FdfModule.Ppis.items():
GuidDict[key] = item
else: else:
FileStatementGuid = FfsObj.NameGuid FileStatementGuid = FfsObj.NameGuid
if FileStatementGuid in FileGuidList: if FileStatementGuid in FileGuidList:
@ -661,13 +653,13 @@ class GenFds :
FileGuidList.append(FileStatementGuid) FileGuidList.append(FileStatementGuid)
Name = [] Name = []
FfsPath = os.path.join(GenFdsGlobalVariable.FvDir, 'Ffs') FfsPath = os.path.join(GenFdsGlobalVariable.FvDir, 'Ffs')
FfsPath = glob.glob(os.path.join(FfsPath, FileStatementGuid) + '*') FfsPath = glob(os.path.join(FfsPath, FileStatementGuid) + '*')
if not FfsPath: if not FfsPath:
continue continue
if not os.path.exists(FfsPath[0]): if not os.path.exists(FfsPath[0]):
continue continue
MatchDict = {} MatchDict = {}
ReFileEnds = re.compile('\S+(.ui)$|\S+(fv.sec.txt)$|\S+(.pe32.txt)$|\S+(.te.txt)$|\S+(.pic.txt)$|\S+(.raw.txt)$|\S+(.ffs.txt)$') ReFileEnds = compile('\S+(.ui)$|\S+(fv.sec.txt)$|\S+(.pe32.txt)$|\S+(.te.txt)$|\S+(.pic.txt)$|\S+(.raw.txt)$|\S+(.ffs.txt)$')
FileList = os.listdir(FfsPath[0]) FileList = os.listdir(FfsPath[0])
for File in FileList: for File in FileList:
Match = ReFileEnds.search(File) Match = ReFileEnds.search(File)
@ -724,16 +716,10 @@ class GenFds :
os.remove(GuidXRefFileName) os.remove(GuidXRefFileName)
GuidXRefFile.close() GuidXRefFile.close()
##Define GenFd as static function
GenFd = staticmethod(GenFd)
GetFvBlockSize = staticmethod(GetFvBlockSize)
DisplayFvSpaceInfo = staticmethod(DisplayFvSpaceInfo)
PreprocessImage = staticmethod(PreprocessImage)
GenerateGuidXRefFile = staticmethod(GenerateGuidXRefFile)
if __name__ == '__main__': if __name__ == '__main__':
r = main() r = main()
## 0-127 is a safe return range, and 1 is a standard default error ## 0-127 is a safe return range, and 1 is a standard default error
if r < 0 or r > 127: r = 1 if r < 0 or r > 127:
sys.exit(r) r = 1
exit(r)

View File

@ -16,13 +16,15 @@
# Import Modules # Import Modules
# #
from __future__ import print_function from __future__ import print_function
import Common.LongFilePathOs as os from __future__ import absolute_import
import sys
import subprocess
import struct
import array
from Common.BuildToolError import * import Common.LongFilePathOs as os
from sys import stdout
from subprocess import PIPE,Popen
from struct import Struct
from array import array
from Common.BuildToolError import COMMAND_FAILURE,GENFDS_ERROR
from Common import EdkLogger from Common import EdkLogger
from Common.Misc import SaveFileOnChange from Common.Misc import SaveFileOnChange
@ -89,7 +91,7 @@ class GenFdsGlobalVariable:
EFI_FIRMWARE_FILE_SYSTEM3_GUID = '5473C07A-3DCB-4dca-BD6F-1E9689E7349A' EFI_FIRMWARE_FILE_SYSTEM3_GUID = '5473C07A-3DCB-4dca-BD6F-1E9689E7349A'
LARGE_FILE_SIZE = 0x1000000 LARGE_FILE_SIZE = 0x1000000
SectionHeader = struct.Struct("3B 1B") SectionHeader = Struct("3B 1B")
# FvName, FdName, CapName in FDF, Image file name # FvName, FdName, CapName in FDF, Image file name
ImageBinDict = {} ImageBinDict = {}
@ -97,7 +99,7 @@ class GenFdsGlobalVariable:
## LoadBuildRule ## LoadBuildRule
# #
@staticmethod @staticmethod
def __LoadBuildRule(): def _LoadBuildRule():
if GenFdsGlobalVariable.__BuildRuleDatabase: if GenFdsGlobalVariable.__BuildRuleDatabase:
return GenFdsGlobalVariable.__BuildRuleDatabase return GenFdsGlobalVariable.__BuildRuleDatabase
BuildConfigurationFile = os.path.normpath(os.path.join(GenFdsGlobalVariable.ConfDir, "target.txt")) BuildConfigurationFile = os.path.normpath(os.path.join(GenFdsGlobalVariable.ConfDir, "target.txt"))
@ -139,43 +141,42 @@ class GenFdsGlobalVariable:
if not Arch in GenFdsGlobalVariable.OutputDirDict: if not Arch in GenFdsGlobalVariable.OutputDirDict:
return {} return {}
BuildRuleDatabase = GenFdsGlobalVariable.__LoadBuildRule() BuildRuleDatabase = GenFdsGlobalVariable._LoadBuildRule()
if not BuildRuleDatabase: if not BuildRuleDatabase:
return {} return {}
PathClassObj = PathClass(Inf.MetaFile.File, PathClassObj = PathClass(Inf.MetaFile.File,
GenFdsGlobalVariable.WorkSpaceDir) GenFdsGlobalVariable.WorkSpaceDir)
Macro = {}
Macro["WORKSPACE" ] = GenFdsGlobalVariable.WorkSpaceDir
Macro["MODULE_NAME" ] = Inf.BaseName
Macro["MODULE_GUID" ] = Inf.Guid
Macro["MODULE_VERSION" ] = Inf.Version
Macro["MODULE_TYPE" ] = Inf.ModuleType
Macro["MODULE_FILE" ] = str(PathClassObj)
Macro["MODULE_FILE_BASE_NAME" ] = PathClassObj.BaseName
Macro["MODULE_RELATIVE_DIR" ] = PathClassObj.SubDir
Macro["MODULE_DIR" ] = PathClassObj.SubDir
Macro["BASE_NAME" ] = Inf.BaseName
Macro["ARCH" ] = Arch
Macro["TOOLCHAIN" ] = GenFdsGlobalVariable.ToolChainTag
Macro["TOOLCHAIN_TAG" ] = GenFdsGlobalVariable.ToolChainTag
Macro["TOOL_CHAIN_TAG" ] = GenFdsGlobalVariable.ToolChainTag
Macro["TARGET" ] = GenFdsGlobalVariable.TargetName
Macro["BUILD_DIR" ] = GenFdsGlobalVariable.OutputDirDict[Arch]
Macro["BIN_DIR" ] = os.path.join(GenFdsGlobalVariable.OutputDirDict[Arch], Arch)
Macro["LIB_DIR" ] = os.path.join(GenFdsGlobalVariable.OutputDirDict[Arch], Arch)
BuildDir = os.path.join( BuildDir = os.path.join(
GenFdsGlobalVariable.OutputDirDict[Arch], GenFdsGlobalVariable.OutputDirDict[Arch],
Arch, Arch,
PathClassObj.SubDir, PathClassObj.SubDir,
PathClassObj.BaseName PathClassObj.BaseName
) )
Macro["MODULE_BUILD_DIR" ] = BuildDir BinDir = os.path.join(GenFdsGlobalVariable.OutputDirDict[Arch], Arch)
Macro["OUTPUT_DIR" ] = os.path.join(BuildDir, "OUTPUT") Macro = {
Macro["DEBUG_DIR" ] = os.path.join(BuildDir, "DEBUG") "WORKSPACE":GenFdsGlobalVariable.WorkSpaceDir,
"MODULE_NAME":Inf.BaseName,
"MODULE_GUID":Inf.Guid,
"MODULE_VERSION":Inf.Version,
"MODULE_TYPE":Inf.ModuleType,
"MODULE_FILE":str(PathClassObj),
"MODULE_FILE_BASE_NAME":PathClassObj.BaseName,
"MODULE_RELATIVE_DIR":PathClassObj.SubDir,
"MODULE_DIR":PathClassObj.SubDir,
"BASE_NAME":Inf.BaseName,
"ARCH":Arch,
"TOOLCHAIN":GenFdsGlobalVariable.ToolChainTag,
"TOOLCHAIN_TAG":GenFdsGlobalVariable.ToolChainTag,
"TOOL_CHAIN_TAG":GenFdsGlobalVariable.ToolChainTag,
"TARGET":GenFdsGlobalVariable.TargetName,
"BUILD_DIR":GenFdsGlobalVariable.OutputDirDict[Arch],
"BIN_DIR":BinDir,
"LIB_DIR":BinDir,
"MODULE_BUILD_DIR":BuildDir,
"OUTPUT_DIR":os.path.join(BuildDir, "OUTPUT"),
"DEBUG_DIR":os.path.join(BuildDir, "DEBUG")
}
BuildRules = {} BuildRules = {}
for Type in BuildRuleDatabase.FileTypeList: for Type in BuildRuleDatabase.FileTypeList:
@ -216,12 +217,12 @@ class GenFdsGlobalVariable:
if not Inf.IsBinaryModule: if not Inf.IsBinaryModule:
for File in Inf.Sources: for File in Inf.Sources:
if File.TagName in ("", "*", GenFdsGlobalVariable.ToolChainTag) and \ if File.TagName in {"", "*", GenFdsGlobalVariable.ToolChainTag} and \
File.ToolChainFamily in ("", "*", GenFdsGlobalVariable.ToolChainFamily): File.ToolChainFamily in {"", "*", GenFdsGlobalVariable.ToolChainFamily}:
FileList.append((File, DataType.TAB_UNKNOWN_FILE)) FileList.append((File, DataType.TAB_UNKNOWN_FILE))
for File in Inf.Binaries: for File in Inf.Binaries:
if File.Target in [DataType.TAB_COMMON, '*', GenFdsGlobalVariable.TargetName]: if File.Target in {DataType.TAB_COMMON, '*', GenFdsGlobalVariable.TargetName}:
FileList.append((File, File.Type)) FileList.append((File, File.Type))
for File, FileType in FileList: for File, FileType in FileList:
@ -233,7 +234,7 @@ class GenFdsGlobalVariable:
Source = SourceList[Index] Source = SourceList[Index]
Index = Index + 1 Index = Index + 1
if File.IsBinary and File == Source and Inf.Binaries is not None and File in Inf.Binaries: if File.IsBinary and File == Source and Inf.Binaries and File in Inf.Binaries:
# Skip all files that are not binary libraries # Skip all files that are not binary libraries
if not Inf.LibraryClass: if not Inf.LibraryClass:
continue continue
@ -287,19 +288,18 @@ class GenFdsGlobalVariable:
# @param Workspace The directory of workspace # @param Workspace The directory of workspace
# @param ArchList The Arch list of platform # @param ArchList The Arch list of platform
# #
@staticmethod
def SetDir (OutputDir, FdfParser, WorkSpace, ArchList): def SetDir (OutputDir, FdfParser, WorkSpace, ArchList):
GenFdsGlobalVariable.VerboseLogger("GenFdsGlobalVariable.OutputDir :%s" % OutputDir) GenFdsGlobalVariable.VerboseLogger("GenFdsGlobalVariable.OutputDir:%s" % OutputDir)
# GenFdsGlobalVariable.OutputDirDict = OutputDir
GenFdsGlobalVariable.FdfParser = FdfParser GenFdsGlobalVariable.FdfParser = FdfParser
GenFdsGlobalVariable.WorkSpace = WorkSpace GenFdsGlobalVariable.WorkSpace = WorkSpace
GenFdsGlobalVariable.FvDir = os.path.join(GenFdsGlobalVariable.OutputDirDict[ArchList[0]], DataType.TAB_FV_DIRECTORY) GenFdsGlobalVariable.FvDir = os.path.join(GenFdsGlobalVariable.OutputDirDict[ArchList[0]], DataType.TAB_FV_DIRECTORY)
if not os.path.exists(GenFdsGlobalVariable.FvDir) : if not os.path.exists(GenFdsGlobalVariable.FvDir):
os.makedirs(GenFdsGlobalVariable.FvDir) os.makedirs(GenFdsGlobalVariable.FvDir)
GenFdsGlobalVariable.FfsDir = os.path.join(GenFdsGlobalVariable.FvDir, 'Ffs') GenFdsGlobalVariable.FfsDir = os.path.join(GenFdsGlobalVariable.FvDir, 'Ffs')
if not os.path.exists(GenFdsGlobalVariable.FfsDir) : if not os.path.exists(GenFdsGlobalVariable.FfsDir):
os.makedirs(GenFdsGlobalVariable.FfsDir) os.makedirs(GenFdsGlobalVariable.FfsDir)
T_CHAR_LF = '\n'
# #
# Create FV Address inf file # Create FV Address inf file
# #
@ -308,7 +308,7 @@ class GenFdsGlobalVariable:
# #
# Add [Options] # Add [Options]
# #
FvAddressFile.writelines("[options]" + T_CHAR_LF) FvAddressFile.writelines("[options]" + DataType.TAB_LINE_BREAK)
BsAddress = '0' BsAddress = '0'
for Arch in ArchList: for Arch in ArchList:
if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].BsBaseAddress: if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].BsBaseAddress:
@ -317,19 +317,22 @@ class GenFdsGlobalVariable:
FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS = " + \ FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS = " + \
BsAddress + \ BsAddress + \
T_CHAR_LF) DataType.TAB_LINE_BREAK)
RtAddress = '0' RtAddress = '0'
for Arch in ArchList: for Arch in reversed(ArchList):
if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].RtBaseAddress: temp = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].RtBaseAddress
RtAddress = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].RtBaseAddress if temp:
RtAddress = temp
break
FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS = " + \ FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS = " + \
RtAddress + \ RtAddress + \
T_CHAR_LF) DataType.TAB_LINE_BREAK)
FvAddressFile.close() FvAddressFile.close()
@staticmethod
def SetEnv(FdfParser, WorkSpace, ArchList, GlobalData): def SetEnv(FdfParser, WorkSpace, ArchList, GlobalData):
GenFdsGlobalVariable.ModuleFile = WorkSpace.ModuleFile GenFdsGlobalVariable.ModuleFile = WorkSpace.ModuleFile
GenFdsGlobalVariable.FdfParser = FdfParser GenFdsGlobalVariable.FdfParser = FdfParser
@ -360,7 +363,6 @@ class GenFdsGlobalVariable:
if not os.path.exists(GenFdsGlobalVariable.FfsDir): if not os.path.exists(GenFdsGlobalVariable.FfsDir):
os.makedirs(GenFdsGlobalVariable.FfsDir) os.makedirs(GenFdsGlobalVariable.FfsDir)
T_CHAR_LF = '\n'
# #
# Create FV Address inf file # Create FV Address inf file
# #
@ -369,7 +371,7 @@ class GenFdsGlobalVariable:
# #
# Add [Options] # Add [Options]
# #
FvAddressFile.writelines("[options]" + T_CHAR_LF) FvAddressFile.writelines("[options]" + DataType.TAB_LINE_BREAK)
BsAddress = '0' BsAddress = '0'
for Arch in ArchList: for Arch in ArchList:
BsAddress = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, BsAddress = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch,
@ -380,20 +382,20 @@ class GenFdsGlobalVariable:
FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS = " + \ FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS = " + \
BsAddress + \ BsAddress + \
T_CHAR_LF) DataType.TAB_LINE_BREAK)
RtAddress = '0' RtAddress = '0'
for Arch in ArchList: for Arch in reversed(ArchList):
if GenFdsGlobalVariable.WorkSpace.BuildObject[ temp = GenFdsGlobalVariable.WorkSpace.BuildObject[
GenFdsGlobalVariable.ActivePlatform, Arch, GlobalData.gGlobalDefines['TARGET'], GenFdsGlobalVariable.ActivePlatform, Arch, GlobalData.gGlobalDefines['TARGET'],
GlobalData.gGlobalDefines["TOOL_CHAIN_TAG"]].RtBaseAddress: GlobalData.gGlobalDefines["TOOL_CHAIN_TAG"]].RtBaseAddress
RtAddress = GenFdsGlobalVariable.WorkSpace.BuildObject[ if temp:
GenFdsGlobalVariable.ActivePlatform, Arch, GlobalData.gGlobalDefines['TARGET'], RtAddress = temp
GlobalData.gGlobalDefines["TOOL_CHAIN_TAG"]].RtBaseAddress break
FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS = " + \ FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS = " + \
RtAddress + \ RtAddress + \
T_CHAR_LF) DataType.TAB_LINE_BREAK)
FvAddressFile.close() FvAddressFile.close()
@ -401,6 +403,7 @@ class GenFdsGlobalVariable:
# #
# @param String String that may contain macro # @param String String that may contain macro
# #
@staticmethod
def ReplaceWorkspaceMacro(String): def ReplaceWorkspaceMacro(String):
String = mws.handleWsMacro(String) String = mws.handleWsMacro(String)
Str = String.replace('$(WORKSPACE)', GenFdsGlobalVariable.WorkSpaceDir) Str = String.replace('$(WORKSPACE)', GenFdsGlobalVariable.WorkSpaceDir)
@ -424,7 +427,7 @@ class GenFdsGlobalVariable:
if not os.path.exists(Output): if not os.path.exists(Output):
return True return True
# always update "Output" if no "Input" given # always update "Output" if no "Input" given
if Input is None or len(Input) == 0: if not Input:
return True return True
# if fdf file is changed after the 'Output" is generated, update the 'Output' # if fdf file is changed after the 'Output" is generated, update the 'Output'
@ -449,9 +452,9 @@ class GenFdsGlobalVariable:
Cmd += ("-s", Type) Cmd += ("-s", Type)
if CompressionType: if CompressionType:
Cmd += ("-c", CompressionType) Cmd += ("-c", CompressionType)
if Guid is not None: if Guid:
Cmd += ("-g", Guid) Cmd += ("-g", Guid)
if DummyFile is not None: if DummyFile:
Cmd += ("--dummy", DummyFile) Cmd += ("--dummy", DummyFile)
if GuidHdrLen: if GuidHdrLen:
Cmd += ("-l", GuidHdrLen) Cmd += ("-l", GuidHdrLen)
@ -473,7 +476,7 @@ class GenFdsGlobalVariable:
if ' '.join(Cmd).strip() not in GenFdsGlobalVariable.SecCmdList: if ' '.join(Cmd).strip() not in GenFdsGlobalVariable.SecCmdList:
GenFdsGlobalVariable.SecCmdList.append(' '.join(Cmd).strip()) GenFdsGlobalVariable.SecCmdList.append(' '.join(Cmd).strip())
else: else:
SectionData = array.array('B', [0, 0, 0, 0]) SectionData = array('B', [0, 0, 0, 0])
SectionData.fromstring(Ui.encode("utf_16_le")) SectionData.fromstring(Ui.encode("utf_16_le"))
SectionData.append(0) SectionData.append(0)
SectionData.append(0) SectionData.append(0)
@ -571,9 +574,9 @@ class GenFdsGlobalVariable:
if BaseAddress: if BaseAddress:
Cmd += ("-r", BaseAddress) Cmd += ("-r", BaseAddress)
if ForceRebase == False: if not ForceRebase:
Cmd += ("-F", "FALSE") Cmd += ("-F", "FALSE")
elif ForceRebase == True: else:
Cmd += ("-F", "TRUE") Cmd += ("-F", "TRUE")
if Capsule: if Capsule:
@ -634,7 +637,7 @@ class GenFdsGlobalVariable:
Revision=None, DeviceId=None, VendorId=None, IsMakefile=False): Revision=None, DeviceId=None, VendorId=None, IsMakefile=False):
InputList = [] InputList = []
Cmd = ["EfiRom"] Cmd = ["EfiRom"]
if len(EfiInput) > 0: if EfiInput:
if Compress: if Compress:
Cmd.append("-ec") Cmd.append("-ec")
@ -645,7 +648,7 @@ class GenFdsGlobalVariable:
Cmd.append(EfiFile) Cmd.append(EfiFile)
InputList.append (EfiFile) InputList.append (EfiFile)
if len(BinaryInput) > 0: if BinaryInput:
Cmd.append("-b") Cmd.append("-b")
for BinFile in BinaryInput: for BinFile in BinaryInput:
Cmd.append(BinFile) Cmd.append(BinFile)
@ -656,13 +659,13 @@ class GenFdsGlobalVariable:
return return
GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, InputList)) GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, InputList))
if ClassCode is not None: if ClassCode:
Cmd += ("-l", ClassCode) Cmd += ("-l", ClassCode)
if Revision is not None: if Revision:
Cmd += ("-r", Revision) Cmd += ("-r", Revision)
if DeviceId is not None: if DeviceId:
Cmd += ("-i", DeviceId) Cmd += ("-i", DeviceId)
if VendorId is not None: if VendorId:
Cmd += ("-f", VendorId) Cmd += ("-f", VendorId)
Cmd += ("-o", Output) Cmd += ("-o", Output)
@ -688,6 +691,7 @@ class GenFdsGlobalVariable:
else: else:
GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to call " + ToolPath, returnValue) GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to call " + ToolPath, returnValue)
@staticmethod
def CallExternalTool (cmd, errorMess, returnValue=[]): def CallExternalTool (cmd, errorMess, returnValue=[]):
if type(cmd) not in (tuple, list): if type(cmd) not in (tuple, list):
@ -701,19 +705,19 @@ class GenFdsGlobalVariable:
cmd += ('-v',) cmd += ('-v',)
GenFdsGlobalVariable.InfLogger (cmd) GenFdsGlobalVariable.InfLogger (cmd)
else: else:
sys.stdout.write ('#') stdout.write ('#')
sys.stdout.flush() stdout.flush()
GenFdsGlobalVariable.SharpCounter = GenFdsGlobalVariable.SharpCounter + 1 GenFdsGlobalVariable.SharpCounter = GenFdsGlobalVariable.SharpCounter + 1
if GenFdsGlobalVariable.SharpCounter % GenFdsGlobalVariable.SharpNumberPerLine == 0: if GenFdsGlobalVariable.SharpCounter % GenFdsGlobalVariable.SharpNumberPerLine == 0:
sys.stdout.write('\n') stdout.write('\n')
try: try:
PopenObject = subprocess.Popen(' '.join(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) PopenObject = Popen(' '.join(cmd), stdout=PIPE, stderr=PIPE, shell=True)
except Exception as X: except Exception as X:
EdkLogger.error("GenFds", COMMAND_FAILURE, ExtraData="%s: %s" % (str(X), cmd[0])) EdkLogger.error("GenFds", COMMAND_FAILURE, ExtraData="%s: %s" % (str(X), cmd[0]))
(out, error) = PopenObject.communicate() (out, error) = PopenObject.communicate()
while PopenObject.returncode is None : while PopenObject.returncode is None:
PopenObject.wait() PopenObject.wait()
if returnValue != [] and returnValue[0] != 0: if returnValue != [] and returnValue[0] != 0:
#get command return value #get command return value
@ -727,45 +731,52 @@ class GenFdsGlobalVariable:
print("###", cmd) print("###", cmd)
EdkLogger.error("GenFds", COMMAND_FAILURE, errorMess) EdkLogger.error("GenFds", COMMAND_FAILURE, errorMess)
@staticmethod
def VerboseLogger (msg): def VerboseLogger (msg):
EdkLogger.verbose(msg) EdkLogger.verbose(msg)
@staticmethod
def InfLogger (msg): def InfLogger (msg):
EdkLogger.info(msg) EdkLogger.info(msg)
@staticmethod
def ErrorLogger (msg, File=None, Line=None, ExtraData=None): def ErrorLogger (msg, File=None, Line=None, ExtraData=None):
EdkLogger.error('GenFds', GENFDS_ERROR, msg, File, Line, ExtraData) EdkLogger.error('GenFds', GENFDS_ERROR, msg, File, Line, ExtraData)
@staticmethod
def DebugLogger (Level, msg): def DebugLogger (Level, msg):
EdkLogger.debug(Level, msg) EdkLogger.debug(Level, msg)
## ReplaceWorkspaceMacro() ## MacroExtend()
# #
# @param Str String that may contain macro # @param Str String that may contain macro
# @param MacroDict Dictionary that contains macro value pair # @param MacroDict Dictionary that contains macro value pair
# #
@staticmethod
def MacroExtend (Str, MacroDict={}, Arch=DataType.TAB_COMMON): def MacroExtend (Str, MacroDict={}, Arch=DataType.TAB_COMMON):
if Str is None : if Str is None:
return None return None
Dict = {'$(WORKSPACE)' : GenFdsGlobalVariable.WorkSpaceDir, Dict = {'$(WORKSPACE)': GenFdsGlobalVariable.WorkSpaceDir,
'$(EDK_SOURCE)' : GenFdsGlobalVariable.EdkSourceDir, '$(EDK_SOURCE)': GenFdsGlobalVariable.EdkSourceDir,
# '$(OUTPUT_DIRECTORY)': GenFdsGlobalVariable.OutputDirFromDsc, # '$(OUTPUT_DIRECTORY)': GenFdsGlobalVariable.OutputDirFromDsc,
'$(TARGET)' : GenFdsGlobalVariable.TargetName, '$(TARGET)': GenFdsGlobalVariable.TargetName,
'$(TOOL_CHAIN_TAG)' : GenFdsGlobalVariable.ToolChainTag, '$(TOOL_CHAIN_TAG)': GenFdsGlobalVariable.ToolChainTag,
'$(SPACE)' : ' ' '$(SPACE)': ' '
} }
OutputDir = GenFdsGlobalVariable.OutputDirFromDscDict[GenFdsGlobalVariable.ArchList[0]]
if Arch != DataType.TAB_COMMON and Arch in GenFdsGlobalVariable.ArchList: if Arch != DataType.TAB_COMMON and Arch in GenFdsGlobalVariable.ArchList:
OutputDir = GenFdsGlobalVariable.OutputDirFromDscDict[Arch] OutputDir = GenFdsGlobalVariable.OutputDirFromDscDict[Arch]
else:
OutputDir = GenFdsGlobalVariable.OutputDirFromDscDict[GenFdsGlobalVariable.ArchList[0]]
Dict['$(OUTPUT_DIRECTORY)'] = OutputDir Dict['$(OUTPUT_DIRECTORY)'] = OutputDir
if MacroDict is not None and len (MacroDict) != 0: if MacroDict:
Dict.update(MacroDict) Dict.update(MacroDict)
for key in Dict: for key in Dict:
if Str.find(key) >= 0 : if Str.find(key) >= 0:
Str = Str.replace (key, Dict[key]) Str = Str.replace (key, Dict[key])
if Str.find('$(ARCH)') >= 0: if Str.find('$(ARCH)') >= 0:
@ -780,14 +791,14 @@ class GenFdsGlobalVariable:
# #
# @param PcdPattern pattern that labels a PCD. # @param PcdPattern pattern that labels a PCD.
# #
@staticmethod
def GetPcdValue (PcdPattern): def GetPcdValue (PcdPattern):
if PcdPattern is None : if PcdPattern is None:
return None return None
PcdPair = PcdPattern.lstrip('PCD(').rstrip(')').strip().split('.') PcdPair = PcdPattern.lstrip('PCD(').rstrip(')').strip().split('.')
TokenSpace = PcdPair[0] TokenSpace = PcdPair[0]
TokenCName = PcdPair[1] TokenCName = PcdPair[1]
PcdValue = ''
for Arch in GenFdsGlobalVariable.ArchList: for Arch in GenFdsGlobalVariable.ArchList:
Platform = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] Platform = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
PcdDict = Platform.Pcds PcdDict = Platform.Pcds
@ -799,8 +810,7 @@ class GenFdsGlobalVariable:
if PcdObj.DatumType != DataType.TAB_VOID: if PcdObj.DatumType != DataType.TAB_VOID:
EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not VOID* datum type." % PcdPattern) EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not VOID* datum type." % PcdPattern)
PcdValue = PcdObj.DefaultValue return PcdObj.DefaultValue
return PcdValue
for Package in GenFdsGlobalVariable.WorkSpace.GetPackageList(GenFdsGlobalVariable.ActivePlatform, for Package in GenFdsGlobalVariable.WorkSpace.GetPackageList(GenFdsGlobalVariable.ActivePlatform,
Arch, Arch,
@ -815,21 +825,9 @@ class GenFdsGlobalVariable:
if PcdObj.DatumType != DataType.TAB_VOID: if PcdObj.DatumType != DataType.TAB_VOID:
EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not VOID* datum type." % PcdPattern) EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not VOID* datum type." % PcdPattern)
PcdValue = PcdObj.DefaultValue return PcdObj.DefaultValue
return PcdValue
return PcdValue return ''
SetDir = staticmethod(SetDir)
SetEnv = staticmethod(SetEnv)
ReplaceWorkspaceMacro = staticmethod(ReplaceWorkspaceMacro)
CallExternalTool = staticmethod(CallExternalTool)
VerboseLogger = staticmethod(VerboseLogger)
InfLogger = staticmethod(InfLogger)
ErrorLogger = staticmethod(ErrorLogger)
DebugLogger = staticmethod(DebugLogger)
MacroExtend = staticmethod (MacroExtend)
GetPcdValue = staticmethod(GetPcdValue)
## FindExtendTool() ## FindExtendTool()
# #
@ -863,7 +861,7 @@ def FindExtendTool(KeyStringList, CurrentArchList, NameGuid):
ToolOptionKey = None ToolOptionKey = None
KeyList = None KeyList = None
for ToolDef in ToolDefinition.items(): for ToolDef in ToolDefinition.items():
if NameGuid.lower() == ToolDef[1].lower() : if NameGuid.lower() == ToolDef[1].lower():
KeyList = ToolDef[0].split('_') KeyList = ToolDef[0].split('_')
Key = KeyList[0] + \ Key = KeyList[0] + \
'_' + \ '_' + \

View File

@ -19,7 +19,7 @@
from __future__ import absolute_import from __future__ import absolute_import
from . import Section from . import Section
import subprocess import subprocess
from .Ffs import Ffs from .Ffs import SectionSuffix
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
from .GenFdsGlobalVariable import FindExtendTool from .GenFdsGlobalVariable import FindExtendTool
@ -126,7 +126,7 @@ class GuidSection(GuidSectionClassObject) :
ModuleName + \ ModuleName + \
SUP_MODULE_SEC + \ SUP_MODULE_SEC + \
SecNum + \ SecNum + \
Ffs.SectionSuffix['GUIDED'] SectionSuffix['GUIDED']
OutputFile = os.path.normpath(OutputFile) OutputFile = os.path.normpath(OutputFile)
ExternalTool = None ExternalTool = None

View File

@ -26,8 +26,6 @@ from Common.Misc import SaveFileOnChange
from Common import EdkLogger from Common import EdkLogger
from Common.BuildToolError import * from Common.BuildToolError import *
T_CHAR_LF = '\n'
## ##
# #
# #
@ -36,9 +34,9 @@ class OPTIONROM (OptionRomClassObject):
# #
# @param self The object pointer # @param self The object pointer
# #
def __init__(self): def __init__(self, Name = ""):
OptionRomClassObject.__init__(self) OptionRomClassObject.__init__(self)
self.DriverName = Name
## AddToBuffer() ## AddToBuffer()
# #

View File

@ -20,7 +20,6 @@ from struct import *
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
from io import BytesIO from io import BytesIO
import string import string
from CommonDataClass.FdfClass import RegionClassObject
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
from stat import * from stat import *
from Common import EdkLogger from Common import EdkLogger
@ -32,15 +31,20 @@ from Common.DataType import BINARY_FILE_TYPE_FV
## generate Region ## generate Region
# #
# #
class Region(RegionClassObject): class Region(object):
## The constructor ## The constructor
# #
# @param self The object pointer # @param self The object pointer
# #
def __init__(self): def __init__(self):
RegionClassObject.__init__(self) self.Offset = None # The begin position of the Region
self.Size = None # The Size of the Region
self.PcdOffset = None
self.PcdSize = None
self.SetVarDict = {}
self.RegionType = None
self.RegionDataList = []
## PadBuffer() ## PadBuffer()
# #

View File

@ -17,7 +17,7 @@
# #
from __future__ import absolute_import from __future__ import absolute_import
from . import Section from . import Section
from .Ffs import Ffs from .Ffs import SectionSuffix
import subprocess import subprocess
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
@ -59,7 +59,7 @@ class UiSection (UiSectionClassObject):
self.StringData = FfsInf.__ExtendMacro__(self.StringData) self.StringData = FfsInf.__ExtendMacro__(self.StringData)
self.FileName = FfsInf.__ExtendMacro__(self.FileName) self.FileName = FfsInf.__ExtendMacro__(self.FileName)
OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + SecNum + Ffs.SectionSuffix.get(BINARY_FILE_TYPE_UI)) OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + SecNum + SectionSuffix.get(BINARY_FILE_TYPE_UI))
if self.StringData is not None : if self.StringData is not None :
NameString = self.StringData NameString = self.StringData

View File

@ -1,7 +1,7 @@
## @file ## @file
# process Version section generation # process Version section generation
# #
# Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.<BR> # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
# #
# This program and the accompanying materials # This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License # are licensed and made available under the terms and conditions of the BSD License
@ -16,10 +16,8 @@
# Import Modules # Import Modules
# #
from __future__ import absolute_import from __future__ import absolute_import
from .Ffs import Ffs from .Ffs import SectionSuffix
from . import Section
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
import subprocess
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
from CommonDataClass.FdfClass import VerSectionClassObject from CommonDataClass.FdfClass import VerSectionClassObject
from Common.LongFilePathSupport import OpenLongFilePath as open from Common.LongFilePathSupport import OpenLongFilePath as open
@ -54,29 +52,27 @@ class VerSection (VerSectionClassObject):
# #
# Prepare the parameter of GenSection # Prepare the parameter of GenSection
# #
if FfsInf is not None: if FfsInf:
self.Alignment = FfsInf.__ExtendMacro__(self.Alignment) self.Alignment = FfsInf.__ExtendMacro__(self.Alignment)
self.BuildNum = FfsInf.__ExtendMacro__(self.BuildNum) self.BuildNum = FfsInf.__ExtendMacro__(self.BuildNum)
self.StringData = FfsInf.__ExtendMacro__(self.StringData) self.StringData = FfsInf.__ExtendMacro__(self.StringData)
self.FileName = FfsInf.__ExtendMacro__(self.FileName) self.FileName = FfsInf.__ExtendMacro__(self.FileName)
OutputFile = os.path.join(OutputPath, OutputFile = os.path.join(OutputPath,
ModuleName + SUP_MODULE_SEC + SecNum + Ffs.SectionSuffix.get('VERSION')) ModuleName + SUP_MODULE_SEC + SecNum + SectionSuffix.get('VERSION'))
OutputFile = os.path.normpath(OutputFile) OutputFile = os.path.normpath(OutputFile)
# Get String Data # Get String Data
StringData = '' StringData = ''
if self.StringData is not None: if self.StringData:
StringData = self.StringData StringData = self.StringData
elif self.FileName is not None: elif self.FileName:
FileNameStr = GenFdsGlobalVariable.ReplaceWorkspaceMacro(self.FileName) FileNameStr = GenFdsGlobalVariable.ReplaceWorkspaceMacro(self.FileName)
FileNameStr = GenFdsGlobalVariable.MacroExtend(FileNameStr, Dict) FileNameStr = GenFdsGlobalVariable.MacroExtend(FileNameStr, Dict)
FileObj = open(FileNameStr, 'r') FileObj = open(FileNameStr, 'r')
StringData = FileObj.read() StringData = FileObj.read()
StringData = '"' + StringData + '"' StringData = '"' + StringData + '"'
FileObj.close() FileObj.close()
else:
StringData = ''
GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION', GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',
Ver=StringData, BuildNumber=self.BuildNum, IsMakefile=IsMakefile) Ver=StringData, BuildNumber=self.BuildNum, IsMakefile=IsMakefile)
OutputFileList = [] OutputFileList = []

View File

@ -18,21 +18,24 @@
from __future__ import absolute_import from __future__ import absolute_import
from .GenFdsGlobalVariable import GenFdsGlobalVariable from .GenFdsGlobalVariable import GenFdsGlobalVariable
import Common.LongFilePathOs as os import Common.LongFilePathOs as os
from CommonDataClass.FdfClass import VtfClassObject
from Common.LongFilePathSupport import OpenLongFilePath as open from Common.LongFilePathSupport import OpenLongFilePath as open
T_CHAR_LF = '\n' from Common.DataType import TAB_LINE_BREAK
## generate VTF ## generate VTF
# #
# #
class Vtf (VtfClassObject): class Vtf (object):
## The constructor ## The constructor
# #
# @param self The object pointer # @param self The object pointer
# #
def __init__(self): def __init__(self):
VtfClassObject.__init__(self) self.KeyArch = None
self.ArchList = None
self.UiName = None
self.ResetBin = None
self.ComponentStatementList = []
## GenVtf() method ## GenVtf() method
# #
@ -44,7 +47,6 @@ class Vtf (VtfClassObject):
# #
def GenVtf(self, FdAddressDict) : def GenVtf(self, FdAddressDict) :
self.GenBsfInf() self.GenBsfInf()
OutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiName + '.Vtf')
BaseAddArg = self.GetBaseAddressArg(FdAddressDict) BaseAddArg = self.GetBaseAddressArg(FdAddressDict)
OutputArg, VtfRawDict = self.GenOutputArg() OutputArg, VtfRawDict = self.GenOutputArg()
@ -69,57 +71,57 @@ class Vtf (VtfClassObject):
FvList = self.GetFvList() FvList = self.GetFvList()
self.BsfInfName = os.path.join(GenFdsGlobalVariable.FvDir, self.UiName + '.inf') self.BsfInfName = os.path.join(GenFdsGlobalVariable.FvDir, self.UiName + '.inf')
BsfInf = open(self.BsfInfName, 'w+') BsfInf = open(self.BsfInfName, 'w+')
if self.ResetBin is not None: if self.ResetBin:
BsfInf.writelines ("[OPTIONS]" + T_CHAR_LF) BsfInf.writelines ("[OPTIONS]" + TAB_LINE_BREAK)
BsfInf.writelines ("IA32_RST_BIN" + \ BsfInf.writelines ("IA32_RST_BIN" + \
" = " + \ " = " + \
GenFdsGlobalVariable.MacroExtend(GenFdsGlobalVariable.ReplaceWorkspaceMacro(self.ResetBin)) + \ GenFdsGlobalVariable.MacroExtend(GenFdsGlobalVariable.ReplaceWorkspaceMacro(self.ResetBin)) + \
T_CHAR_LF) TAB_LINE_BREAK)
BsfInf.writelines (T_CHAR_LF) BsfInf.writelines (TAB_LINE_BREAK)
BsfInf.writelines ("[COMPONENTS]" + T_CHAR_LF) BsfInf.writelines ("[COMPONENTS]" + TAB_LINE_BREAK)
for ComponentObj in self.ComponentStatementList : for ComponentObj in self.ComponentStatementList :
BsfInf.writelines ("COMP_NAME" + \ BsfInf.writelines ("COMP_NAME" + \
" = " + \ " = " + \
ComponentObj.CompName + \ ComponentObj.CompName + \
T_CHAR_LF) TAB_LINE_BREAK)
if ComponentObj.CompLoc.upper() == 'NONE': if ComponentObj.CompLoc.upper() == 'NONE':
BsfInf.writelines ("COMP_LOC" + \ BsfInf.writelines ("COMP_LOC" + \
" = " + \ " = " + \
'N' + \ 'N' + \
T_CHAR_LF) TAB_LINE_BREAK)
elif ComponentObj.FilePos is not None: elif ComponentObj.FilePos:
BsfInf.writelines ("COMP_LOC" + \ BsfInf.writelines ("COMP_LOC" + \
" = " + \ " = " + \
ComponentObj.FilePos + \ ComponentObj.FilePos + \
T_CHAR_LF) TAB_LINE_BREAK)
else: else:
Index = FvList.index(ComponentObj.CompLoc.upper()) Index = FvList.index(ComponentObj.CompLoc.upper())
if Index == 0: if Index == 0:
BsfInf.writelines ("COMP_LOC" + \ BsfInf.writelines ("COMP_LOC" + \
" = " + \ " = " + \
'F' + \ 'F' + \
T_CHAR_LF) TAB_LINE_BREAK)
elif Index == 1: elif Index == 1:
BsfInf.writelines ("COMP_LOC" + \ BsfInf.writelines ("COMP_LOC" + \
" = " + \ " = " + \
'S' + \ 'S' + \
T_CHAR_LF) TAB_LINE_BREAK)
BsfInf.writelines ("COMP_TYPE" + \ BsfInf.writelines ("COMP_TYPE" + \
" = " + \ " = " + \
ComponentObj.CompType + \ ComponentObj.CompType + \
T_CHAR_LF) TAB_LINE_BREAK)
BsfInf.writelines ("COMP_VER" + \ BsfInf.writelines ("COMP_VER" + \
" = " + \ " = " + \
ComponentObj.CompVer + \ ComponentObj.CompVer + \
T_CHAR_LF) TAB_LINE_BREAK)
BsfInf.writelines ("COMP_CS" + \ BsfInf.writelines ("COMP_CS" + \
" = " + \ " = " + \
ComponentObj.CompCs + \ ComponentObj.CompCs + \
T_CHAR_LF) TAB_LINE_BREAK)
BinPath = ComponentObj.CompBin BinPath = ComponentObj.CompBin
if BinPath != '-': if BinPath != '-':
@ -127,7 +129,7 @@ class Vtf (VtfClassObject):
BsfInf.writelines ("COMP_BIN" + \ BsfInf.writelines ("COMP_BIN" + \
" = " + \ " = " + \
BinPath + \ BinPath + \
T_CHAR_LF) TAB_LINE_BREAK)
SymPath = ComponentObj.CompSym SymPath = ComponentObj.CompSym
if SymPath != '-': if SymPath != '-':
@ -135,12 +137,12 @@ class Vtf (VtfClassObject):
BsfInf.writelines ("COMP_SYM" + \ BsfInf.writelines ("COMP_SYM" + \
" = " + \ " = " + \
SymPath + \ SymPath + \
T_CHAR_LF) TAB_LINE_BREAK)
BsfInf.writelines ("COMP_SIZE" + \ BsfInf.writelines ("COMP_SIZE" + \
" = " + \ " = " + \
ComponentObj.CompSize + \ ComponentObj.CompSize + \
T_CHAR_LF) TAB_LINE_BREAK)
BsfInf.writelines (T_CHAR_LF) BsfInf.writelines (TAB_LINE_BREAK)
BsfInf.close() BsfInf.close()

View File

@ -46,6 +46,7 @@ from Common.StringUtils import NormPath
from Common.DataType import * from Common.DataType import *
import collections import collections
from Common.Expression import * from Common.Expression import *
from GenFds.AprioriSection import DXE_APRIORI_GUID, PEI_APRIORI_GUID
## Pattern to extract contents in EDK DXS files ## Pattern to extract contents in EDK DXS files
gDxsDependencyPattern = re.compile(r"DEPENDENCY_START(.+)DEPENDENCY_END", re.DOTALL) gDxsDependencyPattern = re.compile(r"DEPENDENCY_START(.+)DEPENDENCY_END", re.DOTALL)
@ -1873,8 +1874,8 @@ class FdRegionReport(object):
# #
# Add PEI and DXE a priori files GUIDs defined in PI specification. # Add PEI and DXE a priori files GUIDs defined in PI specification.
# #
self._GuidsDb["1B45CC0A-156A-428A-AF62-49864DA0E6E6"] = "PEI Apriori" self._GuidsDb[PEI_APRIORI_GUID] = "PEI Apriori"
self._GuidsDb["FC510EE7-FFDC-11D4-BD41-0080C73C8881"] = "DXE Apriori" self._GuidsDb[DXE_APRIORI_GUID] = "DXE Apriori"
# #
# Add ACPI table storage file # Add ACPI table storage file
# #