diff options
author | Gao, Liming <liming.gao@intel.com> | 2014-01-27 05:23:15 +0000 |
---|---|---|
committer | lgao4 <lgao4@6f19259b-4bc3-4df7-8a09-765794883524> | 2014-01-27 05:23:15 +0000 |
commit | f51461c829c124288a930829a78e2a5a799f4039 (patch) | |
tree | 1072993516da9d887f0e0fd876c9ac5630c19ae2 /BaseTools/Source/Python/UPT | |
parent | 7771be9fd0b9b3c7f5c0659c416535171de31191 (diff) | |
download | edk2-platforms-f51461c829c124288a930829a78e2a5a799f4039.tar.xz |
Sync BaseTool trunk (version r2649) into EDKII BaseTools.
Signed-off-by: Gao, Liming <liming.gao@intel.com>
git-svn-id: https://svn.code.sf.net/p/edk2/code/trunk/edk2@15188 6f19259b-4bc3-4df7-8a09-765794883524
Diffstat (limited to 'BaseTools/Source/Python/UPT')
-rw-r--r-- | BaseTools/Source/Python/UPT/BuildVersion.py | 2 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Core/__init__.py | 38 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/GenMetaFile/__init__.py | 38 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Library/ExpressionValidate.py | 2 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Library/GlobalData.py | 196 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Library/Misc.py | 1948 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Library/Xml/__init__.py | 38 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Library/__init__.py | 38 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Logger/Log.py | 650 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Logger/ToolError.py | 354 | ||||
-rw-r--r-- | BaseTools/Source/Python/UPT/Xml/__init__.py | 38 |
11 files changed, 1671 insertions, 1671 deletions
diff --git a/BaseTools/Source/Python/UPT/BuildVersion.py b/BaseTools/Source/Python/UPT/BuildVersion.py index 1ce93dbe8b..8b86b37e30 100644 --- a/BaseTools/Source/Python/UPT/BuildVersion.py +++ b/BaseTools/Source/Python/UPT/BuildVersion.py @@ -17,4 +17,4 @@ Build version information
'''
-gBUILD_VERSION = "Build 2640"
+gBUILD_VERSION = "Build 2649"
diff --git a/BaseTools/Source/Python/UPT/Core/__init__.py b/BaseTools/Source/Python/UPT/Core/__init__.py index 39c78e8ecf..efe9cd09b7 100644 --- a/BaseTools/Source/Python/UPT/Core/__init__.py +++ b/BaseTools/Source/Python/UPT/Core/__init__.py @@ -1,20 +1,20 @@ -## @file -# Python 'Library' package initialization file. -# -# This file is required to make Python interpreter treat the directory -# as containing package. -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. -# - -''' -Core init file +## @file
+# Python 'Library' package initialization file.
+#
+# This file is required to make Python interpreter treat the directory
+# as containing package.
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+#
+
+'''
+Core init file
'''
\ No newline at end of file diff --git a/BaseTools/Source/Python/UPT/GenMetaFile/__init__.py b/BaseTools/Source/Python/UPT/GenMetaFile/__init__.py index 0f6ce81579..269ba0bc48 100644 --- a/BaseTools/Source/Python/UPT/GenMetaFile/__init__.py +++ b/BaseTools/Source/Python/UPT/GenMetaFile/__init__.py @@ -1,20 +1,20 @@ -## @file -# Python 'Library' package initialization file. -# -# This file is required to make Python interpreter treat the directory -# as containing package. -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. -# - -''' -GenMetaFile +## @file
+# Python 'Library' package initialization file.
+#
+# This file is required to make Python interpreter treat the directory
+# as containing package.
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+#
+
+'''
+GenMetaFile
'''
\ No newline at end of file diff --git a/BaseTools/Source/Python/UPT/Library/ExpressionValidate.py b/BaseTools/Source/Python/UPT/Library/ExpressionValidate.py index 91041c7a64..3b476b4c48 100644 --- a/BaseTools/Source/Python/UPT/Library/ExpressionValidate.py +++ b/BaseTools/Source/Python/UPT/Library/ExpressionValidate.py @@ -93,7 +93,7 @@ class _ExprBase: ## IsCurrentOp
#
- # @param OpList: option list + # @param OpList: option list
#
def IsCurrentOp(self, OpList):
self.SkipWhitespace()
diff --git a/BaseTools/Source/Python/UPT/Library/GlobalData.py b/BaseTools/Source/Python/UPT/Library/GlobalData.py index 3f72f22738..e47e24a714 100644 --- a/BaseTools/Source/Python/UPT/Library/GlobalData.py +++ b/BaseTools/Source/Python/UPT/Library/GlobalData.py @@ -1,99 +1,99 @@ -## @file -# This file is used to define common static strings and global data used by UPT -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. - -''' -GlobalData -''' - -# -# The workspace directory -# -gWORKSPACE = '.' - -# -# INF module directory -# -gINF_MODULE_DIR = "." -gINF_MODULE_NAME = '' - -# -# the directory to holds upt related files -# -gUPT_DIR = r"Conf/upt/" - -# -# Log file for invalid meta-data files during force removing -# -gINVALID_MODULE_FILE = gUPT_DIR + r"Invalid_Modules.log" - -# -# File name for content zip file in the distribution -# -gCONTENT_FILE = "dist.content" - -# -# File name for XML file in the distibution -# -gDESC_FILE = 'dist.pkg' - -# -# Case Insensitive flag -# -gCASE_INSENSITIVE = '' - -# -# All Files dictionary -# -gALL_FILES = {} - -# -# Database instance -# -gDB = None - -# -# list for files that are found in module level but not in INF files, -# items are (File, ModulePath), all these should be relative to $(WORKSPACE) -# -gMISS_FILE_IN_MODLIST = [] - -# -# Global Current Line -# -gINF_CURRENT_LINE = None - -# -# Global pkg list -# -gWSPKG_LIST = [] - -# -# Flag used to take WARN as ERROR. -# By default, only ERROR message will break the tools execution. -# -gWARNING_AS_ERROR = False - -# -# Used to specify the temp directory to hold the unpacked distribution files -# -gUNPACK_DIR = None - -# -# Flag used to mark whether the INF file is Binary INF or not. -# -gIS_BINARY_INF = False -# -# Used by Library instance parser -# {FilePath: FileObj} -# +## @file
+# This file is used to define common static strings and global data used by UPT
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+
+'''
+GlobalData
+'''
+
+#
+# The workspace directory
+#
+gWORKSPACE = '.'
+
+#
+# INF module directory
+#
+gINF_MODULE_DIR = "."
+gINF_MODULE_NAME = ''
+
+#
+# the directory to holds upt related files
+#
+gUPT_DIR = r"Conf/upt/"
+
+#
+# Log file for invalid meta-data files during force removing
+#
+gINVALID_MODULE_FILE = gUPT_DIR + r"Invalid_Modules.log"
+
+#
+# File name for content zip file in the distribution
+#
+gCONTENT_FILE = "dist.content"
+
+#
+# File name for XML file in the distibution
+#
+gDESC_FILE = 'dist.pkg'
+
+#
+# Case Insensitive flag
+#
+gCASE_INSENSITIVE = ''
+
+#
+# All Files dictionary
+#
+gALL_FILES = {}
+
+#
+# Database instance
+#
+gDB = None
+
+#
+# list for files that are found in module level but not in INF files,
+# items are (File, ModulePath), all these should be relative to $(WORKSPACE)
+#
+gMISS_FILE_IN_MODLIST = []
+
+#
+# Global Current Line
+#
+gINF_CURRENT_LINE = None
+
+#
+# Global pkg list
+#
+gWSPKG_LIST = []
+
+#
+# Flag used to take WARN as ERROR.
+# By default, only ERROR message will break the tools execution.
+#
+gWARNING_AS_ERROR = False
+
+#
+# Used to specify the temp directory to hold the unpacked distribution files
+#
+gUNPACK_DIR = None
+
+#
+# Flag used to mark whether the INF file is Binary INF or not.
+#
+gIS_BINARY_INF = False
+#
+# Used by Library instance parser
+# {FilePath: FileObj}
+#
gLIBINSTANCEDICT = {}
\ No newline at end of file diff --git a/BaseTools/Source/Python/UPT/Library/Misc.py b/BaseTools/Source/Python/UPT/Library/Misc.py index 889b777d19..750805e328 100644 --- a/BaseTools/Source/Python/UPT/Library/Misc.py +++ b/BaseTools/Source/Python/UPT/Library/Misc.py @@ -1,974 +1,974 @@ -## @file -# Common routines used by all tools -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. -# - -''' -Misc -''' - -## -# Import Modules -# -import os.path -from os import access -from os import F_OK -from os import makedirs -from os import getcwd -from os import chdir -from os import listdir -from os import remove -from os import rmdir -from os import linesep -from os import walk -from os import environ -import re -from UserDict import IterableUserDict - -import Logger.Log as Logger -from Logger import StringTable as ST -from Logger import ToolError -from Library import GlobalData -from Library.DataType import SUP_MODULE_LIST -from Library.DataType import END_OF_LINE -from Library.DataType import TAB_SPLIT -from Library.DataType import LANGUAGE_EN_US -from Library.String import GetSplitValueList -from Library.ParserValidate import IsValidHexVersion -from Library.ParserValidate import IsValidPath -from Object.POM.CommonObject import TextObject - -## Convert GUID string in xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx style to C -# structure style -# -# @param Guid: The GUID string -# -def GuidStringToGuidStructureString(Guid): - GuidList = Guid.split('-') - Result = '{' - for Index in range(0, 3, 1): - Result = Result + '0x' + GuidList[Index] + ', ' - Result = Result + '{0x' + GuidList[3][0:2] + ', 0x' + GuidList[3][2:4] - for Index in range(0, 12, 2): - Result = Result + ', 0x' + GuidList[4][Index:Index + 2] - Result += '}}' - return Result - -## Check whether GUID string is of format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -# -# @param GuidValue: The GUID value -# -def CheckGuidRegFormat(GuidValue): - ## Regular expression used to find out register format of GUID - # - RegFormatGuidPattern = re.compile("^\s*([0-9a-fA-F]){8}-" - "([0-9a-fA-F]){4}-" - "([0-9a-fA-F]){4}-" - "([0-9a-fA-F]){4}-" - "([0-9a-fA-F]){12}\s*$") - - if RegFormatGuidPattern.match(GuidValue): - return True - else: - return False - - -## Convert GUID string in C structure style to -# xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -# -# @param GuidValue: The GUID value in C structure format -# -def GuidStructureStringToGuidString(GuidValue): - GuidValueString = GuidValue.lower().replace("{", "").replace("}", "").\ - replace(" ", "").replace(";", "") - GuidValueList = GuidValueString.split(",") - if len(GuidValueList) != 11: - return '' - try: - return "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x" % ( - int(GuidValueList[0], 16), - int(GuidValueList[1], 16), - int(GuidValueList[2], 16), - int(GuidValueList[3], 16), - int(GuidValueList[4], 16), - int(GuidValueList[5], 16), - int(GuidValueList[6], 16), - int(GuidValueList[7], 16), - int(GuidValueList[8], 16), - int(GuidValueList[9], 16), - int(GuidValueList[10], 16) - ) - except BaseException: - return '' - -## Create directories -# -# @param Directory: The directory name -# -def CreateDirectory(Directory): - if Directory == None or Directory.strip() == "": - return True - try: - if not access(Directory, F_OK): - makedirs(Directory) - except BaseException: - return False - return True - -## Remove directories, including files and sub-directories in it -# -# @param Directory: The directory name -# -def RemoveDirectory(Directory, Recursively=False): - if Directory == None or Directory.strip() == "" or not \ - os.path.exists(Directory): - return - if Recursively: - CurrentDirectory = getcwd() - chdir(Directory) - for File in listdir("."): - if os.path.isdir(File): - RemoveDirectory(File, Recursively) - else: - remove(File) - chdir(CurrentDirectory) - rmdir(Directory) - -## Store content in file -# -# This method is used to save file only when its content is changed. This is -# quite useful for "make" system to decide what will be re-built and what -# won't. -# -# @param File: The path of file -# @param Content: The new content of the file -# @param IsBinaryFile: The flag indicating if the file is binary file -# or not -# -def SaveFileOnChange(File, Content, IsBinaryFile=True): - if not IsBinaryFile: - Content = Content.replace("\n", linesep) - - if os.path.exists(File): - try: - if Content == open(File, "rb").read(): - return False - except BaseException: - Logger.Error(None, ToolError.FILE_OPEN_FAILURE, ExtraData=File) - - CreateDirectory(os.path.dirname(File)) - try: - FileFd = open(File, "wb") - FileFd.write(Content) - FileFd.close() - except BaseException: - Logger.Error(None, ToolError.FILE_CREATE_FAILURE, ExtraData=File) - - return True - -## Get all files of a directory -# -# @param Root: Root dir -# @param SkipList : The files need be skipped -# -def GetFiles(Root, SkipList=None, FullPath=True): - OriPath = os.path.normpath(Root) - FileList = [] - for Root, Dirs, Files in walk(Root): - if SkipList: - for Item in SkipList: - if Item in Dirs: - Dirs.remove(Item) - for Dir in Dirs: - if Dir.startswith('.'): - Dirs.remove(Dir) - - for File in Files: - if File.startswith('.'): - continue - File = os.path.normpath(os.path.join(Root, File)) - if not FullPath: - File = File[len(OriPath) + 1:] - FileList.append(File) - - return FileList - -## Get all non-metadata files of a directory -# -# @param Root: Root Dir -# @param SkipList : List of path need be skipped -# @param FullPath: True if the returned file should be full path -# @param PrefixPath: the path that need to be added to the files found -# @return: the list of files found -# -def GetNonMetaDataFiles(Root, SkipList, FullPath, PrefixPath): - FileList = GetFiles(Root, SkipList, FullPath) - NewFileList = [] - for File in FileList: - ExtName = os.path.splitext(File)[1] - # - # skip '.dec', '.inf', '.dsc', '.fdf' files - # - if ExtName.lower() not in ['.dec', '.inf', '.dsc', '.fdf']: - NewFileList.append(os.path.normpath(os.path.join(PrefixPath, File))) - - return NewFileList - -## Check if given file exists or not -# -# @param File: File name or path to be checked -# @param Dir: The directory the file is relative to -# -def ValidFile(File, Ext=None): - File = File.replace('\\', '/') - if Ext != None: - FileExt = os.path.splitext(File)[1] - if FileExt.lower() != Ext.lower(): - return False - if not os.path.exists(File): - return False - return True - -## RealPath -# -# @param File: File name or path to be checked -# @param Dir: The directory the file is relative to -# @param OverrideDir: The override directory -# -def RealPath(File, Dir='', OverrideDir=''): - NewFile = os.path.normpath(os.path.join(Dir, File)) - NewFile = GlobalData.gALL_FILES[NewFile] - if not NewFile and OverrideDir: - NewFile = os.path.normpath(os.path.join(OverrideDir, File)) - NewFile = GlobalData.gALL_FILES[NewFile] - return NewFile - -## RealPath2 -# -# @param File: File name or path to be checked -# @param Dir: The directory the file is relative to -# @param OverrideDir: The override directory -# -def RealPath2(File, Dir='', OverrideDir=''): - if OverrideDir: - NewFile = GlobalData.gALL_FILES[os.path.normpath(os.path.join\ - (OverrideDir, File))] - if NewFile: - if OverrideDir[-1] == os.path.sep: - return NewFile[len(OverrideDir):], NewFile[0:len(OverrideDir)] - else: - return NewFile[len(OverrideDir) + 1:], \ - NewFile[0:len(OverrideDir)] - - NewFile = GlobalData.gALL_FILES[os.path.normpath(os.path.join(Dir, File))] - if NewFile: - if Dir: - if Dir[-1] == os.path.sep: - return NewFile[len(Dir):], NewFile[0:len(Dir)] - else: - return NewFile[len(Dir) + 1:], NewFile[0:len(Dir)] - else: - return NewFile, '' - - return None, None - -## A dict which can access its keys and/or values orderly -# -# The class implements a new kind of dict which its keys or values can be -# accessed in the order they are added into the dict. It guarantees the order -# by making use of an internal list to keep a copy of keys. -# -class Sdict(IterableUserDict): - ## Constructor - # - def __init__(self): - IterableUserDict.__init__(self) - self._key_list = [] - - ## [] operator - # - def __setitem__(self, Key, Value): - if Key not in self._key_list: - self._key_list.append(Key) - IterableUserDict.__setitem__(self, Key, Value) - - ## del operator - # - def __delitem__(self, Key): - self._key_list.remove(Key) - IterableUserDict.__delitem__(self, Key) - - ## used in "for k in dict" loop to ensure the correct order - # - def __iter__(self): - return self.iterkeys() - - ## len() support - # - def __len__(self): - return len(self._key_list) - - ## "in" test support - # - def __contains__(self, Key): - return Key in self._key_list - - ## indexof support - # - def index(self, Key): - return self._key_list.index(Key) - - ## insert support - # - def insert(self, Key, Newkey, Newvalue, Order): - Index = self._key_list.index(Key) - if Order == 'BEFORE': - self._key_list.insert(Index, Newkey) - IterableUserDict.__setitem__(self, Newkey, Newvalue) - elif Order == 'AFTER': - self._key_list.insert(Index + 1, Newkey) - IterableUserDict.__setitem__(self, Newkey, Newvalue) - - ## append support - # - def append(self, Sdict2): - for Key in Sdict2: - if Key not in self._key_list: - self._key_list.append(Key) - IterableUserDict.__setitem__(self, Key, Sdict2[Key]) - ## hash key - # - def has_key(self, Key): - return Key in self._key_list - - ## Empty the dict - # - def clear(self): - self._key_list = [] - IterableUserDict.clear(self) - - ## Return a copy of keys - # - def keys(self): - Keys = [] - for Key in self._key_list: - Keys.append(Key) - return Keys - - ## Return a copy of values - # - def values(self): - Values = [] - for Key in self._key_list: - Values.append(self[Key]) - return Values - - ## Return a copy of (key, value) list - # - def items(self): - Items = [] - for Key in self._key_list: - Items.append((Key, self[Key])) - return Items - - ## Iteration support - # - def iteritems(self): - return iter(self.items()) - - ## Keys interation support - # - def iterkeys(self): - return iter(self.keys()) - - ## Values interation support - # - def itervalues(self): - return iter(self.values()) - - ## Return value related to a key, and remove the (key, value) from the dict - # - def pop(self, Key, *Dv): - Value = None - if Key in self._key_list: - Value = self[Key] - self.__delitem__(Key) - elif len(Dv) != 0 : - Value = Dv[0] - return Value - - ## Return (key, value) pair, and remove the (key, value) from the dict - # - def popitem(self): - Key = self._key_list[-1] - Value = self[Key] - self.__delitem__(Key) - return Key, Value - ## update method - # - def update(self, Dict=None, **Kwargs): - if Dict != None: - for Key1, Val1 in Dict.items(): - self[Key1] = Val1 - if len(Kwargs): - for Key1, Val1 in Kwargs.items(): - self[Key1] = Val1 - -## CommonPath -# -# @param PathList: PathList -# -def CommonPath(PathList): - Path1 = min(PathList).split(os.path.sep) - Path2 = max(PathList).split(os.path.sep) - for Index in xrange(min(len(Path1), len(Path2))): - if Path1[Index] != Path2[Index]: - return os.path.sep.join(Path1[:Index]) - return os.path.sep.join(Path1) - -## PathClass -# -class PathClass(object): - def __init__(self, File='', Root='', AlterRoot='', Type='', IsBinary=False, - Arch='COMMON', ToolChainFamily='', Target='', TagName='', \ - ToolCode=''): - self.Arch = Arch - self.File = str(File) - if os.path.isabs(self.File): - self.Root = '' - self.AlterRoot = '' - else: - self.Root = str(Root) - self.AlterRoot = str(AlterRoot) - - # - # Remove any '.' and '..' in path - # - if self.Root: - self.Path = os.path.normpath(os.path.join(self.Root, self.File)) - self.Root = os.path.normpath(CommonPath([self.Root, self.Path])) - # - # eliminate the side-effect of 'C:' - # - if self.Root[-1] == ':': - self.Root += os.path.sep - # - # file path should not start with path separator - # - if self.Root[-1] == os.path.sep: - self.File = self.Path[len(self.Root):] - else: - self.File = self.Path[len(self.Root) + 1:] - else: - self.Path = os.path.normpath(self.File) - - self.SubDir, self.Name = os.path.split(self.File) - self.BaseName, self.Ext = os.path.splitext(self.Name) - - if self.Root: - if self.SubDir: - self.Dir = os.path.join(self.Root, self.SubDir) - else: - self.Dir = self.Root - else: - self.Dir = self.SubDir - - if IsBinary: - self.Type = Type - else: - self.Type = self.Ext.lower() - - self.IsBinary = IsBinary - self.Target = Target - self.TagName = TagName - self.ToolCode = ToolCode - self.ToolChainFamily = ToolChainFamily - - self._Key = None - - ## Convert the object of this class to a string - # - # Convert member Path of the class to a string - # - def __str__(self): - return self.Path - - ## Override __eq__ function - # - # Check whether PathClass are the same - # - def __eq__(self, Other): - if type(Other) == type(self): - return self.Path == Other.Path - else: - return self.Path == str(Other) - - ## Override __hash__ function - # - # Use Path as key in hash table - # - def __hash__(self): - return hash(self.Path) - - ## _GetFileKey - # - def _GetFileKey(self): - if self._Key == None: - self._Key = self.Path.upper() - return self._Key - ## Validate - # - def Validate(self, Type='', CaseSensitive=True): - if GlobalData.gCASE_INSENSITIVE: - CaseSensitive = False - if Type and Type.lower() != self.Type: - return ToolError.FILE_TYPE_MISMATCH, '%s (expect %s but got %s)' % \ - (self.File, Type, self.Type) - - RealFile, RealRoot = RealPath2(self.File, self.Root, self.AlterRoot) - if not RealRoot and not RealFile: - RealFile = self.File - if self.AlterRoot: - RealFile = os.path.join(self.AlterRoot, self.File) - elif self.Root: - RealFile = os.path.join(self.Root, self.File) - return ToolError.FILE_NOT_FOUND, os.path.join(self.AlterRoot, RealFile) - - ErrorCode = 0 - ErrorInfo = '' - if RealRoot != self.Root or RealFile != self.File: - if CaseSensitive and (RealFile != self.File or \ - (RealRoot != self.Root and RealRoot != \ - self.AlterRoot)): - ErrorCode = ToolError.FILE_CASE_MISMATCH - ErrorInfo = self.File + '\n\t' + RealFile + \ - " [in file system]" - - self.SubDir, self.Name = os.path.split(RealFile) - self.BaseName, self.Ext = os.path.splitext(self.Name) - if self.SubDir: - self.Dir = os.path.join(RealRoot, self.SubDir) - else: - self.Dir = RealRoot - self.File = RealFile - self.Root = RealRoot - self.Path = os.path.join(RealRoot, RealFile) - return ErrorCode, ErrorInfo - - Key = property(_GetFileKey) - -## Check environment variables -# -# Check environment variables that must be set for build. Currently they are -# -# WORKSPACE The directory all packages/platforms start from -# EDK_TOOLS_PATH The directory contains all tools needed by the build -# PATH $(EDK_TOOLS_PATH)/Bin/<sys> must be set in PATH -# -# If any of above environment variable is not set or has error, the build -# will be broken. -# -def CheckEnvVariable(): - # - # check WORKSPACE - # - if "WORKSPACE" not in environ: - Logger.Error("UPT", - ToolError.UPT_ENVIRON_MISSING_ERROR, - ST.ERR_NOT_FOUND_ENVIRONMENT, - ExtraData="WORKSPACE") - - WorkspaceDir = os.path.normpath(environ["WORKSPACE"]) - if not os.path.exists(WorkspaceDir): - Logger.Error("UPT", - ToolError.UPT_ENVIRON_MISSING_ERROR, - ST.ERR_WORKSPACE_NOTEXIST, - ExtraData="%s" % WorkspaceDir) - elif ' ' in WorkspaceDir: - Logger.Error("UPT", - ToolError.FORMAT_NOT_SUPPORTED, - ST.ERR_SPACE_NOTALLOWED, - ExtraData=WorkspaceDir) - -## Check whether all module types are in list -# -# check whether all module types (SUP_MODULE_LIST) are in list -# -# @param ModuleList: a list of ModuleType -# -def IsAllModuleList(ModuleList): - NewModuleList = [Module.upper() for Module in ModuleList] - for Module in SUP_MODULE_LIST: - if Module not in NewModuleList: - return False - else: - return True - -## Dictionary that use comment(GenericComment, TailComment) as value, -# if a new comment which key already in the dic is inserted, then the -# comment will be merged. -# Key is (Statement, SupArch), when TailComment is added, it will ident -# according to Statement -# -class MergeCommentDict(dict): - ## []= operator - # - def __setitem__(self, Key, CommentVal): - GenericComment, TailComment = CommentVal - if Key in self: - OrigVal1, OrigVal2 = dict.__getitem__(self, Key) - Statement = Key[0] - dict.__setitem__(self, Key, (OrigVal1 + GenericComment, OrigVal2 \ - + len(Statement) * ' ' + TailComment)) - else: - dict.__setitem__(self, Key, (GenericComment, TailComment)) - - ## =[] operator - # - def __getitem__(self, Key): - return dict.__getitem__(self, Key) - - -## GenDummyHelpTextObj -# -# @retval HelpTxt: Generated dummy help text object -# -def GenDummyHelpTextObj(): - HelpTxt = TextObject() - HelpTxt.SetLang(LANGUAGE_EN_US) - HelpTxt.SetString(' ') - return HelpTxt - -## ConvertVersionToDecimal, the minor version should be within 0 - 99 -# <HexVersion> ::= "0x" <Major> <Minor> -# <Major> ::= (a-fA-F0-9){4} -# <Minor> ::= (a-fA-F0-9){4} -# <DecVersion> ::= (0-65535) ["." (0-99)] -# -# @param StringIn: The string contains version defined in INF file. -# It can be Decimal or Hex -# -def ConvertVersionToDecimal(StringIn): - if IsValidHexVersion(StringIn): - Value = int(StringIn, 16) - Major = Value >> 16 - Minor = Value & 0xFFFF - MinorStr = str(Minor) - if len(MinorStr) == 1: - MinorStr = '0' + MinorStr - return str(Major) + '.' + MinorStr - else: - if StringIn.find(TAB_SPLIT) != -1: - return StringIn - elif StringIn: - return StringIn + '.0' - else: - # - # when StringIn is '', return it directly - # - return StringIn - -## GetHelpStringByRemoveHashKey -# -# Remove hash key at the header of string and return the remain. -# -# @param String: The string need to be processed. -# -def GetHelpStringByRemoveHashKey(String): - ReturnString = '' - PattenRemoveHashKey = re.compile(r"^[#+\s]+", re.DOTALL) - String = String.strip() - if String == '': - return String - - LineList = GetSplitValueList(String, END_OF_LINE) - for Line in LineList: - ValueList = PattenRemoveHashKey.split(Line) - if len(ValueList) == 1: - ReturnString += ValueList[0] + END_OF_LINE - else: - ReturnString += ValueList[1] + END_OF_LINE - - if ReturnString.endswith('\n') and not ReturnString.endswith('\n\n') and ReturnString != '\n': - ReturnString = ReturnString[:-1] - - return ReturnString - -## ConvPathFromAbsToRel -# -# Get relative file path from absolute path. -# -# @param Path: The string contain file absolute path. -# @param Root: The string contain the parent path of Path in. -# -# -def ConvPathFromAbsToRel(Path, Root): - Path = os.path.normpath(Path) - Root = os.path.normpath(Root) - FullPath = os.path.normpath(os.path.join(Root, Path)) - - # - # If Path is absolute path. - # It should be in Root. - # - if os.path.isabs(Path): - return FullPath[FullPath.find(Root) + len(Root) + 1:] - - else: - return Path - -## ConvertPath -# -# Convert special characters to '_', '\' to '/' -# return converted path: Test!1.inf -> Test_1.inf -# -# @param Path: Path to be converted -# -def ConvertPath(Path): - RetPath = '' - for Char in Path.strip(): - if Char.isalnum() or Char in '.-_/': - RetPath = RetPath + Char - elif Char == '\\': - RetPath = RetPath + '/' - else: - RetPath = RetPath + '_' - return RetPath - -## ConvertSpec -# -# during install, convert the Spec string extract from UPD into INF allowable definition, -# the difference is period is allowed in the former (not the first letter) but not in the latter. -# return converted Spec string -# -# @param SpecStr: SpecStr to be converted -# -def ConvertSpec(SpecStr): - RetStr = '' - for Char in SpecStr: - if Char.isalnum() or Char == '_': - RetStr = RetStr + Char - else: - RetStr = RetStr + '_' - - return RetStr - - -## IsEqualList -# -# Judge two lists are identical(contain same item). -# The rule is elements in List A are in List B and elements in List B are in List A. -# -# @param ListA, ListB Lists need to be judged. -# -# @return True ListA and ListB are identical -# @return False ListA and ListB are different with each other -# -def IsEqualList(ListA, ListB): - if ListA == ListB: - return True - - for ItemA in ListA: - if not ItemA in ListB: - return False - - for ItemB in ListB: - if not ItemB in ListA: - return False - - return True - -## ConvertArchList -# -# Convert item in ArchList if the start character is lower case. -# In UDP spec, Arch is only allowed as: [A-Z]([a-zA-Z0-9])* -# -# @param ArchList The ArchList need to be converted. -# -# @return NewList The ArchList been converted. -# -def ConvertArchList(ArchList): - NewArchList = [] - if not ArchList: - return NewArchList - - if type(ArchList) == list: - for Arch in ArchList: - Arch = Arch.upper() - NewArchList.append(Arch) - elif type(ArchList) == str: - ArchList = ArchList.upper() - NewArchList.append(ArchList) - - return NewArchList - -## ProcessLineExtender -# -# Process the LineExtender of Line in LineList. -# If one line ends with a line extender, then it will be combined together with next line. -# -# @param LineList The LineList need to be processed. -# -# @return NewList The ArchList been processed. -# -def ProcessLineExtender(LineList): - NewList = [] - Count = 0 - while Count < len(LineList): - if LineList[Count].strip().endswith("\\") and Count + 1 < len(LineList): - NewList.append(LineList[Count].strip()[:-2] + LineList[Count + 1]) - Count = Count + 1 - else: - NewList.append(LineList[Count]) - - Count = Count + 1 - - return NewList - -## ProcessEdkComment -# -# Process EDK style comment in LineList: c style /* */ comment or cpp style // comment -# -# -# @param LineList The LineList need to be processed. -# -# @return LineList The LineList been processed. -# @return FirstPos Where Edk comment is first found, -1 if not found -# -def ProcessEdkComment(LineList): - FindEdkBlockComment = False - Count = 0 - StartPos = -1 - EndPos = -1 - FirstPos = -1 - - while(Count < len(LineList)): - Line = LineList[Count].strip() - if Line.startswith("/*"): - # - # handling c style comment - # - StartPos = Count - while Count < len(LineList): - Line = LineList[Count].strip() - if Line.endswith("*/"): - if (Count == StartPos) and Line.strip() == '/*/': - Count = Count + 1 - continue - EndPos = Count - FindEdkBlockComment = True - break - Count = Count + 1 - - if FindEdkBlockComment: - if FirstPos == -1: - FirstPos = StartPos - for Index in xrange(StartPos, EndPos+1): - LineList[Index] = '' - FindEdkBlockComment = False - elif Line.find("//") != -1 and not Line.startswith("#"): - # - # handling cpp style comment - # - LineList[Count] = Line.replace("//", '#') - if FirstPos == -1: - FirstPos = Count - - Count = Count + 1 - - return LineList, FirstPos - -## GetLibInstanceInfo -# -# Get the information from Library Instance INF file. -# -# @param string. A string start with # and followed by INF file path -# @param WorkSpace. The WorkSpace directory used to combined with INF file path. -# -# @return GUID, Version -def GetLibInstanceInfo(String, WorkSpace, LineNo): - - FileGuidString = "" - VerString = "" - - OrignalString = String - String = String.strip() - if not String: - return None, None - # - # Remove "#" characters at the beginning - # - String = GetHelpStringByRemoveHashKey(String) - String = String.strip() - - # - # Validate file name exist. - # - FullFileName = os.path.normpath(os.path.realpath(os.path.join(WorkSpace, String))) - if not (ValidFile(FullFileName)): - Logger.Error("InfParser", - ToolError.FORMAT_INVALID, - ST.ERR_FILELIST_EXIST % (String), - File=GlobalData.gINF_MODULE_NAME, - Line=LineNo, - ExtraData=OrignalString) - - # - # Validate file exist/format. - # - if IsValidPath(String, WorkSpace): - IsValidFileFlag = True - else: - Logger.Error("InfParser", - ToolError.FORMAT_INVALID, - ST.ERR_INF_PARSER_FILE_NOT_EXIST_OR_NAME_INVALID % (String), - File=GlobalData.gINF_MODULE_NAME, - Line=LineNo, - ExtraData=OrignalString) - return False - if IsValidFileFlag: - FileLinesList = [] - - try: - FInputfile = open(FullFileName, "rb", 0) - try: - FileLinesList = FInputfile.readlines() - except BaseException: - Logger.Error("InfParser", - ToolError.FILE_READ_FAILURE, - ST.ERR_FILE_OPEN_FAILURE, - File=FullFileName) - finally: - FInputfile.close() - except BaseException: - Logger.Error("InfParser", - ToolError.FILE_READ_FAILURE, - ST.ERR_FILE_OPEN_FAILURE, - File=FullFileName) - - ReFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$") - ReVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$") - - FileLinesList = ProcessLineExtender(FileLinesList) - - for Line in FileLinesList: - if ReFileGuidPattern.match(Line): - FileGuidString = Line - if ReVerStringPattern.match(Line): - VerString = Line - - if FileGuidString: - FileGuidString = GetSplitValueList(FileGuidString, '=', 1)[1] - if VerString: - VerString = GetSplitValueList(VerString, '=', 1)[1] - - return FileGuidString, VerString +## @file
+# Common routines used by all tools
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+#
+
+'''
+Misc
+'''
+
+##
+# Import Modules
+#
+import os.path
+from os import access
+from os import F_OK
+from os import makedirs
+from os import getcwd
+from os import chdir
+from os import listdir
+from os import remove
+from os import rmdir
+from os import linesep
+from os import walk
+from os import environ
+import re
+from UserDict import IterableUserDict
+
+import Logger.Log as Logger
+from Logger import StringTable as ST
+from Logger import ToolError
+from Library import GlobalData
+from Library.DataType import SUP_MODULE_LIST
+from Library.DataType import END_OF_LINE
+from Library.DataType import TAB_SPLIT
+from Library.DataType import LANGUAGE_EN_US
+from Library.String import GetSplitValueList
+from Library.ParserValidate import IsValidHexVersion
+from Library.ParserValidate import IsValidPath
+from Object.POM.CommonObject import TextObject
+
+## Convert GUID string in xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx style to C
+# structure style
+#
+# @param Guid: The GUID string
+#
+def GuidStringToGuidStructureString(Guid):
+ GuidList = Guid.split('-')
+ Result = '{'
+ for Index in range(0, 3, 1):
+ Result = Result + '0x' + GuidList[Index] + ', '
+ Result = Result + '{0x' + GuidList[3][0:2] + ', 0x' + GuidList[3][2:4]
+ for Index in range(0, 12, 2):
+ Result = Result + ', 0x' + GuidList[4][Index:Index + 2]
+ Result += '}}'
+ return Result
+
+## Check whether GUID string is of format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+#
+# @param GuidValue: The GUID value
+#
+def CheckGuidRegFormat(GuidValue):
+ ## Regular expression used to find out register format of GUID
+ #
+ RegFormatGuidPattern = re.compile("^\s*([0-9a-fA-F]){8}-"
+ "([0-9a-fA-F]){4}-"
+ "([0-9a-fA-F]){4}-"
+ "([0-9a-fA-F]){4}-"
+ "([0-9a-fA-F]){12}\s*$")
+
+ if RegFormatGuidPattern.match(GuidValue):
+ return True
+ else:
+ return False
+
+
+## Convert GUID string in C structure style to
+# xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+#
+# @param GuidValue: The GUID value in C structure format
+#
+def GuidStructureStringToGuidString(GuidValue):
+ GuidValueString = GuidValue.lower().replace("{", "").replace("}", "").\
+ replace(" ", "").replace(";", "")
+ GuidValueList = GuidValueString.split(",")
+ if len(GuidValueList) != 11:
+ return ''
+ try:
+ return "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x" % (
+ int(GuidValueList[0], 16),
+ int(GuidValueList[1], 16),
+ int(GuidValueList[2], 16),
+ int(GuidValueList[3], 16),
+ int(GuidValueList[4], 16),
+ int(GuidValueList[5], 16),
+ int(GuidValueList[6], 16),
+ int(GuidValueList[7], 16),
+ int(GuidValueList[8], 16),
+ int(GuidValueList[9], 16),
+ int(GuidValueList[10], 16)
+ )
+ except BaseException:
+ return ''
+
+## Create directories
+#
+# @param Directory: The directory name
+#
+def CreateDirectory(Directory):
+ if Directory == None or Directory.strip() == "":
+ return True
+ try:
+ if not access(Directory, F_OK):
+ makedirs(Directory)
+ except BaseException:
+ return False
+ return True
+
+## Remove directories, including files and sub-directories in it
+#
+# @param Directory: The directory name
+#
+def RemoveDirectory(Directory, Recursively=False):
+ if Directory == None or Directory.strip() == "" or not \
+ os.path.exists(Directory):
+ return
+ if Recursively:
+ CurrentDirectory = getcwd()
+ chdir(Directory)
+ for File in listdir("."):
+ if os.path.isdir(File):
+ RemoveDirectory(File, Recursively)
+ else:
+ remove(File)
+ chdir(CurrentDirectory)
+ rmdir(Directory)
+
+## Store content in file
+#
+# This method is used to save file only when its content is changed. This is
+# quite useful for "make" system to decide what will be re-built and what
+# won't.
+#
+# @param File: The path of file
+# @param Content: The new content of the file
+# @param IsBinaryFile: The flag indicating if the file is binary file
+# or not
+#
+def SaveFileOnChange(File, Content, IsBinaryFile=True):
+ if not IsBinaryFile:
+ Content = Content.replace("\n", linesep)
+
+ if os.path.exists(File):
+ try:
+ if Content == open(File, "rb").read():
+ return False
+ except BaseException:
+ Logger.Error(None, ToolError.FILE_OPEN_FAILURE, ExtraData=File)
+
+ CreateDirectory(os.path.dirname(File))
+ try:
+ FileFd = open(File, "wb")
+ FileFd.write(Content)
+ FileFd.close()
+ except BaseException:
+ Logger.Error(None, ToolError.FILE_CREATE_FAILURE, ExtraData=File)
+
+ return True
+
+## Get all files of a directory
+#
+# @param Root: Root dir
+# @param SkipList : The files need be skipped
+#
+def GetFiles(Root, SkipList=None, FullPath=True):
+ OriPath = os.path.normpath(Root)
+ FileList = []
+ for Root, Dirs, Files in walk(Root):
+ if SkipList:
+ for Item in SkipList:
+ if Item in Dirs:
+ Dirs.remove(Item)
+ for Dir in Dirs:
+ if Dir.startswith('.'):
+ Dirs.remove(Dir)
+
+ for File in Files:
+ if File.startswith('.'):
+ continue
+ File = os.path.normpath(os.path.join(Root, File))
+ if not FullPath:
+ File = File[len(OriPath) + 1:]
+ FileList.append(File)
+
+ return FileList
+
+## Get all non-metadata files of a directory
+#
+# @param Root: Root Dir
+# @param SkipList : List of path need be skipped
+# @param FullPath: True if the returned file should be full path
+# @param PrefixPath: the path that need to be added to the files found
+# @return: the list of files found
+#
+def GetNonMetaDataFiles(Root, SkipList, FullPath, PrefixPath):
+ FileList = GetFiles(Root, SkipList, FullPath)
+ NewFileList = []
+ for File in FileList:
+ ExtName = os.path.splitext(File)[1]
+ #
+ # skip '.dec', '.inf', '.dsc', '.fdf' files
+ #
+ if ExtName.lower() not in ['.dec', '.inf', '.dsc', '.fdf']:
+ NewFileList.append(os.path.normpath(os.path.join(PrefixPath, File)))
+
+ return NewFileList
+
+## Check if given file exists or not
+#
+# @param File: File name or path to be checked
+# @param Dir: The directory the file is relative to
+#
+def ValidFile(File, Ext=None):
+ File = File.replace('\\', '/')
+ if Ext != None:
+ FileExt = os.path.splitext(File)[1]
+ if FileExt.lower() != Ext.lower():
+ return False
+ if not os.path.exists(File):
+ return False
+ return True
+
+## RealPath
+#
+# @param File: File name or path to be checked
+# @param Dir: The directory the file is relative to
+# @param OverrideDir: The override directory
+#
+def RealPath(File, Dir='', OverrideDir=''):
+ NewFile = os.path.normpath(os.path.join(Dir, File))
+ NewFile = GlobalData.gALL_FILES[NewFile]
+ if not NewFile and OverrideDir:
+ NewFile = os.path.normpath(os.path.join(OverrideDir, File))
+ NewFile = GlobalData.gALL_FILES[NewFile]
+ return NewFile
+
+## RealPath2
+#
+# @param File: File name or path to be checked
+# @param Dir: The directory the file is relative to
+# @param OverrideDir: The override directory
+#
+def RealPath2(File, Dir='', OverrideDir=''):
+ if OverrideDir:
+ NewFile = GlobalData.gALL_FILES[os.path.normpath(os.path.join\
+ (OverrideDir, File))]
+ if NewFile:
+ if OverrideDir[-1] == os.path.sep:
+ return NewFile[len(OverrideDir):], NewFile[0:len(OverrideDir)]
+ else:
+ return NewFile[len(OverrideDir) + 1:], \
+ NewFile[0:len(OverrideDir)]
+
+ NewFile = GlobalData.gALL_FILES[os.path.normpath(os.path.join(Dir, File))]
+ if NewFile:
+ if Dir:
+ if Dir[-1] == os.path.sep:
+ return NewFile[len(Dir):], NewFile[0:len(Dir)]
+ else:
+ return NewFile[len(Dir) + 1:], NewFile[0:len(Dir)]
+ else:
+ return NewFile, ''
+
+ return None, None
+
+## A dict which can access its keys and/or values orderly
+#
+# The class implements a new kind of dict which its keys or values can be
+# accessed in the order they are added into the dict. It guarantees the order
+# by making use of an internal list to keep a copy of keys.
+#
+class Sdict(IterableUserDict):
+ ## Constructor
+ #
+ def __init__(self):
+ IterableUserDict.__init__(self)
+ self._key_list = []
+
+ ## [] operator
+ #
+ def __setitem__(self, Key, Value):
+ if Key not in self._key_list:
+ self._key_list.append(Key)
+ IterableUserDict.__setitem__(self, Key, Value)
+
+ ## del operator
+ #
+ def __delitem__(self, Key):
+ self._key_list.remove(Key)
+ IterableUserDict.__delitem__(self, Key)
+
+ ## used in "for k in dict" loop to ensure the correct order
+ #
+ def __iter__(self):
+ return self.iterkeys()
+
+ ## len() support
+ #
+ def __len__(self):
+ return len(self._key_list)
+
+ ## "in" test support
+ #
+ def __contains__(self, Key):
+ return Key in self._key_list
+
+ ## indexof support
+ #
+ def index(self, Key):
+ return self._key_list.index(Key)
+
+ ## insert support
+ #
+ def insert(self, Key, Newkey, Newvalue, Order):
+ Index = self._key_list.index(Key)
+ if Order == 'BEFORE':
+ self._key_list.insert(Index, Newkey)
+ IterableUserDict.__setitem__(self, Newkey, Newvalue)
+ elif Order == 'AFTER':
+ self._key_list.insert(Index + 1, Newkey)
+ IterableUserDict.__setitem__(self, Newkey, Newvalue)
+
+ ## append support
+ #
+ def append(self, Sdict2):
+ for Key in Sdict2:
+ if Key not in self._key_list:
+ self._key_list.append(Key)
+ IterableUserDict.__setitem__(self, Key, Sdict2[Key])
+ ## hash key
+ #
+ def has_key(self, Key):
+ return Key in self._key_list
+
+ ## Empty the dict
+ #
+ def clear(self):
+ self._key_list = []
+ IterableUserDict.clear(self)
+
+ ## Return a copy of keys
+ #
+ def keys(self):
+ Keys = []
+ for Key in self._key_list:
+ Keys.append(Key)
+ return Keys
+
+ ## Return a copy of values
+ #
+ def values(self):
+ Values = []
+ for Key in self._key_list:
+ Values.append(self[Key])
+ return Values
+
+ ## Return a copy of (key, value) list
+ #
+ def items(self):
+ Items = []
+ for Key in self._key_list:
+ Items.append((Key, self[Key]))
+ return Items
+
+ ## Iteration support
+ #
+ def iteritems(self):
+ return iter(self.items())
+
+ ## Keys interation support
+ #
+ def iterkeys(self):
+ return iter(self.keys())
+
+ ## Values interation support
+ #
+ def itervalues(self):
+ return iter(self.values())
+
+ ## Return value related to a key, and remove the (key, value) from the dict
+ #
+ def pop(self, Key, *Dv):
+ Value = None
+ if Key in self._key_list:
+ Value = self[Key]
+ self.__delitem__(Key)
+ elif len(Dv) != 0 :
+ Value = Dv[0]
+ return Value
+
+ ## Return (key, value) pair, and remove the (key, value) from the dict
+ #
+ def popitem(self):
+ Key = self._key_list[-1]
+ Value = self[Key]
+ self.__delitem__(Key)
+ return Key, Value
+ ## update method
+ #
+ def update(self, Dict=None, **Kwargs):
+ if Dict != None:
+ for Key1, Val1 in Dict.items():
+ self[Key1] = Val1
+ if len(Kwargs):
+ for Key1, Val1 in Kwargs.items():
+ self[Key1] = Val1
+
+## CommonPath
+#
+# @param PathList: PathList
+#
+def CommonPath(PathList):
+ Path1 = min(PathList).split(os.path.sep)
+ Path2 = max(PathList).split(os.path.sep)
+ for Index in xrange(min(len(Path1), len(Path2))):
+ if Path1[Index] != Path2[Index]:
+ return os.path.sep.join(Path1[:Index])
+ return os.path.sep.join(Path1)
+
+## PathClass
+#
+class PathClass(object):
+ def __init__(self, File='', Root='', AlterRoot='', Type='', IsBinary=False,
+ Arch='COMMON', ToolChainFamily='', Target='', TagName='', \
+ ToolCode=''):
+ self.Arch = Arch
+ self.File = str(File)
+ if os.path.isabs(self.File):
+ self.Root = ''
+ self.AlterRoot = ''
+ else:
+ self.Root = str(Root)
+ self.AlterRoot = str(AlterRoot)
+
+ #
+ # Remove any '.' and '..' in path
+ #
+ if self.Root:
+ self.Path = os.path.normpath(os.path.join(self.Root, self.File))
+ self.Root = os.path.normpath(CommonPath([self.Root, self.Path]))
+ #
+ # eliminate the side-effect of 'C:'
+ #
+ if self.Root[-1] == ':':
+ self.Root += os.path.sep
+ #
+ # file path should not start with path separator
+ #
+ if self.Root[-1] == os.path.sep:
+ self.File = self.Path[len(self.Root):]
+ else:
+ self.File = self.Path[len(self.Root) + 1:]
+ else:
+ self.Path = os.path.normpath(self.File)
+
+ self.SubDir, self.Name = os.path.split(self.File)
+ self.BaseName, self.Ext = os.path.splitext(self.Name)
+
+ if self.Root:
+ if self.SubDir:
+ self.Dir = os.path.join(self.Root, self.SubDir)
+ else:
+ self.Dir = self.Root
+ else:
+ self.Dir = self.SubDir
+
+ if IsBinary:
+ self.Type = Type
+ else:
+ self.Type = self.Ext.lower()
+
+ self.IsBinary = IsBinary
+ self.Target = Target
+ self.TagName = TagName
+ self.ToolCode = ToolCode
+ self.ToolChainFamily = ToolChainFamily
+
+ self._Key = None
+
+ ## Convert the object of this class to a string
+ #
+ # Convert member Path of the class to a string
+ #
+ def __str__(self):
+ return self.Path
+
+ ## Override __eq__ function
+ #
+ # Check whether PathClass are the same
+ #
+ def __eq__(self, Other):
+ if type(Other) == type(self):
+ return self.Path == Other.Path
+ else:
+ return self.Path == str(Other)
+
+ ## Override __hash__ function
+ #
+ # Use Path as key in hash table
+ #
+ def __hash__(self):
+ return hash(self.Path)
+
+ ## _GetFileKey
+ #
+ def _GetFileKey(self):
+ if self._Key == None:
+ self._Key = self.Path.upper()
+ return self._Key
+ ## Validate
+ #
+ def Validate(self, Type='', CaseSensitive=True):
+ if GlobalData.gCASE_INSENSITIVE:
+ CaseSensitive = False
+ if Type and Type.lower() != self.Type:
+ return ToolError.FILE_TYPE_MISMATCH, '%s (expect %s but got %s)' % \
+ (self.File, Type, self.Type)
+
+ RealFile, RealRoot = RealPath2(self.File, self.Root, self.AlterRoot)
+ if not RealRoot and not RealFile:
+ RealFile = self.File
+ if self.AlterRoot:
+ RealFile = os.path.join(self.AlterRoot, self.File)
+ elif self.Root:
+ RealFile = os.path.join(self.Root, self.File)
+ return ToolError.FILE_NOT_FOUND, os.path.join(self.AlterRoot, RealFile)
+
+ ErrorCode = 0
+ ErrorInfo = ''
+ if RealRoot != self.Root or RealFile != self.File:
+ if CaseSensitive and (RealFile != self.File or \
+ (RealRoot != self.Root and RealRoot != \
+ self.AlterRoot)):
+ ErrorCode = ToolError.FILE_CASE_MISMATCH
+ ErrorInfo = self.File + '\n\t' + RealFile + \
+ " [in file system]"
+
+ self.SubDir, self.Name = os.path.split(RealFile)
+ self.BaseName, self.Ext = os.path.splitext(self.Name)
+ if self.SubDir:
+ self.Dir = os.path.join(RealRoot, self.SubDir)
+ else:
+ self.Dir = RealRoot
+ self.File = RealFile
+ self.Root = RealRoot
+ self.Path = os.path.join(RealRoot, RealFile)
+ return ErrorCode, ErrorInfo
+
+ Key = property(_GetFileKey)
+
+## Check environment variables
+#
+# Check environment variables that must be set for build. Currently they are
+#
+# WORKSPACE The directory all packages/platforms start from
+# EDK_TOOLS_PATH The directory contains all tools needed by the build
+# PATH $(EDK_TOOLS_PATH)/Bin/<sys> must be set in PATH
+#
+# If any of above environment variable is not set or has error, the build
+# will be broken.
+#
+def CheckEnvVariable():
+ #
+ # check WORKSPACE
+ #
+ if "WORKSPACE" not in environ:
+ Logger.Error("UPT",
+ ToolError.UPT_ENVIRON_MISSING_ERROR,
+ ST.ERR_NOT_FOUND_ENVIRONMENT,
+ ExtraData="WORKSPACE")
+
+ WorkspaceDir = os.path.normpath(environ["WORKSPACE"])
+ if not os.path.exists(WorkspaceDir):
+ Logger.Error("UPT",
+ ToolError.UPT_ENVIRON_MISSING_ERROR,
+ ST.ERR_WORKSPACE_NOTEXIST,
+ ExtraData="%s" % WorkspaceDir)
+ elif ' ' in WorkspaceDir:
+ Logger.Error("UPT",
+ ToolError.FORMAT_NOT_SUPPORTED,
+ ST.ERR_SPACE_NOTALLOWED,
+ ExtraData=WorkspaceDir)
+
+## Check whether all module types are in list
+#
+# check whether all module types (SUP_MODULE_LIST) are in list
+#
+# @param ModuleList: a list of ModuleType
+#
+def IsAllModuleList(ModuleList):
+ NewModuleList = [Module.upper() for Module in ModuleList]
+ for Module in SUP_MODULE_LIST:
+ if Module not in NewModuleList:
+ return False
+ else:
+ return True
+
+## Dictionary that use comment(GenericComment, TailComment) as value,
+# if a new comment which key already in the dic is inserted, then the
+# comment will be merged.
+# Key is (Statement, SupArch), when TailComment is added, it will ident
+# according to Statement
+#
+class MergeCommentDict(dict):
+ ## []= operator
+ #
+ def __setitem__(self, Key, CommentVal):
+ GenericComment, TailComment = CommentVal
+ if Key in self:
+ OrigVal1, OrigVal2 = dict.__getitem__(self, Key)
+ Statement = Key[0]
+ dict.__setitem__(self, Key, (OrigVal1 + GenericComment, OrigVal2 \
+ + len(Statement) * ' ' + TailComment))
+ else:
+ dict.__setitem__(self, Key, (GenericComment, TailComment))
+
+ ## =[] operator
+ #
+ def __getitem__(self, Key):
+ return dict.__getitem__(self, Key)
+
+
+## GenDummyHelpTextObj
+#
+# @retval HelpTxt: Generated dummy help text object
+#
+def GenDummyHelpTextObj():
+ HelpTxt = TextObject()
+ HelpTxt.SetLang(LANGUAGE_EN_US)
+ HelpTxt.SetString(' ')
+ return HelpTxt
+
+## ConvertVersionToDecimal, the minor version should be within 0 - 99
+# <HexVersion> ::= "0x" <Major> <Minor>
+# <Major> ::= (a-fA-F0-9){4}
+# <Minor> ::= (a-fA-F0-9){4}
+# <DecVersion> ::= (0-65535) ["." (0-99)]
+#
+# @param StringIn: The string contains version defined in INF file.
+# It can be Decimal or Hex
+#
+def ConvertVersionToDecimal(StringIn):
+ if IsValidHexVersion(StringIn):
+ Value = int(StringIn, 16)
+ Major = Value >> 16
+ Minor = Value & 0xFFFF
+ MinorStr = str(Minor)
+ if len(MinorStr) == 1:
+ MinorStr = '0' + MinorStr
+ return str(Major) + '.' + MinorStr
+ else:
+ if StringIn.find(TAB_SPLIT) != -1:
+ return StringIn
+ elif StringIn:
+ return StringIn + '.0'
+ else:
+ #
+ # when StringIn is '', return it directly
+ #
+ return StringIn
+
+## GetHelpStringByRemoveHashKey
+#
+# Remove hash key at the header of string and return the remain.
+#
+# @param String: The string need to be processed.
+#
+def GetHelpStringByRemoveHashKey(String):
+ ReturnString = ''
+ PattenRemoveHashKey = re.compile(r"^[#+\s]+", re.DOTALL)
+ String = String.strip()
+ if String == '':
+ return String
+
+ LineList = GetSplitValueList(String, END_OF_LINE)
+ for Line in LineList:
+ ValueList = PattenRemoveHashKey.split(Line)
+ if len(ValueList) == 1:
+ ReturnString += ValueList[0] + END_OF_LINE
+ else:
+ ReturnString += ValueList[1] + END_OF_LINE
+
+ if ReturnString.endswith('\n') and not ReturnString.endswith('\n\n') and ReturnString != '\n':
+ ReturnString = ReturnString[:-1]
+
+ return ReturnString
+
+## ConvPathFromAbsToRel
+#
+# Get relative file path from absolute path.
+#
+# @param Path: The string contain file absolute path.
+# @param Root: The string contain the parent path of Path in.
+#
+#
+def ConvPathFromAbsToRel(Path, Root):
+ Path = os.path.normpath(Path)
+ Root = os.path.normpath(Root)
+ FullPath = os.path.normpath(os.path.join(Root, Path))
+
+ #
+ # If Path is absolute path.
+ # It should be in Root.
+ #
+ if os.path.isabs(Path):
+ return FullPath[FullPath.find(Root) + len(Root) + 1:]
+
+ else:
+ return Path
+
+## ConvertPath
+#
+# Convert special characters to '_', '\' to '/'
+# return converted path: Test!1.inf -> Test_1.inf
+#
+# @param Path: Path to be converted
+#
+def ConvertPath(Path):
+ RetPath = ''
+ for Char in Path.strip():
+ if Char.isalnum() or Char in '.-_/':
+ RetPath = RetPath + Char
+ elif Char == '\\':
+ RetPath = RetPath + '/'
+ else:
+ RetPath = RetPath + '_'
+ return RetPath
+
+## ConvertSpec
+#
+# during install, convert the Spec string extract from UPD into INF allowable definition,
+# the difference is period is allowed in the former (not the first letter) but not in the latter.
+# return converted Spec string
+#
+# @param SpecStr: SpecStr to be converted
+#
+def ConvertSpec(SpecStr):
+ RetStr = ''
+ for Char in SpecStr:
+ if Char.isalnum() or Char == '_':
+ RetStr = RetStr + Char
+ else:
+ RetStr = RetStr + '_'
+
+ return RetStr
+
+
+## IsEqualList
+#
+# Judge two lists are identical(contain same item).
+# The rule is elements in List A are in List B and elements in List B are in List A.
+#
+# @param ListA, ListB Lists need to be judged.
+#
+# @return True ListA and ListB are identical
+# @return False ListA and ListB are different with each other
+#
+def IsEqualList(ListA, ListB):
+ if ListA == ListB:
+ return True
+
+ for ItemA in ListA:
+ if not ItemA in ListB:
+ return False
+
+ for ItemB in ListB:
+ if not ItemB in ListA:
+ return False
+
+ return True
+
+## ConvertArchList
+#
+# Convert item in ArchList if the start character is lower case.
+# In UDP spec, Arch is only allowed as: [A-Z]([a-zA-Z0-9])*
+#
+# @param ArchList The ArchList need to be converted.
+#
+# @return NewList The ArchList been converted.
+#
+def ConvertArchList(ArchList):
+ NewArchList = []
+ if not ArchList:
+ return NewArchList
+
+ if type(ArchList) == list:
+ for Arch in ArchList:
+ Arch = Arch.upper()
+ NewArchList.append(Arch)
+ elif type(ArchList) == str:
+ ArchList = ArchList.upper()
+ NewArchList.append(ArchList)
+
+ return NewArchList
+
+## ProcessLineExtender
+#
+# Process the LineExtender of Line in LineList.
+# If one line ends with a line extender, then it will be combined together with next line.
+#
+# @param LineList The LineList need to be processed.
+#
+# @return NewList The ArchList been processed.
+#
+def ProcessLineExtender(LineList):
+ NewList = []
+ Count = 0
+ while Count < len(LineList):
+ if LineList[Count].strip().endswith("\\") and Count + 1 < len(LineList):
+ NewList.append(LineList[Count].strip()[:-2] + LineList[Count + 1])
+ Count = Count + 1
+ else:
+ NewList.append(LineList[Count])
+
+ Count = Count + 1
+
+ return NewList
+
+## ProcessEdkComment
+#
+# Process EDK style comment in LineList: c style /* */ comment or cpp style // comment
+#
+#
+# @param LineList The LineList need to be processed.
+#
+# @return LineList The LineList been processed.
+# @return FirstPos Where Edk comment is first found, -1 if not found
+#
+def ProcessEdkComment(LineList):
+ FindEdkBlockComment = False
+ Count = 0
+ StartPos = -1
+ EndPos = -1
+ FirstPos = -1
+
+ while(Count < len(LineList)):
+ Line = LineList[Count].strip()
+ if Line.startswith("/*"):
+ #
+ # handling c style comment
+ #
+ StartPos = Count
+ while Count < len(LineList):
+ Line = LineList[Count].strip()
+ if Line.endswith("*/"):
+ if (Count == StartPos) and Line.strip() == '/*/':
+ Count = Count + 1
+ continue
+ EndPos = Count
+ FindEdkBlockComment = True
+ break
+ Count = Count + 1
+
+ if FindEdkBlockComment:
+ if FirstPos == -1:
+ FirstPos = StartPos
+ for Index in xrange(StartPos, EndPos+1):
+ LineList[Index] = ''
+ FindEdkBlockComment = False
+ elif Line.find("//") != -1 and not Line.startswith("#"):
+ #
+ # handling cpp style comment
+ #
+ LineList[Count] = Line.replace("//", '#')
+ if FirstPos == -1:
+ FirstPos = Count
+
+ Count = Count + 1
+
+ return LineList, FirstPos
+
+## GetLibInstanceInfo
+#
+# Get the information from Library Instance INF file.
+#
+# @param string. A string start with # and followed by INF file path
+# @param WorkSpace. The WorkSpace directory used to combined with INF file path.
+#
+# @return GUID, Version
+def GetLibInstanceInfo(String, WorkSpace, LineNo):
+
+ FileGuidString = ""
+ VerString = ""
+
+ OrignalString = String
+ String = String.strip()
+ if not String:
+ return None, None
+ #
+ # Remove "#" characters at the beginning
+ #
+ String = GetHelpStringByRemoveHashKey(String)
+ String = String.strip()
+
+ #
+ # Validate file name exist.
+ #
+ FullFileName = os.path.normpath(os.path.realpath(os.path.join(WorkSpace, String)))
+ if not (ValidFile(FullFileName)):
+ Logger.Error("InfParser",
+ ToolError.FORMAT_INVALID,
+ ST.ERR_FILELIST_EXIST % (String),
+ File=GlobalData.gINF_MODULE_NAME,
+ Line=LineNo,
+ ExtraData=OrignalString)
+
+ #
+ # Validate file exist/format.
+ #
+ if IsValidPath(String, WorkSpace):
+ IsValidFileFlag = True
+ else:
+ Logger.Error("InfParser",
+ ToolError.FORMAT_INVALID,
+ ST.ERR_INF_PARSER_FILE_NOT_EXIST_OR_NAME_INVALID % (String),
+ File=GlobalData.gINF_MODULE_NAME,
+ Line=LineNo,
+ ExtraData=OrignalString)
+ return False
+ if IsValidFileFlag:
+ FileLinesList = []
+
+ try:
+ FInputfile = open(FullFileName, "rb", 0)
+ try:
+ FileLinesList = FInputfile.readlines()
+ except BaseException:
+ Logger.Error("InfParser",
+ ToolError.FILE_READ_FAILURE,
+ ST.ERR_FILE_OPEN_FAILURE,
+ File=FullFileName)
+ finally:
+ FInputfile.close()
+ except BaseException:
+ Logger.Error("InfParser",
+ ToolError.FILE_READ_FAILURE,
+ ST.ERR_FILE_OPEN_FAILURE,
+ File=FullFileName)
+
+ ReFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$")
+ ReVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$")
+
+ FileLinesList = ProcessLineExtender(FileLinesList)
+
+ for Line in FileLinesList:
+ if ReFileGuidPattern.match(Line):
+ FileGuidString = Line
+ if ReVerStringPattern.match(Line):
+ VerString = Line
+
+ if FileGuidString:
+ FileGuidString = GetSplitValueList(FileGuidString, '=', 1)[1]
+ if VerString:
+ VerString = GetSplitValueList(VerString, '=', 1)[1]
+
+ return FileGuidString, VerString
diff --git a/BaseTools/Source/Python/UPT/Library/Xml/__init__.py b/BaseTools/Source/Python/UPT/Library/Xml/__init__.py index 5d268d990b..f09eece5fb 100644 --- a/BaseTools/Source/Python/UPT/Library/Xml/__init__.py +++ b/BaseTools/Source/Python/UPT/Library/Xml/__init__.py @@ -1,20 +1,20 @@ -## @file -# Python 'Library' package initialization file. -# -# This file is required to make Python interpreter treat the directory -# as containing package. -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. -# - -''' -Xml +## @file
+# Python 'Library' package initialization file.
+#
+# This file is required to make Python interpreter treat the directory
+# as containing package.
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+#
+
+'''
+Xml
'''
\ No newline at end of file diff --git a/BaseTools/Source/Python/UPT/Library/__init__.py b/BaseTools/Source/Python/UPT/Library/__init__.py index b265bc873c..6a98cd80a3 100644 --- a/BaseTools/Source/Python/UPT/Library/__init__.py +++ b/BaseTools/Source/Python/UPT/Library/__init__.py @@ -1,20 +1,20 @@ -## @file -# Python 'Library' package initialization file. -# -# This file is required to make Python interpreter treat the directory -# as containing package. -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. -# - -''' -Library +## @file
+# Python 'Library' package initialization file.
+#
+# This file is required to make Python interpreter treat the directory
+# as containing package.
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+#
+
+'''
+Library
'''
\ No newline at end of file diff --git a/BaseTools/Source/Python/UPT/Logger/Log.py b/BaseTools/Source/Python/UPT/Logger/Log.py index 0915bb7263..407a1b32b6 100644 --- a/BaseTools/Source/Python/UPT/Logger/Log.py +++ b/BaseTools/Source/Python/UPT/Logger/Log.py @@ -1,325 +1,325 @@ -## @file -# This file implements the log mechanism for Python tools. -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. -# - -''' -Logger -''' - -## Import modules -from sys import argv -from sys import stdout -from sys import stderr -import os.path -from os import remove -from logging import getLogger -from logging import Formatter -from logging import StreamHandler -from logging import FileHandler -from traceback import extract_stack - -from Logger.ToolError import FatalError -from Logger.ToolError import WARNING_AS_ERROR -from Logger.ToolError import gERROR_MESSAGE -from Logger.ToolError import UNKNOWN_ERROR -from Library import GlobalData - -# -# Log level constants -# -DEBUG_0 = 1 -DEBUG_1 = 2 -DEBUG_2 = 3 -DEBUG_3 = 4 -DEBUG_4 = 5 -DEBUG_5 = 6 -DEBUG_6 = 7 -DEBUG_7 = 8 -DEBUG_8 = 9 -DEBUG_9 = 10 -VERBOSE = 15 -INFO = 20 -WARN = 30 -QUIET = 40 -QUIET_1 = 41 -ERROR = 50 -SILENT = 60 - -IS_RAISE_ERROR = True -SUPRESS_ERROR = False - -# -# Tool name -# -_TOOL_NAME = os.path.basename(argv[0]) -# -# For validation purpose -# -_LOG_LEVELS = [DEBUG_0, DEBUG_1, DEBUG_2, DEBUG_3, DEBUG_4, DEBUG_5, DEBUG_6, \ - DEBUG_7, DEBUG_8, DEBUG_9, VERBOSE, WARN, INFO, ERROR, QUIET, \ - QUIET_1, SILENT] -# -# For DEBUG level (All DEBUG_0~9 are applicable) -# -_DEBUG_LOGGER = getLogger("tool_debug") -_DEBUG_FORMATTER = Formatter("[%(asctime)s.%(msecs)d]: %(message)s", \ - datefmt="%H:%M:%S") -# -# For VERBOSE, INFO, WARN level -# -_INFO_LOGGER = getLogger("tool_info") -_INFO_FORMATTER = Formatter("%(message)s") -# -# For ERROR level -# -_ERROR_LOGGER = getLogger("tool_error") -_ERROR_FORMATTER = Formatter("%(message)s") - -# -# String templates for ERROR/WARN/DEBUG log message -# -_ERROR_MESSAGE_TEMPLATE = \ -('\n\n%(tool)s...\n%(file)s(%(line)s): error %(errorcode)04X: %(msg)s\n\t%(extra)s') - -__ERROR_MESSAGE_TEMPLATE_WITHOUT_FILE = \ -'\n\n%(tool)s...\n : error %(errorcode)04X: %(msg)s\n\t%(extra)s' - -_WARNING_MESSAGE_TEMPLATE = '%(tool)s...\n%(file)s(%(line)s): warning: %(msg)s' -_WARNING_MESSAGE_TEMPLATE_WITHOUT_FILE = '%(tool)s: : warning: %(msg)s' -_DEBUG_MESSAGE_TEMPLATE = '%(file)s(%(line)s): debug: \n %(msg)s' - - -# -# Log INFO message -# -#Info = _INFO_LOGGER.info - -def Info(msg, *args, **kwargs): - _INFO_LOGGER.info(msg, *args, **kwargs) - -# -# Log information which should be always put out -# -def Quiet(msg, *args, **kwargs): - _ERROR_LOGGER.error(msg, *args, **kwargs) - -## Log debug message -# -# @param Level DEBUG level (DEBUG0~9) -# @param Message Debug information -# @param ExtraData More information associated with "Message" -# -def Debug(Level, Message, ExtraData=None): - if _DEBUG_LOGGER.level > Level: - return - if Level > DEBUG_9: - return - # - # Find out the caller method information - # - CallerStack = extract_stack()[-2] - TemplateDict = { - "file" : CallerStack[0], - "line" : CallerStack[1], - "msg" : Message, - } - - if ExtraData != None: - LogText = _DEBUG_MESSAGE_TEMPLATE % TemplateDict + "\n %s" % ExtraData - else: - LogText = _DEBUG_MESSAGE_TEMPLATE % TemplateDict - - _DEBUG_LOGGER.log(Level, LogText) - -## Log verbose message -# -# @param Message Verbose information -# -def Verbose(Message): - return _INFO_LOGGER.log(VERBOSE, Message) - -## Log warning message -# -# Warning messages are those which might be wrong but won't fail the tool. -# -# @param ToolName The name of the tool. If not given, the name of caller -# method will be used. -# @param Message Warning information -# @param File The name of file which caused the warning. -# @param Line The line number in the "File" which caused the warning. -# @param ExtraData More information associated with "Message" -# -def Warn(ToolName, Message, File=None, Line=None, ExtraData=None): - if _INFO_LOGGER.level > WARN: - return - # - # if no tool name given, use caller's source file name as tool name - # - if ToolName == None or ToolName == "": - ToolName = os.path.basename(extract_stack()[-2][0]) - - if Line == None: - Line = "..." - else: - Line = "%d" % Line - - TemplateDict = { - "tool" : ToolName, - "file" : File, - "line" : Line, - "msg" : Message, - } - - if File != None: - LogText = _WARNING_MESSAGE_TEMPLATE % TemplateDict - else: - LogText = _WARNING_MESSAGE_TEMPLATE_WITHOUT_FILE % TemplateDict - - if ExtraData != None: - LogText += "\n %s" % ExtraData - - _INFO_LOGGER.log(WARN, LogText) - # - # Raise an execption if indicated - # - if GlobalData.gWARNING_AS_ERROR == True: - raise FatalError(WARNING_AS_ERROR) - -## Log ERROR message -# -# Once an error messages is logged, the tool's execution will be broken by -# raising an execption. If you don't want to break the execution later, you -# can give "RaiseError" with "False" value. -# -# @param ToolName The name of the tool. If not given, the name of caller -# method will be used. -# @param ErrorCode The error code -# @param Message Warning information -# @param File The name of file which caused the error. -# @param Line The line number in the "File" which caused the warning. -# @param ExtraData More information associated with "Message" -# @param RaiseError Raise an exception to break the tool's executuion if -# it's True. This is the default behavior. -# -def Error(ToolName, ErrorCode, Message=None, File=None, Line=None, \ - ExtraData=None, RaiseError=IS_RAISE_ERROR): - if ToolName: - pass - if Line == None: - Line = "..." - else: - Line = "%d" % Line - - if Message == None: - if ErrorCode in gERROR_MESSAGE: - Message = gERROR_MESSAGE[ErrorCode] - else: - Message = gERROR_MESSAGE[UNKNOWN_ERROR] - - if ExtraData == None: - ExtraData = "" - - TemplateDict = { - "tool" : _TOOL_NAME, - "file" : File, - "line" : Line, - "errorcode" : ErrorCode, - "msg" : Message, - "extra" : ExtraData - } - - if File != None: - LogText = _ERROR_MESSAGE_TEMPLATE % TemplateDict - else: - LogText = __ERROR_MESSAGE_TEMPLATE_WITHOUT_FILE % TemplateDict - - if not SUPRESS_ERROR: - _ERROR_LOGGER.log(ERROR, LogText) - if RaiseError: - raise FatalError(ErrorCode) - - -## Initialize log system -# -def Initialize(): - # - # Since we use different format to log different levels of message into - # different place (stdout or stderr), we have to use different "Logger" - # objects to do this. - # - # For DEBUG level (All DEBUG_0~9 are applicable) - _DEBUG_LOGGER.setLevel(INFO) - _DebugChannel = StreamHandler(stdout) - _DebugChannel.setFormatter(_DEBUG_FORMATTER) - _DEBUG_LOGGER.addHandler(_DebugChannel) - # - # For VERBOSE, INFO, WARN level - # - _INFO_LOGGER.setLevel(INFO) - _InfoChannel = StreamHandler(stdout) - _InfoChannel.setFormatter(_INFO_FORMATTER) - _INFO_LOGGER.addHandler(_InfoChannel) - # - # For ERROR level - # - _ERROR_LOGGER.setLevel(INFO) - _ErrorCh = StreamHandler(stderr) - _ErrorCh.setFormatter(_ERROR_FORMATTER) - _ERROR_LOGGER.addHandler(_ErrorCh) - - -## Set log level -# -# @param Level One of log level in _LogLevel -# -def SetLevel(Level): - if Level not in _LOG_LEVELS: - Info("Not supported log level (%d). Use default level instead." % \ - Level) - Level = INFO - _DEBUG_LOGGER.setLevel(Level) - _INFO_LOGGER.setLevel(Level) - _ERROR_LOGGER.setLevel(Level) - -## Get current log level -# -def GetLevel(): - return _INFO_LOGGER.getEffectiveLevel() - -## Raise up warning as error -# -def SetWarningAsError(): - GlobalData.gWARNING_AS_ERROR = True - -## Specify a file to store the log message as well as put on console -# -# @param LogFile The file path used to store the log message -# -def SetLogFile(LogFile): - if os.path.exists(LogFile): - remove(LogFile) - - _Ch = FileHandler(LogFile) - _Ch.setFormatter(_DEBUG_FORMATTER) - _DEBUG_LOGGER.addHandler(_Ch) - - _Ch = FileHandler(LogFile) - _Ch.setFormatter(_INFO_FORMATTER) - _INFO_LOGGER.addHandler(_Ch) - - _Ch = FileHandler(LogFile) - _Ch.setFormatter(_ERROR_FORMATTER) - _ERROR_LOGGER.addHandler(_Ch) - - - +## @file
+# This file implements the log mechanism for Python tools.
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+#
+
+'''
+Logger
+'''
+
+## Import modules
+from sys import argv
+from sys import stdout
+from sys import stderr
+import os.path
+from os import remove
+from logging import getLogger
+from logging import Formatter
+from logging import StreamHandler
+from logging import FileHandler
+from traceback import extract_stack
+
+from Logger.ToolError import FatalError
+from Logger.ToolError import WARNING_AS_ERROR
+from Logger.ToolError import gERROR_MESSAGE
+from Logger.ToolError import UNKNOWN_ERROR
+from Library import GlobalData
+
+#
+# Log level constants
+#
+DEBUG_0 = 1
+DEBUG_1 = 2
+DEBUG_2 = 3
+DEBUG_3 = 4
+DEBUG_4 = 5
+DEBUG_5 = 6
+DEBUG_6 = 7
+DEBUG_7 = 8
+DEBUG_8 = 9
+DEBUG_9 = 10
+VERBOSE = 15
+INFO = 20
+WARN = 30
+QUIET = 40
+QUIET_1 = 41
+ERROR = 50
+SILENT = 60
+
+IS_RAISE_ERROR = True
+SUPRESS_ERROR = False
+
+#
+# Tool name
+#
+_TOOL_NAME = os.path.basename(argv[0])
+#
+# For validation purpose
+#
+_LOG_LEVELS = [DEBUG_0, DEBUG_1, DEBUG_2, DEBUG_3, DEBUG_4, DEBUG_5, DEBUG_6, \
+ DEBUG_7, DEBUG_8, DEBUG_9, VERBOSE, WARN, INFO, ERROR, QUIET, \
+ QUIET_1, SILENT]
+#
+# For DEBUG level (All DEBUG_0~9 are applicable)
+#
+_DEBUG_LOGGER = getLogger("tool_debug")
+_DEBUG_FORMATTER = Formatter("[%(asctime)s.%(msecs)d]: %(message)s", \
+ datefmt="%H:%M:%S")
+#
+# For VERBOSE, INFO, WARN level
+#
+_INFO_LOGGER = getLogger("tool_info")
+_INFO_FORMATTER = Formatter("%(message)s")
+#
+# For ERROR level
+#
+_ERROR_LOGGER = getLogger("tool_error")
+_ERROR_FORMATTER = Formatter("%(message)s")
+
+#
+# String templates for ERROR/WARN/DEBUG log message
+#
+_ERROR_MESSAGE_TEMPLATE = \
+('\n\n%(tool)s...\n%(file)s(%(line)s): error %(errorcode)04X: %(msg)s\n\t%(extra)s')
+
+__ERROR_MESSAGE_TEMPLATE_WITHOUT_FILE = \
+'\n\n%(tool)s...\n : error %(errorcode)04X: %(msg)s\n\t%(extra)s'
+
+_WARNING_MESSAGE_TEMPLATE = '%(tool)s...\n%(file)s(%(line)s): warning: %(msg)s'
+_WARNING_MESSAGE_TEMPLATE_WITHOUT_FILE = '%(tool)s: : warning: %(msg)s'
+_DEBUG_MESSAGE_TEMPLATE = '%(file)s(%(line)s): debug: \n %(msg)s'
+
+
+#
+# Log INFO message
+#
+#Info = _INFO_LOGGER.info
+
+def Info(msg, *args, **kwargs):
+ _INFO_LOGGER.info(msg, *args, **kwargs)
+
+#
+# Log information which should be always put out
+#
+def Quiet(msg, *args, **kwargs):
+ _ERROR_LOGGER.error(msg, *args, **kwargs)
+
+## Log debug message
+#
+# @param Level DEBUG level (DEBUG0~9)
+# @param Message Debug information
+# @param ExtraData More information associated with "Message"
+#
+def Debug(Level, Message, ExtraData=None):
+ if _DEBUG_LOGGER.level > Level:
+ return
+ if Level > DEBUG_9:
+ return
+ #
+ # Find out the caller method information
+ #
+ CallerStack = extract_stack()[-2]
+ TemplateDict = {
+ "file" : CallerStack[0],
+ "line" : CallerStack[1],
+ "msg" : Message,
+ }
+
+ if ExtraData != None:
+ LogText = _DEBUG_MESSAGE_TEMPLATE % TemplateDict + "\n %s" % ExtraData
+ else:
+ LogText = _DEBUG_MESSAGE_TEMPLATE % TemplateDict
+
+ _DEBUG_LOGGER.log(Level, LogText)
+
+## Log verbose message
+#
+# @param Message Verbose information
+#
+def Verbose(Message):
+ return _INFO_LOGGER.log(VERBOSE, Message)
+
+## Log warning message
+#
+# Warning messages are those which might be wrong but won't fail the tool.
+#
+# @param ToolName The name of the tool. If not given, the name of caller
+# method will be used.
+# @param Message Warning information
+# @param File The name of file which caused the warning.
+# @param Line The line number in the "File" which caused the warning.
+# @param ExtraData More information associated with "Message"
+#
+def Warn(ToolName, Message, File=None, Line=None, ExtraData=None):
+ if _INFO_LOGGER.level > WARN:
+ return
+ #
+ # if no tool name given, use caller's source file name as tool name
+ #
+ if ToolName == None or ToolName == "":
+ ToolName = os.path.basename(extract_stack()[-2][0])
+
+ if Line == None:
+ Line = "..."
+ else:
+ Line = "%d" % Line
+
+ TemplateDict = {
+ "tool" : ToolName,
+ "file" : File,
+ "line" : Line,
+ "msg" : Message,
+ }
+
+ if File != None:
+ LogText = _WARNING_MESSAGE_TEMPLATE % TemplateDict
+ else:
+ LogText = _WARNING_MESSAGE_TEMPLATE_WITHOUT_FILE % TemplateDict
+
+ if ExtraData != None:
+ LogText += "\n %s" % ExtraData
+
+ _INFO_LOGGER.log(WARN, LogText)
+ #
+ # Raise an execption if indicated
+ #
+ if GlobalData.gWARNING_AS_ERROR == True:
+ raise FatalError(WARNING_AS_ERROR)
+
+## Log ERROR message
+#
+# Once an error messages is logged, the tool's execution will be broken by
+# raising an execption. If you don't want to break the execution later, you
+# can give "RaiseError" with "False" value.
+#
+# @param ToolName The name of the tool. If not given, the name of caller
+# method will be used.
+# @param ErrorCode The error code
+# @param Message Warning information
+# @param File The name of file which caused the error.
+# @param Line The line number in the "File" which caused the warning.
+# @param ExtraData More information associated with "Message"
+# @param RaiseError Raise an exception to break the tool's executuion if
+# it's True. This is the default behavior.
+#
+def Error(ToolName, ErrorCode, Message=None, File=None, Line=None, \
+ ExtraData=None, RaiseError=IS_RAISE_ERROR):
+ if ToolName:
+ pass
+ if Line == None:
+ Line = "..."
+ else:
+ Line = "%d" % Line
+
+ if Message == None:
+ if ErrorCode in gERROR_MESSAGE:
+ Message = gERROR_MESSAGE[ErrorCode]
+ else:
+ Message = gERROR_MESSAGE[UNKNOWN_ERROR]
+
+ if ExtraData == None:
+ ExtraData = ""
+
+ TemplateDict = {
+ "tool" : _TOOL_NAME,
+ "file" : File,
+ "line" : Line,
+ "errorcode" : ErrorCode,
+ "msg" : Message,
+ "extra" : ExtraData
+ }
+
+ if File != None:
+ LogText = _ERROR_MESSAGE_TEMPLATE % TemplateDict
+ else:
+ LogText = __ERROR_MESSAGE_TEMPLATE_WITHOUT_FILE % TemplateDict
+
+ if not SUPRESS_ERROR:
+ _ERROR_LOGGER.log(ERROR, LogText)
+ if RaiseError:
+ raise FatalError(ErrorCode)
+
+
+## Initialize log system
+#
+def Initialize():
+ #
+ # Since we use different format to log different levels of message into
+ # different place (stdout or stderr), we have to use different "Logger"
+ # objects to do this.
+ #
+ # For DEBUG level (All DEBUG_0~9 are applicable)
+ _DEBUG_LOGGER.setLevel(INFO)
+ _DebugChannel = StreamHandler(stdout)
+ _DebugChannel.setFormatter(_DEBUG_FORMATTER)
+ _DEBUG_LOGGER.addHandler(_DebugChannel)
+ #
+ # For VERBOSE, INFO, WARN level
+ #
+ _INFO_LOGGER.setLevel(INFO)
+ _InfoChannel = StreamHandler(stdout)
+ _InfoChannel.setFormatter(_INFO_FORMATTER)
+ _INFO_LOGGER.addHandler(_InfoChannel)
+ #
+ # For ERROR level
+ #
+ _ERROR_LOGGER.setLevel(INFO)
+ _ErrorCh = StreamHandler(stderr)
+ _ErrorCh.setFormatter(_ERROR_FORMATTER)
+ _ERROR_LOGGER.addHandler(_ErrorCh)
+
+
+## Set log level
+#
+# @param Level One of log level in _LogLevel
+#
+def SetLevel(Level):
+ if Level not in _LOG_LEVELS:
+ Info("Not supported log level (%d). Use default level instead." % \
+ Level)
+ Level = INFO
+ _DEBUG_LOGGER.setLevel(Level)
+ _INFO_LOGGER.setLevel(Level)
+ _ERROR_LOGGER.setLevel(Level)
+
+## Get current log level
+#
+def GetLevel():
+ return _INFO_LOGGER.getEffectiveLevel()
+
+## Raise up warning as error
+#
+def SetWarningAsError():
+ GlobalData.gWARNING_AS_ERROR = True
+
+## Specify a file to store the log message as well as put on console
+#
+# @param LogFile The file path used to store the log message
+#
+def SetLogFile(LogFile):
+ if os.path.exists(LogFile):
+ remove(LogFile)
+
+ _Ch = FileHandler(LogFile)
+ _Ch.setFormatter(_DEBUG_FORMATTER)
+ _DEBUG_LOGGER.addHandler(_Ch)
+
+ _Ch = FileHandler(LogFile)
+ _Ch.setFormatter(_INFO_FORMATTER)
+ _INFO_LOGGER.addHandler(_Ch)
+
+ _Ch = FileHandler(LogFile)
+ _Ch.setFormatter(_ERROR_FORMATTER)
+ _ERROR_LOGGER.addHandler(_Ch)
+
+
+
diff --git a/BaseTools/Source/Python/UPT/Logger/ToolError.py b/BaseTools/Source/Python/UPT/Logger/ToolError.py index 906d03337c..5065b370a3 100644 --- a/BaseTools/Source/Python/UPT/Logger/ToolError.py +++ b/BaseTools/Source/Python/UPT/Logger/ToolError.py @@ -1,177 +1,177 @@ -## @file -# Standardized Error Hanlding infrastructures. -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. -# - -''' -ToolError -''' - -import Logger.StringTable as ST - -FILE_OPEN_FAILURE = 1 -FILE_WRITE_FAILURE = 2 -FILE_PARSE_FAILURE = 3 -FILE_READ_FAILURE = 4 -FILE_CREATE_FAILURE = 5 -FILE_CHECKSUM_FAILURE = 6 -FILE_COMPRESS_FAILURE = 7 -FILE_DECOMPRESS_FAILURE = 8 -FILE_MOVE_FAILURE = 9 -FILE_DELETE_FAILURE = 10 -FILE_COPY_FAILURE = 11 -FILE_POSITIONING_FAILURE = 12 -FILE_ALREADY_EXIST = 13 -FILE_NOT_FOUND = 14 -FILE_TYPE_MISMATCH = 15 -FILE_CASE_MISMATCH = 16 -FILE_DUPLICATED = 17 -FILE_UNKNOWN_ERROR = 0x0FFF - -OPTION_UNKNOWN = 0x1000 -OPTION_MISSING = 0x1001 -OPTION_CONFLICT = 0x1002 -OPTION_VALUE_INVALID = 0x1003 -OPTION_DEPRECATED = 0x1004 -OPTION_NOT_SUPPORTED = 0x1005 -OPTION_UNKNOWN_ERROR = 0x1FFF - -PARAMETER_INVALID = 0x2000 -PARAMETER_MISSING = 0x2001 -PARAMETER_UNKNOWN_ERROR = 0x2FFF - -FORMAT_INVALID = 0x3000 -FORMAT_NOT_SUPPORTED = 0x3001 -FORMAT_UNKNOWN = 0x3002 -FORMAT_UNKNOWN_ERROR = 0x3FFF - -RESOURCE_NOT_AVAILABLE = 0x4000 -RESOURCE_ALLOCATE_FAILURE = 0x4001 -RESOURCE_FULL = 0x4002 -RESOURCE_OVERFLOW = 0x4003 -RESOURCE_UNDERRUN = 0x4004 -RESOURCE_UNKNOWN_ERROR = 0x4FFF - -ATTRIBUTE_NOT_AVAILABLE = 0x5000 -ATTRIBUTE_GET_FAILURE = 0x5001 -ATTRIBUTE_SET_FAILURE = 0x5002 -ATTRIBUTE_UPDATE_FAILURE = 0x5003 -ATTRIBUTE_ACCESS_DENIED = 0x5004 -ATTRIBUTE_RETRIEVE_FAILURE = 0x5005 -ATTRIBUTE_UNKNOWN_ERROR = 0x5FFF -ATTRIBUTE_RETRIEVE_FAILURE = 0x5F00 - -IO_NOT_READY = 0x6000 -IO_BUSY = 0x6001 -IO_TIMEOUT = 0x6002 -IO_UNKNOWN_ERROR = 0x6FFF - -COMMAND_FAILURE = 0x7000 - -CODE_ERROR = 0xC0DE - -AUTOGEN_ERROR = 0xF000 -PARSER_ERROR = 0xF001 -BUILD_ERROR = 0xF002 -GENFDS_ERROR = 0xF003 -ECC_ERROR = 0xF004 -EOT_ERROR = 0xF005 -DDC_ERROR = 0xF009 -WARNING_AS_ERROR = 0xF006 -MIGRATION_ERROR = 0xF010 -EDK1_INF_ERROR = 0xF011 -ABORT_ERROR = 0xFFFE -UNKNOWN_ERROR = 0xFFFF - -UPT_ALREADY_INSTALLED_ERROR = 0xD000 -UPT_ENVIRON_MISSING_ERROR = 0xD001 -UPT_REPKG_ERROR = 0xD002 -UPT_ALREADY_RUNNING_ERROR = 0xD003 -UPT_MUL_DEC_ERROR = 0xD004 -UPT_DB_UPDATE_ERROR = 0xD005 -UPT_INI_PARSE_ERROR = 0xE000 - -## Error message of each error code -# -gERROR_MESSAGE = { - FILE_NOT_FOUND : ST.ERR_FILE_NOT_FOUND, - FILE_OPEN_FAILURE : ST.ERR_FILE_OPEN_FAILURE, - FILE_WRITE_FAILURE : ST.ERR_FILE_WRITE_FAILURE, - FILE_PARSE_FAILURE : ST.ERR_FILE_PARSE_FAILURE, - FILE_READ_FAILURE : ST.ERR_FILE_READ_FAILURE, - FILE_CREATE_FAILURE : ST.ERR_FILE_CREATE_FAILURE, - FILE_CHECKSUM_FAILURE : ST.ERR_FILE_CHECKSUM_FAILURE, - FILE_COMPRESS_FAILURE : ST.ERR_FILE_COMPRESS_FAILURE, - FILE_DECOMPRESS_FAILURE : ST.ERR_FILE_DECOMPRESS_FAILURE, - FILE_MOVE_FAILURE : ST.ERR_FILE_MOVE_FAILURE, - FILE_DELETE_FAILURE : ST.ERR_FILE_DELETE_FAILURE, - FILE_COPY_FAILURE : ST.ERR_FILE_COPY_FAILURE, - FILE_POSITIONING_FAILURE: ST.ERR_FILE_POSITIONING_FAILURE, - FILE_ALREADY_EXIST : ST.ERR_FILE_ALREADY_EXIST, - FILE_TYPE_MISMATCH : ST.ERR_FILE_TYPE_MISMATCH , - FILE_CASE_MISMATCH : ST.ERR_FILE_CASE_MISMATCH, - FILE_DUPLICATED : ST.ERR_FILE_DUPLICATED, - FILE_UNKNOWN_ERROR : ST.ERR_FILE_UNKNOWN_ERROR, - - OPTION_UNKNOWN : ST.ERR_OPTION_UNKNOWN, - OPTION_MISSING : ST.ERR_OPTION_MISSING, - OPTION_CONFLICT : ST.ERR_OPTION_CONFLICT, - OPTION_VALUE_INVALID : ST.ERR_OPTION_VALUE_INVALID, - OPTION_DEPRECATED : ST.ERR_OPTION_DEPRECATED, - OPTION_NOT_SUPPORTED : ST.ERR_OPTION_NOT_SUPPORTED, - OPTION_UNKNOWN_ERROR : ST.ERR_OPTION_UNKNOWN_ERROR, - - PARAMETER_INVALID : ST.ERR_PARAMETER_INVALID, - PARAMETER_MISSING : ST.ERR_PARAMETER_MISSING, - PARAMETER_UNKNOWN_ERROR : ST.ERR_PARAMETER_UNKNOWN_ERROR, - - FORMAT_INVALID : ST.ERR_FORMAT_INVALID, - FORMAT_NOT_SUPPORTED : ST.ERR_FORMAT_NOT_SUPPORTED, - FORMAT_UNKNOWN : ST.ERR_FORMAT_UNKNOWN, - FORMAT_UNKNOWN_ERROR : ST.ERR_FORMAT_UNKNOWN_ERROR, - - RESOURCE_NOT_AVAILABLE : ST.ERR_RESOURCE_NOT_AVAILABLE, - RESOURCE_ALLOCATE_FAILURE : ST.ERR_RESOURCE_ALLOCATE_FAILURE, - RESOURCE_FULL : ST.ERR_RESOURCE_FULL, - RESOURCE_OVERFLOW : ST.ERR_RESOURCE_OVERFLOW, - RESOURCE_UNDERRUN : ST.ERR_RESOURCE_UNDERRUN, - RESOURCE_UNKNOWN_ERROR : ST.ERR_RESOURCE_UNKNOWN_ERROR, - - ATTRIBUTE_NOT_AVAILABLE : ST.ERR_ATTRIBUTE_NOT_AVAILABLE, - ATTRIBUTE_RETRIEVE_FAILURE : ST.ERR_ATTRIBUTE_RETRIEVE_FAILURE, - ATTRIBUTE_SET_FAILURE : ST.ERR_ATTRIBUTE_SET_FAILURE, - ATTRIBUTE_UPDATE_FAILURE: ST.ERR_ATTRIBUTE_UPDATE_FAILURE, - ATTRIBUTE_ACCESS_DENIED : ST.ERR_ATTRIBUTE_ACCESS_DENIED, - ATTRIBUTE_UNKNOWN_ERROR : ST.ERR_ATTRIBUTE_UNKNOWN_ERROR, - - COMMAND_FAILURE : ST.ERR_COMMAND_FAILURE, - - IO_NOT_READY : ST.ERR_IO_NOT_READY, - IO_BUSY : ST.ERR_IO_BUSY, - IO_TIMEOUT : ST.ERR_IO_TIMEOUT, - IO_UNKNOWN_ERROR : ST.ERR_IO_UNKNOWN_ERROR, - - UNKNOWN_ERROR : ST.ERR_UNKNOWN_ERROR, - - UPT_ALREADY_INSTALLED_ERROR : ST.ERR_UPT_ALREADY_INSTALLED_ERROR, - UPT_ENVIRON_MISSING_ERROR : ST.ERR_UPT_ENVIRON_MISSING_ERROR, - UPT_REPKG_ERROR : ST.ERR_UPT_REPKG_ERROR, - UPT_ALREADY_RUNNING_ERROR : ST.ERR_UPT_ALREADY_RUNNING_ERROR, - UPT_MUL_DEC_ERROR : ST.ERR_MUL_DEC_ERROR, - UPT_INI_PARSE_ERROR : ST.ERR_UPT_INI_PARSE_ERROR, -} - -## Exception indicating a fatal error -# -class FatalError(Exception): - pass - +## @file
+# Standardized Error Hanlding infrastructures.
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+#
+
+'''
+ToolError
+'''
+
+import Logger.StringTable as ST
+
+FILE_OPEN_FAILURE = 1
+FILE_WRITE_FAILURE = 2
+FILE_PARSE_FAILURE = 3
+FILE_READ_FAILURE = 4
+FILE_CREATE_FAILURE = 5
+FILE_CHECKSUM_FAILURE = 6
+FILE_COMPRESS_FAILURE = 7
+FILE_DECOMPRESS_FAILURE = 8
+FILE_MOVE_FAILURE = 9
+FILE_DELETE_FAILURE = 10
+FILE_COPY_FAILURE = 11
+FILE_POSITIONING_FAILURE = 12
+FILE_ALREADY_EXIST = 13
+FILE_NOT_FOUND = 14
+FILE_TYPE_MISMATCH = 15
+FILE_CASE_MISMATCH = 16
+FILE_DUPLICATED = 17
+FILE_UNKNOWN_ERROR = 0x0FFF
+
+OPTION_UNKNOWN = 0x1000
+OPTION_MISSING = 0x1001
+OPTION_CONFLICT = 0x1002
+OPTION_VALUE_INVALID = 0x1003
+OPTION_DEPRECATED = 0x1004
+OPTION_NOT_SUPPORTED = 0x1005
+OPTION_UNKNOWN_ERROR = 0x1FFF
+
+PARAMETER_INVALID = 0x2000
+PARAMETER_MISSING = 0x2001
+PARAMETER_UNKNOWN_ERROR = 0x2FFF
+
+FORMAT_INVALID = 0x3000
+FORMAT_NOT_SUPPORTED = 0x3001
+FORMAT_UNKNOWN = 0x3002
+FORMAT_UNKNOWN_ERROR = 0x3FFF
+
+RESOURCE_NOT_AVAILABLE = 0x4000
+RESOURCE_ALLOCATE_FAILURE = 0x4001
+RESOURCE_FULL = 0x4002
+RESOURCE_OVERFLOW = 0x4003
+RESOURCE_UNDERRUN = 0x4004
+RESOURCE_UNKNOWN_ERROR = 0x4FFF
+
+ATTRIBUTE_NOT_AVAILABLE = 0x5000
+ATTRIBUTE_GET_FAILURE = 0x5001
+ATTRIBUTE_SET_FAILURE = 0x5002
+ATTRIBUTE_UPDATE_FAILURE = 0x5003
+ATTRIBUTE_ACCESS_DENIED = 0x5004
+ATTRIBUTE_RETRIEVE_FAILURE = 0x5005
+ATTRIBUTE_UNKNOWN_ERROR = 0x5FFF
+ATTRIBUTE_RETRIEVE_FAILURE = 0x5F00
+
+IO_NOT_READY = 0x6000
+IO_BUSY = 0x6001
+IO_TIMEOUT = 0x6002
+IO_UNKNOWN_ERROR = 0x6FFF
+
+COMMAND_FAILURE = 0x7000
+
+CODE_ERROR = 0xC0DE
+
+AUTOGEN_ERROR = 0xF000
+PARSER_ERROR = 0xF001
+BUILD_ERROR = 0xF002
+GENFDS_ERROR = 0xF003
+ECC_ERROR = 0xF004
+EOT_ERROR = 0xF005
+DDC_ERROR = 0xF009
+WARNING_AS_ERROR = 0xF006
+MIGRATION_ERROR = 0xF010
+EDK1_INF_ERROR = 0xF011
+ABORT_ERROR = 0xFFFE
+UNKNOWN_ERROR = 0xFFFF
+
+UPT_ALREADY_INSTALLED_ERROR = 0xD000
+UPT_ENVIRON_MISSING_ERROR = 0xD001
+UPT_REPKG_ERROR = 0xD002
+UPT_ALREADY_RUNNING_ERROR = 0xD003
+UPT_MUL_DEC_ERROR = 0xD004
+UPT_DB_UPDATE_ERROR = 0xD005
+UPT_INI_PARSE_ERROR = 0xE000
+
+## Error message of each error code
+#
+gERROR_MESSAGE = {
+ FILE_NOT_FOUND : ST.ERR_FILE_NOT_FOUND,
+ FILE_OPEN_FAILURE : ST.ERR_FILE_OPEN_FAILURE,
+ FILE_WRITE_FAILURE : ST.ERR_FILE_WRITE_FAILURE,
+ FILE_PARSE_FAILURE : ST.ERR_FILE_PARSE_FAILURE,
+ FILE_READ_FAILURE : ST.ERR_FILE_READ_FAILURE,
+ FILE_CREATE_FAILURE : ST.ERR_FILE_CREATE_FAILURE,
+ FILE_CHECKSUM_FAILURE : ST.ERR_FILE_CHECKSUM_FAILURE,
+ FILE_COMPRESS_FAILURE : ST.ERR_FILE_COMPRESS_FAILURE,
+ FILE_DECOMPRESS_FAILURE : ST.ERR_FILE_DECOMPRESS_FAILURE,
+ FILE_MOVE_FAILURE : ST.ERR_FILE_MOVE_FAILURE,
+ FILE_DELETE_FAILURE : ST.ERR_FILE_DELETE_FAILURE,
+ FILE_COPY_FAILURE : ST.ERR_FILE_COPY_FAILURE,
+ FILE_POSITIONING_FAILURE: ST.ERR_FILE_POSITIONING_FAILURE,
+ FILE_ALREADY_EXIST : ST.ERR_FILE_ALREADY_EXIST,
+ FILE_TYPE_MISMATCH : ST.ERR_FILE_TYPE_MISMATCH ,
+ FILE_CASE_MISMATCH : ST.ERR_FILE_CASE_MISMATCH,
+ FILE_DUPLICATED : ST.ERR_FILE_DUPLICATED,
+ FILE_UNKNOWN_ERROR : ST.ERR_FILE_UNKNOWN_ERROR,
+
+ OPTION_UNKNOWN : ST.ERR_OPTION_UNKNOWN,
+ OPTION_MISSING : ST.ERR_OPTION_MISSING,
+ OPTION_CONFLICT : ST.ERR_OPTION_CONFLICT,
+ OPTION_VALUE_INVALID : ST.ERR_OPTION_VALUE_INVALID,
+ OPTION_DEPRECATED : ST.ERR_OPTION_DEPRECATED,
+ OPTION_NOT_SUPPORTED : ST.ERR_OPTION_NOT_SUPPORTED,
+ OPTION_UNKNOWN_ERROR : ST.ERR_OPTION_UNKNOWN_ERROR,
+
+ PARAMETER_INVALID : ST.ERR_PARAMETER_INVALID,
+ PARAMETER_MISSING : ST.ERR_PARAMETER_MISSING,
+ PARAMETER_UNKNOWN_ERROR : ST.ERR_PARAMETER_UNKNOWN_ERROR,
+
+ FORMAT_INVALID : ST.ERR_FORMAT_INVALID,
+ FORMAT_NOT_SUPPORTED : ST.ERR_FORMAT_NOT_SUPPORTED,
+ FORMAT_UNKNOWN : ST.ERR_FORMAT_UNKNOWN,
+ FORMAT_UNKNOWN_ERROR : ST.ERR_FORMAT_UNKNOWN_ERROR,
+
+ RESOURCE_NOT_AVAILABLE : ST.ERR_RESOURCE_NOT_AVAILABLE,
+ RESOURCE_ALLOCATE_FAILURE : ST.ERR_RESOURCE_ALLOCATE_FAILURE,
+ RESOURCE_FULL : ST.ERR_RESOURCE_FULL,
+ RESOURCE_OVERFLOW : ST.ERR_RESOURCE_OVERFLOW,
+ RESOURCE_UNDERRUN : ST.ERR_RESOURCE_UNDERRUN,
+ RESOURCE_UNKNOWN_ERROR : ST.ERR_RESOURCE_UNKNOWN_ERROR,
+
+ ATTRIBUTE_NOT_AVAILABLE : ST.ERR_ATTRIBUTE_NOT_AVAILABLE,
+ ATTRIBUTE_RETRIEVE_FAILURE : ST.ERR_ATTRIBUTE_RETRIEVE_FAILURE,
+ ATTRIBUTE_SET_FAILURE : ST.ERR_ATTRIBUTE_SET_FAILURE,
+ ATTRIBUTE_UPDATE_FAILURE: ST.ERR_ATTRIBUTE_UPDATE_FAILURE,
+ ATTRIBUTE_ACCESS_DENIED : ST.ERR_ATTRIBUTE_ACCESS_DENIED,
+ ATTRIBUTE_UNKNOWN_ERROR : ST.ERR_ATTRIBUTE_UNKNOWN_ERROR,
+
+ COMMAND_FAILURE : ST.ERR_COMMAND_FAILURE,
+
+ IO_NOT_READY : ST.ERR_IO_NOT_READY,
+ IO_BUSY : ST.ERR_IO_BUSY,
+ IO_TIMEOUT : ST.ERR_IO_TIMEOUT,
+ IO_UNKNOWN_ERROR : ST.ERR_IO_UNKNOWN_ERROR,
+
+ UNKNOWN_ERROR : ST.ERR_UNKNOWN_ERROR,
+
+ UPT_ALREADY_INSTALLED_ERROR : ST.ERR_UPT_ALREADY_INSTALLED_ERROR,
+ UPT_ENVIRON_MISSING_ERROR : ST.ERR_UPT_ENVIRON_MISSING_ERROR,
+ UPT_REPKG_ERROR : ST.ERR_UPT_REPKG_ERROR,
+ UPT_ALREADY_RUNNING_ERROR : ST.ERR_UPT_ALREADY_RUNNING_ERROR,
+ UPT_MUL_DEC_ERROR : ST.ERR_MUL_DEC_ERROR,
+ UPT_INI_PARSE_ERROR : ST.ERR_UPT_INI_PARSE_ERROR,
+}
+
+## Exception indicating a fatal error
+#
+class FatalError(Exception):
+ pass
+
diff --git a/BaseTools/Source/Python/UPT/Xml/__init__.py b/BaseTools/Source/Python/UPT/Xml/__init__.py index 5d268d990b..f09eece5fb 100644 --- a/BaseTools/Source/Python/UPT/Xml/__init__.py +++ b/BaseTools/Source/Python/UPT/Xml/__init__.py @@ -1,20 +1,20 @@ -## @file -# Python 'Library' package initialization file. -# -# This file is required to make Python interpreter treat the directory -# as containing package. -# -# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> -# -# 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. -# - -''' -Xml +## @file
+# Python 'Library' package initialization file.
+#
+# This file is required to make Python interpreter treat the directory
+# as containing package.
+#
+# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
+#
+# 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.
+#
+
+'''
+Xml
'''
\ No newline at end of file |