]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/Common/Misc.py
Revert BaseTools: PYTHON3 migration
[mirror_edk2.git] / BaseTools / Source / Python / Common / Misc.py
index 2ac592d26bac82e78fb39cf95f30fc0e9a4e7da2..0efd8b05a87798a093759be5e0d6f251dfcc0cbb 100644 (file)
@@ -14,6 +14,7 @@
 ##\r
 # Import Modules\r
 #\r
+from __future__ import absolute_import\r
 import Common.LongFilePathOs as os\r
 import sys\r
 import string\r
@@ -24,8 +25,8 @@ import pickle
 import array\r
 import shutil\r
 from struct import pack\r
-from collections import UserDict as IterableUserDict\r
-from collections import OrderedDict\r
+from UserDict import IterableUserDict\r
+from UserList import UserList\r
 \r
 from Common import EdkLogger as EdkLogger\r
 from Common import GlobalData as GlobalData\r
@@ -454,16 +455,13 @@ 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 isinstance(Content, bytes):\r
-                with open(File, "rb") as f:\r
-                    if Content == f.read():\r
-                        return False\r
-            else:\r
-                with open(File, "r") as f:\r
-                    if Content == f.read():\r
-                        return False\r
+            if Content == open(File, "rb").read():\r
+                return False\r
         except:\r
             EdkLogger.error(None, FILE_OPEN_FAILURE, ExtraData=File)\r
 \r
@@ -477,12 +475,19 @@ def SaveFileOnChange(File, Content, IsBinaryFile=True):
             EdkLogger.error(None, PERMISSION_FAILURE, "Do not have write permission on directory %s" % DirName)\r
 \r
     try:\r
-        if isinstance(Content, bytes):\r
-            with open(File, "wb") as Fd:\r
+        if GlobalData.gIsWindows:\r
+            try:\r
+                from .PyUtility import SaveFileToDisk\r
+                if not SaveFileToDisk(File, Content):\r
+                    EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData=File)\r
+            except:\r
+                Fd = open(File, "wb")\r
                 Fd.write(Content)\r
+                Fd.close()\r
         else:\r
-            with open(File, "w") as Fd:\r
-                Fd.write(Content)\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
@@ -641,7 +646,7 @@ def RealPath2(File, Dir='', OverrideDir=''):
 #\r
 def GuidValue(CName, PackageList, Inffile = None):\r
     for P in PackageList:\r
-        GuidKeys = list(P.Guids.keys())\r
+        GuidKeys = 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
@@ -660,7 +665,7 @@ def GuidValue(CName, PackageList, Inffile = None):
 #\r
 def ProtocolValue(CName, PackageList, Inffile = None):\r
     for P in PackageList:\r
-        ProtocolKeys = list(P.Protocols.keys())\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
@@ -679,7 +684,7 @@ def ProtocolValue(CName, PackageList, Inffile = None):
 #\r
 def PpiValue(CName, PackageList, Inffile = None):\r
     for P in PackageList:\r
-        PpiKeys = list(P.Ppis.keys())\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
@@ -975,7 +980,7 @@ class sdict(IterableUserDict):
 \r
     ## append support\r
     def append(self, sdict):\r
-        for key in sdict.keys():\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
@@ -1015,11 +1020,11 @@ class sdict(IterableUserDict):
 \r
     ## Keys interation support\r
     def iterkeys(self):\r
-        return self.keys()\r
+        return iter(self.keys())\r
 \r
     ## Values interation support\r
     def itervalues(self):\r
-        return self.values()\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
@@ -1028,7 +1033,7 @@ class sdict(IterableUserDict):
             value = self[key]\r
             self.__delitem__(key)\r
         elif len(dv) != 0 :\r
-            value = dv[0]\r
+            value = kv[0]\r
         return value\r
 \r
     ## Return (key, value) pair, and remove the (key, value) from the dict\r
