X-Git-Url: https://git.proxmox.com/?a=blobdiff_plain;f=BaseTools%2FSource%2FPython%2FWorkspace%2FMetaFileParser.py;h=0a131fc76981fea60f8c4a4f97a3d6ed2bec167c;hb=d847ac1f27cca3e78698559a7c96f5f5d115bc8b;hp=6a30d45b3dbf7059cd21309776769ae1ef1e3d81;hpb=ae7b6df816e913394a7f11264f24953658ff34ba;p=mirror_edk2.git diff --git a/BaseTools/Source/Python/Workspace/MetaFileParser.py b/BaseTools/Source/Python/Workspace/MetaFileParser.py index 6a30d45b3d..0a131fc769 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileParser.py @@ -1,44 +1,46 @@ ## @file # This file is used to parse meta files # -# Copyright (c) 2008 - 2017, Intel Corporation. All rights reserved.
-# (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
-# 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. +# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
+# (C) Copyright 2015-2018 Hewlett Packard Enterprise Development LP
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## # Import Modules # +from __future__ import print_function +from __future__ import absolute_import import Common.LongFilePathOs as os import re import time import copy -import md5 +from hashlib import md5 import Common.EdkLogger as EdkLogger import Common.GlobalData as GlobalData from CommonDataClass.DataClass import * from Common.DataType import * -from Common.String import * -from Common.Misc import GuidStructureStringToGuidString, CheckPcdDatum, PathClass, AnalyzePcdData, AnalyzeDscPcd, AnalyzePcdExpression +from Common.StringUtils import * +from Common.Misc import GuidStructureStringToGuidString, CheckPcdDatum, PathClass, AnalyzePcdData, AnalyzeDscPcd, AnalyzePcdExpression, ParseFieldValue, StructPattern from Common.Expression import * from CommonDataClass.Exceptions import * from Common.LongFilePathSupport import OpenLongFilePath as open +from collections import defaultdict +from .MetaFileTable import MetaFileStorage +from .MetaFileCommentParser import CheckInfComment +from Common.DataType import TAB_COMMENT_EDK_START, TAB_COMMENT_EDK_END -from MetaFileTable import MetaFileStorage -from MetaFileCommentParser import CheckInfComment +## RegEx for finding file versions +hexVersionPattern = re.compile(r'0[xX][\da-f-A-F]{5,8}') +decVersionPattern = re.compile(r'\d+\.\d+') +CODEPattern = re.compile(r"{CODE\([a-fA-F0-9Xx\{\},\s]*\)}") ## A decorator used to parse macro definition def ParseMacro(Parser): def MacroParser(self): - Match = gMacroDefPattern.match(self._CurrentLine) + Match = GlobalData.gMacroDefPattern.match(self._CurrentLine) if not Match: # Not 'DEFINE/EDK_GLOBAL' statement, call decorated method Parser(self) @@ -59,7 +61,7 @@ def ParseMacro(Parser): EdkLogger.error('Parser', FORMAT_INVALID, "%s can only be defined via environment variable" % Name, ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) # Only upper case letters, digit and '_' are allowed - if not gMacroNamePattern.match(Name): + if not GlobalData.gMacroNamePattern.match(Name): EdkLogger.error('Parser', FORMAT_INVALID, "The macro name must be in the pattern [A-Z][A-Z0-9_]*", ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) @@ -73,10 +75,10 @@ def ParseMacro(Parser): # # First judge whether this DEFINE is in conditional directive statements or not. # - if type(self) == DscParser and self._InDirective > -1: + if isinstance(self, DscParser) and self._InDirective > -1: pass else: - if type(self) == DecParser: + if isinstance(self, DecParser): if MODEL_META_DATA_HEADER in self._SectionType: self._FileLocalMacros[Name] = Value else: @@ -87,7 +89,7 @@ def ParseMacro(Parser): self._ConstructSectionMacroDict(Name, Value) # EDK_GLOBAL defined macros - elif type(self) != DscParser: + elif not isinstance(self, DscParser): EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL can only be used in .dsc file", ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) elif self._SectionType != MODEL_META_DATA_HEADER: @@ -159,7 +161,7 @@ class MetaFileParser(object): self._FileDir = self.MetaFile.Dir self._Defines = {} self._FileLocalMacros = {} - self._SectionsMacroDict = {} + self._SectionsMacroDict = defaultdict(dict) # for recursive parsing self._Owner = [Owner] @@ -182,6 +184,11 @@ class MetaFileParser(object): self._PostProcessed = False # Different version of meta-file has different way to parse. self._Version = 0 + self._GuidDict = {} # for Parser PCD value {GUID(gTokeSpaceGuidName)} + + self._PcdCodeValue = "" + self._PcdDataTypeCODE = False + self._CurrentPcdName = "" ## Store the parsed data in table def _Store(self, *Args): @@ -198,19 +205,19 @@ class MetaFileParser(object): ## Set parsing complete flag in both class and table def _Done(self): self._Finished = True - ## Do not set end flag when processing included files - if self._From == -1: - self._Table.SetEndFlag() + self._Table.SetEndFlag() def _PostProcess(self): self._PostProcessed = True ## Get the parse complete flag - def _GetFinished(self): + @property + def Finished(self): return self._Finished ## Set the complete flag - def _SetFinished(self, Value): + @Finished.setter + def Finished(self, Value): self._Finished = Value ## Remove records that do not match given Filter Arch @@ -218,7 +225,7 @@ class MetaFileParser(object): NewRecordList = [] for Record in RecordList: Arch = Record[3] - if Arch == 'COMMON' or Arch == FilterArch: + if Arch == TAB_ARCH_COMMON or Arch == FilterArch: NewRecordList.append(Record) return NewRecordList @@ -227,20 +234,14 @@ class MetaFileParser(object): # DataInfo = [data_type, scope1(arch), scope2(platform/moduletype)] # def __getitem__(self, DataInfo): - if type(DataInfo) != type(()): + if not isinstance(DataInfo, type(())): DataInfo = (DataInfo,) # Parse the file first, if necessary - if not self._Finished: - if self._RawTable.IsIntegrity(): - self._Finished = True - else: - self._Table = self._RawTable - self._PostProcessed = False - self.Start() + self.StartParse() # No specific ARCH or Platform given, use raw data - if self._RawTable and (len(DataInfo) == 1 or DataInfo[1] == None): + if self._RawTable and (len(DataInfo) == 1 or DataInfo[1] is None): return self._FilterRecordList(self._RawTable.Query(*DataInfo), self._Arch) # Do post-process if necessary @@ -249,6 +250,14 @@ class MetaFileParser(object): return self._FilterRecordList(self._Table.Query(*DataInfo), DataInfo[1]) + def StartParse(self): + if not self._Finished: + if self._RawTable.IsIntegrity(): + self._Finished = True + else: + self._Table = self._RawTable + self._PostProcessed = False + self.Start() ## Data parser for the common format in different type of file # # The common format in the meatfile is like @@ -269,7 +278,7 @@ class MetaFileParser(object): TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT) self._ValueList[0:len(TokenList)] = TokenList # Don't do macro replacement for dsc file at this point - if type(self) != DscParser: + if not isinstance(self, DscParser): Macros = self._Macros self._ValueList = [ReplaceMacro(Value, Macros) for Value in self._ValueList] @@ -296,7 +305,7 @@ class MetaFileParser(object): for Item in GetSplitValueList(self._CurrentLine[1:-1], TAB_COMMA_SPLIT): if Item == '': continue - ItemList = GetSplitValueList(Item, TAB_SPLIT,2) + ItemList = GetSplitValueList(Item, TAB_SPLIT, 3) # different section should not mix in one section if self._SectionName != '' and self._SectionName != ItemList[0].upper(): EdkLogger.error('Parser', FORMAT_INVALID, "Different section names in the same section", @@ -305,7 +314,7 @@ class MetaFileParser(object): if self._SectionName in self.DataType: self._SectionType = self.DataType[self._SectionName] # Check if the section name is valid - if self._SectionName not in SECTIONS_HAVE_ITEM_AFTER_ARCH and len(ItemList) > 3: + if self._SectionName not in SECTIONS_HAVE_ITEM_AFTER_ARCH_SET and len(ItemList) > 3: EdkLogger.error("Parser", FORMAT_UNKNOWN_ERROR, "%s is not a valid section name" % Item, self.MetaFile, self._LineIndex + 1, self._CurrentLine) elif self._Version >= 0x00010005: @@ -318,21 +327,26 @@ class MetaFileParser(object): if len(ItemList) > 1: S1 = ItemList[1].upper() else: - S1 = 'COMMON' + S1 = TAB_ARCH_COMMON + S1 = ReplaceMacro(S1, self._Macros) ArchList.add(S1) # S2 may be Platform or ModuleType if len(ItemList) > 2: - if self._SectionName.upper() in SECTIONS_HAVE_ITEM_PCD: + if self._SectionName.upper() in SECTIONS_HAVE_ITEM_PCD_SET: S2 = ItemList[2] else: S2 = ItemList[2].upper() else: - S2 = 'COMMON' - self._Scope.append([S1, S2]) + S2 = TAB_COMMON + if len(ItemList) > 3: + S3 = ItemList[3] + else: + S3 = TAB_COMMON + self._Scope.append([S1, S2, S3]) # 'COMMON' must not be used with specific ARCHs at the same section - if 'COMMON' in ArchList and len(ArchList) > 1: + if TAB_ARCH_COMMON in ArchList and len(ArchList) > 1: EdkLogger.error('Parser', FORMAT_INVALID, "'common' ARCH must not be used with specific ARCHs", File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine) # If the section information is needed later, it should be stored in database @@ -359,20 +373,23 @@ class MetaFileParser(object): EdkLogger.error("Parser", FORMAT_INVALID, "Global macro %s is not permitted." % (Macro), ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) else: EdkLogger.error("Parser", FORMAT_INVALID, "%s not defined" % (Macro), ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) - # Sometimes, we need to make differences between EDK and EDK2 modules + # Sometimes, we need to make differences between EDK and EDK2 modules if Name == 'INF_VERSION': - if re.match(r'0[xX][\da-f-A-F]{5,8}', Value): - self._Version = int(Value, 0) - elif re.match(r'\d+\.\d+', Value): + if hexVersionPattern.match(Value): + self._Version = int(Value, 0) + elif decVersionPattern.match(Value): ValueList = Value.split('.') - Major = '%04o' % int(ValueList[0], 0) - Minor = '%04o' % int(ValueList[1], 0) - self._Version = int('0x' + Major + Minor, 0) + Major = int(ValueList[0], 0) + Minor = int(ValueList[1], 0) + if Major > 0xffff or Minor > 0xffff: + EdkLogger.error('Parser', FORMAT_INVALID, "Invalid version number", + ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) + self._Version = int('0x{0:04x}{1:04x}'.format(Major, Minor), 0) else: EdkLogger.error('Parser', FORMAT_INVALID, "Invalid version number", ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) - if type(self) == InfParser and self._Version < 0x00010005: + if isinstance(self, InfParser) and self._Version < 0x00010005: # EDK module allows using defines as macros self._FileLocalMacros[Name] = Value self._Defines[Name] = Value @@ -388,7 +405,7 @@ class MetaFileParser(object): self._ValueList[1] = TokenList2[1] # keys else: self._ValueList[1] = TokenList[0] - if len(TokenList) == 2 and type(self) != DscParser: # value + if len(TokenList) == 2 and not isinstance(self, DscParser): # value self._ValueList[2] = ReplaceMacro(TokenList[1], self._Macros) if self._ValueList[1].count('_') != 4: @@ -402,29 +419,30 @@ class MetaFileParser(object): ) def GetValidExpression(self, TokenSpaceGuid, PcdCName): return self._Table.GetValidExpression(TokenSpaceGuid, PcdCName) - def _GetMacros(self): + + @property + def _Macros(self): Macros = {} Macros.update(self._FileLocalMacros) Macros.update(self._GetApplicableSectionMacro()) return Macros - ## Construct section Macro dict + ## Construct section Macro dict def _ConstructSectionMacroDict(self, Name, Value): - ScopeKey = [(Scope[0], Scope[1]) for Scope in self._Scope] + ScopeKey = [(Scope[0], Scope[1], Scope[2]) for Scope in self._Scope] ScopeKey = tuple(ScopeKey) - SectionDictKey = self._SectionType, ScopeKey # # DecParser SectionType is a list, will contain more than one item only in Pcd Section - # As Pcd section macro usage is not alllowed, so here it is safe + # As Pcd section macro usage is not allowed, so here it is safe # - if type(self) == DecParser: + if isinstance(self, DecParser): SectionDictKey = self._SectionType[0], ScopeKey - if SectionDictKey not in self._SectionsMacroDict: - self._SectionsMacroDict[SectionDictKey] = {} - SectionLocalMacros = self._SectionsMacroDict[SectionDictKey] - SectionLocalMacros[Name] = Value + else: + SectionDictKey = self._SectionType, ScopeKey + + self._SectionsMacroDict[SectionDictKey][Name] = Value - ## Get section Macros that are applicable to current line, which may come from other sections + ## Get section Macros that are applicable to current line, which may come from other sections ## that share the same name while scope is wider def _GetApplicableSectionMacro(self): Macros = {} @@ -434,7 +452,7 @@ class MetaFileParser(object): SpeSpeMacroDict = {} ActiveSectionType = self._SectionType - if type(self) == DecParser: + if isinstance(self, DecParser): ActiveSectionType = self._SectionType[0] for (SectionType, Scope) in self._SectionsMacroDict: @@ -442,20 +460,20 @@ class MetaFileParser(object): continue for ActiveScope in self._Scope: - Scope0, Scope1 = ActiveScope[0], ActiveScope[1] - if(Scope0, Scope1) not in Scope: + Scope0, Scope1, Scope2= ActiveScope[0], ActiveScope[1], ActiveScope[2] + if(Scope0, Scope1, Scope2) not in Scope: break else: SpeSpeMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)]) for ActiveScope in self._Scope: - Scope0, Scope1 = ActiveScope[0], ActiveScope[1] - if(Scope0, Scope1) not in Scope and (Scope0, "COMMON") not in Scope and ("COMMON", Scope1) not in Scope: + Scope0, Scope1, Scope2 = ActiveScope[0], ActiveScope[1], ActiveScope[2] + if(Scope0, Scope1, Scope2) not in Scope and (Scope0, TAB_COMMON, TAB_COMMON) not in Scope and (TAB_COMMON, Scope1, TAB_COMMON) not in Scope: break else: ComSpeMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)]) - if ("COMMON", "COMMON") in Scope: + if (TAB_COMMON, TAB_COMMON, TAB_COMMON) in Scope: ComComMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)]) Macros.update(ComComMacroDict) @@ -464,10 +482,40 @@ class MetaFileParser(object): return Macros - _SectionParser = {} - Finished = property(_GetFinished, _SetFinished) - _Macros = property(_GetMacros) + def ProcessMultipleLineCODEValue(self,Content): + CODEBegin = False + CODELine = "" + continuelinecount = 0 + newContent = [] + for Index in range(0, len(Content)): + Line = Content[Index] + if CODEBegin: + CODELine = CODELine + Line + continuelinecount +=1 + if ")}" in Line: + newContent.append(CODELine) + for _ in range(continuelinecount): + newContent.append("") + CODEBegin = False + CODELine = "" + continuelinecount = 0 + else: + if not Line: + newContent.append(Line) + continue + if "{CODE(" not in Line: + newContent.append(Line) + continue + elif CODEPattern.findall(Line): + newContent.append(Line) + continue + else: + CODEBegin = True + CODELine = Line + return newContent + + _SectionParser = {} ## INF file parser class # @@ -523,7 +571,8 @@ class InfParser(MetaFileParser): NmakeLine = '' Content = '' try: - Content = open(str(self.MetaFile), 'r').readlines() + with open(str(self.MetaFile), 'r') as File: + Content = File.readlines() except: EdkLogger.error("Parser", FILE_READ_FAILURE, ExtraData=self.MetaFile) @@ -547,10 +596,10 @@ class InfParser(MetaFileParser): SectionComments.extend(Comments) Comments = [] continue - if Line.find(DataType.TAB_COMMENT_EDK_START) > -1: + if Line.find(TAB_COMMENT_EDK_START) > -1: IsFindBlockComment = True continue - if Line.find(DataType.TAB_COMMENT_EDK_END) > -1: + if Line.find(TAB_COMMENT_EDK_END) > -1: IsFindBlockComment = False continue if IsFindBlockComment: @@ -563,8 +612,8 @@ class InfParser(MetaFileParser): if Line[0] == TAB_SECTION_START and Line[-1] == TAB_SECTION_END: if not GetHeaderComment: for Cmt, LNo in Comments: - self._Store(MODEL_META_DATA_HEADER_COMMENT, Cmt, '', '', 'COMMON', - 'COMMON', self._Owner[-1], LNo, -1, LNo, -1, 0) + self._Store(MODEL_META_DATA_HEADER_COMMENT, Cmt, '', '', TAB_COMMON, + TAB_COMMON, self._Owner[-1], LNo, -1, LNo, -1, 0) GetHeaderComment = True else: TailComments.extend(SectionComments + Comments) @@ -615,7 +664,7 @@ class InfParser(MetaFileParser): self._ValueList = ['', '', ''] # parse current line, result will be put in self._ValueList self._SectionParser[self._SectionType](self) - if self._ValueList == None or self._ItemType == MODEL_META_DATA_DEFINE: + if self._ValueList is None or self._ItemType == MODEL_META_DATA_DEFINE: self._ItemType = -1 Comments = [] continue @@ -627,7 +676,7 @@ class InfParser(MetaFileParser): # Model, Value1, Value2, Value3, Arch, Platform, BelongsToItem=-1, # LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1 # - for Arch, Platform in self._Scope: + for Arch, Platform, _ in self._Scope: LastItem = self._Store(self._SectionType, self._ValueList[0], self._ValueList[1], @@ -653,8 +702,8 @@ class InfParser(MetaFileParser): # If there are tail comments in INF file, save to database whatever the comments are for Comment in TailComments: - self._Store(MODEL_META_DATA_TAIL_COMMENT, Comment[0], '', '', 'COMMON', - 'COMMON', self._Owner[-1], -1, -1, -1, -1, 0) + self._Store(MODEL_META_DATA_TAIL_COMMENT, Comment[0], '', '', TAB_COMMON, + TAB_COMMON, self._Owner[-1], -1, -1, -1, -1, 0) self._Done() ## Data parser for the format in which there's path @@ -670,18 +719,6 @@ class InfParser(MetaFileParser): Value = self._ValueList[Index] if not Value: continue - - if Value.upper().find('$(EFI_SOURCE)\Edk'.upper()) > -1 or Value.upper().find('$(EFI_SOURCE)/Edk'.upper()) > -1: - Value = '$(EDK_SOURCE)' + Value[17:] - if Value.find('$(EFI_SOURCE)') > -1 or Value.find('$(EDK_SOURCE)') > -1: - pass - elif Value.startswith('.'): - pass - elif Value.startswith('$('): - pass - else: - Value = '$(EFI_SOURCE)/' + Value - self._ValueList[Index] = ReplaceMacro(Value, Macros) ## Parse [Sources] section @@ -753,9 +790,13 @@ class InfParser(MetaFileParser): if self._ValueList[2] != '': InfPcdValueList = GetSplitValueList(TokenList[1], TAB_VALUE_SPLIT, 1) if InfPcdValueList[0] in ['True', 'true', 'TRUE']: - self._ValueList[2] = TokenList[1].replace(InfPcdValueList[0], '1', 1); + self._ValueList[2] = TokenList[1].replace(InfPcdValueList[0], '1', 1) elif InfPcdValueList[0] in ['False', 'false', 'FALSE']: - self._ValueList[2] = TokenList[1].replace(InfPcdValueList[0], '0', 1); + self._ValueList[2] = TokenList[1].replace(InfPcdValueList[0], '0', 1) + elif isinstance(InfPcdValueList[0], str) and InfPcdValueList[0].find('$(') >= 0: + Value = ReplaceExprMacro(InfPcdValueList[0],self._Macros) + if Value != '0': + self._ValueList[2] = Value if (self._ValueList[0], self._ValueList[1]) not in self.PcdsDict: self.PcdsDict[self._ValueList[0], self._ValueList[1]] = self._SectionType elif self.PcdsDict[self._ValueList[0], self._ValueList[1]] != self._SectionType: @@ -804,6 +845,7 @@ class DscParser(MetaFileParser): # DSC file supported data types (one type per section) DataType = { TAB_SKUIDS.upper() : MODEL_EFI_SKU_ID, + TAB_DEFAULT_STORES.upper() : MODEL_EFI_DEFAULT_STORES, TAB_LIBRARIES.upper() : MODEL_EFI_LIBRARY_INSTANCE, TAB_LIBRARY_CLASSES.upper() : MODEL_EFI_LIBRARY_CLASS, TAB_BUILD_OPTIONS.upper() : MODEL_META_DATA_BUILD_OPTION, @@ -817,7 +859,6 @@ class DscParser(MetaFileParser): TAB_PCDS_DYNAMIC_EX_HII_NULL.upper() : MODEL_PCD_DYNAMIC_EX_HII, TAB_PCDS_DYNAMIC_EX_VPD_NULL.upper() : MODEL_PCD_DYNAMIC_EX_VPD, TAB_COMPONENTS.upper() : MODEL_META_DATA_COMPONENT, - TAB_COMPONENTS_SOURCE_OVERRIDE_PATH.upper() : MODEL_META_DATA_COMPONENT_SOURCE_OVERRIDE_PATH, TAB_DSC_DEFINES.upper() : MODEL_META_DATA_HEADER, TAB_DSC_DEFINES_DEFINE : MODEL_META_DATA_DEFINE, TAB_DSC_DEFINES_EDKGLOBAL : MODEL_META_DATA_GLOBAL_DEFINE, @@ -829,6 +870,7 @@ class DscParser(MetaFileParser): TAB_ELSE.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSE, TAB_END_IF.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF, TAB_USER_EXTENSIONS.upper() : MODEL_META_DATA_USER_EXTENSION, + TAB_ERROR.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_ERROR, } # Valid names in define section @@ -875,7 +917,7 @@ class DscParser(MetaFileParser): # def __init__(self, FilePath, FileType, Arch, Table, Owner= -1, From= -1): # prevent re-initialization - if hasattr(self, "_Table"): + if hasattr(self, "_Table") and self._Table is Table: return MetaFileParser.__init__(self, FilePath, FileType, Arch, Table, Owner, From) self._Version = 0x00010005 # Only EDK2 dsc file is supported @@ -897,15 +939,21 @@ class DscParser(MetaFileParser): # self._IdMapping = {-1:-1} + self._Content = None + ## Parser starter def Start(self): Content = '' try: - Content = open(str(self.MetaFile), 'r').readlines() + with open(str(self.MetaFile), 'r') as File: + Content = File.readlines() except: EdkLogger.error("Parser", FILE_READ_FAILURE, ExtraData=self.MetaFile) OwnerId = {} + + Content = self.ProcessMultipleLineCODEValue(Content) + for Index in range(0, len(Content)): Line = CleanString(Content[Index]) # skip empty line @@ -926,17 +974,24 @@ class DscParser(MetaFileParser): self._SubsectionType = MODEL_UNKNOWN self._SubsectionName = '' self._Owner[-1] = -1 - OwnerId = {} + OwnerId.clear() continue # subsection header elif Line[0] == TAB_OPTION_START and Line[-1] == TAB_OPTION_END: self._SubsectionType = MODEL_META_DATA_SUBSECTION_HEADER # directive line elif Line[0] == '!': - self._DirectiveParser() + TokenList = GetSplitValueList(Line, ' ', 1) + if TokenList[0] == TAB_INCLUDE: + for Arch, ModuleType, DefaultStore in self._Scope: + if self._SubsectionType != MODEL_UNKNOWN and Arch in OwnerId: + self._Owner[-1] = OwnerId[Arch] + self._DirectiveParser() + else: + self._DirectiveParser() continue if Line[0] == TAB_OPTION_START and not self._InSubsection: - EdkLogger.error("Parser", FILE_READ_FAILURE, "Missing the '{' before %s in Line %s" % (Line, Index+1),ExtraData=self.MetaFile) + EdkLogger.error("Parser", FILE_READ_FAILURE, "Missing the '{' before %s in Line %s" % (Line, Index+1), ExtraData=self.MetaFile) if self._InSubsection: SectionType = self._SubsectionType @@ -945,16 +1000,21 @@ class DscParser(MetaFileParser): self._ItemType = SectionType self._ValueList = ['', '', ''] + # "SET pcd = pcd_expression" syntax is not supported in Dsc file. + if self._CurrentLine.upper().strip().startswith("SET "): + EdkLogger.error('Parser', FORMAT_INVALID, '''"SET pcd = pcd_expression" syntax is not support in Dsc file''', + ExtraData=self._CurrentLine, + File=self.MetaFile, Line=self._LineIndex + 1) self._SectionParser[SectionType](self) - if self._ValueList == None: + if self._ValueList is None: continue # # Model, Value1, Value2, Value3, Arch, ModuleType, BelongsToItem=-1, BelongsToFile=-1, # LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1 # - for Arch, ModuleType in self._Scope: + for Arch, ModuleType, DefaultStore in self._Scope: Owner = self._Owner[-1] - if self._SubsectionType != MODEL_UNKNOWN: + if self._SubsectionType != MODEL_UNKNOWN and Arch in OwnerId: Owner = OwnerId[Arch] self._LastItem = self._Store( self._ItemType, @@ -963,6 +1023,7 @@ class DscParser(MetaFileParser): self._ValueList[2], Arch, ModuleType, + DefaultStore, Owner, self._From, self._LineIndex + 1, @@ -1015,9 +1076,11 @@ class DscParser(MetaFileParser): ExtraData=self._CurrentLine) ItemType = self.DataType[DirectiveName] - Scope = [['COMMON', 'COMMON']] + Scope = [[TAB_COMMON, TAB_COMMON, TAB_COMMON]] if ItemType == MODEL_META_DATA_INCLUDE: Scope = self._Scope + elif ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ERROR: + Scope = self._Scope if ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF: # Remove all directives between !if and !endif, including themselves while self._DirectiveStack: @@ -1031,7 +1094,7 @@ class DscParser(MetaFileParser): EdkLogger.error("Parser", FORMAT_INVALID, "Redundant '!endif'", File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine) - elif ItemType != MODEL_META_DATA_INCLUDE: + elif ItemType not in {MODEL_META_DATA_INCLUDE, MODEL_META_DATA_CONDITIONAL_STATEMENT_ERROR}: # Break if there's a !else is followed by a !elseif if ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF and \ self._DirectiveStack and \ @@ -1045,7 +1108,7 @@ class DscParser(MetaFileParser): # Model, Value1, Value2, Value3, Arch, ModuleType, BelongsToItem=-1, BelongsToFile=-1, # LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1 # - for Arch, ModuleType in Scope: + for Arch, ModuleType, DefaultStore in Scope: self._LastItem = self._Store( ItemType, self._ValueList[0], @@ -1053,6 +1116,7 @@ class DscParser(MetaFileParser): self._ValueList[2], Arch, ModuleType, + DefaultStore, self._Owner[-1], self._From, self._LineIndex + 1, @@ -1088,9 +1152,16 @@ class DscParser(MetaFileParser): @ParseMacro def _SkuIdParser(self): + TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT) + if len(TokenList) not in (2, 3): + EdkLogger.error('Parser', FORMAT_INVALID, "Correct format is '|[|]'", + ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) + self._ValueList[0:len(TokenList)] = TokenList + @ParseMacro + def _DefaultStoresParser(self): TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT) if len(TokenList) != 2: - EdkLogger.error('Parser', FORMAT_INVALID, "Correct format is '|'", + EdkLogger.error('Parser', FORMAT_INVALID, "Correct format is '|'", ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) self._ValueList[0:len(TokenList)] = TokenList @@ -1099,6 +1170,9 @@ class DscParser(MetaFileParser): def _LibraryInstanceParser(self): self._ValueList[0] = self._CurrentLine + + def _DecodeCODEData(self): + pass ## PCD sections parser # # [PcdsFixedAtBuild] @@ -1115,13 +1189,36 @@ class DscParser(MetaFileParser): # @ParseMacro def _PcdParser(self): + if self._PcdDataTypeCODE: + self._PcdCodeValue = self._PcdCodeValue + "\n " + self._CurrentLine + if self._CurrentLine.endswith(")}"): + self._CurrentLine = "|".join((self._CurrentPcdName, self._PcdCodeValue)) + self._PcdDataTypeCODE = False + self._PcdCodeValue = "" + else: + self._ValueList = None + return TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT, 1) + self._CurrentPcdName = TokenList[0] + if len(TokenList) == 2 and TokenList[1].strip().startswith("{CODE"): + self._PcdDataTypeCODE = True + self._PcdCodeValue = TokenList[1].strip() + + if self._PcdDataTypeCODE: + if self._CurrentLine.endswith(")}"): + self._PcdDataTypeCODE = False + self._PcdCodeValue = "" + else: + self._ValueList = None + return self._ValueList[0:1] = GetSplitValueList(TokenList[0], TAB_SPLIT) PcdNameTockens = GetSplitValueList(TokenList[0], TAB_SPLIT) if len(PcdNameTockens) == 2: self._ValueList[0], self._ValueList[1] = PcdNameTockens[0], PcdNameTockens[1] elif len(PcdNameTockens) == 3: self._ValueList[0], self._ValueList[1] = ".".join((PcdNameTockens[0], PcdNameTockens[1])), PcdNameTockens[2] + elif len(PcdNameTockens) > 3: + self._ValueList[0], self._ValueList[1] = ".".join((PcdNameTockens[0], PcdNameTockens[1])), ".".join(PcdNameTockens[2:]) if len(TokenList) == 2: self._ValueList[2] = TokenList[1] if self._ValueList[0] == '' or self._ValueList[1] == '': @@ -1130,9 +1227,9 @@ class DscParser(MetaFileParser): File=self.MetaFile, Line=self._LineIndex + 1) if self._ValueList[2] == '': # - # The PCD values are optional for FIXEDATBUILD and PATCHABLEINMODULE + # The PCD values are optional for FIXEDATBUILD, PATCHABLEINMODULE, Dynamic/DynamicEx default # - if self._SectionType in (MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE): + if self._SectionType in (MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAULT): return EdkLogger.error('Parser', FORMAT_INVALID, "No PCD value given", ExtraData=self._CurrentLine + " (.|)", @@ -1140,7 +1237,7 @@ class DscParser(MetaFileParser): # Validate the datum type of Dynamic Defaul PCD and DynamicEx Default PCD ValueList = GetSplitValueList(self._ValueList[2]) - if len(ValueList) > 1 and ValueList[1] in [TAB_UINT8 , TAB_UINT16, TAB_UINT32 , TAB_UINT64] \ + if len(ValueList) > 1 and ValueList[1] in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64] \ and self._ItemType in [MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAULT]: EdkLogger.error('Parser', FORMAT_INVALID, "The datum type '%s' of PCD is wrong" % ValueList[1], ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) @@ -1148,7 +1245,7 @@ class DscParser(MetaFileParser): # Validate the VariableName of DynamicHii and DynamicExHii for PCD Entry must not be an empty string if self._ItemType in [MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_EX_HII]: DscPcdValueList = GetSplitValueList(TokenList[1], TAB_VALUE_SPLIT, 1) - if len(DscPcdValueList[0].replace('L','').replace('"','').strip()) == 0: + if len(DscPcdValueList[0].replace('L', '').replace('"', '').strip()) == 0: EdkLogger.error('Parser', FORMAT_INVALID, "The VariableName field in the HII format PCD entry must not be an empty string", ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) @@ -1166,6 +1263,7 @@ class DscParser(MetaFileParser): if self._CurrentLine[-1] == '{': self._ValueList[0] = self._CurrentLine[0:-1].strip() self._InSubsection = True + self._SubsectionType = MODEL_UNKNOWN else: self._ValueList[0] = self._CurrentLine @@ -1188,8 +1286,6 @@ class DscParser(MetaFileParser): self._ValueList[0:len(TokenList)] = TokenList - def _CompponentSourceOverridePathParser(self): - self._ValueList[0] = self._CurrentLine ## [BuildOptions] section parser @ParseMacro @@ -1216,7 +1312,8 @@ class DscParser(MetaFileParser): ) ## Override parent's method since we'll do all macro replacements in parser - def _GetMacros(self): + @property + def _Macros(self): Macros = {} Macros.update(self._FileLocalMacros) Macros.update(self._GetApplicableSectionMacro()) @@ -1226,6 +1323,13 @@ class DscParser(MetaFileParser): # PCD cannot be referenced in macro definition if self._ItemType not in [MODEL_META_DATA_DEFINE, MODEL_META_DATA_GLOBAL_DEFINE]: Macros.update(self._Symbols) + if GlobalData.BuildOptionPcd: + for Item in GlobalData.BuildOptionPcd: + if isinstance(Item, tuple): + continue + PcdName, TmpValue = Item.split("=") + TmpValue = BuildOptionValue(TmpValue, self._GuidDict) + Macros[PcdName.strip()] = TmpValue return Macros def _PostProcess(self): @@ -1243,6 +1347,7 @@ class DscParser(MetaFileParser): MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF : self.__ProcessDirective, MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF : self.__ProcessDirective, MODEL_EFI_SKU_ID : self.__ProcessSkuId, + MODEL_EFI_DEFAULT_STORES : self.__ProcessDefaultStores, MODEL_EFI_LIBRARY_INSTANCE : self.__ProcessLibraryInstance, MODEL_EFI_LIBRARY_CLASS : self.__ProcessLibraryClass, MODEL_PCD_FIXED_AT_BUILD : self.__ProcessPcd, @@ -1255,19 +1360,18 @@ class DscParser(MetaFileParser): MODEL_PCD_DYNAMIC_EX_HII : self.__ProcessPcd, MODEL_PCD_DYNAMIC_EX_VPD : self.__ProcessPcd, MODEL_META_DATA_COMPONENT : self.__ProcessComponent, - MODEL_META_DATA_COMPONENT_SOURCE_OVERRIDE_PATH : self.__ProcessSourceOverridePath, MODEL_META_DATA_BUILD_OPTION : self.__ProcessBuildOption, MODEL_UNKNOWN : self._Skip, MODEL_META_DATA_USER_EXTENSION : self._SkipUserExtension, + MODEL_META_DATA_CONDITIONAL_STATEMENT_ERROR : self._ProcessError, } - self._Table = MetaFileStorage(self._RawTable.Cur, self.MetaFile, MODEL_FILE_DSC, True) - self._Table.Create() + self._Table = MetaFileStorage(self._RawTable.DB, self.MetaFile, MODEL_FILE_DSC, True) self._DirectiveStack = [] self._DirectiveEvalStack = [] self._FileWithError = self.MetaFile self._FileLocalMacros = {} - self._SectionsMacroDict = {} + self._SectionsMacroDict.clear() GlobalData.gPlatformDefines = {} # Get all macro and PCD which has straitforward value @@ -1276,7 +1380,7 @@ class DscParser(MetaFileParser): self._ContentIndex = 0 self._InSubsection = False while self._ContentIndex < len(self._Content) : - Id, self._ItemType, V1, V2, V3, S1, S2, Owner, self._From, \ + Id, self._ItemType, V1, V2, V3, S1, S2, S3, Owner, self._From, \ LineStart, ColStart, LineEnd, ColEnd, Enabled = self._Content[self._ContentIndex] if self._From < 0: @@ -1284,7 +1388,7 @@ class DscParser(MetaFileParser): self._ContentIndex += 1 - self._Scope = [[S1, S2]] + self._Scope = [[S1, S2, S3]] # # For !include directive, handle it specially, # merge arch and module type in case of duplicate items @@ -1293,9 +1397,9 @@ class DscParser(MetaFileParser): if self._ContentIndex >= len(self._Content): break Record = self._Content[self._ContentIndex] - if LineStart == Record[9] and LineEnd == Record[11]: - if [Record[5], Record[6]] not in self._Scope: - self._Scope.append([Record[5], Record[6]]) + if LineStart == Record[10] and LineEnd == Record[12]: + if [Record[5], Record[6], Record[7]] not in self._Scope: + self._Scope.append([Record[5], Record[6], Record[7]]) self._ContentIndex += 1 else: break @@ -1309,8 +1413,8 @@ class DscParser(MetaFileParser): self._InSubsection = False try: Processer[self._ItemType]() - except EvaluationException, Excpt: - # + except EvaluationException as Excpt: + # # Only catch expression evaluation error here. We need to report # the precise number of line on which the error occurred # @@ -1331,12 +1435,12 @@ class DscParser(MetaFileParser): EdkLogger.error('Parser', FORMAT_INVALID, "Invalid expression: %s" % str(Excpt), File=self._FileWithError, ExtraData=' '.join(self._ValueList), Line=self._LineIndex + 1) - except MacroException, Excpt: + except MacroException as Excpt: EdkLogger.error('Parser', FORMAT_INVALID, str(Excpt), File=self._FileWithError, ExtraData=' '.join(self._ValueList), Line=self._LineIndex + 1) - if self._ValueList == None: + if self._ValueList is None: continue NewOwner = self._IdMapping.get(Owner, -1) @@ -1348,6 +1452,7 @@ class DscParser(MetaFileParser): self._ValueList[2], S1, S2, + S3, NewOwner, self._From, self._LineIndex + 1, @@ -1361,6 +1466,10 @@ class DscParser(MetaFileParser): GlobalData.gPlatformDefines.update(self._FileLocalMacros) self._PostProcessed = True self._Content = None + def _ProcessError(self): + if not self._Enabled: + return + EdkLogger.error('Parser', ERROR_STATEMENT, self._ValueList[1], File=self.MetaFile, Line=self._LineIndex + 1) def __ProcessSectionHeader(self): self._SectionName = self._ValueList[0] @@ -1377,13 +1486,18 @@ class DscParser(MetaFileParser): self._SubsectionType = MODEL_UNKNOWN def __RetrievePcdValue(self): - Content = open(str(self.MetaFile), 'r').readlines() + try: + with open(str(self.MetaFile), 'r') as File: + Content = File.readlines() + except: + EdkLogger.error("Parser", FILE_READ_FAILURE, ExtraData=self.MetaFile) + GlobalData.gPlatformOtherPcds['DSCFILE'] = str(self.MetaFile) for PcdType in (MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_VPD, MODEL_PCD_DYNAMIC_EX_DEFAULT, MODEL_PCD_DYNAMIC_EX_HII, MODEL_PCD_DYNAMIC_EX_VPD): Records = self._RawTable.Query(PcdType, BelongsToItem= -1.0) - for TokenSpaceGuid, PcdName, Value, Dummy2, Dummy3, ID, Line in Records: + for TokenSpaceGuid, PcdName, Value, Dummy2, Dummy3, Dummy4, ID, Line in Records: Name = TokenSpaceGuid + '.' + PcdName if Name not in GlobalData.gPlatformOtherPcds: PcdLine = Line @@ -1428,11 +1542,11 @@ class DscParser(MetaFileParser): Macros.update(GlobalData.gGlobalDefines) try: Result = ValueExpression(self._ValueList[1], Macros)() - except SymbolNotFound, Exc: + except SymbolNotFound as Exc: EdkLogger.debug(EdkLogger.DEBUG_5, str(Exc), self._ValueList[1]) Result = False - except WrnExpression, Excpt: - # + except WrnExpression as Excpt: + # # Catch expression evaluation warning here. We need to report # the precise number of line and return the evaluation result # @@ -1478,18 +1592,8 @@ class DscParser(MetaFileParser): # Allow using system environment variables in path after !include # __IncludeMacros['WORKSPACE'] = GlobalData.gGlobalDefines['WORKSPACE'] - if "ECP_SOURCE" in GlobalData.gGlobalDefines.keys(): - __IncludeMacros['ECP_SOURCE'] = GlobalData.gGlobalDefines['ECP_SOURCE'] # - # During GenFds phase call DSC parser, will go into this branch. - # - elif "ECP_SOURCE" in GlobalData.gCommandLineDefines.keys(): - __IncludeMacros['ECP_SOURCE'] = GlobalData.gCommandLineDefines['ECP_SOURCE'] - - __IncludeMacros['EFI_SOURCE'] = GlobalData.gGlobalDefines['EFI_SOURCE'] - __IncludeMacros['EDK_SOURCE'] = GlobalData.gGlobalDefines['EDK_SOURCE'] - # - # Allow using MACROs comes from [Defines] section to keep compatible. + # Allow using MACROs comes from [Defines] section to keep compatible. # __IncludeMacros.update(self._Macros) @@ -1511,33 +1615,26 @@ class DscParser(MetaFileParser): self._FileWithError = IncludedFile1 - IncludedFileTable = MetaFileStorage(self._Table.Cur, IncludedFile1, MODEL_FILE_DSC, False) - Owner = self._Content[self._ContentIndex - 1][0] + FromItem = self._Content[self._ContentIndex - 1][0] + if self._InSubsection: + Owner = self._Content[self._ContentIndex - 1][8] + else: + Owner = self._Content[self._ContentIndex - 1][0] + IncludedFileTable = MetaFileStorage(self._RawTable.DB, IncludedFile1, MODEL_FILE_DSC, False, FromItem=FromItem) Parser = DscParser(IncludedFile1, self._FileType, self._Arch, IncludedFileTable, - Owner=Owner, From=Owner) + Owner=Owner, From=FromItem) self.IncludedFiles.add (IncludedFile1) - # Does not allow lower level included file to include upper level included file - if Parser._From != Owner and int(Owner) > int (Parser._From): - EdkLogger.error('parser', FILE_ALREADY_EXIST, File=self._FileWithError, - Line=self._LineIndex + 1, ExtraData="{0} is already included at a higher level.".format(IncludedFile1)) - - # set the parser status with current status Parser._SectionName = self._SectionName + Parser._SubsectionType = self._SubsectionType + Parser._InSubsection = self._InSubsection Parser._SectionType = self._SectionType Parser._Scope = self._Scope Parser._Enabled = self._Enabled # Parse the included file - Parser.Start() - - # update current status with sub-parser's status - self._SectionName = Parser._SectionName - self._SectionType = Parser._SectionType - self._Scope = Parser._Scope - self._Enabled = Parser._Enabled - + Parser.StartParse() # Insert all records in the table for the included file into dsc file table Records = IncludedFileTable.GetAll() if Records: @@ -1549,6 +1646,9 @@ class DscParser(MetaFileParser): def __ProcessSkuId(self): self._ValueList = [ReplaceMacro(Value, self._Macros, RaiseError=True) for Value in self._ValueList] + def __ProcessDefaultStores(self): + self._ValueList = [ReplaceMacro(Value, self._Macros, RaiseError=True) + for Value in self._ValueList] def __ProcessLibraryInstance(self): self._ValueList = [ReplaceMacro(Value, self._Macros) for Value in self._ValueList] @@ -1563,14 +1663,20 @@ class DscParser(MetaFileParser): ValList, Valid, Index = AnalyzeDscPcd(self._ValueList[2], self._ItemType) if not Valid: + if self._ItemType in (MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAULT, MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE): + if ValList[1] != TAB_VOID and StructPattern.match(ValList[1]) is None and ValList[2]: + EdkLogger.error('build', FORMAT_INVALID, "Pcd format incorrect. The datum type info should be VOID* or a valid struct name.", File=self._FileWithError, + Line=self._LineIndex + 1, ExtraData="%s.%s|%s" % (self._ValueList[0], self._ValueList[1], self._ValueList[2])) EdkLogger.error('build', FORMAT_INVALID, "Pcd format incorrect.", File=self._FileWithError, Line=self._LineIndex + 1, ExtraData="%s.%s|%s" % (self._ValueList[0], self._ValueList[1], self._ValueList[2])) PcdValue = ValList[Index] if PcdValue and "." not in self._ValueList[0]: try: ValList[Index] = ValueExpression(PcdValue, self._Macros)(True) - except WrnExpression, Value: + except WrnExpression as Value: ValList[Index] = Value.result + except: + pass if ValList[Index] == 'True': ValList[Index] = '1' @@ -1583,21 +1689,24 @@ class DscParser(MetaFileParser): try: self._ValueList[2] = '|'.join(ValList) except Exception: - print ValList + print(ValList) def __ProcessComponent(self): self._ValueList[0] = ReplaceMacro(self._ValueList[0], self._Macros) - def __ProcessSourceOverridePath(self): - self._ValueList[0] = ReplaceMacro(self._ValueList[0], self._Macros) - def __ProcessBuildOption(self): self._ValueList = [ReplaceMacro(Value, self._Macros, RaiseError=False) for Value in self._ValueList] + def DisableOverrideComponent(self,module_id): + for ori_id in self._IdMapping: + if self._IdMapping[ori_id] == module_id: + self._RawTable.DisableComponent(ori_id) + _SectionParser = { MODEL_META_DATA_HEADER : _DefineParser, MODEL_EFI_SKU_ID : _SkuIdParser, + MODEL_EFI_DEFAULT_STORES : _DefaultStoresParser, MODEL_EFI_LIBRARY_INSTANCE : _LibraryInstanceParser, MODEL_EFI_LIBRARY_CLASS : _LibraryClassParser, MODEL_PCD_FIXED_AT_BUILD : _PcdParser, @@ -1610,7 +1719,6 @@ class DscParser(MetaFileParser): MODEL_PCD_DYNAMIC_EX_HII : _PcdParser, MODEL_PCD_DYNAMIC_EX_VPD : _PcdParser, MODEL_META_DATA_COMPONENT : _ComponentParser, - MODEL_META_DATA_COMPONENT_SOURCE_OVERRIDE_PATH : _CompponentSourceOverridePathParser, MODEL_META_DATA_BUILD_OPTION : _BuildOptionParser, MODEL_UNKNOWN : MetaFileParser._Skip, MODEL_META_DATA_USER_EXTENSION : MetaFileParser._SkipUserExtension, @@ -1618,8 +1726,6 @@ class DscParser(MetaFileParser): MODEL_META_DATA_SUBSECTION_HEADER : _SubsectionHeaderParser, } - _Macros = property(_GetMacros) - ## DEC file parser class # # @param FilePath The path of platform description file @@ -1668,14 +1774,19 @@ class DecParser(MetaFileParser): self._include_flag = False self._package_flag = False + self._RestofValue = "" + ## Parser starter def Start(self): Content = '' try: - Content = open(str(self.MetaFile), 'r').readlines() + with open(str(self.MetaFile), 'r') as File: + Content = File.readlines() except: EdkLogger.error("Parser", FILE_READ_FAILURE, ExtraData=self.MetaFile) + Content = self.ProcessMultipleLineCODEValue(Content) + self._DefinesCount = 0 for Index in range(0, len(Content)): Line, Comment = CleanString2(Content[Index]) @@ -1708,7 +1819,7 @@ class DecParser(MetaFileParser): # section content self._ValueList = ['', '', ''] self._SectionParser[self._SectionType[0]](self) - if self._ValueList == None or self._ItemType == MODEL_META_DATA_DEFINE: + if self._ValueList is None or self._ItemType == MODEL_META_DATA_DEFINE: self._ItemType = -1 self._Comments = [] continue @@ -1751,7 +1862,7 @@ class DecParser(MetaFileParser): if self._DefinesCount > 1: EdkLogger.error('Parser', FORMAT_INVALID, 'Multiple [Defines] section is exist.', self.MetaFile ) if self._DefinesCount == 0: - EdkLogger.error('Parser', FORMAT_INVALID, 'No [Defines] section exist.',self.MetaFile) + EdkLogger.error('Parser', FORMAT_INVALID, 'No [Defines] section exist.', self.MetaFile) self._Done() @@ -1800,7 +1911,7 @@ class DecParser(MetaFileParser): if len(ItemList) > 1: S1 = ItemList[1].upper() else: - S1 = 'COMMON' + S1 = TAB_ARCH_COMMON ArchList.add(S1) # S2 may be Platform or ModuleType if len(ItemList) > 2: @@ -1811,18 +1922,18 @@ class DecParser(MetaFileParser): EdkLogger.error("Parser", FORMAT_INVALID, 'Please use keyword "Private" as section tag modifier.', File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine) else: - S2 = 'COMMON' + S2 = TAB_COMMON PrivateList.add(S2) if [S1, S2, self.DataType[self._SectionName]] not in self._Scope: self._Scope.append([S1, S2, self.DataType[self._SectionName]]) # 'COMMON' must not be used with specific ARCHs at the same section - if 'COMMON' in ArchList and len(ArchList) > 1: + if TAB_ARCH_COMMON in ArchList and len(ArchList) > 1: EdkLogger.error('Parser', FORMAT_INVALID, "'common' ARCH must not be used with specific ARCHs", File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine) # It is not permissible to mix section tags without the Private attribute with section tags with the Private attribute - if 'COMMON' in PrivateList and len(PrivateList) > 1: + if TAB_COMMON in PrivateList and len(PrivateList) > 1: EdkLogger.error('Parser', FORMAT_INVALID, "Can't mix section tags without the Private attribute with section tags with the Private attribute", File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine) @@ -1849,6 +1960,19 @@ class DecParser(MetaFileParser): File=self.MetaFile, Line=self._LineIndex + 1) self._ValueList[0] = TokenList[0] self._ValueList[1] = TokenList[1] + if self._ValueList[0] not in self._GuidDict: + self._GuidDict[self._ValueList[0]] = self._ValueList[1] + + def ParsePcdName(self,namelist): + if "[" in namelist[1]: + pcdname = namelist[1][:namelist[1].index("[")] + arrayindex = namelist[1][namelist[1].index("["):] + namelist[1] = pcdname + if len(namelist) == 2: + namelist.append(arrayindex) + else: + namelist[2] = ".".join((arrayindex,namelist[2])) + return namelist ## PCD sections parser # @@ -1860,40 +1984,75 @@ class DecParser(MetaFileParser): # @ParseMacro def _PcdParser(self): + if self._CurrentStructurePcdName: self._ValueList[0] = self._CurrentStructurePcdName if "|" not in self._CurrentLine: if "" == self._CurrentLine: self._include_flag = True + self._package_flag = False self._ValueList = None return if "" == self._CurrentLine: self._package_flag = True self._ValueList = None + self._include_flag = False return if self._include_flag: - self._ValueList[1] = "_" + md5.new(self._CurrentLine).hexdigest() + self._ValueList[1] = "_" + md5(self._CurrentLine.encode('utf-8')).hexdigest() self._ValueList[2] = self._CurrentLine - self._include_flag = False if self._package_flag and "}" != self._CurrentLine: - self._ValueList[1] = "_" + md5.new(self._CurrentLine).hexdigest() + self._ValueList[1] = "_" + md5(self._CurrentLine.encode('utf-8')).hexdigest() self._ValueList[2] = self._CurrentLine if self._CurrentLine == "}": self._package_flag = False + self._include_flag = False self._ValueList = None return else: PcdTockens = self._CurrentLine.split(TAB_VALUE_SPLIT) - PcdNames = PcdTockens[0].split(TAB_SPLIT) + PcdNames = self.ParsePcdName(PcdTockens[0].split(TAB_SPLIT)) if len(PcdNames) == 2: - self._CurrentStructurePcdName = "" + if PcdNames[1].strip().endswith("]"): + PcdName = PcdNames[1][:PcdNames[1].index('[')] + Index = PcdNames[1][PcdNames[1].index('['):] + self._ValueList[0] = TAB_SPLIT.join((PcdNames[0],PcdName)) + self._ValueList[1] = Index + self._ValueList[2] = PcdTockens[1] + else: + self._CurrentStructurePcdName = "" else: - self._ValueList[1] = PcdNames[2] + if self._CurrentStructurePcdName != TAB_SPLIT.join(PcdNames[:2]): + EdkLogger.error('Parser', FORMAT_INVALID, "Pcd Name does not match: %s and %s " % (self._CurrentStructurePcdName, TAB_SPLIT.join(PcdNames[:2])), + File=self.MetaFile, Line=self._LineIndex + 1) + self._ValueList[1] = TAB_SPLIT.join(PcdNames[2:]) self._ValueList[2] = PcdTockens[1] if not self._CurrentStructurePcdName: + if self._PcdDataTypeCODE: + if ")}" in self._CurrentLine: + ValuePart,RestofValue = self._CurrentLine.split(")}") + self._PcdCodeValue = self._PcdCodeValue + "\n " + ValuePart + self._CurrentLine = "|".join((self._CurrentPcdName, self._PcdCodeValue,RestofValue)) + self._PcdDataTypeCODE = False + self._PcdCodeValue = "" + else: + self._PcdCodeValue = self._PcdCodeValue + "\n " + self._CurrentLine + self._ValueList = None + return TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT, 1) + self._CurrentPcdName = TokenList[0] + if len(TokenList) == 2 and TokenList[1].strip().startswith("{CODE"): + if ")}" in self._CurrentLine: + self._PcdDataTypeCODE = False + self._PcdCodeValue = "" + else: + self._PcdDataTypeCODE = True + self._PcdCodeValue = TokenList[1].strip() + self._ValueList = None + return + self._ValueList[0:1] = GetSplitValueList(TokenList[0], TAB_SPLIT) ValueRe = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*') # check PCD information @@ -1962,15 +2121,10 @@ class DecParser(MetaFileParser): PcdValue = ValueList[0] if PcdValue: try: - ValueList[0] = ValueExpression(PcdValue, self._AllPcdDict)(True) - except WrnExpression, Value: - ValueList[0] = Value.result - - if ValueList[0] == 'True': - ValueList[0] = '1' - if ValueList[0] == 'False': - ValueList[0] = '0' - + self._GuidDict.update(self._AllPcdDict) + ValueList[0] = ValueExpressionEx(ValueList[0], ValueList[1], self._GuidDict)(True) + except BadExpression as Value: + EdkLogger.error('Parser', FORMAT_INVALID, Value, ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) # check format of default value against the datum type IsValid, Cause = CheckPcdDatum(ValueList[1], ValueList[0]) if not IsValid: