]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/Common/Misc.py
BaseTools: remove unused import thread
[mirror_edk2.git] / BaseTools / Source / Python / Common / Misc.py
index fd53b6b046c4442ea066f2c7e4cd3bf3e80d3be5..fd948c727a4f9b7a09360529f38533d3243f8654 100644 (file)
 ##\r
 # Import Modules\r
 #\r
+from __future__ import absolute_import\r
 import Common.LongFilePathOs as os\r
 import sys\r
 import string\r
-import thread\r
 import threading\r
 import time\r
 import re\r
@@ -30,10 +30,10 @@ from UserList import UserList
 \r
 from Common import EdkLogger as EdkLogger\r
 from Common import GlobalData as GlobalData\r
-from DataType import *\r
-from BuildToolError import *\r
+from .DataType import *\r
+from .BuildToolError import *\r
 from CommonDataClass.DataClass import *\r
-from Parsing import GetSplitValueList\r
+from .Parsing import GetSplitValueList\r
 from Common.LongFilePathSupport import OpenLongFilePath as open\r
 from Common.MultipleWorkspace import MultipleWorkspace as mws\r
 import uuid\r
@@ -55,12 +55,19 @@ gFileTimeStampCache = {}    # {file path : file time stamp}
 ## Dictionary used to store dependencies of files\r
 gDependencyDatabase = {}    # arch : {file path : [dependent files list]}\r
 \r
+#\r
+# If a module is built more than once with different PCDs or library classes\r
+# a temporary INF file with same content is created, the temporary file is removed\r
+# when build exits.\r
+#\r
+_TempInfs = []\r
+\r
 def GetVariableOffset(mapfilepath, efifilepath, varnames):\r
-    """ Parse map file to get variable offset in current EFI file \r
+    """ Parse map file to get variable offset in current EFI file\r
     @param mapfilepath    Map file absolution path\r
     @param efifilepath:   EFI binary file full path\r
     @param varnames       iteratable container whose elements are variable names to be searched\r
