## @file\r
# Common routines used by all tools\r
#\r
-# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>\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
# 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
import pickle\r
import array\r
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
+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
+\r
## Regular expression used to find out place holders in string template\r
gPlaceholderPattern = re.compile("\$\{([^$()\s]+)\}", re.MULTILINE | re.UNICODE)\r
\r
\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
# @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
+ if IsBinaryFile:\r
+ try:\r
+ with open(File, "wb") as Fd:\r
+ Fd.write(Content)\r
+ except IOError as X:\r
+ EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData='IOError %s' % X)\r
+ else:\r
+ try:\r
+ with open(File, 'w') 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
-## 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
-\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
-\r
## Retrieve and cache the real path name in file system\r
#\r
# @param Root The root directory of path relative to\r
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
#\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
\r
## Constructor\r
def __init__(self, Template=None):\r
- self.String = ''\r
+ self.String = []\r
self.IsBinary = False\r
self._Template = Template\r
self._TemplateSectionList = self._Parse(Template)\r
# @retval string The string replaced\r
#\r
def __str__(self):\r
- return self.String\r
+ return "".join(self.String)\r
\r
## Split the template string into fragments per the ${BEGIN} and ${END} flags\r
#\r
def Append(self, AppendString, Dictionary=None):\r
if Dictionary:\r
SectionList = self._Parse(AppendString)\r
- self.String += "".join(S.Instantiate(Dictionary) for S in SectionList)\r
+ self.String.append( "".join(S.Instantiate(Dictionary) for S in SectionList))\r
else:\r
- self.String += AppendString\r
+ if isinstance(AppendString,list):\r
+ self.String.extend(AppendString)\r
+ else:\r
+ self.String.append(AppendString)\r
\r
## Replace the string template with dictionary of placeholders\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
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
_ListType = type([])\r
_TupleType = type(())\r
_Wildcard = 'COMMON'\r
- _ValidWildcardList = ['COMMON', 'DEFAULT', 'ALL', '*', 'PLATFORM']\r
+ _ValidWildcardList = ['COMMON', 'DEFAULT', 'ALL', TAB_STAR, 'PLATFORM']\r
\r
def __init__(self, _Single_=False, _Level_=2):\r
self._Level_ = _Level_\r
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
- Setting = Setting.strip()\r
+ RanStr = ''.join(sample(string.ascii_letters + string.digits, 8))\r
+ Setting = Setting.replace('\\\\', RanStr).strip()\r
# There might be escaped quote in a string: \", \\\" , \', \\\'\r
Data = Setting\r
# There might be '|' in string and in ( ... | ... ), replace it with '-'\r
break\r
FieldList.append(Setting[StartPos:Pos].strip())\r
StartPos = Pos + 1\r
-\r
+ for i, ch in enumerate(FieldList):\r
+ if RanStr in ch:\r
+ FieldList[i] = ch.replace(RanStr,'\\\\')\r
return FieldList\r
\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
-\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
+\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
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
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
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
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
\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
# @retval True The two PathClass are the same\r
#\r
def __eq__(self, Other):\r
- if isinstance(Other, type(self)):\r
- return self.Path == Other.Path\r
- else:\r
- return self.Path == str(Other)\r
+ return self.Path == str(Other)\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
# @retval 1 The first PathClass is Bigger than the second PathClass\r
def __cmp__(self, Other):\r
- if isinstance(Other, type(self)):\r
- OtherKey = Other.Path\r
- else:\r
- OtherKey = str(Other)\r
+ OtherKey = str(Other)\r
\r
SelfKey = self.Path\r
if SelfKey == OtherKey:\r
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
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
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
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
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
# @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
Guid[10],\r
)\r
\r
-##\r
+## DeepCopy dict/OrderedDict recusively\r
#\r
-# This acts like the main() function for the script, unless it is 'import'ed into another\r
-# script.\r
+# @param ori_dict a nested dict or ordereddict\r
#\r
-if __name__ == '__main__':\r
- pass\r
+# @retval new dict or orderdict\r
+#\r
+def CopyDict(ori_dict):\r
+ dict_type = ori_dict.__class__\r
+ if dict_type not in (dict,OrderedDict):\r
+ return ori_dict\r
+ new_dict = dict_type()\r
+ for key in ori_dict:\r
+ if isinstance(ori_dict[key],(dict,OrderedDict)):\r
+ new_dict[key] = CopyDict(ori_dict[key])\r
+ else:\r
+ new_dict[key] = ori_dict[key]\r
+ return new_dict\r
\r
+#\r
+# Remove the c/c++ comments: // and /* */\r
+#\r
+def RemoveCComments(ctext):\r
+ return re.sub('//.*?\n|/\*.*?\*/', '\n', ctext, flags=re.S)\r