Check In tool source code based on Build tool project revision r1655.

git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@8964 6f19259b-4bc3-4df7-8a09-765794883524
This commit is contained in:
lgao4
2009-07-17 09:10:31 +00:00
parent 577e30cdb4
commit 30fdf1140b
532 changed files with 231447 additions and 32 deletions

View File

@@ -0,0 +1,327 @@
## @file
# Collects the Guid Information in current workspace.
#
# Copyright (c) 2007, 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 fnmatch
from Common.EdkIIWorkspace import EdkIIWorkspace
from Common.MigrationUtilities import *
## A class for EdkII work space to resolve Guids
#
# This class inherits from EdkIIWorkspace and collects the Guids information
# in current workspace. The Guids information is important to translate the
# package Guids and recommended library instances Guids to relative file path
# (to workspace directory) in MSA files.
#
class EdkIIWorkspaceGuidsInfo(EdkIIWorkspace):
## The classconstructor
#
# The constructor initialize workspace directory. It does not collect
# pakage and module Guids info at initialization; instead, it collects them
# on the fly.
#
# @param self The object pointer
#
def __init__(self):
# Initialize parent class.
EdkIIWorkspace.__init__(self)
# The internal map from Guid to FilePath.
self.__GuidToFilePath = {}
# The internal package directory list.
self.__PackageDirList = []
# The internal flag to indicate whether package Guids info has been initialized
# to avoid re-collection collected.
self.__PackageGuidInitialized = False
# The internal flag to indicate whether module Guids info has been initialized
# to avoid re-collection collected.
self.__ModuleGuidInitialized = False
## Add Guid, Version and FilePath to Guids database
#
# Add Guid, Version and FilePath to Guids database. It constructs a map
# table from Guid, Version to FilePath internally. If also detects possible
# Guid collision. For now, the version information is simply ignored and
# Guid value itself acts as master key.
#
# @param self The object pointer
# @param Guid The Guid Value
# @param Version The version information
# @param FilePath The Guid related file path
#
# @retval True The Guid value is successfully added to map table
# @retval False The Guid is an empty string or the map table
# already contains a same Guid
#
def __AddGuidToFilePath(self, Guid, Version, FilePath):
if Guid == "":
EdkLogger.info("Cannot find Guid in file %s" % FilePath)
return False
#Add the Guid value to map table to ensure case insensitive comparison.
OldFilePath = self.__GuidToFilePath.setdefault(Guid.lower(), FilePath)
if OldFilePath == FilePath:
EdkLogger.verbose("File %s has new Guid '%s'" % (FilePath, Guid))
return True
else:
EdkLogger.info("File %s has duplicate Guid with & %s" % (FilePath, OldFilePath))
return False
## Gets file information from a module description file
#
# Extracts Module Name, File Guid and Version number from INF, MSA and NMSA
# file. It supports to exact such information from text based INF file or
# XML based (N)MSA file.
#
# @param self The object pointer
# @param FileName The input module file name
#
# @retval True This module file represents a new module discovered
# in current workspace
# @retval False This module file is not regarded as a valid module
# The File Guid cannot be extracted or the another
# file with the same Guid already exists
#
def __GetModuleFileInfo(self, FileName):
if fnmatch.fnmatch(FileName, "*.inf"):
TagTuple = ("BASE_NAME", "FILE_GUID", "VERSION_STRING")
(Name, Guid, Version) = GetTextFileInfo(FileName, TagTuple)
else :
XmlTag1 = "ModuleSurfaceArea/MsaHeader/ModuleName"
XmlTag2 = "ModuleSurfaceArea/MsaHeader/GuidValue"
XmlTag3 = "ModuleSurfaceArea/MsaHeader/Version"
TagTuple = (XmlTag1, XmlTag2, XmlTag3)
(Name, Guid, Version) = GetXmlFileInfo(FileName, TagTuple)
return self.__AddGuidToFilePath(Guid, Version, FileName)
## Gets file information from a package description file
#
# Extracts Package Name, File Guid and Version number from INF, SPD and NSPD
# file. It supports to exact such information from text based DEC file or
# XML based (N)SPD file. EDK Compatibility Package is hardcoded to be
# ignored since no EDKII INF file depends on that package.
#
# @param self The object pointer
# @param FileName The input package file name
#
# @retval True This package file represents a new package
# discovered in current workspace
# @retval False This package is not regarded as a valid package
# The File Guid cannot be extracted or the another
# file with the same Guid already exists
#
def __GetPackageFileInfo(self, FileName):
if fnmatch.fnmatch(FileName, "*.dec"):
TagTuple = ("PACKAGE_NAME", "PACKAGE_GUID", "PACKAGE_VERSION")
(Name, Guid, Version) = GetTextFileInfo(FileName, TagTuple)
else:
XmlTag1 = "PackageSurfaceArea/SpdHeader/PackageName"
XmlTag2 = "PackageSurfaceArea/SpdHeader/GuidValue"
XmlTag3 = "PackageSurfaceArea/SpdHeader/Version"
TagTuple = (XmlTag1, XmlTag2, XmlTag3)
(Name, Guid, Version) = GetXmlFileInfo(FileName, TagTuple)
if Name == "EdkCompatibilityPkg":
# Do not scan EDK compatibitilty package to avoid Guid collision
# with those in EDK Glue Library.
EdkLogger.verbose("Bypass EDK Compatibility Pkg")
return False
return self.__AddGuidToFilePath(Guid, Version, FileName)
## Iterate on all package files listed in framework database file
#
# Yields all package description files listed in framework database files.
# The framework database file describes the packages current workspace
# includes.
#
# @param self The object pointer
#
def __FrameworkDatabasePackageFiles(self):
XmlFrameworkDb = XmlParseFile(self.WorkspaceFile)
XmlTag = "FrameworkDatabase/PackageList/Filename"
for PackageFile in XmlElementList(XmlFrameworkDb, XmlTag):
yield os.path.join(self.WorkspaceDir, PackageFile)
## Iterate on all package files in current workspace directory
#
# Yields all package description files listed in current workspace
# directory. This happens when no framework database file exists.
#
# @param self The object pointer
#
def __TraverseAllPackageFiles(self):
for Path, Dirs, Files in os.walk(self.WorkspaceDir):
# Ignore svn version control directory.
if ".svn" in Dirs:
Dirs.remove(".svn")
if "Build" in Dirs:
Dirs.remove("Build")
# Assume priority from high to low: DEC, NSPD, SPD.
PackageFiles = fnmatch.filter(Files, "*.dec")
if len(PackageFiles) == 0:
PackageFiles = fnmatch.filter(Files, "*.nspd")
if len(PackageFiles) == 0:
PackageFiles = fnmatch.filter(Files, "*.spd")
for File in PackageFiles:
# Assume no more package decription file in sub-directory.
del Dirs[:]
yield os.path.join(Path, File)
## Iterate on all module files in current package directory
#
# Yields all module description files listed in current package
# directory.
#
# @param self The object pointer
#
def __TraverseAllModuleFiles(self):
for PackageDir in self.__PackageDirList:
for Path, Dirs, Files in os.walk(PackageDir):
# Ignore svn version control directory.
if ".svn" in Dirs:
Dirs.remove(".svn")
# Assume priority from high to low: INF, NMSA, MSA.
ModuleFiles = fnmatch.filter(Files, "*.inf")
if len(ModuleFiles) == 0:
ModuleFiles = fnmatch.filter(Files, "*.nmsa")
if len(ModuleFiles) == 0:
ModuleFiles = fnmatch.filter(Files, "*.msa")
for File in ModuleFiles:
yield os.path.join(Path, File)
## Initialize package Guids info mapping table
#
# Collects all package guids map to package decription file path. This
# function is invokes on demand to avoid unnecessary directory scan.
#
# @param self The object pointer
#
def __InitializePackageGuidInfo(self):
if self.__PackageGuidInitialized:
return
EdkLogger.verbose("Start to collect Package Guids Info.")
WorkspaceFile = os.path.join("Conf", "FrameworkDatabase.db")
self.WorkspaceFile = os.path.join(self.WorkspaceDir, WorkspaceFile)
# Try to find the frameworkdatabase file to discover package lists
if os.path.exists(self.WorkspaceFile):
TraversePackage = self.__FrameworkDatabasePackageFiles
EdkLogger.verbose("Package list bases on: %s" % self.WorkspaceFile)
else:
TraversePackage = self.__TraverseAllPackageFiles
EdkLogger.verbose("Package list in: %s" % self.WorkspaceDir)
for FileName in TraversePackage():
if self.__GetPackageFileInfo(FileName):
PackageDir = os.path.dirname(FileName)
EdkLogger.verbose("Find new package directory %s" % PackageDir)
self.__PackageDirList.append(PackageDir)
self.__PackageGuidInitialized = True
## Initialize module Guids info mapping table
#
# Collects all module guids map to module decription file path. This
# function is invokes on demand to avoid unnecessary directory scan.
#
# @param self The object pointer
#
def __InitializeModuleGuidInfo(self):
if self.__ModuleGuidInitialized:
return
EdkLogger.verbose("Start to collect Module Guids Info")
self.__InitializePackageGuidInfo()
for FileName in self.__TraverseAllModuleFiles():
if self.__GetModuleFileInfo(FileName):
EdkLogger.verbose("Find new module %s" % FileName)
self.__ModuleGuidInitialized = True
## Get Package file path by Package Guid and Version
#
# Translates the Package Guid and Version to a file path relative
# to workspace directory. If no package in current workspace match the
# input Guid, an empty file path is returned. For now, the version
# value is simply ignored.
#
# @param self The object pointer
# @param Guid The Package Guid value to look for
# @param Version The Package Version value to look for
#
def ResolvePackageFilePath(self, Guid, Version = ""):
self.__InitializePackageGuidInfo()
EdkLogger.verbose("Resolve Package Guid '%s'" % Guid)
FileName = self.__GuidToFilePath.get(Guid.lower(), "")
if FileName == "":
EdkLogger.info("Cannot resolve Package Guid '%s'" % Guid)
else:
FileName = self.WorkspaceRelativePath(FileName)
FileName = os.path.splitext(FileName)[0] + ".dec"
FileName = FileName.replace("\\", "/")
return FileName
## Get Module file path by Module Guid and Version
#
# Translates the Module Guid and Version to a file path relative
# to workspace directory. If no module in current workspace match the
# input Guid, an empty file path is returned. For now, the version
# value is simply ignored.
#
# @param self The object pointer
# @param Guid The Module Guid value to look for
# @param Version The Module Version value to look for
#
def ResolveModuleFilePath(self, Guid, Version = ""):
self.__InitializeModuleGuidInfo()
EdkLogger.verbose("Resolve Module Guid '%s'" % Guid)
FileName = self.__GuidToFilePath.get(Guid.lower(), "")
if FileName == "":
EdkLogger.info("Cannot resolve Module Guid '%s'" % Guid)
else:
FileName = self.WorkspaceRelativePath(FileName)
FileName = os.path.splitext(FileName)[0] + ".inf"
FileName = FileName.replace("\\", "/")
return FileName
# A global class object of EdkIIWorkspaceGuidsInfo for external reference.
gEdkIIWorkspaceGuidsInfo = EdkIIWorkspaceGuidsInfo()
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
# Test the translation of package Guid.
# MdePkgGuid = "1E73767F-8F52-4603-AEB4-F29B510B6766"
# OldMdePkgGuid = "5e0e9358-46b6-4ae2-8218-4ab8b9bbdcec"
# print gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath(MdePkgGuid)
# print gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath(OldMdePkgGuid)
# Test the translation of module Guid.
# UefiLibGuid = "3a004ba5-efe0-4a61-9f1a-267a46ae5ba9"
# UefiDriverModelLibGuid = "52af22ae-9901-4484-8cdc-622dd5838b09"
# print gEdkIIWorkspaceGuidsInfo.ResolvePlatformFilePath(UefiLibGuid)
# print gEdkIIWorkspaceGuidsInfo.ResolvePlatformFilePath(UefiDriverModelLibGuid)
pass

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,563 @@
## @file
# Contains several utilitities shared by migration tools.
#
# Copyright (c) 2007, 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 re
import EdkLogger
from optparse import OptionParser
from Common.BuildToolError import *
from XmlRoutines import *
from CommonDataClass.CommonClass import *
## Set all fields of CommonClass object.
#
# Set all attributes of CommonClass object from XML Dom object of XmlCommon.
#
# @param Common The destine CommonClass object.
# @param XmlCommon The source XML Dom object.
#
def SetCommon(Common, XmlCommon):
XmlTag = "Usage"
Common.Usage = XmlAttribute(XmlCommon, XmlTag).split()
XmlTag = "FeatureFlag"
Common.FeatureFlag = XmlAttribute(XmlCommon, XmlTag)
XmlTag = "SupArchList"
Common.SupArchList = XmlAttribute(XmlCommon, XmlTag).split()
XmlTag = XmlNodeName(XmlCommon) + "/" + "HelpText"
Common.HelpText = XmlElement(XmlCommon, XmlTag)
## Set some fields of CommonHeaderClass object.
#
# Set Name, Guid, FileName and FullPath fields of CommonHeaderClass object from
# XML Dom object of XmlCommonHeader, NameTag and FileName.
#
# @param CommonHeader The destine CommonClass object.
# @param XmlCommonHeader The source XML Dom object.
# @param NameTag The name tag in XML Dom object.
# @param FileName The file name of the XML file.
#
def SetIdentification(CommonHeader, XmlCommonHeader, NameTag, FileName):
XmlParentTag = XmlNodeName(XmlCommonHeader)
XmlTag = XmlParentTag + "/" + NameTag
CommonHeader.Name = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParentTag + "/" + "GuidValue"
CommonHeader.Guid = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParentTag + "/" + "Version"
CommonHeader.Version = XmlElement(XmlCommonHeader, XmlTag)
CommonHeader.FileName = os.path.basename(FileName)
CommonHeader.FullPath = os.path.abspath(FileName)
## Regular expression to match specification and value.
mReSpecification = re.compile(r"(?P<Specification>\w+)\s+(?P<Value>\w*)")
## Add specification to specification dictionary.
#
# Abstract specification name, value pair from Specification String and add them
# to specification dictionary.
#
# @param SpecificationDict The destine Specification dictionary.
# @param SpecificationString The source Specification String from which the
# specification name and value pair is abstracted.
#
def AddToSpecificationDict(SpecificationDict, SpecificationString):
"""Abstract specification name, value pair from Specification String"""
for SpecificationMatch in mReSpecification.finditer(SpecificationString):
Specification = SpecificationMatch.group("Specification")
Value = SpecificationMatch.group("Value")
SpecificationDict[Specification] = Value
## Set all fields of CommonHeaderClass object.
#
# Set all attributes of CommonHeaderClass object from XML Dom object of
# XmlCommonHeader, NameTag and FileName.
#
# @param CommonHeader The destine CommonClass object.
# @param XmlCommonHeader The source XML Dom object.
# @param NameTag The name tag in XML Dom object.
# @param FileName The file name of the XML file.
#
def SetCommonHeader(CommonHeader, XmlCommonHeader):
"""Set all attributes of CommonHeaderClass object from XmlCommonHeader"""
XmlParent = XmlNodeName(XmlCommonHeader)
XmlTag = XmlParent + "/" + "Abstract"
CommonHeader.Abstract = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParent + "/" + "Description"
CommonHeader.Description = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParent + "/" + "Copyright"
CommonHeader.Copyright = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParent + "/" + "License"
CommonHeader.License = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParent + "/" + "Specification"
Specification = XmlElement(XmlCommonHeader, XmlTag)
AddToSpecificationDict(CommonHeader.Specification, Specification)
XmlTag = XmlParent + "/" + "ModuleType"
CommonHeader.ModuleType = XmlElement(XmlCommonHeader, XmlTag)
## Load a new Cloned Record class object.
#
# Read an input XML ClonedRecord DOM object and return an object of Cloned Record
# contained in the DOM object.
#
# @param XmlCloned A child XML DOM object in a Common XML DOM.
#
# @retvel ClonedRecord A new Cloned Record object created by XmlCloned.
#
def LoadClonedRecord(XmlCloned):
ClonedRecord = ClonedRecordClass()
XmlTag = "Id"
ClonedRecord.Id = int(XmlAttribute(XmlCloned, XmlTag))
XmlTag = "FarGuid"
ClonedRecord.FarGuid = XmlAttribute(XmlCloned, XmlTag)
XmlTag = "Cloned/PackageGuid"
ClonedRecord.PackageGuid = XmlElement(XmlCloned, XmlTag)
XmlTag = "Cloned/PackageVersion"
ClonedRecord.PackageVersion = XmlElement(XmlCloned, XmlTag)
XmlTag = "Cloned/ModuleGuid"
ClonedRecord.ModuleGuid = XmlElement(XmlCloned, XmlTag)
XmlTag = "Cloned/ModuleVersion"
ClonedRecord.ModuleVersion = XmlElement(XmlCloned, XmlTag)
return ClonedRecord
## Load a new Guid/Protocol/Ppi common class object.
#
# Read an input XML Guid/Protocol/Ppi DOM object and return an object of
# Guid/Protocol/Ppi contained in the DOM object.
#
# @param XmlGuidProtocolPpiCommon A child XML DOM object in a Common XML DOM.
#
# @retvel GuidProtocolPpiCommon A new GuidProtocolPpiCommon class object
# created by XmlGuidProtocolPpiCommon.
#
def LoadGuidProtocolPpiCommon(XmlGuidProtocolPpiCommon):
GuidProtocolPpiCommon = GuidProtocolPpiCommonClass()
XmlTag = "Name"
GuidProtocolPpiCommon.Name = XmlAttribute(XmlGuidProtocolPpiCommon, XmlTag)
XmlParent = XmlNodeName(XmlGuidProtocolPpiCommon)
if XmlParent == "Entry":
XmlTag = "%s/C_Name" % XmlParent
elif XmlParent == "GuidCNames":
XmlTag = "%s/GuidCName" % XmlParent
else:
XmlTag = "%s/%sCName" % (XmlParent, XmlParent)
GuidProtocolPpiCommon.CName = XmlElement(XmlGuidProtocolPpiCommon, XmlTag)
XmlTag = XmlParent + "/" + "GuidValue"
GuidProtocolPpiCommon.Guid = XmlElement(XmlGuidProtocolPpiCommon, XmlTag)
if XmlParent.endswith("Notify"):
GuidProtocolPpiCommon.Notify = True
XmlTag = "GuidTypeList"
GuidTypes = XmlAttribute(XmlGuidProtocolPpiCommon, XmlTag)
GuidProtocolPpiCommon.GuidTypeList = GuidTypes.split()
XmlTag = "SupModuleList"
SupModules = XmlAttribute(XmlGuidProtocolPpiCommon, XmlTag)
GuidProtocolPpiCommon.SupModuleList = SupModules.split()
SetCommon(GuidProtocolPpiCommon, XmlGuidProtocolPpiCommon)
return GuidProtocolPpiCommon
## Load a new Pcd class object.
#
# Read an input XML Pcd DOM object and return an object of Pcd
# contained in the DOM object.
#
# @param XmlPcd A child XML DOM object in a Common XML DOM.
#
# @retvel Pcd A new Pcd object created by XmlPcd.
#
def LoadPcd(XmlPcd):
"""Return a new PcdClass object equivalent to XmlPcd"""
Pcd = PcdClass()
XmlTag = "PcdEntry/C_Name"
Pcd.CName = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/Token"
Pcd.Token = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/TokenSpaceGuidCName"
Pcd.TokenSpaceGuidCName = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/DatumType"
Pcd.DatumType = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/MaxDatumSize"
Pcd.MaxDatumSize = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/DefaultValue"
Pcd.DefaultValue = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdItemType"
Pcd.ItemType = XmlAttribute(XmlPcd, XmlTag)
XmlTag = "PcdEntry/ValidUsage"
Pcd.ValidUsage = XmlElement(XmlPcd, XmlTag).split()
XmlTag = "SupModuleList"
Pcd.SupModuleList = XmlAttribute(XmlPcd, XmlTag).split()
SetCommon(Pcd, XmlPcd)
return Pcd
## Load a new LibraryClass class object.
#
# Read an input XML LibraryClass DOM object and return an object of LibraryClass
# contained in the DOM object.
#
# @param XmlLibraryClass A child XML DOM object in a Common XML DOM.
#
# @retvel LibraryClass A new LibraryClass object created by XmlLibraryClass.
#
def LoadLibraryClass(XmlLibraryClass):
LibraryClass = LibraryClassClass()
XmlTag = "LibraryClass/Keyword"
LibraryClass.LibraryClass = XmlElement(XmlLibraryClass, XmlTag)
if LibraryClass.LibraryClass == "":
XmlTag = "Name"
LibraryClass.LibraryClass = XmlAttribute(XmlLibraryClass, XmlTag)
XmlTag = "LibraryClass/IncludeHeader"
LibraryClass.IncludeHeader = XmlElement(XmlLibraryClass, XmlTag)
XmlTag = "RecommendedInstanceVersion"
RecommendedInstanceVersion = XmlAttribute(XmlLibraryClass, XmlTag)
LibraryClass.RecommendedInstanceVersion = RecommendedInstanceVersion
XmlTag = "RecommendedInstanceGuid"
RecommendedInstanceGuid = XmlAttribute(XmlLibraryClass, XmlTag)
LibraryClass.RecommendedInstanceGuid = RecommendedInstanceGuid
XmlTag = "SupModuleList"
SupModules = XmlAttribute(XmlLibraryClass, XmlTag)
LibraryClass.SupModuleList = SupModules.split()
SetCommon(LibraryClass, XmlLibraryClass)
return LibraryClass
## Load a new Build Option class object.
#
# Read an input XML BuildOption DOM object and return an object of Build Option
# contained in the DOM object.
#
# @param XmlBuildOption A child XML DOM object in a Common XML DOM.
#
# @retvel BuildOption A new Build Option object created by XmlBuildOption.
#
def LoadBuildOption(XmlBuildOption):
"""Return a new BuildOptionClass object equivalent to XmlBuildOption"""
BuildOption = BuildOptionClass()
BuildOption.Option = XmlElementData(XmlBuildOption)
XmlTag = "BuildTargets"
BuildOption.BuildTargetList = XmlAttribute(XmlBuildOption, XmlTag).split()
XmlTag = "ToolChainFamily"
BuildOption.ToolChainFamily = XmlAttribute(XmlBuildOption, XmlTag)
XmlTag = "TagName"
BuildOption.TagName = XmlAttribute(XmlBuildOption, XmlTag)
XmlTag = "ToolCode"
BuildOption.ToolCode = XmlAttribute(XmlBuildOption, XmlTag)
XmlTag = "SupArchList"
BuildOption.SupArchList = XmlAttribute(XmlBuildOption, XmlTag).split()
return BuildOption
## Load a new User Extensions class object.
#
# Read an input XML UserExtensions DOM object and return an object of User
# Extensions contained in the DOM object.
#
# @param XmlUserExtensions A child XML DOM object in a Common XML DOM.
#
# @retvel UserExtensions A new User Extensions object created by
# XmlUserExtensions.
#
def LoadUserExtensions(XmlUserExtensions):
UserExtensions = UserExtensionsClass()
XmlTag = "UserId"
UserExtensions.UserID = XmlAttribute(XmlUserExtensions, XmlTag)
XmlTag = "Identifier"
UserExtensions.Identifier = XmlAttribute(XmlUserExtensions, XmlTag)
UserExtensions.Content = XmlElementData(XmlUserExtensions)
return UserExtensions
## Store content to a text file object.
#
# Write some text file content to a text file object. The contents may echo
# in screen in a verbose way.
#
# @param TextFile The text file object.
# @param Content The string object to be written to a text file.
#
def StoreTextFile(TextFile, Content):
EdkLogger.verbose(Content)
TextFile.write(Content)
## Add item to a section.
#
# Add an Item with specific CPU architecture to section dictionary.
# The possible duplication is ensured to be removed.
#
# @param Section Section dictionary indexed by CPU architecture.
# @param Arch CPU architecture: Ia32, X64, Ipf, Ebc or Common.
# @param Item The Item to be added to section dictionary.
#
def AddToSection(Section, Arch, Item):
SectionArch = Section.get(Arch, [])
if Item not in SectionArch:
SectionArch.append(Item)
Section[Arch] = SectionArch
## Get section contents.
#
# Return the content of section named SectionName.
# the contents is based on Methods and ObjectLists.
#
# @param SectionName The name of the section.
# @param Method A function returning a string item of an object.
# @param ObjectList The list of object.
#
# @retval Section The string content of a section.
#
def GetSection(SectionName, Method, ObjectList):
SupportedArches = ["common", "Ia32", "X64", "Ipf", "Ebc"]
SectionDict = {}
for Object in ObjectList:
Item = Method(Object)
if Item == "":
continue
Item = " %s" % Item
Arches = Object.SupArchList
if len(Arches) == 0:
AddToSection(SectionDict, "common", Item)
else:
for Arch in SupportedArches:
if Arch.upper() in Arches:
AddToSection(SectionDict, Arch, Item)
Section = ""
for Arch in SupportedArches:
SectionArch = "\n".join(SectionDict.get(Arch, []))
if SectionArch != "":
Section += "[%s.%s]\n%s\n" % (SectionName, Arch, SectionArch)
Section += "\n"
if Section != "":
Section += "\n"
return Section
## Store file header to a text file.
#
# Write standard file header to a text file. The content includes copyright,
# abstract, description and license extracted from CommonHeader class object.
#
# @param TextFile The text file object.
# @param CommonHeader The source CommonHeader class object.
#
def StoreHeader(TextFile, CommonHeader):
CopyRight = CommonHeader.Copyright
Abstract = CommonHeader.Abstract
Description = CommonHeader.Description
License = CommonHeader.License
Header = "#/** @file\n#\n"
Header += "# " + Abstract + "\n#\n"
Header += "# " + Description.strip().replace("\n", "\n# ") + "\n"
Header += "# " + CopyRight + "\n#\n"
Header += "# " + License.replace("\n", "\n# ").replace(" ", " ")
Header += "\n#\n#**/\n\n"
StoreTextFile(TextFile, Header)
## Store file header to a text file.
#
# Write Defines section to a text file. DefinesTupleList determines the content.
#
# @param TextFile The text file object.
# @param DefinesTupleList The list of (Tag, Value) to be added as one item.
#
def StoreDefinesSection(TextFile, DefinesTupleList):
Section = "[Defines]\n"
for DefineItem in DefinesTupleList:
Section += " %-30s = %s\n" % DefineItem
Section += "\n\n"
StoreTextFile(TextFile, Section)
## Add item to PCD dictionary.
#
# Add an PcdClass object to PCD dictionary. The key is generated from
# PcdItemType.
#
# @param PcdDict PCD dictionary indexed by Pcd Item Type.
# @param Arch CPU architecture: Ia32, X64, Ipf, Ebc or Common.
# @param Item The Item to be added to section dictionary.
#
def AddToPcdsDict(PcdDict, PcdItemType, PcdCode):
PcdSectionName = PcdItemType
PcdSectionName = PcdSectionName.title()
PcdSectionName = PcdSectionName.replace("_", "")
PcdSectionName = "Pcds" + PcdSectionName
PcdDict.setdefault(PcdSectionName, []).append(PcdCode)
## Regular expression to match an equation.
mReEquation = re.compile(r"\s*(\S+)\s*=\s*(\S*)\s*")
## Return a value tuple matching information in a text fle.
#
# Parse the text file and return a value tuple corresponding to an input tag
# tuple. In case of any error, an tuple of empty strings is returned.
#
# @param FileName The file name of the text file.
# @param TagTuple A tuple of tags as the key to the value.
#
# @param ValueTupe The returned tuple corresponding to the tag tuple.
#
def GetTextFileInfo(FileName, TagTuple):
ValueTuple = [""] * len(TagTuple)
try:
for Line in open(FileName):
Line = Line.split("#", 1)[0]
MatchEquation = mReEquation.match(Line)
if MatchEquation:
Tag = MatchEquation.group(1).upper()
Value = MatchEquation.group(2)
for Index in range(len(TagTuple)):
if TagTuple[Index] == Tag:
ValueTuple[Index] = Value
except:
EdkLogger.info("IO Error in reading file %s" % FileName)
return ValueTuple
## Return a value tuple matching information in an XML fle.
#
# Parse the XML file and return a value tuple corresponding to an input tag
# tuple. In case of any error, an tuple of empty strings is returned.
#
# @param FileName The file name of the XML file.
# @param TagTuple A tuple of tags as the key to the value.
#
# @param ValueTupe The returned tuple corresponding to the tag tuple.
#
def GetXmlFileInfo(FileName, TagTuple):
XmlDom = XmlParseFile(FileName)
return tuple([XmlElement(XmlDom, XmlTag) for XmlTag in TagTuple])
# Version and Copyright
__version_number__ = "1.0"
__version__ = "%prog Version " + __version_number__
__copyright__ = "Copyright (c) 2007, Intel Corporation. All rights reserved."
## Parse migration command line options
#
# Use standard Python module optparse to parse command line option of this tool.
#
# @param Source The source file type.
# @param Destinate The destinate file type.
#
# @retval Options A optparse object containing the parsed options.
# @retval InputFile Path of an source file to be migrated.
#
def MigrationOptionParser(Source, Destinate):
# use clearer usage to override default usage message
UsageString = "%prog [-a] [-o <output_file>] <input_file>"
Parser = OptionParser(description=__copyright__, version=__version__, usage=UsageString)
HelpText = "The name of the %s file to be created." % Destinate
Parser.add_option("-o", "--output", dest="OutputFile", help=HelpText)
HelpText = "Automatically create the %s file using the name of the %s file and replacing file extension" % (Source, Destinate)
Parser.add_option("-a", "--auto", dest="AutoWrite", action="store_true", default=False, help=HelpText)
Options, Args = Parser.parse_args()
# error check
if len(Args) == 0:
raise MigrationError(OPTION_MISSING, name="Input file", usage=Parser.get_usage())
if len(Args) > 1:
raise MigrationError(OPTION_NOT_SUPPORTED, name="Too many input files", usage=Parser.get_usage())
InputFile = Args[0]
if not os.path.exists(InputFile):
raise MigrationError(FILE_NOT_FOUND, name=InputFile)
if Options.OutputFile:
if Options.AutoWrite:
raise MigrationError(OPTION_CONFLICT, arg1="-o", arg2="-a", usage=Parser.get_usage())
else:
if Options.AutoWrite:
Options.OutputFile = os.path.splitext(InputFile)[0] + "." + Destinate.lower()
else:
raise MigrationError(OPTION_MISSING, name="-o", usage=Parser.get_usage())
return Options, InputFile
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
pass

