]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/Common/Misc.py
BaseTool:Rename xrange() to range()
[mirror_edk2.git] / BaseTools / Source / Python / Common / Misc.py
index ae66afd26f8ace51d86953fb2b7ee5715547305b..01bd62a9e2df45dd44ae70e208a6092adb95d0ab 100644 (file)
@@ -1,7 +1,7 @@
 ## @file\r
 # Common routines used by all tools\r
 #\r
-# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>\r
+# Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.<BR>\r
 # This program and the accompanying materials\r
 # are licensed and made available under the terms and conditions of the BSD License\r
 # which accompanies this distribution.  The full text of the license may be found at\r
@@ -15,7 +15,7 @@
 # Import Modules\r
 #\r
 from __future__ import absolute_import\r
-import Common.LongFilePathOs as os\r
+\r
 import sys\r
 import string\r
 import threading\r
@@ -26,22 +26,22 @@ import array
 import shutil\r
 from random import sample\r
 from struct import pack\r
-from UserDict import IterableUserDict\r
-from UserList import UserList\r
+import uuid\r
+import subprocess\r
+from collections import OrderedDict\r
 \r
+import Common.LongFilePathOs as os\r
 from Common import EdkLogger as EdkLogger\r
 from Common import GlobalData as GlobalData\r
-from .DataType import *\r
-from .BuildToolError import *\r
+from Common.DataType import *\r
+from Common.BuildToolError import *\r
 from CommonDataClass.DataClass import *\r
-from .Parsing import GetSplitValueList\r
+from Common.Parsing import GetSplitValueList\r
 from Common.LongFilePathSupport import OpenLongFilePath as open\r
 from Common.MultipleWorkspace import MultipleWorkspace as mws\r
-import uuid\r
 from CommonDataClass.Exceptions import BadExpression\r
 from Common.caching import cached_property\r
-import subprocess\r
-from collections import OrderedDict\r
+\r
 ## Regular expression used to find out place holders in string template\r
 gPlaceholderPattern = re.compile("\$\{([^$()\s]+)\}", re.MULTILINE | re.UNICODE)\r
 \r
