X-Git-Url: https://git.proxmox.com/?a=blobdiff_plain;f=BaseTools%2FSource%2FPython%2FCommon%2FMisc.py;h=5db9405ddc06264c53a2909b3f08e25efbc29ad7;hb=2e351cbe8e190271b3716284fc1076551d005472;hp=9967ac470cbb225f234d880834979c4a075a817c;hpb=f56c83f815798e52f2a0fd9f71c340ba67958a67;p=mirror_edk2.git diff --git a/BaseTools/Source/Python/Common/Misc.py b/BaseTools/Source/Python/Common/Misc.py index 9967ac470c..5db9405ddc 100644 --- a/BaseTools/Source/Python/Common/Misc.py +++ b/BaseTools/Source/Python/Common/Misc.py @@ -2,13 +2,7 @@ # Common routines used by all tools # # Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.
-# This program and the accompanying materials -# are licensed and made available under the terms and conditions of the BSD License -# which accompanies this distribution. The full text of the license may be found at -# http://opensource.org/licenses/bsd-license.php -# -# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, -# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -456,15 +450,22 @@ def RemoveDirectory(Directory, Recursively=False): # @retval False If the file content is the same # def SaveFileOnChange(File, Content, IsBinaryFile=True): - if not IsBinaryFile: - Content = Content.replace("\n", os.linesep) if os.path.exists(File): - try: - if Content == open(File, "rb").read(): - return False - except: - EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File) + if IsBinaryFile: + try: + with open(File, "rb") as f: + if Content == f.read(): + return False + except: + EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File) + else: + try: + with open(File, "r") as f: + if Content == f.read(): + return False + except: + EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File) DirName = os.path.dirname(File) if not CreateDirectory(DirName): @@ -475,12 +476,18 @@ def SaveFileOnChange(File, Content, IsBinaryFile=True): if not os.access(DirName, os.W_OK): EdkLogger.error(None, PERMISSION_FAILURE, "Do not have write permission on directory %s" % DirName) - try: - Fd = open(File, "wb") - Fd.write(Content) - Fd.close() - except IOError as X: - EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X) + if IsBinaryFile: + try: + with open(File, "wb") as Fd: + Fd.write(Content) + except IOError as X: + EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X) + else: + try: + with open(File, 'w') as Fd: + Fd.write(Content) + except IOError as X: + EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X) return True @@ -574,13 +581,14 @@ def RealPath(File, Dir='', OverrideDir=''): # def GuidValue(CName, PackageList, Inffile = None): for P in PackageList: - GuidKeys = P.Guids.keys() + GuidKeys = list(P.Guids.keys()) if Inffile and P._PrivateGuids: if not Inffile.startswith(P.MetaFile.Dir): GuidKeys = [x for x in P.Guids if x not in P._PrivateGuids] if CName in GuidKeys: return P.Guids[CName] return None + return None ## A string template class # @@ -761,10 +769,10 @@ class Progressor: ## Constructor # - # @param OpenMessage The string printed before progress charaters - # @param CloseMessage The string printed after progress charaters - # @param ProgressChar The charater used to indicate the progress - # @param Interval The interval in seconds between two progress charaters + # @param OpenMessage The string printed before progress characters + # @param CloseMessage The string printed after progress characters + # @param ProgressChar The character used to indicate the progress + # @param Interval The interval in seconds between two progress characters # def __init__(self, OpenMessage="", CloseMessage="", ProgressChar='.', Interval=1.0): self.PromptMessage = OpenMessage @@ -774,9 +782,9 @@ class Progressor: if Progressor._StopFlag is None: Progressor._StopFlag = threading.Event() - ## Start to print progress charater + ## Start to print progress character # - # @param OpenMessage The string printed before progress charaters + # @param OpenMessage The string printed before progress characters # def Start(self, OpenMessage=None): if OpenMessage is not None: @@ -787,9 +795,9 @@ class Progressor: Progressor._ProgressThread.setDaemon(False) Progressor._ProgressThread.start() - ## Stop printing progress charater + ## Stop printing progress character # - # @param CloseMessage The string printed after progress charaters + # @param CloseMessage The string printed after progress characters # def Stop(self, CloseMessage=None): OriginalCodaMessage = self.CodaMessage @@ -1018,6 +1026,7 @@ def ParseFieldValue (Value): p.stderr.close() if err: raise BadExpression("DevicePath: %s" % str(err)) + out = out.decode(encoding='utf-8', errors='ignore') Size = len(out.split()) out = ','.join(out.split()) return '{' + out + '}', Size @@ -1025,7 +1034,7 @@ def ParseFieldValue (Value): if "{CODE(" in Value: return Value, len(Value.split(",")) if isinstance(Value, type(0)): - return Value, (Value.bit_length() + 7) / 8 + return Value, (Value.bit_length() + 7) // 8 if not isinstance(Value, type('')): raise BadExpression('Type %s is %s' %(Value, type(Value))) Value = Value.strip() @@ -1059,7 +1068,10 @@ def ParseFieldValue (Value): if Value[0] == '"' and Value[-1] == '"': Value = Value[1:-1] try: - Value = "'" + uuid.UUID(Value).bytes_le + "'" + Value = str(uuid.UUID(Value).bytes_le) + if Value.startswith("b'"): + Value = Value[2:-1] + Value = "'" + Value + "'" except ValueError as Message: raise BadExpression(Message) Value, Size = ParseFieldValue(Value) @@ -1146,12 +1158,12 @@ def ParseFieldValue (Value): raise BadExpression("invalid hex value: %s" % Value) if Value == 0: return 0, 1 - return Value, (Value.bit_length() + 7) / 8 + return Value, (Value.bit_length() + 7) // 8 if Value[0].isdigit(): Value = int(Value, 10) if Value == 0: return 0, 1 - return Value, (Value.bit_length() + 7) / 8 + return Value, (Value.bit_length() + 7) // 8 if Value.lower() == 'true': return 1, 1 if Value.lower() == 'false': @@ -1310,10 +1322,12 @@ def CheckPcdDatum(Type, Value): return False, "Invalid value [%s] of type [%s]; must be one of TRUE, True, true, 0x1, 0x01, 1"\ ", FALSE, False, false, 0x0, 0x00, 0" % (Value, Type) elif Type in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64]: - if Value and int(Value, 0) < 0: - return False, "PCD can't be set to negative value[%s] for datum type [%s]" % (Value, Type) + if Value.startswith('0') and not Value.lower().startswith('0x') and len(Value) > 1 and Value.lstrip('0'): + Value = Value.lstrip('0') try: - Value = long(Value, 0) + if Value and int(Value, 0) < 0: + return False, "PCD can't be set to negative value[%s] for datum type [%s]" % (Value, Type) + Value = int(Value, 0) if Value > MAX_VAL_TYPE[Type]: return False, "Too large PCD value[%s] for datum type [%s]" % (Value, Type) except: @@ -1403,7 +1417,7 @@ class PathClass(object): ## Override __cmp__ function # - # Customize the comparsion operation of two PathClass + # Customize the comparison operation of two PathClass # # @retval 0 The two PathClass are different # @retval -1 The first PathClass is less than the second PathClass @@ -1498,7 +1512,7 @@ class PathClass(object): self.Path = os.path.join(RealRoot, RealFile) return ErrorCode, ErrorInfo -## Parse PE image to get the required PE informaion. +## Parse PE image to get the required PE information. # class PeImageClass(): ## Constructor @@ -1533,7 +1547,7 @@ class PeImageClass(): ByteArray = array.array('B') ByteArray.fromfile(PeObject, 4) # PE signature should be 'PE\0\0' - if ByteArray.tostring() != 'PE\0\0': + if ByteArray.tostring() != b'PE\0\0': self.ErrorInfo = self.FileName + ' has no valid PE signature PE00' return @@ -1635,7 +1649,7 @@ class SkuClass(): self.SkuIdSet = ['DEFAULT'] self.SkuIdNumberSet = ['0U'] elif SkuIdentifier == 'ALL': - self.SkuIdSet = SkuIds.keys() + self.SkuIdSet = list(SkuIds.keys()) self.SkuIdNumberSet = [num[0].strip() + 'U' for num in SkuIds.values()] else: r = SkuIdentifier.split('|') @@ -1749,7 +1763,7 @@ class SkuClass(): # @retval Value The integer value that the input represents # def GetIntegerValue(Input): - if type(Input) in (int, long): + if not isinstance(Input, str): return Input String = Input if String.endswith("U"):