@@ -1292,12 +1297,12 @@ def ParseDevPathValue (Value):
     if err:\r
         raise BadExpression("DevicePath: %s" % str(err))\r
     Size = len(out.split())\r
-    out = ','.join(out.decode(encoding='utf-8', errors='ignore').split())\r
+    out = ','.join(out.split())\r
     return '{' + out + '}', Size\r
 \r
 def ParseFieldValue (Value):\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
@@ -1331,7 +1336,7 @@ def ParseFieldValue (Value):
         if Value[0] == '"' and Value[-1] == '"':\r
             Value = Value[1:-1]\r
         try:\r
-            Value = "{" + ','.join([str(i) for i in uuid.UUID(Value).bytes_le]) + "}"\r
+            Value = "'" + uuid.UUID(Value).get_bytes_le() + "'"\r
         except ValueError as Message:\r
             raise BadExpression(Message)\r
         Value, Size = ParseFieldValue(Value)\r
@@ -1418,12 +1423,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
@@ -1584,19 +1589,15 @@ 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
         try:\r
-            Val = int(Value, 0)\r
+            Value = long(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
-            try:\r
-                Val = int(Value.lstrip('0'))\r
-            except:\r
-                return False, "Invalid value [%s] of type [%s];" \\r
-                              " must be a hexadecimal, decimal or octal in C language format." % (Value, Type)\r
-        if Val > MAX_VAL_TYPE[Type]:\r
-            return False, "Too large PCD value[%s] for datum type [%s]" % (Value, Type)\r
-        if Val < 0:\r
-            return False, "PCD can't be set to negative value[%s] for datum type [%s]" % (Value, Type)\r
-\r
+            return False, "Invalid value [%s] of type [%s];"\\r
+                          " must be a hexadecimal, decimal or octal in C language format." % (Value, Type)\r
     else:\r
         return True, "StructurePcd"\r
 \r
@@ -1634,7 +1635,7 @@ def SplitOption(OptionString):
 def CommonPath(PathList):\r
     P1 = min(PathList).split(os.path.sep)\r
     P2 = max(PathList).split(os.path.sep)\r
-    for Index in range(min(len(P1), len(P2))):\r
+    for Index in xrange(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
@@ -1859,7 +1860,7 @@ class PeImageClass():
         ByteArray = array.array('B')\r
         ByteArray.fromfile(PeObject, 4)\r
         # PE signature should be 'PE\0\0'\r
-        if ByteArray.tostring() != b'PE\0\0':\r
+        if ByteArray.tostring() != 'PE\0\0':\r
             self.ErrorInfo = self.FileName + ' has no valid PE signature PE00'\r
             return\r
 \r
@@ -1951,7 +1952,7 @@ class SkuClass():
                             ExtraData = "SKU-ID [%s] value %s exceeds the max value of UINT64"\r
                                       % (SkuName, SkuId))\r
 \r
-        self.AvailableSkuIds = OrderedDict()\r
+        self.AvailableSkuIds = sdict()\r
         self.SkuIdSet = []\r
         self.SkuIdNumberSet = []\r
         self.SkuData = SkuIds\r
@@ -1961,7 +1962,7 @@ class SkuClass():
             self.SkuIdSet = ['DEFAULT']\r
             self.SkuIdNumberSet = ['0U']\r
         elif SkuIdentifier == 'ALL':\r
-            self.SkuIdSet = list(SkuIds.keys())\r
+            self.SkuIdSet = SkuIds.keys()\r
             self.SkuIdNumberSet = [num[0].strip() + 'U' for num in SkuIds.values()]\r
         else:\r
             r = SkuIdentifier.split('|')\r
@@ -2081,7 +2082,7 @@ def PackRegistryFormatGuid(Guid):
 #   @retval     Value    The integer value that the input represents\r
 #\r
 def GetIntegerValue(Input):\r
-    if isinstance(Input, int):\r
+    if type(Input) in (int, long):\r
         return Input\r
     String = Input\r
     if String.endswith("U"):\r