@@ -54,9 +54,6 @@ secReGeneral = re.compile('^([\da-fA-F]+):([\da-fA-F]+) +([\da-fA-F]+)[Hh]? +([.
 \r
 StructPattern = re.compile(r'[_a-zA-Z][0-9A-Za-z_]*$')\r
 \r
-## Dictionary used to store file time stamp for quick re-access\r
-gFileTimeStampCache = {}    # {file path : file time stamp}\r
-\r
 ## Dictionary used to store dependencies of files\r
 gDependencyDatabase = {}    # arch : {file path : [dependent files list]}\r
 \r
@@ -566,32 +563,6 @@ def RealPath(File, Dir='', OverrideDir=''):
         NewFile = GlobalData.gAllFiles[NewFile]\r
     return NewFile\r
 \r
-def RealPath2(File, Dir='', OverrideDir=''):\r
-    NewFile = None\r
-    if OverrideDir:\r
-        NewFile = GlobalData.gAllFiles[os.path.normpath(os.path.join(OverrideDir, File))]\r
-        if NewFile:\r
-            if OverrideDir[-1] == os.path.sep:\r
-                return NewFile[len(OverrideDir):], NewFile[0:len(OverrideDir)]\r
-            else:\r
-                return NewFile[len(OverrideDir) + 1:], NewFile[0:len(OverrideDir)]\r
-    if GlobalData.gAllFiles:\r
-        NewFile = GlobalData.gAllFiles[os.path.normpath(os.path.join(Dir, File))]\r
-    if not NewFile:\r
-        NewFile = os.path.normpath(os.path.join(Dir, File))\r
-        if not os.path.exists(NewFile):\r
-            return None, None\r
-    if NewFile:\r
-        if Dir:\r
-            if Dir[-1] == os.path.sep:\r
-                return NewFile[len(Dir):], NewFile[0:len(Dir)]\r
-            else:\r
-                return NewFile[len(Dir) + 1:], NewFile[0:len(Dir)]\r
-        else:\r
-            return NewFile, ''\r
-\r
-    return None, None\r
-\r
 ## Get GUID value from given packages\r
 #\r
 #   @param      CName           The CName of the GUID\r
@@ -857,22 +828,22 @@ class Progressor:
 #  accessed in the order they are added into the dict. It guarantees the order\r
 #  by making use of an internal list to keep a copy of keys.\r
 #\r
-class sdict(IterableUserDict):\r
+class sdict(dict):\r
     ## Constructor\r
     def __init__(self):\r
-        IterableUserDict.__init__(self)\r
+        dict.__init__(self)\r
         self._key_list = []\r
 \r
     ## [] operator\r
     def __setitem__(self, key, value):\r
         if key not in self._key_list:\r
             self._key_list.append(key)\r
-        IterableUserDict.__setitem__(self, key, value)\r
+        dict.__setitem__(self, key, value)\r
 \r
     ## del operator\r
     def __delitem__(self, key):\r
         self._key_list.remove(key)\r
-        IterableUserDict.__delitem__(self, key)\r
+        dict.__delitem__(self, key)\r
 \r
     ## used in "for k in dict" loop to ensure the correct order\r
     def __iter__(self):\r
@@ -895,17 +866,17 @@ class sdict(IterableUserDict):
         index = self._key_list.index(key)\r
         if order == 'BEFORE':\r
             self._key_list.insert(index, newkey)\r
-            IterableUserDict.__setitem__(self, newkey, newvalue)\r
+            dict.__setitem__(self, newkey, newvalue)\r
         elif order == 'AFTER':\r
             self._key_list.insert(index + 1, newkey)\r
-            IterableUserDict.__setitem__(self, newkey, newvalue)\r
+            dict.__setitem__(self, newkey, newvalue)\r
 \r
     ## append support\r
     def append(self, sdict):\r
         for key in sdict:\r
             if key not in self._key_list:\r
                 self._key_list.append(key)\r
-            IterableUserDict.__setitem__(self, key, sdict[key])\r
+            dict.__setitem__(self, key, sdict[key])\r
 \r
     def has_key(self, key):\r
         return key in self._key_list\r
@@ -913,7 +884,7 @@ class sdict(IterableUserDict):
     ## Empty the dict\r
     def clear(self):\r
         self._key_list = []\r
-        IterableUserDict.clear(self)\r
+        dict.clear(self)\r
 \r
     ## Return a copy of keys\r
     def keys(self):\r
@@ -973,44 +944,6 @@ class sdict(IterableUserDict):
             for k, v in kwargs.items():\r
                 self[k] = v\r
 \r
-## Dictionary with restricted keys\r
-#\r
-class rdict(dict):\r
-    ## Constructor\r
-    def __init__(self, KeyList):\r
-        for Key in KeyList:\r
-            dict.__setitem__(self, Key, "")\r
-\r
-    ## []= operator\r
-    def __setitem__(self, key, value):\r
-        if key not in self:\r
-            EdkLogger.error("RestrictedDict", ATTRIBUTE_SET_FAILURE, "Key [%s] is not allowed" % key,\r
-                            ExtraData=", ".join(dict.keys(self)))\r
-        dict.__setitem__(self, key, value)\r
-\r
-    ## =[] operator\r
-    def __getitem__(self, key):\r
-        if key not in self:\r
-            return ""\r
-        return dict.__getitem__(self, key)\r
-\r
-    ## del operator\r
-    def __delitem__(self, key):\r
-        EdkLogger.error("RestrictedDict", ATTRIBUTE_ACCESS_DENIED, ExtraData="del")\r
-\r
-    ## Empty the dict\r
-    def clear(self):\r
-        for Key in self:\r
-            self.__setitem__(Key, "")\r
-\r
-    ## Return value related to a key, and remove the (key, value) from the dict\r
-    def pop(self, key, *dv):\r
-        EdkLogger.error("RestrictedDict", ATTRIBUTE_ACCESS_DENIED, ExtraData="pop")\r
-\r
-    ## Return (key, value) pair, and remove the (key, value) from the dict\r
-    def popitem(self):\r
-        EdkLogger.error("RestrictedDict", ATTRIBUTE_ACCESS_DENIED, ExtraData="popitem")\r
-\r
 ## Dictionary using prioritized list as key\r
 #\r
 class tdict:\r
@@ -1149,22 +1082,6 @@ class tdict:
                 keys |= self.data[Key].GetKeys(KeyIndex - 1)\r
             return keys\r
 \r
-def IsFieldValueAnArray (Value):\r
-    Value = Value.strip()\r
-    if Value.startswith(TAB_GUID) and Value.endswith(')'):\r
-        return True\r
-    if Value.startswith('L"') and Value.endswith('"')  and len(list(Value[2:-1])) > 1:\r
-        return True\r
-    if Value[0] == '"' and Value[-1] == '"' and len(list(Value[1:-1])) > 1:\r
-        return True\r
-    if Value[0] == '{' and Value[-1] == '}':\r
-        return True\r
-    if Value.startswith("L'") and Value.endswith("'") and len(list(Value[2:-1])) > 1:\r
-        return True\r
-    if Value[0] == "'" and Value[-1] == "'" and len(list(Value[1:-1])) > 1:\r
-        return True\r
-    return False\r
-\r
 def AnalyzePcdExpression(Setting):\r
     RanStr = ''.join(sample(string.ascii_letters + string.digits, 8))\r
     Setting = Setting.replace('\\\\', RanStr).strip()\r
@@ -1205,27 +1122,27 @@ def AnalyzePcdExpression(Setting):
             FieldList[i] = ch.replace(RanStr,'\\\\')\r
     return FieldList\r
 \r
-def ParseDevPathValue (Value):\r
-    if '\\' in Value:\r
-        Value.replace('\\', '/').replace(' ', '')\r
+def ParseFieldValue (Value):\r
+    def ParseDevPathValue (Value):\r
+        if '\\' in Value:\r
+            Value.replace('\\', '/').replace(' ', '')\r
 \r
-    Cmd = 'DevicePath ' + '"' + Value + '"'\r
-    try:\r
-        p = subprocess.Popen(Cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
-        out, err = p.communicate()\r
-    except Exception as X:\r
-        raise BadExpression("DevicePath: %s" % (str(X)) )\r
-    finally:\r
-        subprocess._cleanup()\r
-        p.stdout.close()\r
-        p.stderr.close()\r
-    if err:\r
-        raise BadExpression("DevicePath: %s" % str(err))\r
-    Size = len(out.split())\r
-    out = ','.join(out.split())\r
-    return '{' + out + '}', Size\r
+        Cmd = 'DevicePath ' + '"' + Value + '"'\r
+        try:\r
+            p = subprocess.Popen(Cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
+            out, err = p.communicate()\r
+        except Exception as X:\r
+            raise BadExpression("DevicePath: %s" % (str(X)) )\r
+        finally:\r
+            subprocess._cleanup()\r
+            p.stdout.close()\r
+            p.stderr.close()\r
+        if err:\r
+            raise BadExpression("DevicePath: %s" % str(err))\r
+        Size = len(out.split())\r
+        out = ','.join(out.split())\r
+        return '{' + out + '}', Size\r
 \r
-def ParseFieldValue (Value):\r
     if "{CODE(" in Value:\r
         return Value, len(Value.split(","))\r
     if isinstance(Value, type(0)):\r
@@ -1528,82 +1445,14 @@ def CheckPcdDatum(Type, Value):
 \r
     return True, ""\r
 \r
-## Split command line option string to list\r
-#\r
-# subprocess.Popen needs the args to be a sequence. Otherwise there's problem\r
-# in non-windows platform to launch command\r
-#\r
-def SplitOption(OptionString):\r
-    OptionList = []\r
-    LastChar = " "\r
-    OptionStart = 0\r
-    QuotationMark = ""\r
-    for Index in range(0, len(OptionString)):\r
-        CurrentChar = OptionString[Index]\r
-        if CurrentChar in ['"', "'"]:\r
-            if QuotationMark == CurrentChar:\r
-                QuotationMark = ""\r
-            elif QuotationMark == "":\r
-                QuotationMark = CurrentChar\r
-            continue\r
-        elif QuotationMark:\r
-            continue\r
-\r
-        if CurrentChar in ["/", "-"] and LastChar in [" ", "\t", "\r", "\n"]:\r
-            if Index > OptionStart:\r
-                OptionList.append(OptionString[OptionStart:Index - 1])\r
-            OptionStart = Index\r
-        LastChar = CurrentChar\r
-    OptionList.append(OptionString[OptionStart:])\r
-    return OptionList\r
-\r
 def CommonPath(PathList):\r
     P1 = min(PathList).split(os.path.sep)\r
     P2 = max(PathList).split(os.path.sep)\r
-    for Index in xrange(min(len(P1), len(P2))):\r
+    for Index in range(min(len(P1), len(P2))):\r
         if P1[Index] != P2[Index]:\r
             return os.path.sep.join(P1[:Index])\r
     return os.path.sep.join(P1)\r
 \r
-#\r
-# Convert string to C format array\r
-#\r
-def ConvertStringToByteArray(Value):\r
-    Value = Value.strip()\r
-    if not Value:\r
-        return None\r
-    if Value[0] == '{':\r
-        if not Value.endswith('}'):\r
-            return None\r
-        Value = Value.replace(' ', '').replace('{', '').replace('}', '')\r
-        ValFields = Value.split(',')\r
-        try:\r
-            for Index in range(len(ValFields)):\r
-                ValFields[Index] = str(int(ValFields[Index], 0))\r
-        except ValueError:\r
-            return None\r
-        Value = '{' + ','.join(ValFields) + '}'\r
-        return Value\r
-\r
-    Unicode = False\r
-    if Value.startswith('L"'):\r
-        if not Value.endswith('"'):\r
-            return None\r
-        Value = Value[1:]\r
-        Unicode = True\r
-    elif not Value.startswith('"') or not Value.endswith('"'):\r
-        return None\r
-\r
-    Value = eval(Value)         # translate escape character\r
-    NewValue = '{'\r
-    for Index in range(0, len(Value)):\r
-        if Unicode:\r
-            NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ','\r
-        else:\r
-            NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ','\r
-    Value = NewValue + '0}'\r
-    return Value\r
-\r
 class PathClass(object):\r
     def __init__(self, File='', Root='', AlterRoot='', Type='', IsBinary=False,\r
                  Arch='COMMON', ToolChainFamily='', Target='', TagName='', ToolCode=''):\r
@@ -1709,6 +1558,32 @@ class PathClass(object):
         return os.stat(self.Path)[8]\r
 \r
     def Validate(self, Type='', CaseSensitive=True):\r
+        def RealPath2(File, Dir='', OverrideDir=''):\r
+            NewFile = None\r
+            if OverrideDir:\r
+                NewFile = GlobalData.gAllFiles[os.path.normpath(os.path.join(OverrideDir, File))]\r
+                if NewFile:\r
+                    if OverrideDir[-1] == os.path.sep:\r
+                        return NewFile[len(OverrideDir):], NewFile[0:len(OverrideDir)]\r
+                    else:\r
+                        return NewFile[len(OverrideDir) + 1:], NewFile[0:len(OverrideDir)]\r
+            if GlobalData.gAllFiles:\r
+                NewFile = GlobalData.gAllFiles[os.path.normpath(os.path.join(Dir, File))]\r
+            if not NewFile:\r
+                NewFile = os.path.normpath(os.path.join(Dir, File))\r
+                if not os.path.exists(NewFile):\r
+                    return None, None\r
+            if NewFile:\r
+                if Dir:\r
+                    if Dir[-1] == os.path.sep:\r
+                        return NewFile[len(Dir):], NewFile[0:len(Dir)]\r
+                    else:\r
+                        return NewFile[len(Dir) + 1:], NewFile[0:len(Dir)]\r
+                else:\r
+                    return NewFile, ''\r
+\r
+            return None, None\r
+\r
         if GlobalData.gCaseInsensitive:\r
             CaseSensitive = False\r
         if Type and Type.lower() != self.Type:\r
@@ -1988,12 +1863,6 @@ class SkuClass():
         else:\r
             return 'DEFAULT'\r
 \r
-#\r
-# Pack a registry format GUID\r
-#\r
-def PackRegistryFormatGuid(Guid):\r
-    return PackGUID(Guid.split('-'))\r
-\r
 ##  Get the integer value from string like "14U" or integer like 2\r
 #\r
 #   @param      Input   The object that may be either a integer value or a string\r
@@ -2077,11 +1946,3 @@ def CopyDict(ori_dict):
 #\r
 def RemoveCComments(ctext):\r
     return re.sub('//.*?\n|/\*.*?\*/', '\n', ctext, flags=re.S)\r
-##\r
-#\r
-# This acts like the main() function for the script, unless it is 'import'ed into another\r
-# script.\r
-#\r
-if __name__ == '__main__':\r
-    pass\r
-\r