]> 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 d3b71fc4a2662258cbc3410e7c255bd6099d3248..d082c58befda5b46aa3f40113c96f1566ded60fd 100644 (file)
@@ -2,13 +2,7 @@
 # Common routines used by all tools\r
 #\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
-# 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
+# SPDX-License-Identifier: BSD-2-Clause-Patent\r
 #\r
 \r
 ##\r
@@ -28,6 +22,7 @@ from random import sample
 from struct import pack\r
 import uuid\r
 import subprocess\r
+import tempfile\r
 from collections import OrderedDict\r
 \r
 import Common.LongFilePathOs as os\r
@@ -42,6 +37,7 @@ from Common.MultipleWorkspace import MultipleWorkspace as mws
 from CommonDataClass.Exceptions import BadExpression\r
 from Common.caching import cached_property\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
@@ -285,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
@@ -456,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
@@ -475,12 +479,26 @@ 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
+    OpenMode = "w"\r
+    if IsBinaryFile:\r
+        OpenMode = "wb"\r
+\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
     return True\r
 \r
@@ -762,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
@@ -775,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
@@ -788,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
@@ -1019,6 +1037,7 @@ def ParseFieldValue (Value):
             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
@@ -1060,7 +1079,10 @@ def ParseFieldValue (Value):
         if Value[0] == '"' and Value[-1] == '"':\r
             Value = Value[1:-1]\r
         try:\r
-            Value = "'" + uuid.UUID(Value).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
@@ -1384,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
@@ -1406,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
@@ -1501,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
@@ -1536,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
@@ -1752,7 +1775,7 @@ class SkuClass():
 #   @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