## @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 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
-from collections import OrderedDict\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
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
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
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
RanStr = ''.join(sample(string.ascii_letters + string.digits, 8))\r
Setting = Setting.replace('\\\\', RanStr).strip()\r
FieldList[i] = ch.replace(RanStr,'\\\\')\r
return FieldList\r
\r
-def ParseDevPathValue (Value):\r
- if '\\' in Value:\r
- Value.replace('\\', '/').replace(' ', '')\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
+ 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
if "{CODE(" in Value:\r
return Value, len(Value.split(","))\r
if isinstance(Value, type(0)):\r
if Value[0] == '"' and Value[-1] == '"':\r
Value = Value[1:-1]\r
try:\r
- Value = "'" + uuid.UUID(Value).get_bytes_le() + "'"\r
+ Value = "'" + uuid.UUID(Value).bytes_le + "'"\r
except ValueError as Message:\r
raise BadExpression(Message)\r
Value, Size = ParseFieldValue(Value)\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
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
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
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
#\r
def RemoveCComments(ctext):\r
return re.sub('//.*?\n|/\*.*?\*/', '\n', ctext, flags=re.S)\r
-##\r
-#\r
-# This acts like the main() function for the script, unless it is 'import'ed into another\r
-# script.\r
-#\r
-if __name__ == '__main__':\r
- pass\r
-\r