-    \r
+\r
     @return List whos elements are tuple with variable name and raw offset\r
     """\r
     lines = []\r
@@ -70,7 +77,7 @@ def GetVariableOffset(mapfilepath, efifilepath, varnames):
         f.close()\r
     except:\r
         return None\r
-    \r
+\r
     if len(lines) == 0: return None\r
     firstline = lines[0].strip()\r
     if (firstline.startswith("Archive member included ") and\r
@@ -170,7 +177,7 @@ def _parseGeneral(lines, efifilepath, varnames):
             continue\r
         if line.startswith("entry point at"):\r
             status = 3\r
-            continue        \r
+            continue\r
         if status == 1 and len(line) != 0:\r
             m =  secReGeneral.match(line)\r
             assert m is not None, "Fail to parse the section in map file , line is %s" % line\r
@@ -250,7 +257,7 @@ def ProcessDuplicatedInf(Path, BaseName, Workspace):
     #\r
     # A temporary INF is copied to database path which must have write permission\r
     # The temporary will be removed at the end of build\r
-    # In case of name conflict, the file name is \r
+    # In case of name conflict, the file name is\r
     # FILE_GUIDBaseName (0D1B936F-68F3-4589-AFCC-FB8B7AEBC836module.inf)\r
     #\r
     TempFullPath = os.path.join(DbDir,\r
@@ -261,7 +268,7 @@ def ProcessDuplicatedInf(Path, BaseName, Workspace):
     #\r
     # To build same module more than once, the module path with FILE_GUID overridden has\r
     # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the real path\r
-    # in DSC which is used as relative path by C files and other files in INF. \r
+    # in DSC which is used as relative path by C files and other files in INF.\r
     # A trick was used: all module paths are PathClass instances, after the initialization\r
     # of PathClass, the PathClass.Path is overridden by the temporary INF path.\r
     #\r
@@ -280,18 +287,18 @@ def ProcessDuplicatedInf(Path, BaseName, Workspace):
     # If file exists, compare contents\r
     #\r
     if os.path.exists(TempFullPath):\r
-        with open(str(Path), 'rb') as f1: Src = f1.read()\r
-        with open(TempFullPath, 'rb') as f2: Dst = f2.read()\r
-        if Src == Dst:\r
-            return RtPath\r
-    GlobalData.gTempInfs.append(TempFullPath)\r
+        with open(str(Path), 'rb') as f1, open(TempFullPath, 'rb') as f2:\r
+            if f1.read() == f2.read():\r
+                return RtPath\r
+    _TempInfs.append(TempFullPath)\r
     shutil.copy2(str(Path), TempFullPath)\r
     return RtPath\r
 \r
-## Remove temporary created INFs whose paths were saved in gTempInfs\r
+## Remove temporary created INFs whose paths were saved in _TempInfs\r
 #\r
 def ClearDuplicatedInf():\r
-    for File in GlobalData.gTempInfs:\r
+    while _TempInfs:\r
+        File = _TempInfs.pop()\r
         if os.path.exists(File):\r
             os.remove(File)\r
 \r
@@ -467,7 +474,7 @@ def SaveFileOnChange(File, Content, IsBinaryFile=True):
     try:\r
         if GlobalData.gIsWindows:\r
             try:\r
-                from PyUtility import SaveFileToDisk\r
+                from .PyUtility import SaveFileToDisk\r
                 if not SaveFileToDisk(File, Content):\r
                     EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData=File)\r
             except:\r
@@ -1291,9 +1298,9 @@ def ParseDevPathValue (Value):
     return '{' + out + '}', Size\r
 \r
 def ParseFieldValue (Value):\r
-    if type(Value) == type(0):\r
+    if isinstance(Value, type(0)):\r
         return Value, (Value.bit_length() + 7) / 8\r
-    if type(Value) != type(''):\r
+    if not isinstance(Value, type('')):\r
         raise BadExpression('Type %s is %s' %(Value, type(Value)))\r
     Value = Value.strip()\r
     if Value.startswith(TAB_UINT8) and Value.endswith(')'):\r
@@ -1538,29 +1545,29 @@ def AnalyzeDscPcd(Setting, PcdType, DataType=''):
 #  Used to avoid split issue while the value string contain "|" character\r
 #\r
 #  @param[in] Setting:  A String contain value/datum type/token number information;\r
-#  \r
-#  @retval   ValueList: A List contain value, datum type and toke number. \r
+#\r
+#  @retval   ValueList: A List contain value, datum type and toke number.\r
 #\r
 def AnalyzePcdData(Setting):\r
     ValueList = ['', '', '']\r
 \r
     ValueRe = re.compile(r'^\s*L?\".*\|.*\"')\r
     PtrValue = ValueRe.findall(Setting)\r
-    \r
+\r
     ValueUpdateFlag = False\r
-    \r
+\r
     if len(PtrValue) >= 1:\r
         Setting = re.sub(ValueRe, '', Setting)\r
         ValueUpdateFlag = True\r
 \r
     TokenList = Setting.split(TAB_VALUE_SPLIT)\r
     ValueList[0:len(TokenList)] = TokenList\r
-    \r
+\r
     if ValueUpdateFlag:\r
         ValueList[0] = PtrValue[0]\r
-        \r
-    return ValueList   \r
\r
+\r
+    return ValueList\r
+\r
 ## check format of PCD value against its the datum type\r
 #\r
 # For PCD value setting\r
@@ -1584,8 +1591,7 @@ def CheckPcdDatum(Type, Value):
             Printset.add(TAB_PRINTCHAR_BS)\r
             Printset.add(TAB_PRINTCHAR_NUL)\r
             if not set(Value).issubset(Printset):\r
-                PrintList = list(Printset)\r
-                PrintList.sort()\r
+                PrintList = sorted(Printset)\r
                 return False, "Invalid PCD string value of type [%s]; must be printable chars %s." % (Type, PrintList)\r
     elif Type == 'BOOLEAN':\r
         if Value not in ['TRUE', 'True', 'true', '0x1', '0x01', '1', 'FALSE', 'False', 'false', '0x0', '0x00', '0']:\r
@@ -1747,7 +1753,7 @@ class PathClass(object):
     # @retval True  The two PathClass are the same\r
     #\r
     def __eq__(self, Other):\r
-        if type(Other) == type(self):\r
+        if isinstance(Other, type(self)):\r
             return self.Path == Other.Path\r
         else:\r
             return self.Path == str(Other)\r
@@ -1760,11 +1766,11 @@ class PathClass(object):
     # @retval -1    The first PathClass is less than the second PathClass\r
     # @retval 1     The first PathClass is Bigger than the second PathClass\r
     def __cmp__(self, Other):\r
-        if type(Other) == type(self):\r
+        if isinstance(Other, type(self)):\r
             OtherKey = Other.Path\r
         else:\r
             OtherKey = str(Other)\r
-            \r
+\r
         SelfKey = self.Path\r
         if SelfKey == OtherKey:\r
             return 0\r
@@ -1902,7 +1908,7 @@ class PeImageClass():
     def _ByteListToStr(self, ByteList):\r
         String = ''\r
         for index in range(len(ByteList)):\r
-            if ByteList[index] == 0: \r
+            if ByteList[index] == 0:\r
                 break\r
             String += chr(ByteList[index])\r
         return String\r
@@ -1939,11 +1945,11 @@ class DefaultStore():
             if sid == minid:\r
                 return name\r
 class SkuClass():\r
-    \r
+\r
     DEFAULT = 0\r
     SINGLE = 1\r
     MULTIPLE =2\r
-    \r
+\r
     def __init__(self,SkuIdentifier='', SkuIds=None):\r
         if SkuIds is None:\r
             SkuIds = {}\r
@@ -1955,7 +1961,7 @@ class SkuClass():
                 EdkLogger.error("build", PARAMETER_INVALID,\r
                             ExtraData = "SKU-ID [%s] value %s exceeds the max value of UINT64"\r
                                       % (SkuName, SkuId))\r
-        \r
+\r
         self.AvailableSkuIds = sdict()\r
         self.SkuIdSet = []\r
         self.SkuIdNumberSet = []\r
@@ -1969,10 +1975,10 @@ class SkuClass():
             self.SkuIdSet = SkuIds.keys()\r
             self.SkuIdNumberSet = [num[0].strip() + 'U' for num in SkuIds.values()]\r
         else:\r
-            r = SkuIdentifier.split('|') \r
+            r = SkuIdentifier.split('|')\r
             self.SkuIdSet=[(r[k].strip()).upper() for k in range(len(r))]\r
             k = None\r
-            try: \r
+            try:\r
                 self.SkuIdNumberSet = [SkuIds[k][0].strip() + 'U' for k in self.SkuIdSet]\r
             except Exception:\r
                 EdkLogger.error("build", PARAMETER_INVALID,\r
@@ -2010,7 +2016,7 @@ class SkuClass():
             return ["DEFAULT"]\r
         skulist = [sku]\r
         nextsku = sku\r
-        while 1:\r
+        while True:\r
             nextsku = self.GetNextSkuId(nextsku)\r
             skulist.append(nextsku)\r
             if nextsku == "DEFAULT":\r
@@ -2021,7 +2027,7 @@ class SkuClass():
         skuorderset = []\r
         for skuname in self.SkuIdSet:\r
             skuorderset.append(self.GetSkuChain(skuname))\r
-        \r
+\r
         skuorder = []\r
         for index in range(max(len(item) for item in skuorderset)):\r
             for subset in skuorderset:\r
@@ -2033,8 +2039,8 @@ class SkuClass():
 \r
         return skuorder\r
 \r
-    def __SkuUsageType(self): \r
-        \r
+    def __SkuUsageType(self):\r
+\r
         if self.__SkuIdentifier.upper() == "ALL":\r
             return SkuClass.MULTIPLE\r
 \r
@@ -2067,7 +2073,7 @@ class SkuClass():
         return ArrayStr\r
     def __GetAvailableSkuIds(self):\r
         return self.AvailableSkuIds\r
-    \r
+\r
     def __GetSystemSkuID(self):\r
         if self.__SkuUsageType() == SkuClass.SINGLE:\r
             if len(self.SkuIdSet) == 1:\r