]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/Common/Misc.py
BaseTools: Fix private includes for FILE_GUID override
[mirror_edk2.git] / BaseTools / Source / Python / Common / Misc.py
index 6a22d01012988d94e890d18f7b306c489fd58cf9..d082c58befda5b46aa3f40113c96f1566ded60fd 100644 (file)
@@ -1,21 +1,15 @@
 ## @file\r
 # Common routines used by all tools\r
 #\r
-# Copyright (c) 2007 - 2018, 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
-# http://opensource.org/licenses/bsd-license.php\r
-#\r
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+# Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.<BR>\r
+# SPDX-License-Identifier: BSD-2-Clause-Patent\r
 #\r
 \r
 ##\r
 # 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 +20,24 @@ 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
+import tempfile\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
+ArrayIndex = re.compile("\[\s*[0-9a-fA-FxX]*\s*\]")\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 +50,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
@@ -288,6 +281,7 @@ def ProcessDuplicatedInf(Path, BaseName, Workspace):
     #\r
     RtPath.Path = TempFullPath\r
     RtPath.BaseName = BaseName\r
+    RtPath.OriginalPath = Path\r
     #\r
     # If file exists, compare contents\r
     #\r
@@ -459,15 +453,22 @@ def RemoveDirectory(Directory, Recursively=False):
 #   @retval     False           If the file content is the same\r
 #\r
 def SaveFileOnChange(File, Content, IsBinaryFile=True):\r
-    if not IsBinaryFile:\r
-        Content = Content.replace("\n", os.linesep)\r
 \r
     if os.path.exists(File):\r
-        try:\r
-            if Content == open(File, "rb").read():\r
-                return False\r
-        except:\r
-            EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File)\r
+        if IsBinaryFile:\r
+            try:\r
+                with open(File, "rb") as f:\r
+                    if Content == f.read():\r
+                        return False\r
+            except:\r
+                EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File)\r
+        else:\r
+            try:\r
+                with open(File, "r") as f:\r
+                    if Content == f.read():\r
+                        return False\r
+            except:\r
+                EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File)\r
 \r
     DirName = os.path.dirname(File)\r
     if not CreateDirectory(DirName):\r
@@ -478,51 +479,28 @@ def SaveFileOnChange(File, Content, IsBinaryFile=True):
         if not os.access(DirName, os.W_OK):\r
             EdkLogger.error(None, PERMISSION_FAILURE, "Do not have write permission on directory %s" % DirName)\r
 \r
-    try:\r
-        Fd = open(File, "wb")\r
-        Fd.write(Content)\r
-        Fd.close()\r
-    except IOError as X:\r
-        EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X)\r
-\r
-    return True\r
+    OpenMode = "w"\r
+    if IsBinaryFile:\r
+        OpenMode = "wb"\r
 \r
-## Make a Python object persistent on file system\r
-#\r
-#   @param      Data    The object to be stored in file\r
-#   @param      File    The path of file to store the object\r
-#\r
-def DataDump(Data, File):\r
-    Fd = None\r
-    try:\r
-        Fd = open(File, 'wb')\r
-        pickle.dump(Data, Fd, pickle.HIGHEST_PROTOCOL)\r
-    except:\r
-        EdkLogger.error("", FILE_OPEN_FAILURE, ExtraData=File, RaiseError=False)\r
-    finally:\r
-        if Fd is not None:\r
-            Fd.close()\r
+    if GlobalData.gIsWindows and not os.path.exists(File):\r
+        # write temp file, then rename the temp file to the real file\r
+        # to make sure the file be immediate saved to disk\r
+        with tempfile.NamedTemporaryFile(OpenMode, dir=os.path.dirname(File), delete=False) as tf:\r
+            tf.write(Content)\r
+            tempname = tf.name\r
+        try:\r
+            os.rename(tempname, File)\r
+        except:\r
+            EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X)\r
+    else:\r
+        try:\r
+            with open(File, OpenMode) as Fd:\r
+                Fd.write(Content)\r
+        except IOError as X:\r
+            EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X)\r
 \r
-## Restore a Python object from a file\r
-#\r
-#   @param      File    The path of file stored the object\r
-#\r
-#   @retval     object  A python object\r
-#   @retval     None    If failure in file operation\r
-#\r
-def DataRestore(File):\r
-    Data = None\r
-    Fd = None\r
-    try:\r
-        Fd = open(File, 'rb')\r
-        Data = pickle.load(Fd)\r
-    except Exception as e:\r
-        EdkLogger.verbose("Failed to load [%s]\n\t%s" % (File, str(e)))\r
-        Data = None\r
-    finally:\r
-        if Fd is not None:\r
-            Fd.close()\r
-    return Data\r
+    return True\r
 \r
 ## Retrieve and cache the real path name in file system\r
 #\r
