From f51461c829c124288a930829a78e2a5a799f4039 Mon Sep 17 00:00:00 2001 From: "Gao, Liming" Date: Mon, 27 Jan 2014 05:23:15 +0000 Subject: Sync BaseTool trunk (version r2649) into EDKII BaseTools. Signed-off-by: Gao, Liming git-svn-id: https://svn.code.sf.net/p/edk2/code/trunk/edk2@15188 6f19259b-4bc3-4df7-8a09-765794883524 --- BaseTools/Source/Python/GenFds/EfiSection.py | 10 +- BaseTools/Source/Python/GenFds/Fv.py | 14 +- BaseTools/Source/Python/GenFds/GenFds.py | 1076 +++++++-------- .../Source/Python/GenFds/GenFdsGlobalVariable.py | 1436 ++++++++++---------- 4 files changed, 1268 insertions(+), 1268 deletions(-) (limited to 'BaseTools/Source/Python/GenFds') diff --git a/BaseTools/Source/Python/GenFds/EfiSection.py b/BaseTools/Source/Python/GenFds/EfiSection.py index 5419e11fce..3eb4e23842 100644 --- a/BaseTools/Source/Python/GenFds/EfiSection.py +++ b/BaseTools/Source/Python/GenFds/EfiSection.py @@ -80,11 +80,11 @@ class EfiSection (EfiSectionClassObject): FileList = [] if Filename != None: Filename = GenFdsGlobalVariable.MacroExtend(Filename, Dict) - # check if the path is absolute or relative - if os.path.isabs(Filename): - Filename = os.path.normpath(Filename) - else: - Filename = os.path.normpath(os.path.join(FfsInf.EfiOutputPath, Filename)) + # check if the path is absolute or relative + if os.path.isabs(Filename): + Filename = os.path.normpath(Filename) + else: + Filename = os.path.normpath(os.path.join(FfsInf.EfiOutputPath, Filename)) if not self.Optional: FileList.append(Filename) diff --git a/BaseTools/Source/Python/GenFds/Fv.py b/BaseTools/Source/Python/GenFds/Fv.py index d79bed2b28..781c1a045d 100644 --- a/BaseTools/Source/Python/GenFds/Fv.py +++ b/BaseTools/Source/Python/GenFds/Fv.py @@ -296,13 +296,13 @@ class FV (FvClassObject): Buffer = '' for Index in range (0, len(self.FvExtEntryType)): if self.FvExtEntryType[Index] == 'FILE': - # check if the path is absolute or relative - if os.path.isabs(self.FvExtEntryData[Index]): - FileFullPath = os.path.normpath(self.FvExtEntryData[Index]) - else: - FileFullPath = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, self.FvExtEntryData[Index])) - # check if the file path exists or not - if not os.path.isfile(FileFullPath): + # check if the path is absolute or relative + if os.path.isabs(self.FvExtEntryData[Index]): + FileFullPath = os.path.normpath(self.FvExtEntryData[Index]) + else: + FileFullPath = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, self.FvExtEntryData[Index])) + # check if the file path exists or not + if not os.path.isfile(FileFullPath): GenFdsGlobalVariable.ErrorLogger("Error opening FV Extension Header Entry file %s." % (self.FvExtEntryData[Index])) FvExtFile = open (FileFullPath,'rb') FvExtFile.seek(0,2) diff --git a/BaseTools/Source/Python/GenFds/GenFds.py b/BaseTools/Source/Python/GenFds/GenFds.py index eca21642c8..058fa0c6a0 100644 --- a/BaseTools/Source/Python/GenFds/GenFds.py +++ b/BaseTools/Source/Python/GenFds/GenFds.py @@ -1,538 +1,538 @@ -## @file -# generate flash image -# -# Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# - -## -# Import Modules -# -from optparse import OptionParser -import sys -import os -import linecache -import FdfParser -import Common.BuildToolError as BuildToolError -from GenFdsGlobalVariable import GenFdsGlobalVariable -from Workspace.WorkspaceDatabase import WorkspaceDatabase -from Workspace.BuildClassObject import PcdClassObject -from Workspace.BuildClassObject import ModuleBuildClassObject -import RuleComplexFile -from EfiSection import EfiSection -import StringIO -import Common.TargetTxtClassObject as TargetTxtClassObject -import Common.ToolDefClassObject as ToolDefClassObject -import Common.DataType -import Common.GlobalData as GlobalData -from Common import EdkLogger -from Common.String import * -from Common.Misc import DirCache,PathClass -from Common.Misc import SaveFileOnChange -from Common.BuildVersion import gBUILD_VERSION - -## Version and Copyright -versionNumber = "1.0" + ' ' + gBUILD_VERSION -__version__ = "%prog Version " + versionNumber -__copyright__ = "Copyright (c) 2007 - 2013, Intel Corporation All rights reserved." - -## Tool entrance method -# -# This method mainly dispatch specific methods per the command line options. -# If no error found, return zero value so the caller of this tool can know -# if it's executed successfully or not. -# -# @retval 0 Tool was successful -# @retval 1 Tool failed -# -def main(): - global Options - Options = myOptionParser() - - global Workspace - Workspace = "" - ArchList = None - ReturnCode = 0 - - EdkLogger.Initialize() - try: - if Options.verbose != None: - EdkLogger.SetLevel(EdkLogger.VERBOSE) - GenFdsGlobalVariable.VerboseMode = True - - if Options.FixedAddress != None: - GenFdsGlobalVariable.FixedLoadAddress = True - - if Options.quiet != None: - EdkLogger.SetLevel(EdkLogger.QUIET) - if Options.debug != None: - EdkLogger.SetLevel(Options.debug + 1) - GenFdsGlobalVariable.DebugLevel = Options.debug - else: - EdkLogger.SetLevel(EdkLogger.INFO) - - if (Options.Workspace == None): - EdkLogger.error("GenFds", OPTION_MISSING, "WORKSPACE not defined", - ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.") - elif not os.path.exists(Options.Workspace): - EdkLogger.error("GenFds", PARAMETER_INVALID, "WORKSPACE is invalid", - ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.") - else: - Workspace = os.path.normcase(Options.Workspace) - GenFdsGlobalVariable.WorkSpaceDir = Workspace - if 'EDK_SOURCE' in os.environ.keys(): - GenFdsGlobalVariable.EdkSourceDir = os.path.normcase(os.environ['EDK_SOURCE']) - if (Options.debug): - GenFdsGlobalVariable.VerboseLogger( "Using Workspace:" + Workspace) - os.chdir(GenFdsGlobalVariable.WorkSpaceDir) - - if (Options.filename): - FdfFilename = Options.filename - FdfFilename = GenFdsGlobalVariable.ReplaceWorkspaceMacro(FdfFilename) - - if FdfFilename[0:2] == '..': - FdfFilename = os.path.realpath(FdfFilename) - if not os.path.isabs (FdfFilename): - FdfFilename = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, FdfFilename) - if not os.path.exists(FdfFilename): - EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=FdfFilename) - if os.path.normcase (FdfFilename).find(Workspace) != 0: - EdkLogger.error("GenFds", FILE_NOT_FOUND, "FdfFile doesn't exist in Workspace!") - - GenFdsGlobalVariable.FdfFile = FdfFilename - GenFdsGlobalVariable.FdfFileTimeStamp = os.path.getmtime(FdfFilename) - else: - EdkLogger.error("GenFds", OPTION_MISSING, "Missing FDF filename") - - if (Options.BuildTarget): - GenFdsGlobalVariable.TargetName = Options.BuildTarget - else: - EdkLogger.error("GenFds", OPTION_MISSING, "Missing build target") - - if (Options.ToolChain): - GenFdsGlobalVariable.ToolChainTag = Options.ToolChain - else: - EdkLogger.error("GenFds", OPTION_MISSING, "Missing tool chain tag") - - if (Options.activePlatform): - ActivePlatform = Options.activePlatform - ActivePlatform = GenFdsGlobalVariable.ReplaceWorkspaceMacro(ActivePlatform) - - if ActivePlatform[0:2] == '..': - ActivePlatform = os.path.realpath(ActivePlatform) - - if not os.path.isabs (ActivePlatform): - ActivePlatform = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, ActivePlatform) - - if not os.path.exists(ActivePlatform) : - EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!") - - if os.path.normcase (ActivePlatform).find(Workspace) != 0: - EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist in Workspace!") - - ActivePlatform = ActivePlatform[len(Workspace):] - if len(ActivePlatform) > 0 : - if ActivePlatform[0] == '\\' or ActivePlatform[0] == '/': - ActivePlatform = ActivePlatform[1:] - else: - EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!") - else: - EdkLogger.error("GenFds", OPTION_MISSING, "Missing active platform") - - GenFdsGlobalVariable.ActivePlatform = PathClass(NormPath(ActivePlatform), Workspace) - - BuildConfigurationFile = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, "Conf/target.txt")) - if os.path.isfile(BuildConfigurationFile) == True: - TargetTxtClassObject.TargetTxtClassObject(BuildConfigurationFile) - else: - EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=BuildConfigurationFile) - - if Options.Macros: - for Pair in Options.Macros: - Pair.strip('"') - List = Pair.split('=') - if len(List) == 2: - if List[0].strip() == "EFI_SOURCE": - GlobalData.gEfiSource = List[1].strip() - GlobalData.gGlobalDefines["EFI_SOURCE"] = GlobalData.gEfiSource - continue - elif List[0].strip() == "EDK_SOURCE": - GlobalData.gEdkSource = List[1].strip() - GlobalData.gGlobalDefines["EDK_SOURCE"] = GlobalData.gEdkSource - continue - elif List[0].strip() in ["WORKSPACE", "TARGET", "TOOLCHAIN"]: - GlobalData.gGlobalDefines[List[0].strip()] = List[1].strip() - else: - GlobalData.gCommandLineDefines[List[0].strip()] = List[1].strip() - else: - GlobalData.gCommandLineDefines[List[0].strip()] = "TRUE" - os.environ["WORKSPACE"] = Workspace - - """call Workspace build create database""" - BuildWorkSpace = WorkspaceDatabase(None) - BuildWorkSpace.InitDatabase() - - # - # Get files real name in workspace dir - # - GlobalData.gAllFiles = DirCache(Workspace) - GlobalData.gWorkspace = Workspace - - if (Options.archList) : - ArchList = Options.archList.split(',') - else: -# EdkLogger.error("GenFds", OPTION_MISSING, "Missing build ARCH") - ArchList = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList - - TargetArchList = set(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList) & set(ArchList) - if len(TargetArchList) == 0: - EdkLogger.error("GenFds", GENFDS_ERROR, "Target ARCH %s not in platform supported ARCH %s" % (str(ArchList), str(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON'].SupArchList))) - - for Arch in ArchList: - 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): - OutputDirFromCommandLine = GenFdsGlobalVariable.ReplaceWorkspaceMacro(Options.outputDir) - if not os.path.isabs (OutputDirFromCommandLine): - OutputDirFromCommandLine = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, OutputDirFromCommandLine) - for Arch in ArchList: - GenFdsGlobalVariable.OutputDirDict[Arch] = OutputDirFromCommandLine - else: - for Arch in ArchList: - GenFdsGlobalVariable.OutputDirDict[Arch] = os.path.join(GenFdsGlobalVariable.OutputDirFromDscDict[Arch], GenFdsGlobalVariable.TargetName + '_' + GenFdsGlobalVariable.ToolChainTag) - - for Key in GenFdsGlobalVariable.OutputDirDict: - OutputDir = GenFdsGlobalVariable.OutputDirDict[Key] - if OutputDir[0:2] == '..': - OutputDir = os.path.realpath(OutputDir) - - if OutputDir[1] != ':': - OutputDir = os.path.join (GenFdsGlobalVariable.WorkSpaceDir, OutputDir) - - if not os.path.exists(OutputDir): - EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=OutputDir) - GenFdsGlobalVariable.OutputDirDict[Key] = OutputDir - - """ Parse Fdf file, has to place after build Workspace as FDF may contain macros from DSC file """ - FdfParserObj = FdfParser.FdfParser(FdfFilename) - FdfParserObj.ParseFile() - - if FdfParserObj.CycleReferenceCheck(): - EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Cycle Reference Detected in FDF file") - - if (Options.uiFdName) : - if Options.uiFdName.upper() in FdfParserObj.Profile.FdDict.keys(): - GenFds.OnlyGenerateThisFd = Options.uiFdName - else: - EdkLogger.error("GenFds", OPTION_VALUE_INVALID, - "No such an FD in FDF file: %s" % Options.uiFdName) - - if (Options.uiFvName) : - if Options.uiFvName.upper() in FdfParserObj.Profile.FvDict.keys(): - GenFds.OnlyGenerateThisFv = Options.uiFvName - else: - EdkLogger.error("GenFds", OPTION_VALUE_INVALID, - "No such an FV in FDF file: %s" % Options.uiFvName) - - if (Options.uiCapName) : - if Options.uiCapName.upper() in FdfParserObj.Profile.CapsuleDict.keys(): - GenFds.OnlyGenerateThisCap = Options.uiCapName - else: - EdkLogger.error("GenFds", OPTION_VALUE_INVALID, - "No such a Capsule in FDF file: %s" % Options.uiCapName) - - """Modify images from build output if the feature of loading driver at fixed address is on.""" - if GenFdsGlobalVariable.FixedLoadAddress: - GenFds.PreprocessImage(BuildWorkSpace, GenFdsGlobalVariable.ActivePlatform) - """Call GenFds""" - GenFds.GenFd('', FdfParserObj, BuildWorkSpace, ArchList) - - """Generate GUID cross reference file""" - GenFds.GenerateGuidXRefFile(BuildWorkSpace, ArchList) - - """Display FV space info.""" - GenFds.DisplayFvSpaceInfo(FdfParserObj) - - except FdfParser.Warning, X: - EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError = False) - ReturnCode = FORMAT_INVALID - except FatalError, X: - if Options.debug != None: - import traceback - EdkLogger.quiet(traceback.format_exc()) - ReturnCode = X.args[0] - except: - import traceback - EdkLogger.error( - "\nPython", - CODE_ERROR, - "Tools code failure", - ExtraData="Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!\n", - RaiseError=False - ) - EdkLogger.quiet(traceback.format_exc()) - ReturnCode = CODE_ERROR - return ReturnCode - -gParamCheck = [] -def SingleCheckCallback(option, opt_str, value, parser): - if option not in gParamCheck: - setattr(parser.values, option.dest, value) - gParamCheck.append(option) - else: - parser.error("Option %s only allows one instance in command line!" % option) - -## Parse command line options -# -# Using standard Python module optparse to parse command line option of this tool. -# -# @retval Opt A optparse.Values object containing the parsed options -# @retval Args Target of build command -# -def myOptionParser(): - usage = "%prog [options] -f input_file -a arch_list -b build_target -p active_platform -t tool_chain_tag -D \"MacroName [= MacroValue]\"" - Parser = OptionParser(usage=usage,description=__copyright__,version="%prog " + str(versionNumber)) - Parser.add_option("-f", "--file", dest="filename", type="string", help="Name of FDF file to convert", action="callback", callback=SingleCheckCallback) - Parser.add_option("-a", "--arch", dest="archList", help="comma separated list containing one or more of: IA32, X64, IPF, ARM, AARCH64 or EBC which should be built, overrides target.txt?s TARGET_ARCH") - Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.") - Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed.") - Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.") - Parser.add_option("-p", "--platform", type="string", dest="activePlatform", help="Set the ACTIVE_PLATFORM, overrides target.txt ACTIVE_PLATFORM setting.", - action="callback", callback=SingleCheckCallback) - Parser.add_option("-w", "--workspace", type="string", dest="Workspace", default=os.environ.get('WORKSPACE'), help="Set the WORKSPACE", - action="callback", callback=SingleCheckCallback) - Parser.add_option("-o", "--outputDir", type="string", dest="outputDir", help="Name of Build Output directory", - action="callback", callback=SingleCheckCallback) - Parser.add_option("-r", "--rom_image", dest="uiFdName", help="Build the image using the [FD] section named by FdUiName.") - Parser.add_option("-i", "--FvImage", dest="uiFvName", help="Build the FV image using the [FV] section named by UiFvName") - Parser.add_option("-C", "--CapsuleImage", dest="uiCapName", help="Build the Capsule image using the [Capsule] section named by UiCapName") - Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Set the build TARGET, overrides target.txt TARGET setting.", - action="callback", callback=SingleCheckCallback) - Parser.add_option("-t", "--tagname", type="string", dest="ToolChain", help="Using the tools: TOOL_CHAIN_TAG name to build the platform.", - action="callback", callback=SingleCheckCallback) - Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".") - Parser.add_option("-s", "--specifyaddress", dest="FixedAddress", action="store_true", type=None, help="Specify driver load address.") - (Options, args) = Parser.parse_args() - return Options - -## The class implementing the EDK2 flash image generation process -# -# This process includes: -# 1. Collect workspace information, includes platform and module information -# 2. Call methods of Fd class to generate FD -# 3. Call methods of Fv class to generate FV that not belong to FD -# -class GenFds : - FdfParsef = None - # FvName, FdName, CapName in FDF, Image file name - ImageBinDict = {} - OnlyGenerateThisFd = None - OnlyGenerateThisFv = None - OnlyGenerateThisCap = None - - ## GenFd() - # - # @param OutputDir Output directory - # @param FdfParser FDF contents parser - # @param Workspace The directory of workspace - # @param ArchList The Arch list of platform - # - def GenFd (OutputDir, FdfParser, WorkSpace, ArchList): - GenFdsGlobalVariable.SetDir ('', FdfParser, WorkSpace, ArchList) - - GenFdsGlobalVariable.VerboseLogger(" Generate all Fd images and their required FV and Capsule images!") - if GenFds.OnlyGenerateThisCap != None and GenFds.OnlyGenerateThisCap.upper() in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.keys(): - CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.get(GenFds.OnlyGenerateThisCap.upper()) - if CapsuleObj != None: - CapsuleObj.GenCapsule() - return - - if GenFds.OnlyGenerateThisFd != None and GenFds.OnlyGenerateThisFd.upper() in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys(): - FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict.get(GenFds.OnlyGenerateThisFd.upper()) - if FdObj != None: - FdObj.GenFd() - return - elif GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisFv == None: - for FdName in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys(): - FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[FdName] - FdObj.GenFd() - - GenFdsGlobalVariable.VerboseLogger("\n Generate other FV images! ") - if GenFds.OnlyGenerateThisFv != None and GenFds.OnlyGenerateThisFv.upper() in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys(): - FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(GenFds.OnlyGenerateThisFv.upper()) - if FvObj != None: - Buffer = StringIO.StringIO() - FvObj.AddToBuffer(Buffer) - Buffer.close() - return - elif GenFds.OnlyGenerateThisFv == None: - for FvName in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys(): - Buffer = StringIO.StringIO('') - FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict[FvName] - FvObj.AddToBuffer(Buffer) - Buffer.close() - - if GenFds.OnlyGenerateThisFv == None and GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisCap == None: - if GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict != {}: - GenFdsGlobalVariable.VerboseLogger("\n Generate other Capsule images!") - for CapsuleName in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.keys(): - CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict[CapsuleName] - CapsuleObj.GenCapsule() - - if GenFdsGlobalVariable.FdfParser.Profile.OptRomDict != {}: - GenFdsGlobalVariable.VerboseLogger("\n Generate all Option ROM!") - for DriverName in GenFdsGlobalVariable.FdfParser.Profile.OptRomDict.keys(): - OptRomObj = GenFdsGlobalVariable.FdfParser.Profile.OptRomDict[DriverName] - OptRomObj.AddToBuffer(None) - - ## GetFvBlockSize() - # - # @param FvObj Whose block size to get - # @retval int Block size value - # - def GetFvBlockSize(FvObj): - DefaultBlockSize = 0x1 - FdObj = None - if GenFds.OnlyGenerateThisFd != None and GenFds.OnlyGenerateThisFd.upper() in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys(): - FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[GenFds.OnlyGenerateThisFd.upper()] - if FdObj == None: - for ElementFd in GenFdsGlobalVariable.FdfParser.Profile.FdDict.values(): - for ElementRegion in ElementFd.RegionList: - if ElementRegion.RegionType == 'FV': - for ElementRegionData in ElementRegion.RegionDataList: - if ElementRegionData != None and ElementRegionData.upper() == FvObj.UiFvName: - if FvObj.BlockSizeList != []: - return FvObj.BlockSizeList[0][0] - else: - return ElementRegion.BlockSizeOfRegion(ElementFd.BlockSizeList) - if FvObj.BlockSizeList != []: - return FvObj.BlockSizeList[0][0] - return DefaultBlockSize - else: - for ElementRegion in FdObj.RegionList: - if ElementRegion.RegionType == 'FV': - for ElementRegionData in ElementRegion.RegionDataList: - if ElementRegionData != None and ElementRegionData.upper() == FvObj.UiFvName: - if FvObj.BlockSizeList != []: - return FvObj.BlockSizeList[0][0] - else: - return ElementRegion.BlockSizeOfRegion(ElementFd.BlockSizeList) - return DefaultBlockSize - - ## DisplayFvSpaceInfo() - # - # @param FvObj Whose block size to get - # @retval None - # - def DisplayFvSpaceInfo(FdfParser): - - FvSpaceInfoList = [] - MaxFvNameLength = 0 - for FvName in FdfParser.Profile.FvDict: - if len(FvName) > MaxFvNameLength: - MaxFvNameLength = len(FvName) - FvSpaceInfoFileName = os.path.join(GenFdsGlobalVariable.FvDir, FvName.upper() + '.Fv.map') - if os.path.exists(FvSpaceInfoFileName): - FileLinesList = linecache.getlines(FvSpaceInfoFileName) - TotalFound = False - Total = '' - UsedFound = False - Used = '' - FreeFound = False - Free = '' - for Line in FileLinesList: - NameValue = Line.split('=') - if len(NameValue) == 2: - if NameValue[0].strip() == 'EFI_FV_TOTAL_SIZE': - TotalFound = True - Total = NameValue[1].strip() - if NameValue[0].strip() == 'EFI_FV_TAKEN_SIZE': - UsedFound = True - Used = NameValue[1].strip() - if NameValue[0].strip() == 'EFI_FV_SPACE_SIZE': - FreeFound = True - Free = NameValue[1].strip() - - if TotalFound and UsedFound and FreeFound: - FvSpaceInfoList.append((FvName, Total, Used, Free)) - - GenFdsGlobalVariable.InfLogger('\nFV Space Information') - for FvSpaceInfo in FvSpaceInfoList: - Name = FvSpaceInfo[0] - TotalSizeValue = long(FvSpaceInfo[1], 0) - UsedSizeValue = long(FvSpaceInfo[2], 0) - FreeSizeValue = long(FvSpaceInfo[3], 0) - if UsedSizeValue == TotalSizeValue: - Percentage = '100' - else: - Percentage = str((UsedSizeValue+0.0)/TotalSizeValue)[0:4].lstrip('0.') - - GenFdsGlobalVariable.InfLogger(Name + ' ' + '[' + Percentage + '%Full] ' + str(TotalSizeValue) + ' total, ' + str(UsedSizeValue) + ' used, ' + str(FreeSizeValue) + ' free') - - ## PreprocessImage() - # - # @param BuildDb Database from build meta data files - # @param DscFile modules from dsc file will be preprocessed - # @retval None - # - def PreprocessImage(BuildDb, DscFile): - PcdDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Pcds - PcdValue = '' - for Key in PcdDict: - PcdObj = PcdDict[Key] - if PcdObj.TokenCName == 'PcdBsBaseAddress': - PcdValue = PcdObj.DefaultValue - break - - if PcdValue == '': - return - - Int64PcdValue = long(PcdValue, 0) - if Int64PcdValue == 0 or Int64PcdValue < -1: - return - - TopAddress = 0 - if Int64PcdValue > 0: - TopAddress = Int64PcdValue - - ModuleDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Modules - for Key in ModuleDict: - ModuleObj = BuildDb.BuildObject[Key, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] - print ModuleObj.BaseName + ' ' + ModuleObj.ModuleType - - def GenerateGuidXRefFile(BuildDb, ArchList): - GuidXRefFileName = os.path.join(GenFdsGlobalVariable.FvDir, "Guid.xref") - GuidXRefFile = StringIO.StringIO('') - for Arch in ArchList: - PlatformDataBase = BuildDb.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] - for ModuleFile in PlatformDataBase.Modules: - Module = BuildDb.BuildObject[ModuleFile, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] - GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName)) - if GuidXRefFile.getvalue(): - SaveFileOnChange(GuidXRefFileName, GuidXRefFile.getvalue(), False) - GenFdsGlobalVariable.InfLogger("\nGUID cross reference file can be found at %s" % GuidXRefFileName) - elif os.path.exists(GuidXRefFileName): - os.remove(GuidXRefFileName) - 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__': - r = main() - ## 0-127 is a safe return range, and 1 is a standard default error - if r < 0 or r > 127: r = 1 - sys.exit(r) - +## @file +# generate flash image +# +# Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# + +## +# Import Modules +# +from optparse import OptionParser +import sys +import os +import linecache +import FdfParser +import Common.BuildToolError as BuildToolError +from GenFdsGlobalVariable import GenFdsGlobalVariable +from Workspace.WorkspaceDatabase import WorkspaceDatabase +from Workspace.BuildClassObject import PcdClassObject +from Workspace.BuildClassObject import ModuleBuildClassObject +import RuleComplexFile +from EfiSection import EfiSection +import StringIO +import Common.TargetTxtClassObject as TargetTxtClassObject +import Common.ToolDefClassObject as ToolDefClassObject +import Common.DataType +import Common.GlobalData as GlobalData +from Common import EdkLogger +from Common.String import * +from Common.Misc import DirCache,PathClass +from Common.Misc import SaveFileOnChange +from Common.BuildVersion import gBUILD_VERSION + +## Version and Copyright +versionNumber = "1.0" + ' ' + gBUILD_VERSION +__version__ = "%prog Version " + versionNumber +__copyright__ = "Copyright (c) 2007 - 2013, Intel Corporation All rights reserved." + +## Tool entrance method +# +# This method mainly dispatch specific methods per the command line options. +# If no error found, return zero value so the caller of this tool can know +# if it's executed successfully or not. +# +# @retval 0 Tool was successful +# @retval 1 Tool failed +# +def main(): + global Options + Options = myOptionParser() + + global Workspace + Workspace = "" + ArchList = None + ReturnCode = 0 + + EdkLogger.Initialize() + try: + if Options.verbose != None: + EdkLogger.SetLevel(EdkLogger.VERBOSE) + GenFdsGlobalVariable.VerboseMode = True + + if Options.FixedAddress != None: + GenFdsGlobalVariable.FixedLoadAddress = True + + if Options.quiet != None: + EdkLogger.SetLevel(EdkLogger.QUIET) + if Options.debug != None: + EdkLogger.SetLevel(Options.debug + 1) + GenFdsGlobalVariable.DebugLevel = Options.debug + else: + EdkLogger.SetLevel(EdkLogger.INFO) + + if (Options.Workspace == None): + EdkLogger.error("GenFds", OPTION_MISSING, "WORKSPACE not defined", + ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.") + elif not os.path.exists(Options.Workspace): + EdkLogger.error("GenFds", PARAMETER_INVALID, "WORKSPACE is invalid", + ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.") + else: + Workspace = os.path.normcase(Options.Workspace) + GenFdsGlobalVariable.WorkSpaceDir = Workspace + if 'EDK_SOURCE' in os.environ.keys(): + GenFdsGlobalVariable.EdkSourceDir = os.path.normcase(os.environ['EDK_SOURCE']) + if (Options.debug): + GenFdsGlobalVariable.VerboseLogger( "Using Workspace:" + Workspace) + os.chdir(GenFdsGlobalVariable.WorkSpaceDir) + + if (Options.filename): + FdfFilename = Options.filename + FdfFilename = GenFdsGlobalVariable.ReplaceWorkspaceMacro(FdfFilename) + + if FdfFilename[0:2] == '..': + FdfFilename = os.path.realpath(FdfFilename) + if not os.path.isabs (FdfFilename): + FdfFilename = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, FdfFilename) + if not os.path.exists(FdfFilename): + EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=FdfFilename) + if os.path.normcase (FdfFilename).find(Workspace) != 0: + EdkLogger.error("GenFds", FILE_NOT_FOUND, "FdfFile doesn't exist in Workspace!") + + GenFdsGlobalVariable.FdfFile = FdfFilename + GenFdsGlobalVariable.FdfFileTimeStamp = os.path.getmtime(FdfFilename) + else: + EdkLogger.error("GenFds", OPTION_MISSING, "Missing FDF filename") + + if (Options.BuildTarget): + GenFdsGlobalVariable.TargetName = Options.BuildTarget + else: + EdkLogger.error("GenFds", OPTION_MISSING, "Missing build target") + + if (Options.ToolChain): + GenFdsGlobalVariable.ToolChainTag = Options.ToolChain + else: + EdkLogger.error("GenFds", OPTION_MISSING, "Missing tool chain tag") + + if (Options.activePlatform): + ActivePlatform = Options.activePlatform + ActivePlatform = GenFdsGlobalVariable.ReplaceWorkspaceMacro(ActivePlatform) + + if ActivePlatform[0:2] == '..': + ActivePlatform = os.path.realpath(ActivePlatform) + + if not os.path.isabs (ActivePlatform): + ActivePlatform = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, ActivePlatform) + + if not os.path.exists(ActivePlatform) : + EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!") + + if os.path.normcase (ActivePlatform).find(Workspace) != 0: + EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist in Workspace!") + + ActivePlatform = ActivePlatform[len(Workspace):] + if len(ActivePlatform) > 0 : + if ActivePlatform[0] == '\\' or ActivePlatform[0] == '/': + ActivePlatform = ActivePlatform[1:] + else: + EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!") + else: + EdkLogger.error("GenFds", OPTION_MISSING, "Missing active platform") + + GenFdsGlobalVariable.ActivePlatform = PathClass(NormPath(ActivePlatform), Workspace) + + BuildConfigurationFile = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, "Conf/target.txt")) + if os.path.isfile(BuildConfigurationFile) == True: + TargetTxtClassObject.TargetTxtClassObject(BuildConfigurationFile) + else: + EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=BuildConfigurationFile) + + if Options.Macros: + for Pair in Options.Macros: + Pair.strip('"') + List = Pair.split('=') + if len(List) == 2: + if List[0].strip() == "EFI_SOURCE": + GlobalData.gEfiSource = List[1].strip() + GlobalData.gGlobalDefines["EFI_SOURCE"] = GlobalData.gEfiSource + continue + elif List[0].strip() == "EDK_SOURCE": + GlobalData.gEdkSource = List[1].strip() + GlobalData.gGlobalDefines["EDK_SOURCE"] = GlobalData.gEdkSource + continue + elif List[0].strip() in ["WORKSPACE", "TARGET", "TOOLCHAIN"]: + GlobalData.gGlobalDefines[List[0].strip()] = List[1].strip() + else: + GlobalData.gCommandLineDefines[List[0].strip()] = List[1].strip() + else: + GlobalData.gCommandLineDefines[List[0].strip()] = "TRUE" + os.environ["WORKSPACE"] = Workspace + + """call Workspace build create database""" + BuildWorkSpace = WorkspaceDatabase(None) + BuildWorkSpace.InitDatabase() + + # + # Get files real name in workspace dir + # + GlobalData.gAllFiles = DirCache(Workspace) + GlobalData.gWorkspace = Workspace + + if (Options.archList) : + ArchList = Options.archList.split(',') + else: +# EdkLogger.error("GenFds", OPTION_MISSING, "Missing build ARCH") + ArchList = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList + + TargetArchList = set(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList) & set(ArchList) + if len(TargetArchList) == 0: + EdkLogger.error("GenFds", GENFDS_ERROR, "Target ARCH %s not in platform supported ARCH %s" % (str(ArchList), str(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON'].SupArchList))) + + for Arch in ArchList: + 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): + OutputDirFromCommandLine = GenFdsGlobalVariable.ReplaceWorkspaceMacro(Options.outputDir) + if not os.path.isabs (OutputDirFromCommandLine): + OutputDirFromCommandLine = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, OutputDirFromCommandLine) + for Arch in ArchList: + GenFdsGlobalVariable.OutputDirDict[Arch] = OutputDirFromCommandLine + else: + for Arch in ArchList: + GenFdsGlobalVariable.OutputDirDict[Arch] = os.path.join(GenFdsGlobalVariable.OutputDirFromDscDict[Arch], GenFdsGlobalVariable.TargetName + '_' + GenFdsGlobalVariable.ToolChainTag) + + for Key in GenFdsGlobalVariable.OutputDirDict: + OutputDir = GenFdsGlobalVariable.OutputDirDict[Key] + if OutputDir[0:2] == '..': + OutputDir = os.path.realpath(OutputDir) + + if OutputDir[1] != ':': + OutputDir = os.path.join (GenFdsGlobalVariable.WorkSpaceDir, OutputDir) + + if not os.path.exists(OutputDir): + EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=OutputDir) + GenFdsGlobalVariable.OutputDirDict[Key] = OutputDir + + """ Parse Fdf file, has to place after build Workspace as FDF may contain macros from DSC file """ + FdfParserObj = FdfParser.FdfParser(FdfFilename) + FdfParserObj.ParseFile() + + if FdfParserObj.CycleReferenceCheck(): + EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Cycle Reference Detected in FDF file") + + if (Options.uiFdName) : + if Options.uiFdName.upper() in FdfParserObj.Profile.FdDict.keys(): + GenFds.OnlyGenerateThisFd = Options.uiFdName + else: + EdkLogger.error("GenFds", OPTION_VALUE_INVALID, + "No such an FD in FDF file: %s" % Options.uiFdName) + + if (Options.uiFvName) : + if Options.uiFvName.upper() in FdfParserObj.Profile.FvDict.keys(): + GenFds.OnlyGenerateThisFv = Options.uiFvName + else: + EdkLogger.error("GenFds", OPTION_VALUE_INVALID, + "No such an FV in FDF file: %s" % Options.uiFvName) + + if (Options.uiCapName) : + if Options.uiCapName.upper() in FdfParserObj.Profile.CapsuleDict.keys(): + GenFds.OnlyGenerateThisCap = Options.uiCapName + else: + EdkLogger.error("GenFds", OPTION_VALUE_INVALID, + "No such a Capsule in FDF file: %s" % Options.uiCapName) + + """Modify images from build output if the feature of loading driver at fixed address is on.""" + if GenFdsGlobalVariable.FixedLoadAddress: + GenFds.PreprocessImage(BuildWorkSpace, GenFdsGlobalVariable.ActivePlatform) + """Call GenFds""" + GenFds.GenFd('', FdfParserObj, BuildWorkSpace, ArchList) + + """Generate GUID cross reference file""" + GenFds.GenerateGuidXRefFile(BuildWorkSpace, ArchList) + + """Display FV space info.""" + GenFds.DisplayFvSpaceInfo(FdfParserObj) + + except FdfParser.Warning, X: + EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError = False) + ReturnCode = FORMAT_INVALID + except FatalError, X: + if Options.debug != None: + import traceback + EdkLogger.quiet(traceback.format_exc()) + ReturnCode = X.args[0] + except: + import traceback + EdkLogger.error( + "\nPython", + CODE_ERROR, + "Tools code failure", + ExtraData="Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!\n", + RaiseError=False + ) + EdkLogger.quiet(traceback.format_exc()) + ReturnCode = CODE_ERROR + return ReturnCode + +gParamCheck = [] +def SingleCheckCallback(option, opt_str, value, parser): + if option not in gParamCheck: + setattr(parser.values, option.dest, value) + gParamCheck.append(option) + else: + parser.error("Option %s only allows one instance in command line!" % option) + +## Parse command line options +# +# Using standard Python module optparse to parse command line option of this tool. +# +# @retval Opt A optparse.Values object containing the parsed options +# @retval Args Target of build command +# +def myOptionParser(): + usage = "%prog [options] -f input_file -a arch_list -b build_target -p active_platform -t tool_chain_tag -D \"MacroName [= MacroValue]\"" + Parser = OptionParser(usage=usage,description=__copyright__,version="%prog " + str(versionNumber)) + Parser.add_option("-f", "--file", dest="filename", type="string", help="Name of FDF file to convert", action="callback", callback=SingleCheckCallback) + Parser.add_option("-a", "--arch", dest="archList", help="comma separated list containing one or more of: IA32, X64, IPF, ARM, AARCH64 or EBC which should be built, overrides target.txt?s TARGET_ARCH") + Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.") + Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed.") + Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.") + Parser.add_option("-p", "--platform", type="string", dest="activePlatform", help="Set the ACTIVE_PLATFORM, overrides target.txt ACTIVE_PLATFORM setting.", + action="callback", callback=SingleCheckCallback) + Parser.add_option("-w", "--workspace", type="string", dest="Workspace", default=os.environ.get('WORKSPACE'), help="Set the WORKSPACE", + action="callback", callback=SingleCheckCallback) + Parser.add_option("-o", "--outputDir", type="string", dest="outputDir", help="Name of Build Output directory", + action="callback", callback=SingleCheckCallback) + Parser.add_option("-r", "--rom_image", dest="uiFdName", help="Build the image using the [FD] section named by FdUiName.") + Parser.add_option("-i", "--FvImage", dest="uiFvName", help="Build the FV image using the [FV] section named by UiFvName") + Parser.add_option("-C", "--CapsuleImage", dest="uiCapName", help="Build the Capsule image using the [Capsule] section named by UiCapName") + Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Set the build TARGET, overrides target.txt TARGET setting.", + action="callback", callback=SingleCheckCallback) + Parser.add_option("-t", "--tagname", type="string", dest="ToolChain", help="Using the tools: TOOL_CHAIN_TAG name to build the platform.", + action="callback", callback=SingleCheckCallback) + Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".") + Parser.add_option("-s", "--specifyaddress", dest="FixedAddress", action="store_true", type=None, help="Specify driver load address.") + (Options, args) = Parser.parse_args() + return Options + +## The class implementing the EDK2 flash image generation process +# +# This process includes: +# 1. Collect workspace information, includes platform and module information +# 2. Call methods of Fd class to generate FD +# 3. Call methods of Fv class to generate FV that not belong to FD +# +class GenFds : + FdfParsef = None + # FvName, FdName, CapName in FDF, Image file name + ImageBinDict = {} + OnlyGenerateThisFd = None + OnlyGenerateThisFv = None + OnlyGenerateThisCap = None + + ## GenFd() + # + # @param OutputDir Output directory + # @param FdfParser FDF contents parser + # @param Workspace The directory of workspace + # @param ArchList The Arch list of platform + # + def GenFd (OutputDir, FdfParser, WorkSpace, ArchList): + GenFdsGlobalVariable.SetDir ('', FdfParser, WorkSpace, ArchList) + + GenFdsGlobalVariable.VerboseLogger(" Generate all Fd images and their required FV and Capsule images!") + if GenFds.OnlyGenerateThisCap != None and GenFds.OnlyGenerateThisCap.upper() in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.keys(): + CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.get(GenFds.OnlyGenerateThisCap.upper()) + if CapsuleObj != None: + CapsuleObj.GenCapsule() + return + + if GenFds.OnlyGenerateThisFd != None and GenFds.OnlyGenerateThisFd.upper() in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys(): + FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict.get(GenFds.OnlyGenerateThisFd.upper()) + if FdObj != None: + FdObj.GenFd() + return + elif GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisFv == None: + for FdName in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys(): + FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[FdName] + FdObj.GenFd() + + GenFdsGlobalVariable.VerboseLogger("\n Generate other FV images! ") + if GenFds.OnlyGenerateThisFv != None and GenFds.OnlyGenerateThisFv.upper() in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys(): + FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(GenFds.OnlyGenerateThisFv.upper()) + if FvObj != None: + Buffer = StringIO.StringIO() + FvObj.AddToBuffer(Buffer) + Buffer.close() + return + elif GenFds.OnlyGenerateThisFv == None: + for FvName in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys(): + Buffer = StringIO.StringIO('') + FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict[FvName] + FvObj.AddToBuffer(Buffer) + Buffer.close() + + if GenFds.OnlyGenerateThisFv == None and GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisCap == None: + if GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict != {}: + GenFdsGlobalVariable.VerboseLogger("\n Generate other Capsule images!") + for CapsuleName in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.keys(): + CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict[CapsuleName] + CapsuleObj.GenCapsule() + + if GenFdsGlobalVariable.FdfParser.Profile.OptRomDict != {}: + GenFdsGlobalVariable.VerboseLogger("\n Generate all Option ROM!") + for DriverName in GenFdsGlobalVariable.FdfParser.Profile.OptRomDict.keys(): + OptRomObj = GenFdsGlobalVariable.FdfParser.Profile.OptRomDict[DriverName] + OptRomObj.AddToBuffer(None) + + ## GetFvBlockSize() + # + # @param FvObj Whose block size to get + # @retval int Block size value + # + def GetFvBlockSize(FvObj): + DefaultBlockSize = 0x1 + FdObj = None + if GenFds.OnlyGenerateThisFd != None and GenFds.OnlyGenerateThisFd.upper() in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys(): + FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[GenFds.OnlyGenerateThisFd.upper()] + if FdObj == None: + for ElementFd in GenFdsGlobalVariable.FdfParser.Profile.FdDict.values(): + for ElementRegion in ElementFd.RegionList: + if ElementRegion.RegionType == 'FV': + for ElementRegionData in ElementRegion.RegionDataList: + if ElementRegionData != None and ElementRegionData.upper() == FvObj.UiFvName: + if FvObj.BlockSizeList != []: + return FvObj.BlockSizeList[0][0] + else: + return ElementRegion.BlockSizeOfRegion(ElementFd.BlockSizeList) + if FvObj.BlockSizeList != []: + return FvObj.BlockSizeList[0][0] + return DefaultBlockSize + else: + for ElementRegion in FdObj.RegionList: + if ElementRegion.RegionType == 'FV': + for ElementRegionData in ElementRegion.RegionDataList: + if ElementRegionData != None and ElementRegionData.upper() == FvObj.UiFvName: + if FvObj.BlockSizeList != []: + return FvObj.BlockSizeList[0][0] + else: + return ElementRegion.BlockSizeOfRegion(ElementFd.BlockSizeList) + return DefaultBlockSize + + ## DisplayFvSpaceInfo() + # + # @param FvObj Whose block size to get + # @retval None + # + def DisplayFvSpaceInfo(FdfParser): + + FvSpaceInfoList = [] + MaxFvNameLength = 0 + for FvName in FdfParser.Profile.FvDict: + if len(FvName) > MaxFvNameLength: + MaxFvNameLength = len(FvName) + FvSpaceInfoFileName = os.path.join(GenFdsGlobalVariable.FvDir, FvName.upper() + '.Fv.map') + if os.path.exists(FvSpaceInfoFileName): + FileLinesList = linecache.getlines(FvSpaceInfoFileName) + TotalFound = False + Total = '' + UsedFound = False + Used = '' + FreeFound = False + Free = '' + for Line in FileLinesList: + NameValue = Line.split('=') + if len(NameValue) == 2: + if NameValue[0].strip() == 'EFI_FV_TOTAL_SIZE': + TotalFound = True + Total = NameValue[1].strip() + if NameValue[0].strip() == 'EFI_FV_TAKEN_SIZE': + UsedFound = True + Used = NameValue[1].strip() + if NameValue[0].strip() == 'EFI_FV_SPACE_SIZE': + FreeFound = True + Free = NameValue[1].strip() + + if TotalFound and UsedFound and FreeFound: + FvSpaceInfoList.append((FvName, Total, Used, Free)) + + GenFdsGlobalVariable.InfLogger('\nFV Space Information') + for FvSpaceInfo in FvSpaceInfoList: + Name = FvSpaceInfo[0] + TotalSizeValue = long(FvSpaceInfo[1], 0) + UsedSizeValue = long(FvSpaceInfo[2], 0) + FreeSizeValue = long(FvSpaceInfo[3], 0) + if UsedSizeValue == TotalSizeValue: + Percentage = '100' + else: + Percentage = str((UsedSizeValue+0.0)/TotalSizeValue)[0:4].lstrip('0.') + + GenFdsGlobalVariable.InfLogger(Name + ' ' + '[' + Percentage + '%Full] ' + str(TotalSizeValue) + ' total, ' + str(UsedSizeValue) + ' used, ' + str(FreeSizeValue) + ' free') + + ## PreprocessImage() + # + # @param BuildDb Database from build meta data files + # @param DscFile modules from dsc file will be preprocessed + # @retval None + # + def PreprocessImage(BuildDb, DscFile): + PcdDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Pcds + PcdValue = '' + for Key in PcdDict: + PcdObj = PcdDict[Key] + if PcdObj.TokenCName == 'PcdBsBaseAddress': + PcdValue = PcdObj.DefaultValue + break + + if PcdValue == '': + return + + Int64PcdValue = long(PcdValue, 0) + if Int64PcdValue == 0 or Int64PcdValue < -1: + return + + TopAddress = 0 + if Int64PcdValue > 0: + TopAddress = Int64PcdValue + + ModuleDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Modules + for Key in ModuleDict: + ModuleObj = BuildDb.BuildObject[Key, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] + print ModuleObj.BaseName + ' ' + ModuleObj.ModuleType + + def GenerateGuidXRefFile(BuildDb, ArchList): + GuidXRefFileName = os.path.join(GenFdsGlobalVariable.FvDir, "Guid.xref") + GuidXRefFile = StringIO.StringIO('') + for Arch in ArchList: + PlatformDataBase = BuildDb.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] + for ModuleFile in PlatformDataBase.Modules: + Module = BuildDb.BuildObject[ModuleFile, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] + GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName)) + if GuidXRefFile.getvalue(): + SaveFileOnChange(GuidXRefFileName, GuidXRefFile.getvalue(), False) + GenFdsGlobalVariable.InfLogger("\nGUID cross reference file can be found at %s" % GuidXRefFileName) + elif os.path.exists(GuidXRefFileName): + os.remove(GuidXRefFileName) + 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__': + r = main() + ## 0-127 is a safe return range, and 1 is a standard default error + if r < 0 or r > 127: r = 1 + sys.exit(r) + diff --git a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py index 1cd31bccc3..cbf3d980a8 100644 --- a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py +++ b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py @@ -1,722 +1,722 @@ -## @file -# Global variables for GenFds -# -# Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.
-# -# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. -# - -## -# Import Modules -# -import os -import sys -import subprocess -import struct -import array - -from Common.BuildToolError import * -from Common import EdkLogger -from Common.Misc import SaveFileOnChange - -from Common.TargetTxtClassObject import TargetTxtClassObject -from Common.ToolDefClassObject import ToolDefClassObject -from AutoGen.BuildEngine import BuildRule -import Common.DataType as DataType -from Common.Misc import PathClass - -## Global variables -# -# -class GenFdsGlobalVariable: - FvDir = '' - OutputDirDict = {} - BinDir = '' - # will be FvDir + os.sep + 'Ffs' - FfsDir = '' - FdfParser = None - LibDir = '' - WorkSpace = None - WorkSpaceDir = '' - EdkSourceDir = '' - OutputDirFromDscDict = {} - TargetName = '' - ToolChainTag = '' - RuleDict = {} - ArchList = None - VtfDict = {} - ActivePlatform = None - FvAddressFileName = '' - VerboseMode = False - DebugLevel = -1 - SharpCounter = 0 - SharpNumberPerLine = 40 - FdfFile = '' - FdfFileTimeStamp = 0 - FixedLoadAddress = False - PlatformName = '' - - BuildRuleFamily = "MSFT" - ToolChainFamily = "MSFT" - __BuildRuleDatabase = None - - # - # The list whose element are flags to indicate if large FFS or SECTION files exist in FV. - # At the beginning of each generation of FV, false flag is appended to the list, - # after the call to GenerateSection returns, check the size of the output file, - # if it is greater than 0xFFFFFF, the tail flag in list is set to true, - # and EFI_FIRMWARE_FILE_SYSTEM3_GUID is passed to C GenFv. - # At the end of generation of FV, pop the flag. - # List is used as a stack to handle nested FV generation. - # - LargeFileInFvFlags = [] - EFI_FIRMWARE_FILE_SYSTEM3_GUID = '5473C07A-3DCB-4dca-BD6F-1E9689E7349A' - LARGE_FILE_SIZE = 0x1000000 - - SectionHeader = struct.Struct("3B 1B") - - ## LoadBuildRule - # - @staticmethod - def __LoadBuildRule(): - if GenFdsGlobalVariable.__BuildRuleDatabase: - return GenFdsGlobalVariable.__BuildRuleDatabase - BuildConfigurationFile = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, "Conf/target.txt")) - TargetTxt = TargetTxtClassObject() - if os.path.isfile(BuildConfigurationFile) == True: - TargetTxt.LoadTargetTxtFile(BuildConfigurationFile) - if DataType.TAB_TAT_DEFINES_BUILD_RULE_CONF in TargetTxt.TargetTxtDictionary: - BuildRuleFile = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_BUILD_RULE_CONF] - if BuildRuleFile in [None, '']: - BuildRuleFile = 'Conf/build_rule.txt' - GenFdsGlobalVariable.__BuildRuleDatabase = BuildRule(BuildRuleFile) - ToolDefinitionFile = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF] - if ToolDefinitionFile == '': - ToolDefinitionFile = "Conf/tools_def.txt" - if os.path.isfile(ToolDefinitionFile): - ToolDef = ToolDefClassObject() - ToolDef.LoadToolDefFile(ToolDefinitionFile) - ToolDefinition = ToolDef.ToolsDefTxtDatabase - if DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY in ToolDefinition \ - and GenFdsGlobalVariable.ToolChainTag in ToolDefinition[DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY] \ - and ToolDefinition[DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY][GenFdsGlobalVariable.ToolChainTag]: - GenFdsGlobalVariable.BuildRuleFamily = ToolDefinition[DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY][GenFdsGlobalVariable.ToolChainTag] - - if DataType.TAB_TOD_DEFINES_FAMILY in ToolDefinition \ - and GenFdsGlobalVariable.ToolChainTag in ToolDefinition[DataType.TAB_TOD_DEFINES_FAMILY] \ - and ToolDefinition[DataType.TAB_TOD_DEFINES_FAMILY][GenFdsGlobalVariable.ToolChainTag]: - GenFdsGlobalVariable.ToolChainFamily = ToolDefinition[DataType.TAB_TOD_DEFINES_FAMILY][GenFdsGlobalVariable.ToolChainTag] - return GenFdsGlobalVariable.__BuildRuleDatabase - - ## GetBuildRules - # @param Inf: object of InfBuildData - # @param Arch: current arch - # - @staticmethod - def GetBuildRules(Inf, Arch): - if not Arch: - Arch = 'COMMON' - - if not Arch in GenFdsGlobalVariable.OutputDirDict: - return {} - - BuildRuleDatabase = GenFdsGlobalVariable.__LoadBuildRule() - if not BuildRuleDatabase: - return {} - - PathClassObj = PathClass(Inf.MetaFile.File, - 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( - GenFdsGlobalVariable.OutputDirDict[Arch], - Arch, - PathClassObj.SubDir, - PathClassObj.BaseName - ) - Macro["MODULE_BUILD_DIR" ] = BuildDir - Macro["OUTPUT_DIR" ] = os.path.join(BuildDir, "OUTPUT") - Macro["DEBUG_DIR" ] = os.path.join(BuildDir, "DEBUG") - - BuildRules = {} - for Type in BuildRuleDatabase.FileTypeList: - #first try getting build rule by BuildRuleFamily - RuleObject = BuildRuleDatabase[Type, Inf.BuildType, Arch, GenFdsGlobalVariable.BuildRuleFamily] - if not RuleObject: - # build type is always module type, but ... - if Inf.ModuleType != Inf.BuildType: - RuleObject = BuildRuleDatabase[Type, Inf.ModuleType, Arch, GenFdsGlobalVariable.BuildRuleFamily] - #second try getting build rule by ToolChainFamily - if not RuleObject: - RuleObject = BuildRuleDatabase[Type, Inf.BuildType, Arch, GenFdsGlobalVariable.ToolChainFamily] - if not RuleObject: - # build type is always module type, but ... - if Inf.ModuleType != Inf.BuildType: - RuleObject = BuildRuleDatabase[Type, Inf.ModuleType, Arch, GenFdsGlobalVariable.ToolChainFamily] - if not RuleObject: - continue - RuleObject = RuleObject.Instantiate(Macro) - BuildRules[Type] = RuleObject - for Ext in RuleObject.SourceFileExtList: - BuildRules[Ext] = RuleObject - return BuildRules - - ## GetModuleCodaTargetList - # - # @param Inf: object of InfBuildData - # @param Arch: current arch - # - @staticmethod - def GetModuleCodaTargetList(Inf, Arch): - BuildRules = GenFdsGlobalVariable.GetBuildRules(Inf, Arch) - if not BuildRules: - return [] - - TargetList = set() - FileList = [] - for File in Inf.Sources: - if File.TagName in ("", "*", GenFdsGlobalVariable.ToolChainTag) and \ - File.ToolChainFamily in ("", "*", GenFdsGlobalVariable.ToolChainFamily): - FileList.append((File, DataType.TAB_UNKNOWN_FILE)) - - for File in Inf.Binaries: - if File.Target in ['COMMON', '*', GenFdsGlobalVariable.TargetName]: - FileList.append((File, File.Type)) - - for File, FileType in FileList: - LastTarget = None - RuleChain = [] - SourceList = [File] - Index = 0 - while Index < len(SourceList): - Source = SourceList[Index] - Index = Index + 1 - - if File.IsBinary and File == Source and Inf.Binaries != None and File in Inf.Binaries: - # Skip all files that are not binary libraries - if not Inf.LibraryClass: - continue - RuleObject = BuildRules[DataType.TAB_DEFAULT_BINARY_FILE] - elif FileType in BuildRules: - RuleObject = BuildRules[FileType] - elif Source.Ext in BuildRules: - RuleObject = BuildRules[Source.Ext] - else: - # stop at no more rules - if LastTarget: - TargetList.add(str(LastTarget)) - break - - FileType = RuleObject.SourceFileType - - # stop at STATIC_LIBRARY for library - if Inf.LibraryClass and FileType == DataType.TAB_STATIC_LIBRARY: - if LastTarget: - TargetList.add(str(LastTarget)) - break - - Target = RuleObject.Apply(Source) - if not Target: - if LastTarget: - TargetList.add(str(LastTarget)) - break - elif not Target.Outputs: - # Only do build for target with outputs - TargetList.add(str(Target)) - - # to avoid cyclic rule - if FileType in RuleChain: - break - - RuleChain.append(FileType) - SourceList.extend(Target.Outputs) - LastTarget = Target - FileType = DataType.TAB_UNKNOWN_FILE - - return list(TargetList) - - ## SetDir() - # - # @param OutputDir Output directory - # @param FdfParser FDF contents parser - # @param Workspace The directory of workspace - # @param ArchList The Arch list of platform - # - def SetDir (OutputDir, FdfParser, WorkSpace, ArchList): - GenFdsGlobalVariable.VerboseLogger( "GenFdsGlobalVariable.OutputDir :%s" %OutputDir) -# GenFdsGlobalVariable.OutputDirDict = OutputDir - GenFdsGlobalVariable.FdfParser = FdfParser - GenFdsGlobalVariable.WorkSpace = WorkSpace - GenFdsGlobalVariable.FvDir = os.path.join(GenFdsGlobalVariable.OutputDirDict[ArchList[0]], 'FV') - if not os.path.exists(GenFdsGlobalVariable.FvDir) : - os.makedirs(GenFdsGlobalVariable.FvDir) - GenFdsGlobalVariable.FfsDir = os.path.join(GenFdsGlobalVariable.FvDir, 'Ffs') - if not os.path.exists(GenFdsGlobalVariable.FfsDir) : - os.makedirs(GenFdsGlobalVariable.FfsDir) - if ArchList != None: - GenFdsGlobalVariable.ArchList = ArchList - - T_CHAR_LF = '\n' - # - # Create FV Address inf file - # - GenFdsGlobalVariable.FvAddressFileName = os.path.join(GenFdsGlobalVariable.FfsDir, 'FvAddress.inf') - FvAddressFile = open (GenFdsGlobalVariable.FvAddressFileName, 'w') - # - # Add [Options] - # - FvAddressFile.writelines("[options]" + T_CHAR_LF) - BsAddress = '0' - for Arch in ArchList: - if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].BsBaseAddress: - BsAddress = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].BsBaseAddress - break - - FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS = " + \ - BsAddress + \ - T_CHAR_LF) - - RtAddress = '0' - for Arch in ArchList: - if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].RtBaseAddress: - RtAddress = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].RtBaseAddress - - FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS = " + \ - RtAddress + \ - T_CHAR_LF) - - FvAddressFile.close() - - ## ReplaceWorkspaceMacro() - # - # @param String String that may contain macro - # - def ReplaceWorkspaceMacro(String): - Str = String.replace('$(WORKSPACE)', GenFdsGlobalVariable.WorkSpaceDir) - if os.path.exists(Str): - if not os.path.isabs(Str): - Str = os.path.abspath(Str) - else: - Str = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, String) - return os.path.normpath(Str) - - ## Check if the input files are newer than output files - # - # @param Output Path of output file - # @param Input Path list of input files - # - # @retval True if Output doesn't exist, or any Input is newer - # @retval False if all Input is older than Output - # - @staticmethod - def NeedsUpdate(Output, Input): - if not os.path.exists(Output): - return True - # always update "Output" if no "Input" given - if Input == None or len(Input) == 0: - return True - - # if fdf file is changed after the 'Output" is generated, update the 'Output' - OutputTime = os.path.getmtime(Output) - if GenFdsGlobalVariable.FdfFileTimeStamp > OutputTime: - return True - - for F in Input: - # always update "Output" if any "Input" doesn't exist - if not os.path.exists(F): - return True - # always update "Output" if any "Input" is newer than "Output" - if os.path.getmtime(F) > OutputTime: - return True - return False - - @staticmethod - def GenerateSection(Output, Input, Type=None, CompressionType=None, Guid=None, - GuidHdrLen=None, GuidAttr=[], Ui=None, Ver=None, InputAlign=None, BuildNumber=None): - Cmd = ["GenSec"] - if Type not in [None, '']: - Cmd += ["-s", Type] - if CompressionType not in [None, '']: - Cmd += ["-c", CompressionType] - if Guid != None: - Cmd += ["-g", Guid] - if GuidHdrLen not in [None, '']: - Cmd += ["-l", GuidHdrLen] - if len(GuidAttr) != 0: - #Add each guided attribute - for Attr in GuidAttr: - Cmd += ["-r", Attr] - if InputAlign != None: - #Section Align is only for dummy section without section type - for SecAlign in InputAlign: - Cmd += ["--sectionalign", SecAlign] - - CommandFile = Output + '.txt' - if Ui not in [None, '']: - #Cmd += ["-n", '"' + Ui + '"'] - SectionData = array.array('B', [0,0,0,0]) - SectionData.fromstring(Ui.encode("utf_16_le")) - SectionData.append(0) - SectionData.append(0) - Len = len(SectionData) - GenFdsGlobalVariable.SectionHeader.pack_into(SectionData, 0, Len & 0xff, (Len >> 8) & 0xff, (Len >> 16) & 0xff, 0x15) - SaveFileOnChange(Output, SectionData.tostring()) - elif Ver not in [None, '']: - Cmd += ["-n", Ver] - if BuildNumber: - Cmd += ["-j", BuildNumber] - Cmd += ["-o", Output] - - SaveFileOnChange(CommandFile, ' '.join(Cmd), False) - if not GenFdsGlobalVariable.NeedsUpdate(Output, list(Input) + [CommandFile]): - return - - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate section") - else: - Cmd += ["-o", Output] - Cmd += Input - - SaveFileOnChange(CommandFile, ' '.join(Cmd), False) - if GenFdsGlobalVariable.NeedsUpdate(Output, list(Input) + [CommandFile]): - GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate section") - - if (os.path.getsize(Output) >= GenFdsGlobalVariable.LARGE_FILE_SIZE and - GenFdsGlobalVariable.LargeFileInFvFlags): - GenFdsGlobalVariable.LargeFileInFvFlags[-1] = True - - @staticmethod - def GetAlignment (AlignString): - if AlignString == None: - return 0 +## @file +# Global variables for GenFds +# +# Copyright (c) 2007 - 2012, Intel Corporation. All rights reserved.
+# +# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# + +## +# Import Modules +# +import os +import sys +import subprocess +import struct +import array + +from Common.BuildToolError import * +from Common import EdkLogger +from Common.Misc import SaveFileOnChange + +from Common.TargetTxtClassObject import TargetTxtClassObject +from Common.ToolDefClassObject import ToolDefClassObject +from AutoGen.BuildEngine import BuildRule +import Common.DataType as DataType +from Common.Misc import PathClass + +## Global variables +# +# +class GenFdsGlobalVariable: + FvDir = '' + OutputDirDict = {} + BinDir = '' + # will be FvDir + os.sep + 'Ffs' + FfsDir = '' + FdfParser = None + LibDir = '' + WorkSpace = None + WorkSpaceDir = '' + EdkSourceDir = '' + OutputDirFromDscDict = {} + TargetName = '' + ToolChainTag = '' + RuleDict = {} + ArchList = None + VtfDict = {} + ActivePlatform = None + FvAddressFileName = '' + VerboseMode = False + DebugLevel = -1 + SharpCounter = 0 + SharpNumberPerLine = 40 + FdfFile = '' + FdfFileTimeStamp = 0 + FixedLoadAddress = False + PlatformName = '' + + BuildRuleFamily = "MSFT" + ToolChainFamily = "MSFT" + __BuildRuleDatabase = None + + # + # The list whose element are flags to indicate if large FFS or SECTION files exist in FV. + # At the beginning of each generation of FV, false flag is appended to the list, + # after the call to GenerateSection returns, check the size of the output file, + # if it is greater than 0xFFFFFF, the tail flag in list is set to true, + # and EFI_FIRMWARE_FILE_SYSTEM3_GUID is passed to C GenFv. + # At the end of generation of FV, pop the flag. + # List is used as a stack to handle nested FV generation. + # + LargeFileInFvFlags = [] + EFI_FIRMWARE_FILE_SYSTEM3_GUID = '5473C07A-3DCB-4dca-BD6F-1E9689E7349A' + LARGE_FILE_SIZE = 0x1000000 + + SectionHeader = struct.Struct("3B 1B") + + ## LoadBuildRule + # + @staticmethod + def __LoadBuildRule(): + if GenFdsGlobalVariable.__BuildRuleDatabase: + return GenFdsGlobalVariable.__BuildRuleDatabase + BuildConfigurationFile = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, "Conf/target.txt")) + TargetTxt = TargetTxtClassObject() + if os.path.isfile(BuildConfigurationFile) == True: + TargetTxt.LoadTargetTxtFile(BuildConfigurationFile) + if DataType.TAB_TAT_DEFINES_BUILD_RULE_CONF in TargetTxt.TargetTxtDictionary: + BuildRuleFile = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_BUILD_RULE_CONF] + if BuildRuleFile in [None, '']: + BuildRuleFile = 'Conf/build_rule.txt' + GenFdsGlobalVariable.__BuildRuleDatabase = BuildRule(BuildRuleFile) + ToolDefinitionFile = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF] + if ToolDefinitionFile == '': + ToolDefinitionFile = "Conf/tools_def.txt" + if os.path.isfile(ToolDefinitionFile): + ToolDef = ToolDefClassObject() + ToolDef.LoadToolDefFile(ToolDefinitionFile) + ToolDefinition = ToolDef.ToolsDefTxtDatabase + if DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY in ToolDefinition \ + and GenFdsGlobalVariable.ToolChainTag in ToolDefinition[DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY] \ + and ToolDefinition[DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY][GenFdsGlobalVariable.ToolChainTag]: + GenFdsGlobalVariable.BuildRuleFamily = ToolDefinition[DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY][GenFdsGlobalVariable.ToolChainTag] + + if DataType.TAB_TOD_DEFINES_FAMILY in ToolDefinition \ + and GenFdsGlobalVariable.ToolChainTag in ToolDefinition[DataType.TAB_TOD_DEFINES_FAMILY] \ + and ToolDefinition[DataType.TAB_TOD_DEFINES_FAMILY][GenFdsGlobalVariable.ToolChainTag]: + GenFdsGlobalVariable.ToolChainFamily = ToolDefinition[DataType.TAB_TOD_DEFINES_FAMILY][GenFdsGlobalVariable.ToolChainTag] + return GenFdsGlobalVariable.__BuildRuleDatabase + + ## GetBuildRules + # @param Inf: object of InfBuildData + # @param Arch: current arch + # + @staticmethod + def GetBuildRules(Inf, Arch): + if not Arch: + Arch = 'COMMON' + + if not Arch in GenFdsGlobalVariable.OutputDirDict: + return {} + + BuildRuleDatabase = GenFdsGlobalVariable.__LoadBuildRule() + if not BuildRuleDatabase: + return {} + + PathClassObj = PathClass(Inf.MetaFile.File, + 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( + GenFdsGlobalVariable.OutputDirDict[Arch], + Arch, + PathClassObj.SubDir, + PathClassObj.BaseName + ) + Macro["MODULE_BUILD_DIR" ] = BuildDir + Macro["OUTPUT_DIR" ] = os.path.join(BuildDir, "OUTPUT") + Macro["DEBUG_DIR" ] = os.path.join(BuildDir, "DEBUG") + + BuildRules = {} + for Type in BuildRuleDatabase.FileTypeList: + #first try getting build rule by BuildRuleFamily + RuleObject = BuildRuleDatabase[Type, Inf.BuildType, Arch, GenFdsGlobalVariable.BuildRuleFamily] + if not RuleObject: + # build type is always module type, but ... + if Inf.ModuleType != Inf.BuildType: + RuleObject = BuildRuleDatabase[Type, Inf.ModuleType, Arch, GenFdsGlobalVariable.BuildRuleFamily] + #second try getting build rule by ToolChainFamily + if not RuleObject: + RuleObject = BuildRuleDatabase[Type, Inf.BuildType, Arch, GenFdsGlobalVariable.ToolChainFamily] + if not RuleObject: + # build type is always module type, but ... + if Inf.ModuleType != Inf.BuildType: + RuleObject = BuildRuleDatabase[Type, Inf.ModuleType, Arch, GenFdsGlobalVariable.ToolChainFamily] + if not RuleObject: + continue + RuleObject = RuleObject.Instantiate(Macro) + BuildRules[Type] = RuleObject + for Ext in RuleObject.SourceFileExtList: + BuildRules[Ext] = RuleObject + return BuildRules + + ## GetModuleCodaTargetList + # + # @param Inf: object of InfBuildData + # @param Arch: current arch + # + @staticmethod + def GetModuleCodaTargetList(Inf, Arch): + BuildRules = GenFdsGlobalVariable.GetBuildRules(Inf, Arch) + if not BuildRules: + return [] + + TargetList = set() + FileList = [] + for File in Inf.Sources: + if File.TagName in ("", "*", GenFdsGlobalVariable.ToolChainTag) and \ + File.ToolChainFamily in ("", "*", GenFdsGlobalVariable.ToolChainFamily): + FileList.append((File, DataType.TAB_UNKNOWN_FILE)) + + for File in Inf.Binaries: + if File.Target in ['COMMON', '*', GenFdsGlobalVariable.TargetName]: + FileList.append((File, File.Type)) + + for File, FileType in FileList: + LastTarget = None + RuleChain = [] + SourceList = [File] + Index = 0 + while Index < len(SourceList): + Source = SourceList[Index] + Index = Index + 1 + + if File.IsBinary and File == Source and Inf.Binaries != None and File in Inf.Binaries: + # Skip all files that are not binary libraries + if not Inf.LibraryClass: + continue + RuleObject = BuildRules[DataType.TAB_DEFAULT_BINARY_FILE] + elif FileType in BuildRules: + RuleObject = BuildRules[FileType] + elif Source.Ext in BuildRules: + RuleObject = BuildRules[Source.Ext] + else: + # stop at no more rules + if LastTarget: + TargetList.add(str(LastTarget)) + break + + FileType = RuleObject.SourceFileType + + # stop at STATIC_LIBRARY for library + if Inf.LibraryClass and FileType == DataType.TAB_STATIC_LIBRARY: + if LastTarget: + TargetList.add(str(LastTarget)) + break + + Target = RuleObject.Apply(Source) + if not Target: + if LastTarget: + TargetList.add(str(LastTarget)) + break + elif not Target.Outputs: + # Only do build for target with outputs + TargetList.add(str(Target)) + + # to avoid cyclic rule + if FileType in RuleChain: + break + + RuleChain.append(FileType) + SourceList.extend(Target.Outputs) + LastTarget = Target + FileType = DataType.TAB_UNKNOWN_FILE + + return list(TargetList) + + ## SetDir() + # + # @param OutputDir Output directory + # @param FdfParser FDF contents parser + # @param Workspace The directory of workspace + # @param ArchList The Arch list of platform + # + def SetDir (OutputDir, FdfParser, WorkSpace, ArchList): + GenFdsGlobalVariable.VerboseLogger( "GenFdsGlobalVariable.OutputDir :%s" %OutputDir) +# GenFdsGlobalVariable.OutputDirDict = OutputDir + GenFdsGlobalVariable.FdfParser = FdfParser + GenFdsGlobalVariable.WorkSpace = WorkSpace + GenFdsGlobalVariable.FvDir = os.path.join(GenFdsGlobalVariable.OutputDirDict[ArchList[0]], 'FV') + if not os.path.exists(GenFdsGlobalVariable.FvDir) : + os.makedirs(GenFdsGlobalVariable.FvDir) + GenFdsGlobalVariable.FfsDir = os.path.join(GenFdsGlobalVariable.FvDir, 'Ffs') + if not os.path.exists(GenFdsGlobalVariable.FfsDir) : + os.makedirs(GenFdsGlobalVariable.FfsDir) + if ArchList != None: + GenFdsGlobalVariable.ArchList = ArchList + + T_CHAR_LF = '\n' + # + # Create FV Address inf file + # + GenFdsGlobalVariable.FvAddressFileName = os.path.join(GenFdsGlobalVariable.FfsDir, 'FvAddress.inf') + FvAddressFile = open (GenFdsGlobalVariable.FvAddressFileName, 'w') + # + # Add [Options] + # + FvAddressFile.writelines("[options]" + T_CHAR_LF) + BsAddress = '0' + for Arch in ArchList: + if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].BsBaseAddress: + BsAddress = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].BsBaseAddress + break + + FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS = " + \ + BsAddress + \ + T_CHAR_LF) + + RtAddress = '0' + for Arch in ArchList: + if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].RtBaseAddress: + RtAddress = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].RtBaseAddress + + FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS = " + \ + RtAddress + \ + T_CHAR_LF) + + FvAddressFile.close() + + ## ReplaceWorkspaceMacro() + # + # @param String String that may contain macro + # + def ReplaceWorkspaceMacro(String): + Str = String.replace('$(WORKSPACE)', GenFdsGlobalVariable.WorkSpaceDir) + if os.path.exists(Str): + if not os.path.isabs(Str): + Str = os.path.abspath(Str) + else: + Str = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, String) + return os.path.normpath(Str) + + ## Check if the input files are newer than output files + # + # @param Output Path of output file + # @param Input Path list of input files + # + # @retval True if Output doesn't exist, or any Input is newer + # @retval False if all Input is older than Output + # + @staticmethod + def NeedsUpdate(Output, Input): + if not os.path.exists(Output): + return True + # always update "Output" if no "Input" given + if Input == None or len(Input) == 0: + return True + + # if fdf file is changed after the 'Output" is generated, update the 'Output' + OutputTime = os.path.getmtime(Output) + if GenFdsGlobalVariable.FdfFileTimeStamp > OutputTime: + return True + + for F in Input: + # always update "Output" if any "Input" doesn't exist + if not os.path.exists(F): + return True + # always update "Output" if any "Input" is newer than "Output" + if os.path.getmtime(F) > OutputTime: + return True + return False + + @staticmethod + def GenerateSection(Output, Input, Type=None, CompressionType=None, Guid=None, + GuidHdrLen=None, GuidAttr=[], Ui=None, Ver=None, InputAlign=None, BuildNumber=None): + Cmd = ["GenSec"] + if Type not in [None, '']: + Cmd += ["-s", Type] + if CompressionType not in [None, '']: + Cmd += ["-c", CompressionType] + if Guid != None: + Cmd += ["-g", Guid] + if GuidHdrLen not in [None, '']: + Cmd += ["-l", GuidHdrLen] + if len(GuidAttr) != 0: + #Add each guided attribute + for Attr in GuidAttr: + Cmd += ["-r", Attr] + if InputAlign != None: + #Section Align is only for dummy section without section type + for SecAlign in InputAlign: + Cmd += ["--sectionalign", SecAlign] + + CommandFile = Output + '.txt' + if Ui not in [None, '']: + #Cmd += ["-n", '"' + Ui + '"'] + SectionData = array.array('B', [0,0,0,0]) + SectionData.fromstring(Ui.encode("utf_16_le")) + SectionData.append(0) + SectionData.append(0) + Len = len(SectionData) + GenFdsGlobalVariable.SectionHeader.pack_into(SectionData, 0, Len & 0xff, (Len >> 8) & 0xff, (Len >> 16) & 0xff, 0x15) + SaveFileOnChange(Output, SectionData.tostring()) + elif Ver not in [None, '']: + Cmd += ["-n", Ver] + if BuildNumber: + Cmd += ["-j", BuildNumber] + Cmd += ["-o", Output] + + SaveFileOnChange(CommandFile, ' '.join(Cmd), False) + if not GenFdsGlobalVariable.NeedsUpdate(Output, list(Input) + [CommandFile]): + return + + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate section") + else: + Cmd += ["-o", Output] + Cmd += Input + + SaveFileOnChange(CommandFile, ' '.join(Cmd), False) + if GenFdsGlobalVariable.NeedsUpdate(Output, list(Input) + [CommandFile]): + GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate section") + + if (os.path.getsize(Output) >= GenFdsGlobalVariable.LARGE_FILE_SIZE and + GenFdsGlobalVariable.LargeFileInFvFlags): + GenFdsGlobalVariable.LargeFileInFvFlags[-1] = True + + @staticmethod + def GetAlignment (AlignString): + if AlignString == None: + return 0 if AlignString in ("1K", "2K", "4K", "8K", "16K", "32K", "64K"): return int (AlignString.rstrip('K')) * 1024 else: return int (AlignString) - - @staticmethod - def GenerateFfs(Output, Input, Type, Guid, Fixed=False, CheckSum=False, Align=None, - SectionAlign=None): - Cmd = ["GenFfs", "-t", Type, "-g", Guid] - if Fixed == True: - Cmd += ["-x"] - if CheckSum: - Cmd += ["-s"] - if Align not in [None, '']: - Cmd += ["-a", Align] - - Cmd += ["-o", Output] - for I in range(0, len(Input)): - Cmd += ("-i", Input[I]) - if SectionAlign not in [None, '', []] and SectionAlign[I] not in [None, '']: - Cmd += ("-n", SectionAlign[I]) - - CommandFile = Output + '.txt' - SaveFileOnChange(CommandFile, ' '.join(Cmd), False) - if not GenFdsGlobalVariable.NeedsUpdate(Output, list(Input) + [CommandFile]): - return - GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) - - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate FFS") - - @staticmethod - def GenerateFirmwareVolume(Output, Input, BaseAddress=None, ForceRebase=None, Capsule=False, Dump=False, - AddressFile=None, MapFile=None, FfsList=[], FileSystemGuid=None): - if not GenFdsGlobalVariable.NeedsUpdate(Output, Input+FfsList): - return - GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) - - Cmd = ["GenFv"] - if BaseAddress not in [None, '']: - Cmd += ["-r", BaseAddress] - - if ForceRebase == False: - Cmd +=["-F", "FALSE"] - elif ForceRebase == True: - Cmd +=["-F", "TRUE"] - - if Capsule: - Cmd += ["-c"] - if Dump: - Cmd += ["-p"] - if AddressFile not in [None, '']: - Cmd += ["-a", AddressFile] - if MapFile not in [None, '']: - Cmd += ["-m", MapFile] - if FileSystemGuid: - Cmd += ["-g", FileSystemGuid] - Cmd += ["-o", Output] - for I in Input: - Cmd += ["-i", I] - - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate FV") - - @staticmethod - def GenerateVtf(Output, Input, BaseAddress=None, FvSize=None): - if not GenFdsGlobalVariable.NeedsUpdate(Output, Input): - return - GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) - - Cmd = ["GenVtf"] - if BaseAddress not in [None, ''] and FvSize not in [None, ''] \ - and len(BaseAddress) == len(FvSize): - for I in range(0, len(BaseAddress)): - Cmd += ["-r", BaseAddress[I], "-s", FvSize[I]] - Cmd += ["-o", Output] - for F in Input: - Cmd += ["-f", F] - - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate VTF") - - @staticmethod - def GenerateFirmwareImage(Output, Input, Type="efi", SubType=None, Zero=False, - Strip=False, Replace=False, TimeStamp=None, Join=False, - Align=None, Padding=None, Convert=False): - if not GenFdsGlobalVariable.NeedsUpdate(Output, Input): - return - GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) - - Cmd = ["GenFw"] - if Type.lower() == "te": - Cmd += ["-t"] - if SubType not in [None, '']: - Cmd += ["-e", SubType] - if TimeStamp not in [None, '']: - Cmd += ["-s", TimeStamp] - if Align not in [None, '']: - Cmd += ["-a", Align] - if Padding not in [None, '']: - Cmd += ["-p", Padding] - if Zero: - Cmd += ["-z"] - if Strip: - Cmd += ["-l"] - if Replace: - Cmd += ["-r"] - if Join: - Cmd += ["-j"] - if Convert: - Cmd += ["-m"] - Cmd += ["-o", Output] - Cmd += Input - - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate firmware image") - - @staticmethod - def GenerateOptionRom(Output, EfiInput, BinaryInput, Compress=False, ClassCode=None, - Revision=None, DeviceId=None, VendorId=None): - InputList = [] - Cmd = ["EfiRom"] - if len(EfiInput) > 0: - - if Compress: - Cmd += ["-ec"] - else: - Cmd += ["-e"] - - for EfiFile in EfiInput: - Cmd += [EfiFile] - InputList.append (EfiFile) - - if len(BinaryInput) > 0: - Cmd += ["-b"] - for BinFile in BinaryInput: - Cmd += [BinFile] - InputList.append (BinFile) - - # Check List - if not GenFdsGlobalVariable.NeedsUpdate(Output, InputList): - return - GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, InputList)) - - if ClassCode != None: - Cmd += ["-l", ClassCode] - if Revision != None: - Cmd += ["-r", Revision] - if DeviceId != None: - Cmd += ["-i", DeviceId] - if VendorId != None: - Cmd += ["-f", VendorId] - - Cmd += ["-o", Output] - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate option rom") - - @staticmethod - def GuidTool(Output, Input, ToolPath, Options='', returnValue=[]): - if not GenFdsGlobalVariable.NeedsUpdate(Output, Input): - return - GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) - - Cmd = [ToolPath, ] - Cmd += Options.split(' ') - Cmd += ["-o", Output] - Cmd += Input - - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to call " + ToolPath, returnValue) - - def CallExternalTool (cmd, errorMess, returnValue=[]): - - if type(cmd) not in (tuple, list): - GenFdsGlobalVariable.ErrorLogger("ToolError! Invalid parameter type in call to CallExternalTool") - - if GenFdsGlobalVariable.DebugLevel != -1: - cmd += ('--debug', str(GenFdsGlobalVariable.DebugLevel)) - GenFdsGlobalVariable.InfLogger (cmd) - - if GenFdsGlobalVariable.VerboseMode: - cmd += ('-v',) - GenFdsGlobalVariable.InfLogger (cmd) - else: - sys.stdout.write ('#') - sys.stdout.flush() - GenFdsGlobalVariable.SharpCounter = GenFdsGlobalVariable.SharpCounter + 1 - if GenFdsGlobalVariable.SharpCounter % GenFdsGlobalVariable.SharpNumberPerLine == 0: - sys.stdout.write('\n') - - try: - PopenObject = subprocess.Popen(' '.join(cmd), stdout=subprocess.PIPE, stderr= subprocess.PIPE, shell=True) - except Exception, X: - EdkLogger.error("GenFds", COMMAND_FAILURE, ExtraData="%s: %s" % (str(X), cmd[0])) - (out, error) = PopenObject.communicate() - - while PopenObject.returncode == None : - PopenObject.wait() - if returnValue != [] and returnValue[0] != 0: - #get command return value - returnValue[0] = PopenObject.returncode - return - if PopenObject.returncode != 0 or GenFdsGlobalVariable.VerboseMode or GenFdsGlobalVariable.DebugLevel != -1: - GenFdsGlobalVariable.InfLogger ("Return Value = %d" %PopenObject.returncode) - GenFdsGlobalVariable.InfLogger (out) - GenFdsGlobalVariable.InfLogger (error) - if PopenObject.returncode != 0: - print "###", cmd - EdkLogger.error("GenFds", COMMAND_FAILURE, errorMess) - - def VerboseLogger (msg): - EdkLogger.verbose(msg) - - def InfLogger (msg): - EdkLogger.info(msg) - - def ErrorLogger (msg, File = None, Line = None, ExtraData = None): - EdkLogger.error('GenFds', GENFDS_ERROR, msg, File, Line, ExtraData) - - def DebugLogger (Level, msg): - EdkLogger.debug(Level, msg) - - ## ReplaceWorkspaceMacro() - # - # @param Str String that may contain macro - # @param MacroDict Dictionary that contains macro value pair - # - def MacroExtend (Str, MacroDict = {}, Arch = 'COMMON'): - if Str == None : - return None - - Dict = {'$(WORKSPACE)' : GenFdsGlobalVariable.WorkSpaceDir, - '$(EDK_SOURCE)' : GenFdsGlobalVariable.EdkSourceDir, -# '$(OUTPUT_DIRECTORY)': GenFdsGlobalVariable.OutputDirFromDsc, - '$(TARGET)' : GenFdsGlobalVariable.TargetName, - '$(TOOL_CHAIN_TAG)' : GenFdsGlobalVariable.ToolChainTag - } - OutputDir = GenFdsGlobalVariable.OutputDirFromDscDict[GenFdsGlobalVariable.ArchList[0]] - if Arch != 'COMMON' and Arch in GenFdsGlobalVariable.ArchList: - OutputDir = GenFdsGlobalVariable.OutputDirFromDscDict[Arch] - - Dict['$(OUTPUT_DIRECTORY)'] = OutputDir - - if MacroDict != None and len (MacroDict) != 0: - Dict.update(MacroDict) - - for key in Dict.keys(): - if Str.find(key) >= 0 : - Str = Str.replace (key, Dict[key]) - - if Str.find('$(ARCH)') >= 0: - if len(GenFdsGlobalVariable.ArchList) == 1: - Str = Str.replace('$(ARCH)', GenFdsGlobalVariable.ArchList[0]) - else: - EdkLogger.error("GenFds", GENFDS_ERROR, "No way to determine $(ARCH) for %s" % Str) - - return Str - - ## GetPcdValue() - # - # @param PcdPattern pattern that labels a PCD. - # - def GetPcdValue (PcdPattern): - if PcdPattern == None : - return None - PcdPair = PcdPattern.lstrip('PCD(').rstrip(')').strip().split('.') - TokenSpace = PcdPair[0] - TokenCName = PcdPair[1] - - PcdValue = '' - for Arch in GenFdsGlobalVariable.ArchList: - Platform = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] - PcdDict = Platform.Pcds - for Key in PcdDict: - PcdObj = PcdDict[Key] - if (PcdObj.TokenCName == TokenCName) and (PcdObj.TokenSpaceGuidCName == TokenSpace): - if PcdObj.Type != 'FixedAtBuild': - EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not FixedAtBuild type." % PcdPattern) - if PcdObj.DatumType != 'VOID*': - EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not VOID* datum type." % PcdPattern) - - PcdValue = PcdObj.DefaultValue - return PcdValue - - for Package in GenFdsGlobalVariable.WorkSpace.GetPackageList(GenFdsGlobalVariable.ActivePlatform, - Arch, - GenFdsGlobalVariable.TargetName, - GenFdsGlobalVariable.ToolChainTag): - PcdDict = Package.Pcds - for Key in PcdDict: - PcdObj = PcdDict[Key] - if (PcdObj.TokenCName == TokenCName) and (PcdObj.TokenSpaceGuidCName == TokenSpace): - if PcdObj.Type != 'FixedAtBuild': - EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not FixedAtBuild type." % PcdPattern) - if PcdObj.DatumType != 'VOID*': - EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not VOID* datum type." % PcdPattern) - - PcdValue = PcdObj.DefaultValue - return PcdValue - - return PcdValue - - SetDir = staticmethod(SetDir) - ReplaceWorkspaceMacro = staticmethod(ReplaceWorkspaceMacro) - CallExternalTool = staticmethod(CallExternalTool) - VerboseLogger = staticmethod(VerboseLogger) - InfLogger = staticmethod(InfLogger) - ErrorLogger = staticmethod(ErrorLogger) - DebugLogger = staticmethod(DebugLogger) - MacroExtend = staticmethod (MacroExtend) - GetPcdValue = staticmethod(GetPcdValue) + + @staticmethod + def GenerateFfs(Output, Input, Type, Guid, Fixed=False, CheckSum=False, Align=None, + SectionAlign=None): + Cmd = ["GenFfs", "-t", Type, "-g", Guid] + if Fixed == True: + Cmd += ["-x"] + if CheckSum: + Cmd += ["-s"] + if Align not in [None, '']: + Cmd += ["-a", Align] + + Cmd += ["-o", Output] + for I in range(0, len(Input)): + Cmd += ("-i", Input[I]) + if SectionAlign not in [None, '', []] and SectionAlign[I] not in [None, '']: + Cmd += ("-n", SectionAlign[I]) + + CommandFile = Output + '.txt' + SaveFileOnChange(CommandFile, ' '.join(Cmd), False) + if not GenFdsGlobalVariable.NeedsUpdate(Output, list(Input) + [CommandFile]): + return + GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) + + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate FFS") + + @staticmethod + def GenerateFirmwareVolume(Output, Input, BaseAddress=None, ForceRebase=None, Capsule=False, Dump=False, + AddressFile=None, MapFile=None, FfsList=[], FileSystemGuid=None): + if not GenFdsGlobalVariable.NeedsUpdate(Output, Input+FfsList): + return + GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) + + Cmd = ["GenFv"] + if BaseAddress not in [None, '']: + Cmd += ["-r", BaseAddress] + + if ForceRebase == False: + Cmd +=["-F", "FALSE"] + elif ForceRebase == True: + Cmd +=["-F", "TRUE"] + + if Capsule: + Cmd += ["-c"] + if Dump: + Cmd += ["-p"] + if AddressFile not in [None, '']: + Cmd += ["-a", AddressFile] + if MapFile not in [None, '']: + Cmd += ["-m", MapFile] + if FileSystemGuid: + Cmd += ["-g", FileSystemGuid] + Cmd += ["-o", Output] + for I in Input: + Cmd += ["-i", I] + + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate FV") + + @staticmethod + def GenerateVtf(Output, Input, BaseAddress=None, FvSize=None): + if not GenFdsGlobalVariable.NeedsUpdate(Output, Input): + return + GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) + + Cmd = ["GenVtf"] + if BaseAddress not in [None, ''] and FvSize not in [None, ''] \ + and len(BaseAddress) == len(FvSize): + for I in range(0, len(BaseAddress)): + Cmd += ["-r", BaseAddress[I], "-s", FvSize[I]] + Cmd += ["-o", Output] + for F in Input: + Cmd += ["-f", F] + + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate VTF") + + @staticmethod + def GenerateFirmwareImage(Output, Input, Type="efi", SubType=None, Zero=False, + Strip=False, Replace=False, TimeStamp=None, Join=False, + Align=None, Padding=None, Convert=False): + if not GenFdsGlobalVariable.NeedsUpdate(Output, Input): + return + GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) + + Cmd = ["GenFw"] + if Type.lower() == "te": + Cmd += ["-t"] + if SubType not in [None, '']: + Cmd += ["-e", SubType] + if TimeStamp not in [None, '']: + Cmd += ["-s", TimeStamp] + if Align not in [None, '']: + Cmd += ["-a", Align] + if Padding not in [None, '']: + Cmd += ["-p", Padding] + if Zero: + Cmd += ["-z"] + if Strip: + Cmd += ["-l"] + if Replace: + Cmd += ["-r"] + if Join: + Cmd += ["-j"] + if Convert: + Cmd += ["-m"] + Cmd += ["-o", Output] + Cmd += Input + + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate firmware image") + + @staticmethod + def GenerateOptionRom(Output, EfiInput, BinaryInput, Compress=False, ClassCode=None, + Revision=None, DeviceId=None, VendorId=None): + InputList = [] + Cmd = ["EfiRom"] + if len(EfiInput) > 0: + + if Compress: + Cmd += ["-ec"] + else: + Cmd += ["-e"] + + for EfiFile in EfiInput: + Cmd += [EfiFile] + InputList.append (EfiFile) + + if len(BinaryInput) > 0: + Cmd += ["-b"] + for BinFile in BinaryInput: + Cmd += [BinFile] + InputList.append (BinFile) + + # Check List + if not GenFdsGlobalVariable.NeedsUpdate(Output, InputList): + return + GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, InputList)) + + if ClassCode != None: + Cmd += ["-l", ClassCode] + if Revision != None: + Cmd += ["-r", Revision] + if DeviceId != None: + Cmd += ["-i", DeviceId] + if VendorId != None: + Cmd += ["-f", VendorId] + + Cmd += ["-o", Output] + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to generate option rom") + + @staticmethod + def GuidTool(Output, Input, ToolPath, Options='', returnValue=[]): + if not GenFdsGlobalVariable.NeedsUpdate(Output, Input): + return + GenFdsGlobalVariable.DebugLogger(EdkLogger.DEBUG_5, "%s needs update because of newer %s" % (Output, Input)) + + Cmd = [ToolPath, ] + Cmd += Options.split(' ') + Cmd += ["-o", Output] + Cmd += Input + + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to call " + ToolPath, returnValue) + + def CallExternalTool (cmd, errorMess, returnValue=[]): + + if type(cmd) not in (tuple, list): + GenFdsGlobalVariable.ErrorLogger("ToolError! Invalid parameter type in call to CallExternalTool") + + if GenFdsGlobalVariable.DebugLevel != -1: + cmd += ('--debug', str(GenFdsGlobalVariable.DebugLevel)) + GenFdsGlobalVariable.InfLogger (cmd) + + if GenFdsGlobalVariable.VerboseMode: + cmd += ('-v',) + GenFdsGlobalVariable.InfLogger (cmd) + else: + sys.stdout.write ('#') + sys.stdout.flush() + GenFdsGlobalVariable.SharpCounter = GenFdsGlobalVariable.SharpCounter + 1 + if GenFdsGlobalVariable.SharpCounter % GenFdsGlobalVariable.SharpNumberPerLine == 0: + sys.stdout.write('\n') + + try: + PopenObject = subprocess.Popen(' '.join(cmd), stdout=subprocess.PIPE, stderr= subprocess.PIPE, shell=True) + except Exception, X: + EdkLogger.error("GenFds", COMMAND_FAILURE, ExtraData="%s: %s" % (str(X), cmd[0])) + (out, error) = PopenObject.communicate() + + while PopenObject.returncode == None : + PopenObject.wait() + if returnValue != [] and returnValue[0] != 0: + #get command return value + returnValue[0] = PopenObject.returncode + return + if PopenObject.returncode != 0 or GenFdsGlobalVariable.VerboseMode or GenFdsGlobalVariable.DebugLevel != -1: + GenFdsGlobalVariable.InfLogger ("Return Value = %d" %PopenObject.returncode) + GenFdsGlobalVariable.InfLogger (out) + GenFdsGlobalVariable.InfLogger (error) + if PopenObject.returncode != 0: + print "###", cmd + EdkLogger.error("GenFds", COMMAND_FAILURE, errorMess) + + def VerboseLogger (msg): + EdkLogger.verbose(msg) + + def InfLogger (msg): + EdkLogger.info(msg) + + def ErrorLogger (msg, File = None, Line = None, ExtraData = None): + EdkLogger.error('GenFds', GENFDS_ERROR, msg, File, Line, ExtraData) + + def DebugLogger (Level, msg): + EdkLogger.debug(Level, msg) + + ## ReplaceWorkspaceMacro() + # + # @param Str String that may contain macro + # @param MacroDict Dictionary that contains macro value pair + # + def MacroExtend (Str, MacroDict = {}, Arch = 'COMMON'): + if Str == None : + return None + + Dict = {'$(WORKSPACE)' : GenFdsGlobalVariable.WorkSpaceDir, + '$(EDK_SOURCE)' : GenFdsGlobalVariable.EdkSourceDir, +# '$(OUTPUT_DIRECTORY)': GenFdsGlobalVariable.OutputDirFromDsc, + '$(TARGET)' : GenFdsGlobalVariable.TargetName, + '$(TOOL_CHAIN_TAG)' : GenFdsGlobalVariable.ToolChainTag + } + OutputDir = GenFdsGlobalVariable.OutputDirFromDscDict[GenFdsGlobalVariable.ArchList[0]] + if Arch != 'COMMON' and Arch in GenFdsGlobalVariable.ArchList: + OutputDir = GenFdsGlobalVariable.OutputDirFromDscDict[Arch] + + Dict['$(OUTPUT_DIRECTORY)'] = OutputDir + + if MacroDict != None and len (MacroDict) != 0: + Dict.update(MacroDict) + + for key in Dict.keys(): + if Str.find(key) >= 0 : + Str = Str.replace (key, Dict[key]) + + if Str.find('$(ARCH)') >= 0: + if len(GenFdsGlobalVariable.ArchList) == 1: + Str = Str.replace('$(ARCH)', GenFdsGlobalVariable.ArchList[0]) + else: + EdkLogger.error("GenFds", GENFDS_ERROR, "No way to determine $(ARCH) for %s" % Str) + + return Str + + ## GetPcdValue() + # + # @param PcdPattern pattern that labels a PCD. + # + def GetPcdValue (PcdPattern): + if PcdPattern == None : + return None + PcdPair = PcdPattern.lstrip('PCD(').rstrip(')').strip().split('.') + TokenSpace = PcdPair[0] + TokenCName = PcdPair[1] + + PcdValue = '' + for Arch in GenFdsGlobalVariable.ArchList: + Platform = GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag] + PcdDict = Platform.Pcds + for Key in PcdDict: + PcdObj = PcdDict[Key] + if (PcdObj.TokenCName == TokenCName) and (PcdObj.TokenSpaceGuidCName == TokenSpace): + if PcdObj.Type != 'FixedAtBuild': + EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not FixedAtBuild type." % PcdPattern) + if PcdObj.DatumType != 'VOID*': + EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not VOID* datum type." % PcdPattern) + + PcdValue = PcdObj.DefaultValue + return PcdValue + + for Package in GenFdsGlobalVariable.WorkSpace.GetPackageList(GenFdsGlobalVariable.ActivePlatform, + Arch, + GenFdsGlobalVariable.TargetName, + GenFdsGlobalVariable.ToolChainTag): + PcdDict = Package.Pcds + for Key in PcdDict: + PcdObj = PcdDict[Key] + if (PcdObj.TokenCName == TokenCName) and (PcdObj.TokenSpaceGuidCName == TokenSpace): + if PcdObj.Type != 'FixedAtBuild': + EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not FixedAtBuild type." % PcdPattern) + if PcdObj.DatumType != 'VOID*': + EdkLogger.error("GenFds", GENFDS_ERROR, "%s is not VOID* datum type." % PcdPattern) + + PcdValue = PcdObj.DefaultValue + return PcdValue + + return PcdValue + + SetDir = staticmethod(SetDir) + ReplaceWorkspaceMacro = staticmethod(ReplaceWorkspaceMacro) + CallExternalTool = staticmethod(CallExternalTool) + VerboseLogger = staticmethod(VerboseLogger) + InfLogger = staticmethod(InfLogger) + ErrorLogger = staticmethod(ErrorLogger) + DebugLogger = staticmethod(DebugLogger) + MacroExtend = staticmethod (MacroExtend) + GetPcdValue = staticmethod(GetPcdValue) -- cgit v1.2.3