View File

@@ -0,0 +1,765 @@
## @file
# Store a Platform class object to an INF file.
#
# Copyright (c) 2007 - 2009, 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 LoadFpd import LoadFpd
from CommonDataClass.PlatformClass import *
from CommonDataClass.FdfClass import *
from Common.MigrationUtilities import *
from Common.ToolDefClassObject import *
from Common.TargetTxtClassObject import *
## Store Defines section
#
# Write [Defines] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Defines section
# @param Platform An input Platform class object
#
def StorePlatformDefinesSection(DscFile, Platform):
PlatformHeader = Platform.Header
DefinesTupleList = []
if PlatformHeader.Name != "":
DefinesTupleList.append(("PLATFORM_NAME", PlatformHeader.Name))
if PlatformHeader.Guid != "":
DefinesTupleList.append(("PLATFORM_GUID", PlatformHeader.Guid))
if PlatformHeader.Version != "":
DefinesTupleList.append(("PLATFORM_VERSION", PlatformHeader.Version))
for key in PlatformHeader.Specification.keys():
SpecificationValue = PlatformHeader.Specification.get(key)
DefinesTupleList.append(("DSC_ SPECIFICATION", SpecificationValue))
if PlatformHeader.OutputDirectory != "":
DefinesTupleList.append(("OUTPUT_DIRECTORY", PlatformHeader.OutputDirectory))
if PlatformHeader.SupArchList != "":
String = "|".join(PlatformHeader.SupArchList)
DefinesTupleList.append(("SUPPORTED_ARCHITECTURES", String))
if PlatformHeader.BuildTargets != "":
String = "|".join(PlatformHeader.BuildTargets)
DefinesTupleList.append(("BUILD_TARGETS", String))
if PlatformHeader.SkuIdName != "":
#DefinesTupleList.append(("SKUID_IDENTIFIER", PlatformHeader.SkuIdName))
String = "|".join(PlatformHeader.SkuIdName)
if String != "":
DefinesTupleList.append(("SKUID_IDENTIFIER", String))
String = Platform.FlashDefinitionFile.FilePath
if String != "":
DefinesTupleList.append(("FLASH_DEFINITION", String))
List = []
List.append("################################################################################")
List.append("#")
List.append("# Defines Section - statements that will be processed to create a Makefile.")
List.append("#")
List.append("################################################################################")
Section = "\n".join(List)
Section += "\n"
StoreTextFile(DscFile, Section)
StoreDefinesSection(DscFile, DefinesTupleList)
## Store SkuIds section
#
# Write [SkuIds] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Library Classes section
# @param Platform An input Platform class object
#
def StorePlatformSkuIdsSection(DscFile, Platform):
List = []
List.append("################################################################################")
List.append("#")
List.append("# SKU Identification section - list of all SKU IDs supported by this Platform.")
List.append("#")
List.append("################################################################################")
Section = "\n".join(List)
Section += "\n"
Section += "[SkuIds]" + '\n'
List = Platform.SkuInfos.SkuInfoList
for Item in List:
Section = Section + "%s" % Item[0] + '|' + "%s" % Item[1] + '\n'
Section = Section + '\n'
StoreTextFile(DscFile, Section)
## Store Build Options section
#
# Write [BuildOptions] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Build Options section
# @param Platform An input Platform class object
#
def StorePlatformBuildOptionsSection(DscFile, Platform):
# which is from tools_def.txt
StandardBuildTargets = ["DEBUG", "RELEASE"]
SupportedArches = ["COMMON", "IA32", "X64", "IPF", "EBC", "ARM"]
Target = TargetTxtClassObject()
WorkSpace = os.getenv('WORKSPACE')
Target.LoadTargetTxtFile(WorkSpace + '\\Conf\\target.txt')
ToolDef = ToolDefClassObject()
ToolDef.LoadToolDefFile(WorkSpace + '\\' + Target.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF])
# Now we have got ToolDef object
#ToolDef.ToolsDefTxtDictionary
Dict = ToolDef.ToolsDefTxtDatabase
Dict1 = ToolDef.ToolsDefTxtDictionary # we care the info in this Dict
#
# We only support *(DEBUG/RELEASE) and *(All Arch: IA32, X64, IPF and EBC) for now
#
SectionWINDDK = ''
SectionVS2003 = ''
SectionVS2005EXP = ''
SectionVS2005STD = ''
SectionVS2005PRO = ''
SectionVS2005TEAMSUITE = ''
SectionUNIXGCC = ''
SectionCYGWINGCC = ''
SectionELFGCC = ''
SectionICC = ''
SectionMYTOOLS = ''
for key in Dict1.keys():
if key.find("_CC_FLAGS") != -1:
if key.find('WINDDK3790x1830') != -1:
SectionWINDDK = " = " + Dict1.get(key) + "\n"
elif key.find('VS2003') != -1:
SectionVS2003 = " = " + Dict1.get(key)+ "\n"
elif key.find('VS2005EXP') != -1:
SectionVS2005EXP = " = " + Dict1.get(key) + "\n"
elif key.find('VS2005STD') != -1:
SectionVS2005STD = " = " + Dict1.get(key) + "\n"
elif key.find('VS2005PRO') != -1:
SectionVS2005PRO = " = " + Dict1.get(key) + "\n"
elif key.find('VS2005TEAMSUITE') != -1:
SectionVS2005TEAMSUITE = " = " + Dict1.get(key) + "\n"
elif key.find('UNIXGCC') != -1:
SectionUNIXGCC = " = " + Dict1.get(key) + "\n"
elif key.find('CYGWINGCC') != -1:
SectionCYGWINGCC = " = " + Dict1.get(key) + "\n"
elif key.find('ELFGCC') != -1:
SectionELFGCC = " = " + Dict1.get(key) + "\n"
elif key.find('ICC') != -1:
SectionICC = " = " + Dict1.get(key) + "\n"
elif key.find('MYTOOLS') != -1:
SectionMYTOOLS = " = " + Dict1.get(key) + "\n"
else:
print "Error!"
#
# First need to check which arch
#
Archs = Platform.Header.SupArchList
BuildTargets = Platform.Header.BuildTargets
#if BuildTargets == StandardBuildTargets:
#print "Debug and Release both support" # skip debug/release string search
#else:
#print "need to search debug/release string"
if len(Archs) == 4:
Arch = "*"
SectionName = "[BuildOptions.Common]\n"
else:
for Arch in Archs:
if Arch == 'IA32':
SectionName = "[BuildOptions.IA32]\n"
elif Arch == 'X64':
SectionName = "[BuildOptions.X64]\n"
elif Arch == 'IPF':
SectionName = "[BuildOptions.IPF]\n"
elif Arch == 'EBC':
SectionName = "[BuildOptions.EBC]\n"
else:
print 'Error!'
Section = ""
if SectionWINDDK != "":
SectionWINDDK = "*_WINDDK3790x1830_" + Arch + "_CC_FLAGS" + SectionWINDDK
Section += SectionWINDDK
if SectionVS2003 != "":
SectionVS2003 = "*_VS2003_" + Arch + "_CC_FLAGS" + SectionVS2003
Section += SectionVS2003
if SectionVS2005EXP != "":
SectionVS2005EXP = "*_VS2005EXP_" + Arch + "_CC_FLAGS" + SectionVS2005EXP
Section += SectionVS2005EXP
if SectionVS2005STD != "":
SectionVS2005STD = "*_VS2005STD_" + Arch + "_CC_FLAGS" + SectionVS2005STD
Section += SectionVS2005STD
if SectionVS2005PRO != "":
SectionVS2005PRO = "*_VS2005PRO_" + Arch + "_CC_FLAGS" + SectionVS2005PRO
Section += SectionVS2005PRO
if SectionVS2005TEAMSUITE != "":
SectionVS2005TEAMSUITE = "*_VS2005TEAMSUITE_" + Arch + "_CC_FLAGS" + SectionVS2005TEAMSUITE
Section += SectionVS2005TEAMSUITE
if SectionUNIXGCC != "":
SectionUNIXGCC = "*_UNIXGCC_" + Arch + "_CC_FLAGS" + SectionUNIXGCC
Section += SectionUNIXGCC
if SectionCYGWINGCC != "":
SectionCYGWINGCC = "*_CYGWINGCC_" + Arch + "_CC_FLAGS" + SectionCYGWINGCC
Section += SectionCYGWINGCC
if SectionELFGCC != "":
SectionELFGCC = "*_ELFGCC_" + Arch + "_CC_FLAGS" + SectionELFGCC
Section += SectionELFGCC
if SectionICC != "":
SectionICC = "*_ICC_" + Arch + "_CC_FLAGS" + SectionICC
Section += SectionICC
if SectionMYTOOLS != "":
SectionMYTOOLS = "*_MYTOOLS_" + Arch + "_CC_FLAGS" + SectionMYTOOLS
Section += SectionMYTOOLS
List = []
List.append("################################################################################")
List.append("#")
List.append("# Build Options section - list of all Build Options supported by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + SectionName + Section
Section += "\n"
StoreTextFile(DscFile, Section)
## Store Libraries section
#
# Write [Libraries] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Library Classes section
# @param Platform An input Platform class object
#
def StorePlatformLibrariesSection(DscFile,Platform):
List = []
List.append("################################################################################")
List.append("#")
List.append("# Libraries section - list of all Libraries needed by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + '[Libraries]\n\n'
StoreTextFile(DscFile, Section)
## Return a Platform Library Class Item
#
# Read the input LibraryClass class object and return one line of Library Class Item.
#
# @param LibraryClass An input LibraryClass class object
#
# @retval LibraryClassItem A Module Library Class Item
#
def GetPlatformLibraryClassItem(LibraryClass):
LibraryClassList = []
LibraryClassList.append(LibraryClass.Name)
LibraryClassList.append(LibraryClass.FilePath)
return "|$(WORKSPACE)/".join(LibraryClassList).rstrip("|")
## Add item to a LibraryClass section
#
# Add an Item with specific Module Type to section dictionary.
# The possible duplication is ensured to be removed.
#
# @param Section Section dictionary indexed by CPU architecture
# @param SupModuleList LibraryClass SupModuleList: BASE, SEC, PEI_CORE, PEIM, etc
# @param Item The Item to be added to section dictionary
#
def AddToLibraryClassSection(Section, SupModuleList, Item):
for ModuleType in SupModuleList:
SectionModule = Section.get(ModuleType, [])
if Item not in SectionModule:
SectionModule.append(Item)
Section[ModuleType] = SectionModule
## Get Library Classes section contents
#
# Return the content of section named SectionName.
# the contents is based on Methods and ObjectLists.
#
# @param SectionName The name of the section
# @param Method A function returning a string item of an object
# @param ObjectList The list of object
#
# @retval Section The string content of a section
#
def GetLibraryClassesSection(SectionName, Method, ObjectList):
SupportedArches = ["COMMON", "IA32", "X64", "IPF", "EBC"]
ModuleTypes = ["BASE","SEC","PEI_CORE","PEIM","DXE_CORE","DXE_DRIVER","DXE_SMM_DRIVER","DXE_SAL_DRIVER","DXE_RUNTIME_DRIVER","UEFI_DRIVER","UEFI_APPLICATION"]
SectionCommonDict = {}
SectionIA32Dict = {}
SectionX64Dict = {}
SectionIPFDict = {}
SectionEBCDict = {}
#ObjectList = list(set(ObjectList)) # delete the same element in the list
for Object in ObjectList:
if Object == None:
continue
Item = Method(Object)
if Item == "":
continue
Item = " %s" % Item
Arches = Object.SupArchList
if len(Arches) == 4:
ModuleType = Object.ModuleType
# [LibraryClasses.Common.ModuleType]
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionCommonDict, SupModuleList, Item)
else:
#
SupModuleList = Object.SupModuleList
#AddToSection(SectionDict, "|".join(SupModuleList), Item)
AddToLibraryClassSection(SectionCommonDict, SupModuleList, Item)
else:
# Arch
for Arch in SupportedArches:
if Arch.upper() in Arches:
if Arch == "IA32":
# [LibraryClasses.IA32.ModuleType]
ModuleType = Object.ModuleType
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionIA32Dict, SupModuleList, Item)
else:
SupModuleList = Object.SupModuleList
AddToLibraryClassSection(SectionIA32Dict, SupModuleList, Item)
elif Arch == "X64":
# [LibraryClasses.X64.ModuleType]
ModuleType = Object.ModuleType
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionX64Dict, SupModuleList, Item)
else:
SupModuleList = Object.SupModuleList
AddToLibraryClassSection(SectionX64Dict, SupModuleList, Item)
elif Arch == "IPF":
# [LibraryClasses.IPF.ModuleType]
ModuleType = Object.ModuleType
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionIPFDict, SupModuleList, Item)
else:
SupModuleList = Object.SupModuleList
AddToLibraryClassSection(SectionIPFDict, SupModuleList, Item)
elif Arch == "EBC":
# [LibraryClasses.EBC.ModuleType]
ModuleType = Object.ModuleType
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionEBCDict, SupModuleList, Item)
else:
SupModuleList = Object.SupModuleList
AddToLibraryClassSection(SectionEBCDict, SupModuleList, Item)
Section = ""
for ModuleType in ModuleTypes:
SectionCommonModule = "\n".join(SectionCommonDict.get(ModuleType, []))
if SectionCommonModule != "":
Section += "[%s.Common.%s]\n%s\n" % (SectionName, ModuleType, SectionCommonModule)
Section += "\n"
for ModuleType in ModuleTypes:
ListIA32 = SectionIA32Dict.get(ModuleType, [])
if ListIA32 != []:
SectionIA32Module = "\n".join(SectionIA32Dict.get(ModuleType, []))
if SectionIA32Module != "":
Section += "[%s.IA32.%s]\n%s\n" % (SectionName, ModuleType, SectionIA32Module)
Section += "\n"
ListX64 = SectionX64Dict.get(ModuleType, [])
if ListX64 != []:
SectionX64Module = "\n".join(SectionX64Dict.get(ModuleType, []))
if SectionX64Module != "":
Section += "[%s.X64.%s]\n%s\n" % (SectionName, ModuleType, SectionX64Module)
Section += "\n"
ListIPF = SectionIPFDict.get(ModuleType, [])
if ListIPF != []:
SectionIPFModule = "\n".join(SectionIPFDict.get(ModuleType, []))
if SectionIPFModule != "":
Section += "[%s.IPF.%s]\n%s\n" % (SectionName, ModuleType, SectionIPFModule)
Section += "\n"
ListEBC = SectionEBCDict.get(ModuleType, [])
if ListEBC != []:
SectionEBCModule = "\n".join(SectionEBCDict.get(ModuleType, []))
if SectionEBCModule != "":
Section += "[%s.EBC.%s]\n%s\n" % (SectionName, ModuleType, SectionEBCModule)
Section += "\n"
if Section != "":
Section += "\n"
return Section
## Store Library Classes section
#
# Write [LibraryClasses] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Library Classes section
# @param Platform An input Platform class object
#
def StorePlatformLibraryClassesSection(DscFile, Platform):
Section = GetLibraryClassesSection("LibraryClasses", GetPlatformLibraryClassItem, Platform.LibraryClasses.LibraryList)
List = []
List.append("################################################################################")
List.append("#")
List.append("# Library Class section - list of all Library Classes needed by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + Section
StoreTextFile(DscFile, Section)
## Store Pcd section
#
# Write [Pcd] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Build Options section
# @param Platform An input Platform class object
#
def StorePlatformPcdSection(DscFile, Platform):
# {PcdsFixedAtBuild:String1, PcdsFixedAtBuild:String2, PcdsPatchableInModule:String3}
SectionDict = {}
#
# [PcdsFixedAtBuild], [PcdsPatchableInModule] and [PcdsFeatureFlag] are from platform.modules
# [PcdsDynamic] is from platform.DynamicPcdBuildDefinitions
#
Modules = Platform.Modules.ModuleList # it's a list of modules
for Module in Modules:
PcdBuildDefinitions = Module.PcdBuildDefinitions # it's a list of PcdData
for PcdData in PcdBuildDefinitions:
if PcdData.ItemType == "FEATURE_FLAG":
List = []
List.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List.append(PcdData.Value)
String = "|".join(List)
ItemType = PcdData.ItemType
SectionPcdsFeatureFlag = SectionDict.get(ItemType, [])
if String not in SectionPcdsFeatureFlag:
SectionPcdsFeatureFlag.append(String)
SectionDict[ItemType] = SectionPcdsFeatureFlag
else:
List = []
List.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List.append(PcdData.Value)
List.append(PcdData.Token)
List.append(PcdData.DatumType)
List.append(PcdData.MaxDatumSize)
String = "|".join(List)
ItemType = PcdData.ItemType
if PcdData.ItemType == "FIXED_AT_BUILD":
SectionPcdsFixedAtBuild = SectionDict.get(ItemType, [])
if String not in SectionPcdsFixedAtBuild:
SectionPcdsFixedAtBuild.append(String)
SectionDict[ItemType] = SectionPcdsFixedAtBuild
#elif PcdData.ItemType == "FEATURE_FLAG":
#SectionPcdsFeatureFlag = SectionDict.get(ItemType, [])
#if String not in SectionPcdsFeatureFlag:
#SectionPcdsFeatureFlag.append(String)
#SectionDict[ItemType] = SectionPcdsFeatureFlag
elif PcdData.ItemType == "PATCHABLE_IN_MODULE":
SectionPcdsPatchableInModule = SectionDict.get(ItemType, [])
if String not in SectionPcdsPatchableInModule:
SectionPcdsPatchableInModule.append(String)
SectionDict[ItemType] = SectionPcdsPatchableInModule
elif PcdData.ItemType == "DYNAMIC":
SectionPcdsDynamic = SectionDict.get(ItemType, [])
if String not in SectionPcdsDynamic:
SectionPcdsDynamic.append(String)
SectionDict[ItemType] = SectionPcdsDynamic
DynamicPcdBuildDefinitions = Platform.DynamicPcdBuildDefinitions # It's a list
for PcdBuildData in DynamicPcdBuildDefinitions:
List = []
List.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List.append(PcdData.Token)
List.append(PcdData.DatumType)
List.append(PcdData.MaxDatumSize)
String = "|".join(List)
if PcdBuildData.ItemType == "DYNAMIC":
ItemType = PcdBuildData.ItemType
SectionPcdsDynamic = SectionDict.get(ItemType, [])
if String not in SectionPcdsDynamic:
SectionPcdsDynamic.append(String)
SectionDict[ItemType] = SectionPcdsDynamic
ItemType = "FIXED_AT_BUILD"
Section = "[PcdsFixedAtBuild]\n " + "\n ".join(SectionDict.get(ItemType, []))
ItemType = "FEATURE_FLAG"
Section += "\n\n[PcdsFeatureFlag]\n " + "\n ".join(SectionDict.get(ItemType, []))
ItemType = "PATCHABLE_IN_MODULE"
Section += "\n\n[PcdsPatchableInModule]\n " + "\n ".join(SectionDict.get(ItemType, []))
Section += "\n\n"
List = []
List.append("################################################################################")
List.append("#")
List.append("# Pcd Dynamic Section - list of all EDK II PCD Entries defined by this Platform.")
List.append("#")
List.append("################################################################################")
String = "\n".join(List)
Section += String
ItemType = "DYNAMIC"
Section += "\n\n[PcdsDynamic]\n " + "\n ".join(SectionDict.get(ItemType, []))
Section += "\n\n"
List = []
List.append("################################################################################")
List.append("#")
List.append("# Pcd Section - list of all EDK II PCD Entries defined by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + Section
StoreTextFile(DscFile, Section)
## Add item to a section
#
# Add an Item with specific CPU architecture to section dictionary.
# The possible duplication is ensured to be removed.
#
# @param Section Section dictionary indexed by CPU architecture
# @param Arch CPU architecture: Ia32, X64, Ipf, Ebc or Common
# @param Item The Item to be added to section dictionary
#
def AddToSection(Section, Arch, Item):
SectionArch = Section.get(Arch, [])
if Item not in SectionArch:
SectionArch.append(Item)
Section[Arch] = SectionArch
## Get section contents
#
# Return the content of section named SectionName.
# the contents is based on Methods and ObjectLists.
#
# @param SectionName The name of the section
# @param Method A function returning a string item of an object
# @param ObjectList The list of object
#
# @retval Section The string content of a section
#
def GetSection(SectionName, Method, ObjectList):
SupportedArches = ["COMMON", "IA32", "X64", "IPF", "EBC"]
SectionDict = {}
for Object in ObjectList:
if Object.FilePath == "":
continue
Item = Method(Object)
if Item == "":
continue
Item = " %s" % Item
Arches = Object.SupArchList
if len(Arches) == 4:
AddToSection(SectionDict, "common", Item)
else:
for Arch in SupportedArches:
if Arch.upper() in Arches:
AddToSection(SectionDict, Arch, Item)
Section = ""
for Arch in SupportedArches:
SectionArch = "\n".join(SectionDict.get(Arch, []))
if SectionArch != "":
Section += "[%s.%s]\n%s\n" % (SectionName, Arch, SectionArch)
Section += "\n"
if Section != "":
Section += "\n"
return Section
## Return a Platform Component Item
#
# Read the input Platform Component object and return one line of Platform Component Item.
#
# @param Component An input Platform Component class object
#
# @retval ComponentItem A Platform Component Item
#
def GetPlatformComponentItem(Component):
List = []
Section = {}
List.append("$(WORKSPACE)/" + Component.FilePath)
LibraryClasses = Component.LibraryClasses
if LibraryClasses != []:
List = []
List.append("$(WORKSPACE)/" + Component.FilePath + " {")
List.append("<LibraryClasses>")
for LibraryClass in LibraryClasses:
if LibraryClass == ["", ""]:
continue
List.append(" " + LibraryClass[0] + "|$(WORKSPACE)/" + LibraryClass[1])
PcdBuildDefinitions = Component.PcdBuildDefinitions
for PcdData in PcdBuildDefinitions:
if PcdData.ItemType == "FEATURE_FLAG":
List1 = []
List1.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List1.append(PcdData.Value)
String = "|".join(List1)
ItemType = PcdData.ItemType
SectionPcd = Section.get(ItemType, [])
if String not in SectionPcd:
SectionPcd.append(String)
Section[ItemType] = SectionPcd
else:
List1 = []
List1.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List1.append(PcdData.Value)
List1.append(PcdData.Token)
List1.append(PcdData.DatumType)
List1.append(PcdData.MaxDatumSize)
String = "|".join(List1)
ItemType = PcdData.ItemType
if ItemType == "FIXED_AT_BUILD":
SectionPcd = Section.get(ItemType, [])
if String not in SectionPcd:
SectionPcd.append(String)
Section[ItemType] = SectionPcd
#elif ItemType == "FEATURE_FLAG":
#SectionPcd = Section.get(ItemType, [])
#if String not in SectionPcd:
#SectionPcd.append(String)
#Section[ItemType] = SectionPcd
elif ItemType == "PATCHABLE_IN_MODULE":
SectionPcd = Section.get(ItemType, [])
if String not in SectionPcd:
SectionPcd.append(String)
Section[ItemType] = SectionPcd
elif ItemType == "DYNAMIC":
SectionPcd = Section.get(ItemType, [])
if String not in SectionPcd:
SectionPcd.append(String)
Section[ItemType] = SectionPcd
ItemType = "FIXED_AT_BUILD"
if Section.get(ItemType, []) != []:
List.append("<PcdsFixedAtBuild>")
List.append(" " + "\n ".join(Section.get(ItemType,[])))
ItemType = "FEATURE_FLAG"
if Section.get(ItemType, []) != []:
List.append("<PcdsFeatureFlag>")
List.append(" " + "\n ".join(Section.get(ItemType,[])))
ItemType = "PATCHABLE_IN_MODULE"
if Section.get(ItemType, []) != []:
List.append("<PcdsPatchableInModule>")
List.append(" " + "\n ".join(Section.get(ItemType,[])))
ItemType = "DYNAMIC"
if Section.get(ItemType, []) != []:
List.append("<PcdsDynamic>")
List.append(" " + "\n ".join(Section.get(ItemType,[])))
ListOption = []
SectionOption = ""
ListBuildOptions = Component.BuildOptions # a list
if ListBuildOptions != []:
SectionOption += "\n <BuildOptions>\n"
for BuildOptions in ListBuildOptions:
Options = BuildOptions.Options
for Option in Options:
for Item in Option.BuildTargetList:
ListOption.append(Item)
List.append(Option.ToolChainFamily)
for Item in Option.SupArchList:
ListOption.append(Item)
ListOption.append(Option.ToolCode)
ListOption.append("FLAGS")
#print ListOption
SectionOption += " " + "_".join(List) + " = " + Option.Option + "\n"
ListOption = []
if SectionOption != "":
List.append(SectionOption)
if List != ["$(WORKSPACE)/" + Component.FilePath]:
List.append("}\n")
return "\n ".join(List)
## Store Components section.
#
# Write [Components] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Components section
# @param Platform An input Platform class object
#
def StorePlatformComponentsSection(DscFile, Platform):
Section = GetSection("Components", GetPlatformComponentItem, Platform.Modules.ModuleList)
List = []
List.append("################################################################################")
List.append("#")
List.append("# Components Section - list of all EDK II Modules needed by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + Section
StoreTextFile(DscFile, Section)
## Store User Extensions section.
#
# Write [UserExtensions] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the User Extensions section
# @param Platform An input Platform class object
#
def StorePlatformUserExtensionsSection(DscFile, Platform):
Section = "".join(map(GetUserExtensions, Platform.UserExtensions))
List = []
List.append("################################################################################")
List.append("#")
List.append("# User Extensions Section - list of all User Extensions specified by user.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + Section
StoreTextFile(DscFile, Section)
## Store a Platform class object to a new DSC file.
#
# Read an input Platform class object and save the contents to a new DSC file.
#
# @param DSCFileName The output DSC file
# @param Platform An input Platform class object
#
def StoreDsc(DscFileName, Platform):
DscFile = open(DscFileName, "w+")
EdkLogger.info("Save file to %s" % DscFileName)
StoreHeader(DscFile, Platform.Header)
StorePlatformDefinesSection(DscFile, Platform)
StorePlatformBuildOptionsSection(DscFile,Platform)
StorePlatformSkuIdsSection(DscFile,Platform)
StorePlatformLibrariesSection(DscFile,Platform) # new in dsc, Edk I components, list of INF files
StorePlatformLibraryClassesSection(DscFile, Platform) # LibraryClasses are from Modules
StorePlatformPcdSection(DscFile, Platform)
#StorePlatformPcdDynamicSection(DscFile, Platform)
StorePlatformComponentsSection(DscFile,Platform)
StorePlatformUserExtensionsSection(DscFile,Platform)
DscFile.close()
if __name__ == '__main__':
pass

View File

@@ -0,0 +1,116 @@
## @file
# Convert an XML-based FPD file to a text-based DSC file.
#
# Copyright (c) 2007, 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, re, sys, xml.dom.minidom #XmlRoutines, EdkIIWorkspace
from LoadFpd import LoadFpd
from StoreDsc import StoreDsc
from optparse import OptionParser
# Version and Copyright
__version_number__ = "1.0"
__version__ = "%prog Version " + __version_number__
__copyright__ = "Copyright (c) 2007, Intel Corporation All rights reserved."
## Parse command line options
#
# Using standard Python module optparse to parse command line option of this tool.
#
# @retval Options A optparse.Values object containing the parsed options
# @retval Args All the arguments got from the command line
#
def MyOptionParser():
""" Argument Parser """
usage = "%prog [options] input_filename"
parser = OptionParser(usage=usage,description=__copyright__,version="%prog " + str(__version_number__))
parser.add_option("-o", "--output", dest="outfile", help="Specific Name of the DSC file to create, otherwise it is the FPD filename with the extension repalced.")
parser.add_option("-a", "--auto", action="store_true", dest="autowrite", default=False, help="Automatically create output files and write the DSC file")
parser.add_option("-q", "--quiet", action="store_const", const=0, dest="verbose", help="Do not print any messages, just return either 0 for succes or 1 for failure")
parser.add_option("-v", "--verbose", action="count", dest="verbose", help="Do not print any messages, just return either 0 for succes or 1 for failure")
parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Enable printing of debug messages.")
parser.add_option("-w", "--workspace", dest="workspace", default=str(os.environ.get('WORKSPACE')), help="Specify workspace directory.")
(options, args) = parser.parse_args(sys.argv[1:])
return options,args
## 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
global Args
global WorkSpace
Options,Args = MyOptionParser()
WorkSpace = ""
#print Options.workspace
if (Options.workspace == None):
print "ERROR: E0000: WORKSPACE not defined.\n Please set the WORKSPACE environment variable to the location of the EDK II install directory."
sys.exit(1)
else:
WorkSpace = Options.workspace
if (Options.debug):
print "Using Workspace:", WorkSpace
try:
Options.verbose +=1
except:
Options.verbose = 1
pass
InputFile = ""
if Args == []:
print "usage:" "%prog [options] input_filename"
else:
InputFile = Args[0]
#print InputFile
if InputFile != "":
FileName = InputFile
if ((Options.verbose > 1) | (Options.autowrite)):
print "FileName:",InputFile
else:
print "ERROR: E0001 - You must specify an input filename"
sys.exit(1)
if (Options.outfile):
OutputFile = Options.outfile
else:
OutputFile = FileName.replace('.fpd', '.dsc')
if ((Options.verbose > 2) or (Options.debug)):
print "Output Filename:", OutputFile
try:
Platform = LoadFpd(FileName)
StoreDsc(OutputFile, Platform)
return 0
except Exception, e:
print e
return 1
if __name__ == '__main__':
sys.exit(Main())
#pass
#global Options
#global Args
#Options,Args = MyOptionParser()
#Main()
#sys.exit(0)