@@ -603,32 +581,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
@@ -640,50 +592,13 @@ def RealPath2(File, Dir='', OverrideDir=''):
 #\r
 def GuidValue(CName, PackageList, Inffile = None):\r
     for P in PackageList:\r
-        GuidKeys = P.Guids.keys()\r
+        GuidKeys = list(P.Guids.keys())\r
         if Inffile and P._PrivateGuids:\r
             if not Inffile.startswith(P.MetaFile.Dir):\r
                 GuidKeys = [x for x in P.Guids if x not in P._PrivateGuids]\r
         if CName in GuidKeys:\r
             return P.Guids[CName]\r
     return None\r
-\r
-## Get Protocol value from given packages\r
-#\r
-#   @param      CName           The CName of the GUID\r
-#   @param      PackageList     List of packages looking-up in\r
-#   @param      Inffile         The driver file\r
-#\r
-#   @retval     GuidValue   if the CName is found in any given package\r
-#   @retval     None        if the CName is not found in all given packages\r
-#\r
-def ProtocolValue(CName, PackageList, Inffile = None):\r
-    for P in PackageList:\r
-        ProtocolKeys = P.Protocols.keys()\r
-        if Inffile and P._PrivateProtocols:\r
-            if not Inffile.startswith(P.MetaFile.Dir):\r
-                ProtocolKeys = [x for x in P.Protocols if x not in P._PrivateProtocols]\r
-        if CName in ProtocolKeys:\r
-            return P.Protocols[CName]\r
-    return None\r
-\r
-## Get PPI value from given packages\r
-#\r
-#   @param      CName           The CName of the GUID\r
-#   @param      PackageList     List of packages looking-up in\r
-#   @param      Inffile         The driver file\r
-#\r
-#   @retval     GuidValue   if the CName is found in any given package\r
-#   @retval     None        if the CName is not found in all given packages\r
-#\r
-def PpiValue(CName, PackageList, Inffile = None):\r
-    for P in PackageList:\r
-        PpiKeys = P.Ppis.keys()\r
-        if Inffile and P._PrivatePpis:\r
-            if not Inffile.startswith(P.MetaFile.Dir):\r
-                PpiKeys = [x for x in P.Ppis if x not in P._PrivatePpis]\r
-        if CName in PpiKeys:\r
-            return P.Ppis[CName]\r
     return None\r
 \r
 ## A string template class\r
@@ -865,10 +780,10 @@ class Progressor:
 \r
     ## Constructor\r
     #\r
-    #   @param      OpenMessage     The string printed before progress charaters\r
-    #   @param      CloseMessage    The string printed after progress charaters\r
-    #   @param      ProgressChar    The charater used to indicate the progress\r
-    #   @param      Interval        The interval in seconds between two progress charaters\r
+    #   @param      OpenMessage     The string printed before progress characters\r
+    #   @param      CloseMessage    The string printed after progress characters\r
+    #   @param      ProgressChar    The character used to indicate the progress\r
+    #   @param      Interval        The interval in seconds between two progress characters\r
     #\r
     def __init__(self, OpenMessage="", CloseMessage="", ProgressChar='.', Interval=1.0):\r
         self.PromptMessage = OpenMessage\r
@@ -878,9 +793,9 @@ class Progressor:
         if Progressor._StopFlag is None:\r
             Progressor._StopFlag = threading.Event()\r
 \r
-    ## Start to print progress charater\r
+    ## Start to print progress character\r
     #\r
-    #   @param      OpenMessage     The string printed before progress charaters\r
+    #   @param      OpenMessage     The string printed before progress characters\r
     #\r
     def Start(self, OpenMessage=None):\r
         if OpenMessage is not None:\r
@@ -891,9 +806,9 @@ class Progressor:
             Progressor._ProgressThread.setDaemon(False)\r
             Progressor._ProgressThread.start()\r
 \r
-    ## Stop printing progress charater\r
+    ## Stop printing progress character\r
     #\r
-    #   @param      CloseMessage    The string printed after progress charaters\r
+    #   @param      CloseMessage    The string printed after progress characters\r
     #\r
     def Stop(self, CloseMessage=None):\r
         OriginalCodaMessage = self.CodaMessage\r
@@ -926,165 +841,6 @@ class Progressor:
             Progressor._ProgressThread.join()\r
             Progressor._ProgressThread = None\r
 \r
