# 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
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
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
#\r
RtPath.Path = TempFullPath\r
RtPath.BaseName = BaseName\r
+ RtPath.OriginalPath = Path\r
#\r
# If file exists, compare contents\r
#\r
# @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
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
#\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
+ return None\r
\r
## A string template class\r
#\r
\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
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
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
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
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
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
\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
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
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
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
# @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