-## A dict which can access its keys and/or values orderly\r
-#\r
-#  The class implements a new kind of dict which its keys or values can be\r
-#  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
-    ## Constructor\r
-    def __init__(self):\r
-        IterableUserDict.__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
-\r
-    ## del operator\r
-    def __delitem__(self, key):\r
-        self._key_list.remove(key)\r
-        IterableUserDict.__delitem__(self, key)\r
-\r
-    ## used in "for k in dict" loop to ensure the correct order\r
-    def __iter__(self):\r
-        return self.iterkeys()\r
-\r
-    ## len() support\r
-    def __len__(self):\r
-        return len(self._key_list)\r
-\r
-    ## "in" test support\r
-    def __contains__(self, key):\r
-        return key in self._key_list\r
-\r
-    ## indexof support\r
-    def index(self, key):\r
-        return self._key_list.index(key)\r
-\r
-    ## insert support\r
-    def insert(self, key, newkey, newvalue, order):\r
-        index = self._key_list.index(key)\r
-        if order == 'BEFORE':\r
-            self._key_list.insert(index, newkey)\r
-            IterableUserDict.__setitem__(self, newkey, newvalue)\r
-        elif order == 'AFTER':\r
-            self._key_list.insert(index + 1, newkey)\r
-            IterableUserDict.__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
-\r
-    def has_key(self, key):\r
-        return key in self._key_list\r
-\r
-    ## Empty the dict\r
-    def clear(self):\r
-        self._key_list = []\r
-        IterableUserDict.clear(self)\r
-\r
-    ## Return a copy of keys\r
-    def keys(self):\r
-        keys = []\r
-        for key in self._key_list:\r
-            keys.append(key)\r
-        return keys\r
-\r
-    ## Return a copy of values\r
-    def values(self):\r
-        values = []\r
-        for key in self._key_list:\r
-            values.append(self[key])\r
-        return values\r
-\r
-    ## Return a copy of (key, value) list\r
-    def items(self):\r
-        items = []\r
-        for key in self._key_list:\r
-            items.append((key, self[key]))\r
-        return items\r
-\r
-    ## Iteration support\r
-    def iteritems(self):\r
-        return iter(self.items())\r
-\r
-    ## Keys interation support\r
-    def iterkeys(self):\r
-        return iter(self.keys())\r
-\r
-    ## Values interation support\r
-    def itervalues(self):\r
-        return iter(self.values())\r
-\r
-    ## Return value related to a key, and remove the (key, value) from the dict\r
-    def pop(self, key, *dv):\r
-        value = None\r
-        if key in self._key_list:\r
-            value = self[key]\r
-            self.__delitem__(key)\r
-        elif len(dv) != 0 :\r
-            value = kv[0]\r
-        return value\r
-\r
-    ## Return (key, value) pair, and remove the (key, value) from the dict\r
-    def popitem(self):\r
-        key = self._key_list[-1]\r
-        value = self[key]\r
-        self.__delitem__(key)\r
-        return key, value\r
-\r
-    def update(self, dict=None, **kwargs):\r
-        if dict is not None:\r
-            for k, v in dict.items():\r
-                self[k] = v\r
-        if len(kwargs):\r
-            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
@@ -1224,22 +980,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
@@ -1280,31 +1020,32 @@ 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
+        out = out.decode(encoding='utf-8', errors='ignore')\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
-        return Value, (Value.bit_length() + 7) / 8\r
+        return Value, (Value.bit_length() + 7) // 8\r
     if not isinstance(Value, type('')):\r
         raise BadExpression('Type %s is %s' %(Value, type(Value)))\r
     Value = Value.strip()\r
@@ -1338,7 +1079,10 @@ def ParseFieldValue (Value):
         if Value[0] == '"' and Value[-1] == '"':\r
             Value = Value[1:-1]\r
         try:\r
-            Value = "'" + uuid.UUID(Value).get_bytes_le() + "'"\r
+            Value = str(uuid.UUID(Value).bytes_le)\r
+            if Value.startswith("b'"):\r
+                Value = Value[2:-1]\r
+            Value = "'" + Value + "'"\r
         except ValueError as Message:\r
             raise BadExpression(Message)\r
         Value, Size = ParseFieldValue(Value)\r
@@ -1425,12 +1169,12 @@ def ParseFieldValue (Value):
             raise BadExpression("invalid hex value: %s" % Value)\r
         if Value == 0:\r
             return 0, 1\r
-        return Value, (Value.bit_length() + 7) / 8\r
+        return Value, (Value.bit_length() + 7) // 8\r
     if Value[0].isdigit():\r
         Value = int(Value, 10)\r
         if Value == 0:\r
             return 0, 1\r
-        return Value, (Value.bit_length() + 7) / 8\r
+        return Value, (Value.bit_length() + 7) // 8\r
     if Value.lower() == 'true':\r
         return 1, 1\r
     if Value.lower() == 'false':\r
@@ -1525,8 +1269,6 @@ def AnalyzeDscPcd(Setting, PcdType, DataType=''):
             Offset = FieldList[2]\r
         if len(FieldList) > 3:\r
             Value = FieldList[3]\r
-            if not Value:\r
-                IsValid = False\r
         if len(FieldList) > 4:\r
             Attribute = FieldList[4]\r
         return [HiiString, Guid, Offset, Value, Attribute], IsValid, 3\r
@@ -1591,10 +1333,12 @@ def CheckPcdDatum(Type, Value):
             return False, "Invalid value [%s] of type [%s]; must be one of TRUE, True, true, 0x1, 0x01, 1"\\r
                           ", FALSE, False, false, 0x0, 0x00, 0" % (Value, Type)\r
     elif Type in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64]:\r
-        if Value and int(Value, 0) < 0:\r
-            return False, "PCD can't be set to negative value[%s] for datum type [%s]" % (Value, Type)\r
+        if Value.startswith('0') and not Value.lower().startswith('0x') and len(Value) > 1 and Value.lstrip('0'):\r
+            Value = Value.lstrip('0')\r
         try:\r
-            Value = long(Value, 0)\r
+            if Value and int(Value, 0) < 0:\r
+                return False, "PCD can't be set to negative value[%s] for datum type [%s]" % (Value, Type)\r
+            Value = int(Value, 0)\r
             if Value > MAX_VAL_TYPE[Type]:\r
                 return False, "Too large PCD value[%s] for datum type [%s]" % (Value, Type)\r
         except:\r
@@ -1605,82 +1349,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
@@ -1730,6 +1406,7 @@ class PathClass(object):
         self.TagName = TagName\r
         self.ToolCode = ToolCode\r
         self.ToolChainFamily = ToolChainFamily\r
+        self.OriginalPath = self\r
 \r
     ## Convert the object of this class to a string\r
     #\r
@@ -1752,7 +1429,7 @@ class PathClass(object):
 \r
     ## Override __cmp__ function\r
     #\r
-    # Customize the comparsion operation of two PathClass\r
+    # Customize the comparison operation of two PathClass\r
     #\r
     # @retval 0     The two PathClass are different\r
     # @retval -1    The first PathClass is less than the second PathClass\r
@@ -1786,6 +1463,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
@@ -1821,7 +1524,7 @@ class PathClass(object):
             self.Path = os.path.join(RealRoot, RealFile)\r
         return ErrorCode, ErrorInfo\r
 \r
-## Parse PE image to get the required PE informaion.\r
+## Parse PE image to get the required PE information.\r
 #\r
 class PeImageClass():\r
     ## Constructor\r
@@ -1856,7 +1559,7 @@ class PeImageClass():
         ByteArray = array.array('B')\r
         ByteArray.fromfile(PeObject, 4)\r
         # PE signature should be 'PE\0\0'\r
-        if ByteArray.tostring() != 'PE\0\0':\r
+        if ByteArray.tostring() != b'PE\0\0':\r
             self.ErrorInfo = self.FileName + ' has no valid PE signature PE00'\r
             return\r
 \r
@@ -1948,7 +1651,7 @@ class SkuClass():
                             ExtraData = "SKU-ID [%s] value %s exceeds the max value of UINT64"\r
                                       % (SkuName, SkuId))\r
 \r
-        self.AvailableSkuIds = sdict()\r
+        self.AvailableSkuIds = OrderedDict()\r
         self.SkuIdSet = []\r
         self.SkuIdNumberSet = []\r
         self.SkuData = SkuIds\r
@@ -1958,7 +1661,7 @@ class SkuClass():
             self.SkuIdSet = ['DEFAULT']\r
             self.SkuIdNumberSet = ['0U']\r
         elif SkuIdentifier == 'ALL':\r
-            self.SkuIdSet = SkuIds.keys()\r
+            self.SkuIdSet = list(SkuIds.keys())\r
             self.SkuIdNumberSet = [num[0].strip() + 'U' for num in SkuIds.values()]\r
         else:\r
             r = SkuIdentifier.split('|')\r
@@ -2065,12 +1768,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
@@ -2078,7 +1775,7 @@ def PackRegistryFormatGuid(Guid):
 #   @retval     Value    The integer value that the input represents\r
 #\r
 def GetIntegerValue(Input):\r
-    if type(Input) in (int, long):\r
+    if not isinstance(Input, str):\r
         return Input\r
     String = Input\r
     if String.endswith("U"):\r
@@ -2148,11 +1845,9 @@ def CopyDict(ori_dict):
         else:\r
             new_dict[key] = ori_dict[key]\r
     return new_dict\r
-##\r
+\r
 #\r
-# This acts like the main() function for the script, unless it is 'import'ed into another\r
-# script.\r
+# Remove the c/c++ comments: // and /* */\r
 #\r
-if __name__ == '__main__':\r
-    pass\r
-\r
+def RemoveCComments(ctext):\r
+    return re.sub('//.*?\n|/\*.*?\*/', '\n', ctext, flags=re.S)\r