]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Workspace/MetaFileParser.py
Sync BaseTools Trunk (version r2518) to EDKII main trunk.
[mirror_edk2.git] / BaseTools / Source / Python / Workspace / MetaFileParser.py
1 ## @file
2 # This file is used to parse meta files
3 #
4 # Copyright (c) 2008 - 2010, Intel Corporation. All rights reserved.<BR>
5 # This program and the accompanying materials
6 # are licensed and made available under the terms and conditions of the BSD License
7 # which accompanies this distribution. The full text of the license may be found at
8 # http://opensource.org/licenses/bsd-license.php
9 #
10 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12 #
13
14 ##
15 # Import Modules
16 #
17 import os
18 import re
19 import time
20 import copy
21
22 import Common.EdkLogger as EdkLogger
23 import Common.GlobalData as GlobalData
24
25 from CommonDataClass.DataClass import *
26 from Common.DataType import *
27 from Common.String import *
28 from Common.Misc import GuidStructureStringToGuidString, CheckPcdDatum, PathClass, AnalyzePcdData
29 from Common.Expression import *
30 from CommonDataClass.Exceptions import *
31
32 from MetaFileTable import MetaFileStorage
33
34 ## A decorator used to parse macro definition
35 def ParseMacro(Parser):
36 def MacroParser(self):
37 Match = gMacroDefPattern.match(self._CurrentLine)
38 if not Match:
39 # Not 'DEFINE/EDK_GLOBAL' statement, call decorated method
40 Parser(self)
41 return
42
43 TokenList = GetSplitValueList(self._CurrentLine[Match.end(1):], TAB_EQUAL_SPLIT, 1)
44 # Syntax check
45 if not TokenList[0]:
46 EdkLogger.error('Parser', FORMAT_INVALID, "No macro name given",
47 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
48 if len(TokenList) < 2:
49 TokenList.append('')
50
51 Type = Match.group(1)
52 Name, Value = TokenList
53 # Global macros can be only defined via environment variable
54 if Name in GlobalData.gGlobalDefines:
55 EdkLogger.error('Parser', FORMAT_INVALID, "%s can only be defined via environment variable" % Name,
56 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
57 # Only upper case letters, digit and '_' are allowed
58 if not gMacroNamePattern.match(Name):
59 EdkLogger.error('Parser', FORMAT_INVALID, "The macro name must be in the pattern [A-Z][A-Z0-9_]*",
60 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
61
62 Value = ReplaceMacro(Value, self._Macros)
63 if Type in self.DataType:
64 self._ItemType = self.DataType[Type]
65 else:
66 self._ItemType = MODEL_META_DATA_DEFINE
67 # DEFINE defined macros
68 if Type == TAB_DSC_DEFINES_DEFINE:
69 #
70 # First judge whether this DEFINE is in conditional directive statements or not.
71 #
72 if type(self) == DscParser and self._InDirective > -1:
73 pass
74 else:
75 if type(self) == DecParser:
76 if MODEL_META_DATA_HEADER in self._SectionType:
77 self._FileLocalMacros[Name] = Value
78 else:
79 self._ConstructSectionMacroDict(Name, Value)
80 elif self._SectionType == MODEL_META_DATA_HEADER:
81 self._FileLocalMacros[Name] = Value
82 else:
83 self._ConstructSectionMacroDict(Name, Value)
84
85 # EDK_GLOBAL defined macros
86 elif type(self) != DscParser:
87 EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL can only be used in .dsc file",
88 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
89 elif self._SectionType != MODEL_META_DATA_HEADER:
90 EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL can only be used under [Defines] section",
91 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
92 elif (Name in self._FileLocalMacros) and (self._FileLocalMacros[Name] != Value):
93 EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL defined a macro with the same name and different value as one defined by 'DEFINE'",
94 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
95
96 self._ValueList = [Type, Name, Value]
97
98 return MacroParser
99
100 ## Base class of parser
101 #
102 # This class is used for derivation purpose. The specific parser for one kind
103 # type file must derive this class and implement some public interfaces.
104 #
105 # @param FilePath The path of platform description file
106 # @param FileType The raw data of DSC file
107 # @param Table Database used to retrieve module/package information
108 # @param Macros Macros used for replacement in file
109 # @param Owner Owner ID (for sub-section parsing)
110 # @param From ID from which the data comes (for !INCLUDE directive)
111 #
112 class MetaFileParser(object):
113 # data type (file content) for specific file type
114 DataType = {}
115
116 # Parser objects used to implement singleton
117 MetaFiles = {}
118
119 ## Factory method
120 #
121 # One file, one parser object. This factory method makes sure that there's
122 # only one object constructed for one meta file.
123 #
124 # @param Class class object of real AutoGen class
125 # (InfParser, DecParser or DscParser)
126 # @param FilePath The path of meta file
127 # @param *args The specific class related parameters
128 # @param **kwargs The specific class related dict parameters
129 #
130 def __new__(Class, FilePath, *args, **kwargs):
131 if FilePath in Class.MetaFiles:
132 return Class.MetaFiles[FilePath]
133 else:
134 ParserObject = super(MetaFileParser, Class).__new__(Class)
135 Class.MetaFiles[FilePath] = ParserObject
136 return ParserObject
137
138 ## Constructor of MetaFileParser
139 #
140 # Initialize object of MetaFileParser
141 #
142 # @param FilePath The path of platform description file
143 # @param FileType The raw data of DSC file
144 # @param Table Database used to retrieve module/package information
145 # @param Macros Macros used for replacement in file
146 # @param Owner Owner ID (for sub-section parsing)
147 # @param From ID from which the data comes (for !INCLUDE directive)
148 #
149 def __init__(self, FilePath, FileType, Table, Owner=-1, From=-1):
150 self._Table = Table
151 self._RawTable = Table
152 self._FileType = FileType
153 self.MetaFile = FilePath
154 self._FileDir = self.MetaFile.Dir
155 self._Defines = {}
156 self._FileLocalMacros = {}
157 self._SectionsMacroDict = {}
158
159 # for recursive parsing
160 self._Owner = [Owner]
161 self._From = From
162
163 # parsr status for parsing
164 self._ValueList = ['', '', '', '', '']
165 self._Scope = []
166 self._LineIndex = 0
167 self._CurrentLine = ''
168 self._SectionType = MODEL_UNKNOWN
169 self._SectionName = ''
170 self._InSubsection = False
171 self._SubsectionType = MODEL_UNKNOWN
172 self._SubsectionName = ''
173 self._ItemType = MODEL_UNKNOWN
174 self._LastItem = -1
175 self._Enabled = 0
176 self._Finished = False
177 self._PostProcessed = False
178 # Different version of meta-file has different way to parse.
179 self._Version = 0
180
181 ## Store the parsed data in table
182 def _Store(self, *Args):
183 return self._Table.Insert(*Args)
184
185 ## Virtual method for starting parse
186 def Start(self):
187 raise NotImplementedError
188
189 ## Notify a post-process is needed
190 def DoPostProcess(self):
191 self._PostProcessed = False
192
193 ## Set parsing complete flag in both class and table
194 def _Done(self):
195 self._Finished = True
196 ## Do not set end flag when processing included files
197 if self._From == -1:
198 self._Table.SetEndFlag()
199
200 def _PostProcess(self):
201 self._PostProcessed = True
202
203 ## Get the parse complete flag
204 def _GetFinished(self):
205 return self._Finished
206
207 ## Set the complete flag
208 def _SetFinished(self, Value):
209 self._Finished = Value
210
211 ## Use [] style to query data in table, just for readability
212 #
213 # DataInfo = [data_type, scope1(arch), scope2(platform/moduletype)]
214 #
215 def __getitem__(self, DataInfo):
216 if type(DataInfo) != type(()):
217 DataInfo = (DataInfo,)
218
219 # Parse the file first, if necessary
220 if not self._Finished:
221 if self._RawTable.IsIntegrity():
222 self._Finished = True
223 else:
224 self._Table = self._RawTable
225 self._PostProcessed = False
226 self.Start()
227
228 # No specific ARCH or Platform given, use raw data
229 if self._RawTable and (len(DataInfo) == 1 or DataInfo[1] == None):
230 return self._RawTable.Query(*DataInfo)
231
232 # Do post-process if necessary
233 if not self._PostProcessed:
234 self._PostProcess()
235
236 return self._Table.Query(*DataInfo)
237
238 ## Data parser for the common format in different type of file
239 #
240 # The common format in the meatfile is like
241 #
242 # xxx1 | xxx2 | xxx3
243 #
244 @ParseMacro
245 def _CommonParser(self):
246 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)
247 self._ValueList[0:len(TokenList)] = TokenList
248
249 ## Data parser for the format in which there's path
250 #
251 # Only path can have macro used. So we need to replace them before use.
252 #
253 @ParseMacro
254 def _PathParser(self):
255 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)
256 self._ValueList[0:len(TokenList)] = TokenList
257 # Don't do macro replacement for dsc file at this point
258 if type(self) != DscParser:
259 Macros = self._Macros
260 self._ValueList = [ReplaceMacro(Value, Macros) for Value in self._ValueList]
261
262 ## Skip unsupported data
263 def _Skip(self):
264 EdkLogger.warn("Parser", "Unrecognized content", File=self.MetaFile,
265 Line=self._LineIndex+1, ExtraData=self._CurrentLine);
266 self._ValueList[0:1] = [self._CurrentLine]
267
268 ## Section header parser
269 #
270 # The section header is always in following format:
271 #
272 # [section_name.arch<.platform|module_type>]
273 #
274 def _SectionHeaderParser(self):
275 self._Scope = []
276 self._SectionName = ''
277 ArchList = set()
278 for Item in GetSplitValueList(self._CurrentLine[1:-1], TAB_COMMA_SPLIT):
279 if Item == '':
280 continue
281 ItemList = GetSplitValueList(Item, TAB_SPLIT)
282 # different section should not mix in one section
283 if self._SectionName != '' and self._SectionName != ItemList[0].upper():
284 EdkLogger.error('Parser', FORMAT_INVALID, "Different section names in the same section",
285 File=self.MetaFile, Line=self._LineIndex+1, ExtraData=self._CurrentLine)
286 self._SectionName = ItemList[0].upper()
287 if self._SectionName in self.DataType:
288 self._SectionType = self.DataType[self._SectionName]
289 else:
290 self._SectionType = MODEL_UNKNOWN
291 EdkLogger.warn("Parser", "Unrecognized section", File=self.MetaFile,
292 Line=self._LineIndex+1, ExtraData=self._CurrentLine)
293 # S1 is always Arch
294 if len(ItemList) > 1:
295 S1 = ItemList[1].upper()
296 else:
297 S1 = 'COMMON'
298 ArchList.add(S1)
299 # S2 may be Platform or ModuleType
300 if len(ItemList) > 2:
301 S2 = ItemList[2].upper()
302 else:
303 S2 = 'COMMON'
304 self._Scope.append([S1, S2])
305
306 # 'COMMON' must not be used with specific ARCHs at the same section
307 if 'COMMON' in ArchList and len(ArchList) > 1:
308 EdkLogger.error('Parser', FORMAT_INVALID, "'common' ARCH must not be used with specific ARCHs",
309 File=self.MetaFile, Line=self._LineIndex+1, ExtraData=self._CurrentLine)
310 # If the section information is needed later, it should be stored in database
311 self._ValueList[0] = self._SectionName
312
313 ## [defines] section parser
314 @ParseMacro
315 def _DefineParser(self):
316 TokenList = GetSplitValueList(self._CurrentLine, TAB_EQUAL_SPLIT, 1)
317 self._ValueList[1:len(TokenList)] = TokenList
318 if not self._ValueList[1]:
319 EdkLogger.error('Parser', FORMAT_INVALID, "No name specified",
320 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
321 if not self._ValueList[2]:
322 EdkLogger.error('Parser', FORMAT_INVALID, "No value specified",
323 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
324
325 self._ValueList = [ReplaceMacro(Value, self._Macros) for Value in self._ValueList]
326 Name, Value = self._ValueList[1], self._ValueList[2]
327 # Sometimes, we need to make differences between EDK and EDK2 modules
328 if Name == 'INF_VERSION':
329 try:
330 self._Version = int(Value, 0)
331 except:
332 EdkLogger.error('Parser', FORMAT_INVALID, "Invalid version number",
333 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
334
335 if type(self) == InfParser and self._Version < 0x00010005:
336 # EDK module allows using defines as macros
337 self._FileLocalMacros[Name] = Value
338 self._Defines[Name] = Value
339
340 ## [BuildOptions] section parser
341 @ParseMacro
342 def _BuildOptionParser(self):
343 self._CurrentLine = CleanString(self._CurrentLine, BuildOption=True)
344 TokenList = GetSplitValueList(self._CurrentLine, TAB_EQUAL_SPLIT, 1)
345 TokenList2 = GetSplitValueList(TokenList[0], ':', 1)
346 if len(TokenList2) == 2:
347 self._ValueList[0] = TokenList2[0] # toolchain family
348 self._ValueList[1] = TokenList2[1] # keys
349 else:
350 self._ValueList[1] = TokenList[0]
351 if len(TokenList) == 2 and type(self) != DscParser: # value
352 self._ValueList[2] = ReplaceMacro(TokenList[1], self._Macros)
353
354 if self._ValueList[1].count('_') != 4:
355 EdkLogger.error(
356 'Parser',
357 FORMAT_INVALID,
358 "'%s' must be in format of <TARGET>_<TOOLCHAIN>_<ARCH>_<TOOL>_FLAGS" % self._ValueList[1],
359 ExtraData=self._CurrentLine,
360 File=self.MetaFile,
361 Line=self._LineIndex+1
362 )
363
364 def _GetMacros(self):
365 Macros = {}
366 Macros.update(self._FileLocalMacros)
367 Macros.update(self._GetApplicableSectionMacro())
368 return Macros
369
370 ## Construct section Macro dict
371 def _ConstructSectionMacroDict(self, Name, Value):
372 ScopeKey = [(Scope[0], Scope[1]) for Scope in self._Scope]
373 ScopeKey = tuple(ScopeKey)
374 SectionDictKey = self._SectionType, ScopeKey
375 #
376 # DecParser SectionType is a list, will contain more than one item only in Pcd Section
377 # As Pcd section macro usage is not alllowed, so here it is safe
378 #
379 if type(self) == DecParser:
380 SectionDictKey = self._SectionType[0], ScopeKey
381 if SectionDictKey not in self._SectionsMacroDict:
382 self._SectionsMacroDict[SectionDictKey] = {}
383 SectionLocalMacros = self._SectionsMacroDict[SectionDictKey]
384 SectionLocalMacros[Name] = Value
385
386 ## Get section Macros that are applicable to current line, which may come from other sections
387 ## that share the same name while scope is wider
388 def _GetApplicableSectionMacro(self):
389 Macros = {}
390
391 ComComMacroDict = {}
392 ComSpeMacroDict = {}
393 SpeSpeMacroDict = {}
394
395 ActiveSectionType = self._SectionType
396 if type(self) == DecParser:
397 ActiveSectionType = self._SectionType[0]
398
399 for (SectionType, Scope) in self._SectionsMacroDict:
400 if SectionType != ActiveSectionType:
401 continue
402
403 for ActiveScope in self._Scope:
404 Scope0, Scope1 = ActiveScope[0], ActiveScope[1]
405 if(Scope0, Scope1) not in Scope:
406 break
407 else:
408 SpeSpeMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)])
409
410 for ActiveScope in self._Scope:
411 Scope0, Scope1 = ActiveScope[0], ActiveScope[1]
412 if(Scope0, Scope1) not in Scope and (Scope0, "COMMON") not in Scope and ("COMMON", Scope1) not in Scope:
413 break
414 else:
415 ComSpeMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)])
416
417 if ("COMMON", "COMMON") in Scope:
418 ComComMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)])
419
420 Macros.update(ComComMacroDict)
421 Macros.update(ComSpeMacroDict)
422 Macros.update(SpeSpeMacroDict)
423
424 return Macros
425
426 _SectionParser = {}
427 Finished = property(_GetFinished, _SetFinished)
428 _Macros = property(_GetMacros)
429
430
431 ## INF file parser class
432 #
433 # @param FilePath The path of platform description file
434 # @param FileType The raw data of DSC file
435 # @param Table Database used to retrieve module/package information
436 # @param Macros Macros used for replacement in file
437 #
438 class InfParser(MetaFileParser):
439 # INF file supported data types (one type per section)
440 DataType = {
441 TAB_UNKNOWN.upper() : MODEL_UNKNOWN,
442 TAB_INF_DEFINES.upper() : MODEL_META_DATA_HEADER,
443 TAB_DSC_DEFINES_DEFINE : MODEL_META_DATA_DEFINE,
444 TAB_BUILD_OPTIONS.upper() : MODEL_META_DATA_BUILD_OPTION,
445 TAB_INCLUDES.upper() : MODEL_EFI_INCLUDE,
446 TAB_LIBRARIES.upper() : MODEL_EFI_LIBRARY_INSTANCE,
447 TAB_LIBRARY_CLASSES.upper() : MODEL_EFI_LIBRARY_CLASS,
448 TAB_PACKAGES.upper() : MODEL_META_DATA_PACKAGE,
449 TAB_NMAKE.upper() : MODEL_META_DATA_NMAKE,
450 TAB_INF_FIXED_PCD.upper() : MODEL_PCD_FIXED_AT_BUILD,
451 TAB_INF_PATCH_PCD.upper() : MODEL_PCD_PATCHABLE_IN_MODULE,
452 TAB_INF_FEATURE_PCD.upper() : MODEL_PCD_FEATURE_FLAG,
453 TAB_INF_PCD_EX.upper() : MODEL_PCD_DYNAMIC_EX,
454 TAB_INF_PCD.upper() : MODEL_PCD_DYNAMIC,
455 TAB_SOURCES.upper() : MODEL_EFI_SOURCE_FILE,
456 TAB_GUIDS.upper() : MODEL_EFI_GUID,
457 TAB_PROTOCOLS.upper() : MODEL_EFI_PROTOCOL,
458 TAB_PPIS.upper() : MODEL_EFI_PPI,
459 TAB_DEPEX.upper() : MODEL_EFI_DEPEX,
460 TAB_BINARIES.upper() : MODEL_EFI_BINARY_FILE,
461 TAB_USER_EXTENSIONS.upper() : MODEL_META_DATA_USER_EXTENSION
462 }
463
464 ## Constructor of InfParser
465 #
466 # Initialize object of InfParser
467 #
468 # @param FilePath The path of module description file
469 # @param FileType The raw data of DSC file
470 # @param Table Database used to retrieve module/package information
471 # @param Macros Macros used for replacement in file
472 #
473 def __init__(self, FilePath, FileType, Table):
474 # prevent re-initialization
475 if hasattr(self, "_Table"):
476 return
477 MetaFileParser.__init__(self, FilePath, FileType, Table)
478
479 ## Parser starter
480 def Start(self):
481 NmakeLine = ''
482 Content = ''
483 try:
484 Content = open(str(self.MetaFile), 'r').readlines()
485 except:
486 EdkLogger.error("Parser", FILE_READ_FAILURE, ExtraData=self.MetaFile)
487
488 # parse the file line by line
489 IsFindBlockComment = False
490
491 for Index in range(0, len(Content)):
492 # skip empty, commented, block commented lines
493 Line = CleanString(Content[Index], AllowCppStyleComment=True)
494 NextLine = ''
495 if Index + 1 < len(Content):
496 NextLine = CleanString(Content[Index + 1])
497 if Line == '':
498 continue
499 if Line.find(DataType.TAB_COMMENT_EDK_START) > -1:
500 IsFindBlockComment = True
501 continue
502 if Line.find(DataType.TAB_COMMENT_EDK_END) > -1:
503 IsFindBlockComment = False
504 continue
505 if IsFindBlockComment:
506 continue
507
508 self._LineIndex = Index
509 self._CurrentLine = Line
510
511 # section header
512 if Line[0] == TAB_SECTION_START and Line[-1] == TAB_SECTION_END:
513 self._SectionHeaderParser()
514 # Check invalid sections
515 if self._Version < 0x00010005:
516 if self._SectionType in [MODEL_META_DATA_BUILD_OPTION,
517 MODEL_EFI_LIBRARY_CLASS,
518 MODEL_META_DATA_PACKAGE,
519 MODEL_PCD_FIXED_AT_BUILD,
520 MODEL_PCD_PATCHABLE_IN_MODULE,
521 MODEL_PCD_FEATURE_FLAG,
522 MODEL_PCD_DYNAMIC_EX,
523 MODEL_PCD_DYNAMIC,
524 MODEL_EFI_GUID,
525 MODEL_EFI_PROTOCOL,
526 MODEL_EFI_PPI,
527 MODEL_META_DATA_USER_EXTENSION]:
528 EdkLogger.error('Parser', FORMAT_INVALID,
529 "Section [%s] is not allowed in inf file without version" % (self._SectionName),
530 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
531 elif self._SectionType in [MODEL_EFI_INCLUDE,
532 MODEL_EFI_LIBRARY_INSTANCE,
533 MODEL_META_DATA_NMAKE]:
534 EdkLogger.error('Parser', FORMAT_INVALID,
535 "Section [%s] is not allowed in inf file with version 0x%08x" % (self._SectionName, self._Version),
536 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
537 continue
538 # merge two lines specified by '\' in section NMAKE
539 elif self._SectionType == MODEL_META_DATA_NMAKE:
540 if Line[-1] == '\\':
541 if NextLine == '':
542 self._CurrentLine = NmakeLine + Line[0:-1]
543 NmakeLine = ''
544 else:
545 if NextLine[0] == TAB_SECTION_START and NextLine[-1] == TAB_SECTION_END:
546 self._CurrentLine = NmakeLine + Line[0:-1]
547 NmakeLine = ''
548 else:
549 NmakeLine = NmakeLine + ' ' + Line[0:-1]
550 continue
551 else:
552 self._CurrentLine = NmakeLine + Line
553 NmakeLine = ''
554
555 # section content
556 self._ValueList = ['','','']
557 # parse current line, result will be put in self._ValueList
558 self._SectionParser[self._SectionType](self)
559 if self._ValueList == None or self._ItemType == MODEL_META_DATA_DEFINE:
560 self._ItemType = -1
561 continue
562 #
563 # Model, Value1, Value2, Value3, Arch, Platform, BelongsToItem=-1,
564 # LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1
565 #
566 for Arch, Platform in self._Scope:
567 self._Store(self._SectionType,
568 self._ValueList[0],
569 self._ValueList[1],
570 self._ValueList[2],
571 Arch,
572 Platform,
573 self._Owner[-1],
574 self._LineIndex+1,
575 -1,
576 self._LineIndex+1,
577 -1,
578 0
579 )
580 if IsFindBlockComment:
581 EdkLogger.error("Parser", FORMAT_INVALID, "Open block comments (starting with /*) are expected to end with */",
582 File=self.MetaFile)
583 self._Done()
584
585 ## Data parser for the format in which there's path
586 #
587 # Only path can have macro used. So we need to replace them before use.
588 #
589 def _IncludeParser(self):
590 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)
591 self._ValueList[0:len(TokenList)] = TokenList
592 Macros = self._Macros
593 if Macros:
594 for Index in range(0, len(self._ValueList)):
595 Value = self._ValueList[Index]
596 if not Value:
597 continue
598
599 if Value.upper().find('$(EFI_SOURCE)\Edk'.upper()) > -1 or Value.upper().find('$(EFI_SOURCE)/Edk'.upper()) > -1:
600 Value = '$(EDK_SOURCE)' + Value[17:]
601 if Value.find('$(EFI_SOURCE)') > -1 or Value.find('$(EDK_SOURCE)') > -1:
602 pass
603 elif Value.startswith('.'):
604 pass
605 elif Value.startswith('$('):
606 pass
607 else:
608 Value = '$(EFI_SOURCE)/' + Value
609
610 self._ValueList[Index] = ReplaceMacro(Value, Macros)
611
612 ## Parse [Sources] section
613 #
614 # Only path can have macro used. So we need to replace them before use.
615 #
616 @ParseMacro
617 def _SourceFileParser(self):
618 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)
619 self._ValueList[0:len(TokenList)] = TokenList
620 Macros = self._Macros
621 # For Acpi tables, remove macro like ' TABLE_NAME=Sata1'
622 if 'COMPONENT_TYPE' in Macros:
623 if self._Defines['COMPONENT_TYPE'].upper() == 'ACPITABLE':
624 self._ValueList[0] = GetSplitValueList(self._ValueList[0], ' ', 1)[0]
625 if self._Defines['BASE_NAME'] == 'Microcode':
626 pass
627 self._ValueList = [ReplaceMacro(Value, Macros) for Value in self._ValueList]
628
629 ## Parse [Binaries] section
630 #
631 # Only path can have macro used. So we need to replace them before use.
632 #
633 @ParseMacro
634 def _BinaryFileParser(self):
635 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT, 2)
636 if len(TokenList) < 2:
637 EdkLogger.error('Parser', FORMAT_INVALID, "No file type or path specified",
638 ExtraData=self._CurrentLine + " (<FileType> | <FilePath> [| <Target>])",
639 File=self.MetaFile, Line=self._LineIndex+1)
640 if not TokenList[0]:
641 EdkLogger.error('Parser', FORMAT_INVALID, "No file type specified",
642 ExtraData=self._CurrentLine + " (<FileType> | <FilePath> [| <Target>])",
643 File=self.MetaFile, Line=self._LineIndex+1)
644 if not TokenList[1]:
645 EdkLogger.error('Parser', FORMAT_INVALID, "No file path specified",
646 ExtraData=self._CurrentLine + " (<FileType> | <FilePath> [| <Target>])",
647 File=self.MetaFile, Line=self._LineIndex+1)
648 self._ValueList[0:len(TokenList)] = TokenList
649 self._ValueList[1] = ReplaceMacro(self._ValueList[1], self._Macros)
650
651 ## [nmake] section parser (Edk.x style only)
652 def _NmakeParser(self):
653 TokenList = GetSplitValueList(self._CurrentLine, TAB_EQUAL_SPLIT, 1)
654 self._ValueList[0:len(TokenList)] = TokenList
655 # remove macros
656 self._ValueList[1] = ReplaceMacro(self._ValueList[1], self._Macros)
657 # remove self-reference in macro setting
658 #self._ValueList[1] = ReplaceMacro(self._ValueList[1], {self._ValueList[0]:''})
659
660 ## [FixedPcd], [FeaturePcd], [PatchPcd], [Pcd] and [PcdEx] sections parser
661 @ParseMacro
662 def _PcdParser(self):
663 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT, 1)
664 ValueList = GetSplitValueList(TokenList[0], TAB_SPLIT)
665 if len(ValueList) != 2:
666 EdkLogger.error('Parser', FORMAT_INVALID, "Illegal token space GUID and PCD name format",
667 ExtraData=self._CurrentLine + " (<TokenSpaceGuidCName>.<PcdCName>)",
668 File=self.MetaFile, Line=self._LineIndex+1)
669 self._ValueList[0:1] = ValueList
670 if len(TokenList) > 1:
671 self._ValueList[2] = TokenList[1]
672 if self._ValueList[0] == '' or self._ValueList[1] == '':
673 EdkLogger.error('Parser', FORMAT_INVALID, "No token space GUID or PCD name specified",
674 ExtraData=self._CurrentLine + " (<TokenSpaceGuidCName>.<PcdCName>)",
675 File=self.MetaFile, Line=self._LineIndex+1)
676
677 # if value are 'True', 'true', 'TRUE' or 'False', 'false', 'FALSE', replace with integer 1 or 0.
678 if self._ValueList[2] != '':
679 InfPcdValueList = GetSplitValueList(TokenList[1], TAB_VALUE_SPLIT, 1)
680 if InfPcdValueList[0] in ['True', 'true', 'TRUE']:
681 self._ValueList[2] = TokenList[1].replace(InfPcdValueList[0], '1', 1);
682 elif InfPcdValueList[0] in ['False', 'false', 'FALSE']:
683 self._ValueList[2] = TokenList[1].replace(InfPcdValueList[0], '0', 1);
684
685 ## [depex] section parser
686 @ParseMacro
687 def _DepexParser(self):
688 self._ValueList[0:1] = [self._CurrentLine]
689
690 _SectionParser = {
691 MODEL_UNKNOWN : MetaFileParser._Skip,
692 MODEL_META_DATA_HEADER : MetaFileParser._DefineParser,
693 MODEL_META_DATA_BUILD_OPTION : MetaFileParser._BuildOptionParser,
694 MODEL_EFI_INCLUDE : _IncludeParser, # for Edk.x modules
695 MODEL_EFI_LIBRARY_INSTANCE : MetaFileParser._CommonParser, # for Edk.x modules
696 MODEL_EFI_LIBRARY_CLASS : MetaFileParser._PathParser,
697 MODEL_META_DATA_PACKAGE : MetaFileParser._PathParser,
698 MODEL_META_DATA_NMAKE : _NmakeParser, # for Edk.x modules
699 MODEL_PCD_FIXED_AT_BUILD : _PcdParser,
700 MODEL_PCD_PATCHABLE_IN_MODULE : _PcdParser,
701 MODEL_PCD_FEATURE_FLAG : _PcdParser,
702 MODEL_PCD_DYNAMIC_EX : _PcdParser,
703 MODEL_PCD_DYNAMIC : _PcdParser,
704 MODEL_EFI_SOURCE_FILE : _SourceFileParser,
705 MODEL_EFI_GUID : MetaFileParser._CommonParser,
706 MODEL_EFI_PROTOCOL : MetaFileParser._CommonParser,
707 MODEL_EFI_PPI : MetaFileParser._CommonParser,
708 MODEL_EFI_DEPEX : _DepexParser,
709 MODEL_EFI_BINARY_FILE : _BinaryFileParser,
710 MODEL_META_DATA_USER_EXTENSION : MetaFileParser._Skip,
711 }
712
713 ## DSC file parser class
714 #
715 # @param FilePath The path of platform description file
716 # @param FileType The raw data of DSC file
717 # @param Table Database used to retrieve module/package information
718 # @param Macros Macros used for replacement in file
719 # @param Owner Owner ID (for sub-section parsing)
720 # @param From ID from which the data comes (for !INCLUDE directive)
721 #
722 class DscParser(MetaFileParser):
723 # DSC file supported data types (one type per section)
724 DataType = {
725 TAB_SKUIDS.upper() : MODEL_EFI_SKU_ID,
726 TAB_LIBRARIES.upper() : MODEL_EFI_LIBRARY_INSTANCE,
727 TAB_LIBRARY_CLASSES.upper() : MODEL_EFI_LIBRARY_CLASS,
728 TAB_BUILD_OPTIONS.upper() : MODEL_META_DATA_BUILD_OPTION,
729 TAB_PCDS_FIXED_AT_BUILD_NULL.upper() : MODEL_PCD_FIXED_AT_BUILD,
730 TAB_PCDS_PATCHABLE_IN_MODULE_NULL.upper() : MODEL_PCD_PATCHABLE_IN_MODULE,
731 TAB_PCDS_FEATURE_FLAG_NULL.upper() : MODEL_PCD_FEATURE_FLAG,
732 TAB_PCDS_DYNAMIC_DEFAULT_NULL.upper() : MODEL_PCD_DYNAMIC_DEFAULT,
733 TAB_PCDS_DYNAMIC_HII_NULL.upper() : MODEL_PCD_DYNAMIC_HII,
734 TAB_PCDS_DYNAMIC_VPD_NULL.upper() : MODEL_PCD_DYNAMIC_VPD,
735 TAB_PCDS_DYNAMIC_EX_DEFAULT_NULL.upper() : MODEL_PCD_DYNAMIC_EX_DEFAULT,
736 TAB_PCDS_DYNAMIC_EX_HII_NULL.upper() : MODEL_PCD_DYNAMIC_EX_HII,
737 TAB_PCDS_DYNAMIC_EX_VPD_NULL.upper() : MODEL_PCD_DYNAMIC_EX_VPD,
738 TAB_COMPONENTS.upper() : MODEL_META_DATA_COMPONENT,
739 TAB_COMPONENTS_SOURCE_OVERRIDE_PATH.upper() : MODEL_META_DATA_COMPONENT_SOURCE_OVERRIDE_PATH,
740 TAB_DSC_DEFINES.upper() : MODEL_META_DATA_HEADER,
741 TAB_DSC_DEFINES_DEFINE : MODEL_META_DATA_DEFINE,
742 TAB_DSC_DEFINES_EDKGLOBAL : MODEL_META_DATA_GLOBAL_DEFINE,
743 TAB_INCLUDE.upper() : MODEL_META_DATA_INCLUDE,
744 TAB_IF.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_IF,
745 TAB_IF_DEF.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_IFDEF,
746 TAB_IF_N_DEF.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF,
747 TAB_ELSE_IF.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF,
748 TAB_ELSE.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSE,
749 TAB_END_IF.upper() : MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF,
750 }
751
752 # Valid names in define section
753 DefineKeywords = [
754 "DSC_SPECIFICATION",
755 "PLATFORM_NAME",
756 "PLATFORM_GUID",
757 "PLATFORM_VERSION",
758 "SKUID_IDENTIFIER",
759 "SUPPORTED_ARCHITECTURES",
760 "BUILD_TARGETS",
761 "OUTPUT_DIRECTORY",
762 "FLASH_DEFINITION",
763 "BUILD_NUMBER",
764 "RFC_LANGUAGES",
765 "ISO_LANGUAGES",
766 "TIME_STAMP_FILE",
767 "VPD_TOOL_GUID",
768 "FIX_LOAD_TOP_MEMORY_ADDRESS"
769 ]
770
771 SymbolPattern = ValueExpression.SymbolPattern
772
773 ## Constructor of DscParser
774 #
775 # Initialize object of DscParser
776 #
777 # @param FilePath The path of platform description file
778 # @param FileType The raw data of DSC file
779 # @param Table Database used to retrieve module/package information
780 # @param Macros Macros used for replacement in file
781 # @param Owner Owner ID (for sub-section parsing)
782 # @param From ID from which the data comes (for !INCLUDE directive)
783 #
784 def __init__(self, FilePath, FileType, Table, Owner=-1, From=-1):
785 # prevent re-initialization
786 if hasattr(self, "_Table"):
787 return
788 MetaFileParser.__init__(self, FilePath, FileType, Table, Owner, From)
789 self._Version = 0x00010005 # Only EDK2 dsc file is supported
790 # to store conditional directive evaluation result
791 self._DirectiveStack = []
792 self._DirectiveEvalStack = []
793 self._Enabled = 1
794
795 #
796 # Specify whether current line is in uncertain condition
797 #
798 self._InDirective = -1
799
800 # Final valid replacable symbols
801 self._Symbols = {}
802 #
803 # Map the ID between the original table and new table to track
804 # the owner item
805 #
806 self._IdMapping = {-1:-1}
807
808 ## Parser starter
809 def Start(self):
810 Content = ''
811 try:
812 Content = open(str(self.MetaFile), 'r').readlines()
813 except:
814 EdkLogger.error("Parser", FILE_READ_FAILURE, ExtraData=self.MetaFile)
815
816 for Index in range(0, len(Content)):
817 Line = CleanString(Content[Index])
818 # skip empty line
819 if Line == '':
820 continue
821
822 self._CurrentLine = Line
823 self._LineIndex = Index
824 if self._InSubsection and self._Owner[-1] == -1:
825 self._Owner.append(self._LastItem)
826
827 # section header
828 if Line[0] == TAB_SECTION_START and Line[-1] == TAB_SECTION_END:
829 self._SectionType = MODEL_META_DATA_SECTION_HEADER
830 # subsection ending
831 elif Line[0] == '}' and self._InSubsection:
832 self._InSubsection = False
833 self._SubsectionType = MODEL_UNKNOWN
834 self._SubsectionName = ''
835 self._Owner[-1] = -1
836 continue
837 # subsection header
838 elif Line[0] == TAB_OPTION_START and Line[-1] == TAB_OPTION_END:
839 self._SubsectionType = MODEL_META_DATA_SUBSECTION_HEADER
840 # directive line
841 elif Line[0] == '!':
842 self._DirectiveParser()
843 continue
844
845 if self._InSubsection:
846 SectionType = self._SubsectionType
847 else:
848 SectionType = self._SectionType
849 self._ItemType = SectionType
850
851 self._ValueList = ['', '', '']
852 self._SectionParser[SectionType](self)
853 if self._ValueList == None:
854 continue
855 #
856 # Model, Value1, Value2, Value3, Arch, ModuleType, BelongsToItem=-1, BelongsToFile=-1,
857 # LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1
858 #
859 for Arch, ModuleType in self._Scope:
860 self._LastItem = self._Store(
861 self._ItemType,
862 self._ValueList[0],
863 self._ValueList[1],
864 self._ValueList[2],
865 Arch,
866 ModuleType,
867 self._Owner[-1],
868 self._From,
869 self._LineIndex+1,
870 -1,
871 self._LineIndex+1,
872 -1,
873 self._Enabled
874 )
875
876 if self._DirectiveStack:
877 Type, Line, Text = self._DirectiveStack[-1]
878 EdkLogger.error('Parser', FORMAT_INVALID, "No matching '!endif' found",
879 ExtraData=Text, File=self.MetaFile, Line=Line)
880 self._Done()
881
882 ## <subsection_header> parser
883 def _SubsectionHeaderParser(self):
884 self._SubsectionName = self._CurrentLine[1:-1].upper()
885 if self._SubsectionName in self.DataType:
886 self._SubsectionType = self.DataType[self._SubsectionName]
887 else:
888 self._SubsectionType = MODEL_UNKNOWN
889 EdkLogger.warn("Parser", "Unrecognized sub-section", File=self.MetaFile,
890 Line=self._LineIndex+1, ExtraData=self._CurrentLine)
891 self._ValueList[0] = self._SubsectionName
892
893 ## Directive statement parser
894 def _DirectiveParser(self):
895 self._ValueList = ['','','']
896 TokenList = GetSplitValueList(self._CurrentLine, ' ', 1)
897 self._ValueList[0:len(TokenList)] = TokenList
898
899 # Syntax check
900 DirectiveName = self._ValueList[0].upper()
901 if DirectiveName not in self.DataType:
902 EdkLogger.error("Parser", FORMAT_INVALID, "Unknown directive [%s]" % DirectiveName,
903 File=self.MetaFile, Line=self._LineIndex+1)
904
905 if DirectiveName in ['!IF', '!IFDEF', '!IFNDEF']:
906 self._InDirective += 1
907
908 if DirectiveName in ['!ENDIF']:
909 self._InDirective -= 1
910
911 if DirectiveName in ['!IF', '!IFDEF', '!INCLUDE', '!IFNDEF', '!ELSEIF'] and self._ValueList[1] == '':
912 EdkLogger.error("Parser", FORMAT_INVALID, "Missing expression",
913 File=self.MetaFile, Line=self._LineIndex+1,
914 ExtraData=self._CurrentLine)
915
916 ItemType = self.DataType[DirectiveName]
917 Scope = [['COMMON', 'COMMON']]
918 if ItemType == MODEL_META_DATA_INCLUDE:
919 Scope = self._Scope
920 if ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF:
921 # Remove all directives between !if and !endif, including themselves
922 while self._DirectiveStack:
923 # Remove any !else or !elseif
924 DirectiveInfo = self._DirectiveStack.pop()
925 if DirectiveInfo[0] in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF,
926 MODEL_META_DATA_CONDITIONAL_STATEMENT_IFDEF,
927 MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF]:
928 break
929 else:
930 EdkLogger.error("Parser", FORMAT_INVALID, "Redundant '!endif'",
931 File=self.MetaFile, Line=self._LineIndex+1,
932 ExtraData=self._CurrentLine)
933 elif ItemType != MODEL_META_DATA_INCLUDE:
934 # Break if there's a !else is followed by a !elseif
935 if ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF and \
936 self._DirectiveStack and \
937 self._DirectiveStack[-1][0] == MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSE:
938 EdkLogger.error("Parser", FORMAT_INVALID, "'!elseif' after '!else'",
939 File=self.MetaFile, Line=self._LineIndex+1,
940 ExtraData=self._CurrentLine)
941 self._DirectiveStack.append((ItemType, self._LineIndex+1, self._CurrentLine))
942 elif self._From > 0:
943 EdkLogger.error('Parser', FORMAT_INVALID,
944 "No '!include' allowed in included file",
945 ExtraData=self._CurrentLine, File=self.MetaFile,
946 Line=self._LineIndex+1)
947
948 #
949 # Model, Value1, Value2, Value3, Arch, ModuleType, BelongsToItem=-1, BelongsToFile=-1,
950 # LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1
951 #
952 for Arch, ModuleType in Scope:
953 self._LastItem = self._Store(
954 ItemType,
955 self._ValueList[0],
956 self._ValueList[1],
957 self._ValueList[2],
958 Arch,
959 ModuleType,
960 self._Owner[-1],
961 self._From,
962 self._LineIndex+1,
963 -1,
964 self._LineIndex+1,
965 -1,
966 0
967 )
968
969 ## [defines] section parser
970 @ParseMacro
971 def _DefineParser(self):
972 TokenList = GetSplitValueList(self._CurrentLine, TAB_EQUAL_SPLIT, 1)
973 self._ValueList[1:len(TokenList)] = TokenList
974
975 # Syntax check
976 if not self._ValueList[1]:
977 EdkLogger.error('Parser', FORMAT_INVALID, "No name specified",
978 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
979 if not self._ValueList[2]:
980 EdkLogger.error('Parser', FORMAT_INVALID, "No value specified",
981 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
982 if not self._ValueList[1] in self.DefineKeywords:
983 EdkLogger.error('Parser', FORMAT_INVALID,
984 "Unknown keyword found: %s. "
985 "If this is a macro you must "
986 "add it as a DEFINE in the DSC" % self._ValueList[1],
987 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
988 self._Defines[self._ValueList[1]] = self._ValueList[2]
989 self._ItemType = self.DataType[TAB_DSC_DEFINES.upper()]
990
991 @ParseMacro
992 def _SkuIdParser(self):
993 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)
994 if len(TokenList) != 2:
995 EdkLogger.error('Parser', FORMAT_INVALID, "Correct format is '<Integer>|<UiName>'",
996 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
997 self._ValueList[0:len(TokenList)] = TokenList
998
999 ## Parse Edk style of library modules
1000 @ParseMacro
1001 def _LibraryInstanceParser(self):
1002 self._ValueList[0] = self._CurrentLine
1003
1004 ## PCD sections parser
1005 #
1006 # [PcdsFixedAtBuild]
1007 # [PcdsPatchableInModule]
1008 # [PcdsFeatureFlag]
1009 # [PcdsDynamicEx
1010 # [PcdsDynamicExDefault]
1011 # [PcdsDynamicExVpd]
1012 # [PcdsDynamicExHii]
1013 # [PcdsDynamic]
1014 # [PcdsDynamicDefault]
1015 # [PcdsDynamicVpd]
1016 # [PcdsDynamicHii]
1017 #
1018 @ParseMacro
1019 def _PcdParser(self):
1020 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT, 1)
1021 self._ValueList[0:1] = GetSplitValueList(TokenList[0], TAB_SPLIT)
1022 if len(TokenList) == 2:
1023 self._ValueList[2] = TokenList[1]
1024 if self._ValueList[0] == '' or self._ValueList[1] == '':
1025 EdkLogger.error('Parser', FORMAT_INVALID, "No token space GUID or PCD name specified",
1026 ExtraData=self._CurrentLine + " (<TokenSpaceGuidCName>.<TokenCName>|<PcdValue>)",
1027 File=self.MetaFile, Line=self._LineIndex+1)
1028 if self._ValueList[2] == '':
1029 EdkLogger.error('Parser', FORMAT_INVALID, "No PCD value given",
1030 ExtraData=self._CurrentLine + " (<TokenSpaceGuidCName>.<TokenCName>|<PcdValue>)",
1031 File=self.MetaFile, Line=self._LineIndex+1)
1032 # if value are 'True', 'true', 'TRUE' or 'False', 'false', 'FALSE', replace with integer 1 or 0.
1033 DscPcdValueList = GetSplitValueList(TokenList[1], TAB_VALUE_SPLIT, 1)
1034 if DscPcdValueList[0] in ['True', 'true', 'TRUE']:
1035 self._ValueList[2] = TokenList[1].replace(DscPcdValueList[0], '1', 1);
1036 elif DscPcdValueList[0] in ['False', 'false', 'FALSE']:
1037 self._ValueList[2] = TokenList[1].replace(DscPcdValueList[0], '0', 1);
1038
1039 ## [components] section parser
1040 @ParseMacro
1041 def _ComponentParser(self):
1042 if self._CurrentLine[-1] == '{':
1043 self._ValueList[0] = self._CurrentLine[0:-1].strip()
1044 self._InSubsection = True
1045 else:
1046 self._ValueList[0] = self._CurrentLine
1047
1048 ## [LibraryClasses] section
1049 @ParseMacro
1050 def _LibraryClassParser(self):
1051 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)
1052 if len(TokenList) < 2:
1053 EdkLogger.error('Parser', FORMAT_INVALID, "No library class or instance specified",
1054 ExtraData=self._CurrentLine + " (<LibraryClassName>|<LibraryInstancePath>)",
1055 File=self.MetaFile, Line=self._LineIndex+1)
1056 if TokenList[0] == '':
1057 EdkLogger.error('Parser', FORMAT_INVALID, "No library class specified",
1058 ExtraData=self._CurrentLine + " (<LibraryClassName>|<LibraryInstancePath>)",
1059 File=self.MetaFile, Line=self._LineIndex+1)
1060 if TokenList[1] == '':
1061 EdkLogger.error('Parser', FORMAT_INVALID, "No library instance specified",
1062 ExtraData=self._CurrentLine + " (<LibraryClassName>|<LibraryInstancePath>)",
1063 File=self.MetaFile, Line=self._LineIndex+1)
1064
1065 self._ValueList[0:len(TokenList)] = TokenList
1066
1067 def _CompponentSourceOverridePathParser(self):
1068 self._ValueList[0] = self._CurrentLine
1069
1070 ## [BuildOptions] section parser
1071 @ParseMacro
1072 def _BuildOptionParser(self):
1073 self._CurrentLine = CleanString(self._CurrentLine, BuildOption=True)
1074 TokenList = GetSplitValueList(self._CurrentLine, TAB_EQUAL_SPLIT, 1)
1075 TokenList2 = GetSplitValueList(TokenList[0], ':', 1)
1076 if len(TokenList2) == 2:
1077 self._ValueList[0] = TokenList2[0] # toolchain family
1078 self._ValueList[1] = TokenList2[1] # keys
1079 else:
1080 self._ValueList[1] = TokenList[0]
1081 if len(TokenList) == 2: # value
1082 self._ValueList[2] = TokenList[1]
1083
1084 if self._ValueList[1].count('_') != 4:
1085 EdkLogger.error(
1086 'Parser',
1087 FORMAT_INVALID,
1088 "'%s' must be in format of <TARGET>_<TOOLCHAIN>_<ARCH>_<TOOL>_FLAGS" % self._ValueList[1],
1089 ExtraData=self._CurrentLine,
1090 File=self.MetaFile,
1091 Line=self._LineIndex+1
1092 )
1093
1094 ## Override parent's method since we'll do all macro replacements in parser
1095 def _GetMacros(self):
1096 Macros = {}
1097 Macros.update(self._FileLocalMacros)
1098 Macros.update(self._GetApplicableSectionMacro())
1099 Macros.update(GlobalData.gEdkGlobal)
1100 Macros.update(GlobalData.gPlatformDefines)
1101 Macros.update(GlobalData.gCommandLineDefines)
1102 # PCD cannot be referenced in macro definition
1103 if self._ItemType not in [MODEL_META_DATA_DEFINE, MODEL_META_DATA_GLOBAL_DEFINE]:
1104 Macros.update(self._Symbols)
1105 return Macros
1106
1107 def _PostProcess(self):
1108 Processer = {
1109 MODEL_META_DATA_SECTION_HEADER : self.__ProcessSectionHeader,
1110 MODEL_META_DATA_SUBSECTION_HEADER : self.__ProcessSubsectionHeader,
1111 MODEL_META_DATA_HEADER : self.__ProcessDefine,
1112 MODEL_META_DATA_DEFINE : self.__ProcessDefine,
1113 MODEL_META_DATA_GLOBAL_DEFINE : self.__ProcessDefine,
1114 MODEL_META_DATA_INCLUDE : self.__ProcessDirective,
1115 MODEL_META_DATA_CONDITIONAL_STATEMENT_IF : self.__ProcessDirective,
1116 MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSE : self.__ProcessDirective,
1117 MODEL_META_DATA_CONDITIONAL_STATEMENT_IFDEF : self.__ProcessDirective,
1118 MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF : self.__ProcessDirective,
1119 MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF : self.__ProcessDirective,
1120 MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF : self.__ProcessDirective,
1121 MODEL_EFI_SKU_ID : self.__ProcessSkuId,
1122 MODEL_EFI_LIBRARY_INSTANCE : self.__ProcessLibraryInstance,
1123 MODEL_EFI_LIBRARY_CLASS : self.__ProcessLibraryClass,
1124 MODEL_PCD_FIXED_AT_BUILD : self.__ProcessPcd,
1125 MODEL_PCD_PATCHABLE_IN_MODULE : self.__ProcessPcd,
1126 MODEL_PCD_FEATURE_FLAG : self.__ProcessPcd,
1127 MODEL_PCD_DYNAMIC_DEFAULT : self.__ProcessPcd,
1128 MODEL_PCD_DYNAMIC_HII : self.__ProcessPcd,
1129 MODEL_PCD_DYNAMIC_VPD : self.__ProcessPcd,
1130 MODEL_PCD_DYNAMIC_EX_DEFAULT : self.__ProcessPcd,
1131 MODEL_PCD_DYNAMIC_EX_HII : self.__ProcessPcd,
1132 MODEL_PCD_DYNAMIC_EX_VPD : self.__ProcessPcd,
1133 MODEL_META_DATA_COMPONENT : self.__ProcessComponent,
1134 MODEL_META_DATA_COMPONENT_SOURCE_OVERRIDE_PATH : self.__ProcessSourceOverridePath,
1135 MODEL_META_DATA_BUILD_OPTION : self.__ProcessBuildOption,
1136 MODEL_UNKNOWN : self._Skip,
1137 MODEL_META_DATA_USER_EXTENSION : self._Skip,
1138 }
1139
1140 self._Table = MetaFileStorage(self._RawTable.Cur, self.MetaFile, MODEL_FILE_DSC, True)
1141 self._Table.Create()
1142 self._DirectiveStack = []
1143 self._DirectiveEvalStack = []
1144 self._FileWithError = self.MetaFile
1145 self._FileLocalMacros = {}
1146 self._SectionsMacroDict = {}
1147 GlobalData.gPlatformDefines = {}
1148
1149 # Get all macro and PCD which has straitforward value
1150 self.__RetrievePcdValue()
1151 self._Content = self._RawTable.GetAll()
1152 self._ContentIndex = 0
1153 while self._ContentIndex < len(self._Content) :
1154 Id, self._ItemType, V1, V2, V3, S1, S2, Owner, self._From, \
1155 LineStart, ColStart, LineEnd, ColEnd, Enabled = self._Content[self._ContentIndex]
1156
1157 if self._From < 0:
1158 self._FileWithError = self.MetaFile
1159
1160 self._ContentIndex += 1
1161
1162 self._Scope = [[S1, S2]]
1163 #
1164 # For !include directive, handle it specially,
1165 # merge arch and module type in case of duplicate items
1166 #
1167 while self._ItemType == MODEL_META_DATA_INCLUDE:
1168 if self._ContentIndex >= len(self._Content):
1169 break
1170 Record = self._Content[self._ContentIndex]
1171 if LineStart == Record[9] and LineEnd == Record[11]:
1172 if [Record[5], Record[6]] not in self._Scope:
1173 self._Scope.append([Record[5], Record[6]])
1174 self._ContentIndex += 1
1175 else:
1176 break
1177
1178 self._LineIndex = LineStart - 1
1179 self._ValueList = [V1, V2, V3]
1180
1181 try:
1182 Processer[self._ItemType]()
1183 except EvaluationException, Excpt:
1184 #
1185 # Only catch expression evaluation error here. We need to report
1186 # the precise number of line on which the error occurred
1187 #
1188 if hasattr(Excpt, 'Pcd'):
1189 if Excpt.Pcd in GlobalData.gPlatformOtherPcds:
1190 Info = GlobalData.gPlatformOtherPcds[Excpt.Pcd]
1191 EdkLogger.error('Parser', FORMAT_INVALID, "Cannot use this PCD (%s) in an expression as"
1192 " it must be defined in a [PcdsFixedAtBuild] or [PcdsFeatureFlag] section"
1193 " of the DSC file, and it is currently defined in this section:"
1194 " %s, line #: %d." % (Excpt.Pcd, Info[0], Info[1]),
1195 File=self._FileWithError, ExtraData=' '.join(self._ValueList),
1196 Line=self._LineIndex+1)
1197 else:
1198 EdkLogger.error('Parser', FORMAT_INVALID, "PCD (%s) is not defined in DSC file" % Excpt.Pcd,
1199 File=self._FileWithError, ExtraData=' '.join(self._ValueList),
1200 Line=self._LineIndex+1)
1201 else:
1202 EdkLogger.error('Parser', FORMAT_INVALID, "Invalid expression: %s" % str(Excpt),
1203 File=self._FileWithError, ExtraData=' '.join(self._ValueList),
1204 Line=self._LineIndex+1)
1205 except MacroException, Excpt:
1206 EdkLogger.error('Parser', FORMAT_INVALID, str(Excpt),
1207 File=self._FileWithError, ExtraData=' '.join(self._ValueList),
1208 Line=self._LineIndex+1)
1209
1210 if self._ValueList == None:
1211 continue
1212
1213 NewOwner = self._IdMapping.get(Owner, -1)
1214 self._Enabled = int((not self._DirectiveEvalStack) or (False not in self._DirectiveEvalStack))
1215 self._LastItem = self._Store(
1216 self._ItemType,
1217 self._ValueList[0],
1218 self._ValueList[1],
1219 self._ValueList[2],
1220 S1,
1221 S2,
1222 NewOwner,
1223 self._From,
1224 self._LineIndex+1,
1225 -1,
1226 self._LineIndex+1,
1227 -1,
1228 self._Enabled
1229 )
1230 self._IdMapping[Id] = self._LastItem
1231
1232 GlobalData.gPlatformDefines.update(self._FileLocalMacros)
1233 self._PostProcessed = True
1234 self._Content = None
1235
1236 def __ProcessSectionHeader(self):
1237 self._SectionName = self._ValueList[0]
1238 if self._SectionName in self.DataType:
1239 self._SectionType = self.DataType[self._SectionName]
1240 else:
1241 self._SectionType = MODEL_UNKNOWN
1242
1243 def __ProcessSubsectionHeader(self):
1244 self._SubsectionName = self._ValueList[0]
1245 if self._SubsectionName in self.DataType:
1246 self._SubsectionType = self.DataType[self._SubsectionName]
1247 else:
1248 self._SubsectionType = MODEL_UNKNOWN
1249
1250 def __RetrievePcdValue(self):
1251 Records = self._RawTable.Query(MODEL_PCD_FEATURE_FLAG, BelongsToItem=-1.0)
1252 for TokenSpaceGuid,PcdName,Value,Dummy2,Dummy3,ID,Line in Records:
1253 Value, DatumType, MaxDatumSize = AnalyzePcdData(Value)
1254 Name = TokenSpaceGuid + '.' + PcdName
1255 self._Symbols[Name] = Value
1256
1257 Records = self._RawTable.Query(MODEL_PCD_FIXED_AT_BUILD, BelongsToItem=-1.0)
1258 for TokenSpaceGuid,PcdName,Value,Dummy2,Dummy3,ID,Line in Records:
1259 Value, DatumType, MaxDatumSize = AnalyzePcdData(Value)
1260 Name = TokenSpaceGuid + '.' + PcdName
1261 self._Symbols[Name] = Value
1262
1263 Content = open(str(self.MetaFile), 'r').readlines()
1264 GlobalData.gPlatformOtherPcds['DSCFILE'] = str(self.MetaFile)
1265 for PcdType in (MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_HII,
1266 MODEL_PCD_DYNAMIC_VPD, MODEL_PCD_DYNAMIC_EX_DEFAULT, MODEL_PCD_DYNAMIC_EX_HII,
1267 MODEL_PCD_DYNAMIC_EX_VPD):
1268 Records = self._RawTable.Query(PcdType, BelongsToItem=-1.0)
1269 for TokenSpaceGuid,PcdName,Value,Dummy2,Dummy3,ID,Line in Records:
1270 Name = TokenSpaceGuid + '.' + PcdName
1271 if Name not in GlobalData.gPlatformOtherPcds:
1272 PcdLine = Line
1273 while not Content[Line - 1].lstrip().startswith(TAB_SECTION_START):
1274 Line -= 1
1275 GlobalData.gPlatformOtherPcds[Name] = (CleanString(Content[Line - 1]), PcdLine, PcdType)
1276
1277 def __ProcessDefine(self):
1278 if not self._Enabled:
1279 return
1280
1281 Type, Name, Value = self._ValueList
1282 Value = ReplaceMacro(Value, self._Macros, False)
1283 if self._ItemType == MODEL_META_DATA_DEFINE:
1284 if self._SectionType == MODEL_META_DATA_HEADER:
1285 self._FileLocalMacros[Name] = Value
1286 else:
1287 self._ConstructSectionMacroDict(Name, Value)
1288 elif self._ItemType == MODEL_META_DATA_GLOBAL_DEFINE:
1289 GlobalData.gEdkGlobal[Name] = Value
1290
1291 #
1292 # Keyword in [Defines] section can be used as Macros
1293 #
1294 if (self._ItemType == MODEL_META_DATA_HEADER) and (self._SectionType == MODEL_META_DATA_HEADER):
1295 self._FileLocalMacros[Name] = Value
1296
1297 self._ValueList = [Type, Name, Value]
1298
1299 def __ProcessDirective(self):
1300 Result = None
1301 if self._ItemType in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF,
1302 MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF]:
1303 Macros = self._Macros
1304 Macros.update(GlobalData.gGlobalDefines)
1305 try:
1306 Result = ValueExpression(self._ValueList[1], Macros)()
1307 except SymbolNotFound, Exc:
1308 EdkLogger.debug(EdkLogger.DEBUG_5, str(Exc), self._ValueList[1])
1309 Result = False
1310 except WrnExpression, Excpt:
1311 #
1312 # Catch expression evaluation warning here. We need to report
1313 # the precise number of line and return the evaluation result
1314 #
1315 EdkLogger.warn('Parser', "Suspicious expression: %s" % str(Excpt),
1316 File=self._FileWithError, ExtraData=' '.join(self._ValueList),
1317 Line=self._LineIndex+1)
1318 Result = Excpt.result
1319
1320 if self._ItemType in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF,
1321 MODEL_META_DATA_CONDITIONAL_STATEMENT_IFDEF,
1322 MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF]:
1323 self._DirectiveStack.append(self._ItemType)
1324 if self._ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_IF:
1325 Result = bool(Result)
1326 else:
1327 Macro = self._ValueList[1]
1328 Macro = Macro[2:-1] if (Macro.startswith("$(") and Macro.endswith(")")) else Macro
1329 Result = Macro in self._Macros
1330 if self._ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF:
1331 Result = not Result
1332 self._DirectiveEvalStack.append(Result)
1333 elif self._ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF:
1334 self._DirectiveStack.append(self._ItemType)
1335 self._DirectiveEvalStack[-1] = not self._DirectiveEvalStack[-1]
1336 self._DirectiveEvalStack.append(bool(Result))
1337 elif self._ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSE:
1338 self._DirectiveStack.append(self._ItemType)
1339 self._DirectiveEvalStack[-1] = not self._DirectiveEvalStack[-1]
1340 self._DirectiveEvalStack.append(True)
1341 elif self._ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF:
1342 # Back to the nearest !if/!ifdef/!ifndef
1343 while self._DirectiveStack:
1344 self._DirectiveEvalStack.pop()
1345 Directive = self._DirectiveStack.pop()
1346 if Directive in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF,
1347 MODEL_META_DATA_CONDITIONAL_STATEMENT_IFDEF,
1348 MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF]:
1349 break
1350 elif self._ItemType == MODEL_META_DATA_INCLUDE:
1351 # The included file must be relative to workspace or same directory as DSC file
1352 __IncludeMacros = {}
1353 #
1354 # Allow using system environment variables in path after !include
1355 #
1356 __IncludeMacros['WORKSPACE'] = GlobalData.gGlobalDefines['WORKSPACE']
1357 if "ECP_SOURCE" in GlobalData.gGlobalDefines.keys():
1358 __IncludeMacros['ECP_SOURCE'] = GlobalData.gGlobalDefines['ECP_SOURCE']
1359 #
1360 # During GenFds phase call DSC parser, will go into this branch.
1361 #
1362 elif "ECP_SOURCE" in GlobalData.gCommandLineDefines.keys():
1363 __IncludeMacros['ECP_SOURCE'] = GlobalData.gCommandLineDefines['ECP_SOURCE']
1364
1365 __IncludeMacros['EFI_SOURCE'] = GlobalData.gGlobalDefines['EFI_SOURCE']
1366 __IncludeMacros['EDK_SOURCE'] = GlobalData.gGlobalDefines['EDK_SOURCE']
1367 #
1368 # Allow using MACROs comes from [Defines] section to keep compatible.
1369 #
1370 __IncludeMacros.update(self._Macros)
1371
1372 IncludedFile = NormPath(ReplaceMacro(self._ValueList[1], __IncludeMacros, RaiseError=True))
1373 #
1374 # First search the include file under the same directory as DSC file
1375 #
1376 IncludedFile1 = PathClass(IncludedFile, self.MetaFile.Dir)
1377 ErrorCode, ErrorInfo1 = IncludedFile1.Validate()
1378 if ErrorCode != 0:
1379 #
1380 # Also search file under the WORKSPACE directory
1381 #
1382 IncludedFile1 = PathClass(IncludedFile, GlobalData.gWorkspace)
1383 ErrorCode, ErrorInfo2 = IncludedFile1.Validate()
1384 if ErrorCode != 0:
1385 EdkLogger.error('parser', ErrorCode, File=self._FileWithError,
1386 Line=self._LineIndex+1, ExtraData=ErrorInfo1 + "\n"+ ErrorInfo2)
1387
1388 self._FileWithError = IncludedFile1
1389
1390 IncludedFileTable = MetaFileStorage(self._Table.Cur, IncludedFile1, MODEL_FILE_DSC, False)
1391 Owner = self._Content[self._ContentIndex-1][0]
1392 Parser = DscParser(IncludedFile1, self._FileType, IncludedFileTable,
1393 Owner=Owner, From=Owner)
1394
1395 # set the parser status with current status
1396 Parser._SectionName = self._SectionName
1397 Parser._SectionType = self._SectionType
1398 Parser._Scope = self._Scope
1399 Parser._Enabled = self._Enabled
1400 # Parse the included file
1401 Parser.Start()
1402
1403 # update current status with sub-parser's status
1404 self._SectionName = Parser._SectionName
1405 self._SectionType = Parser._SectionType
1406 self._Scope = Parser._Scope
1407 self._Enabled = Parser._Enabled
1408
1409 # Insert all records in the table for the included file into dsc file table
1410 Records = IncludedFileTable.GetAll()
1411 if Records:
1412 self._Content[self._ContentIndex:self._ContentIndex] = Records
1413 self._Content.pop(self._ContentIndex-1)
1414 self._ValueList = None
1415 self._ContentIndex -= 1
1416
1417 def __ProcessSkuId(self):
1418 self._ValueList = [ReplaceMacro(Value, self._Macros, RaiseError=True)
1419 for Value in self._ValueList]
1420
1421 def __ProcessLibraryInstance(self):
1422 self._ValueList = [ReplaceMacro(Value, self._Macros) for Value in self._ValueList]
1423
1424 def __ProcessLibraryClass(self):
1425 self._ValueList[1] = ReplaceMacro(self._ValueList[1], self._Macros, RaiseError=True)
1426
1427 def __ProcessPcd(self):
1428 PcdValue = None
1429 ValueList = GetSplitValueList(self._ValueList[2])
1430 #
1431 # PCD value can be an expression
1432 #
1433 if len(ValueList) > 1 and ValueList[1] == 'VOID*':
1434 PcdValue = ValueList[0]
1435 try:
1436 ValueList[0] = ValueExpression(PcdValue, self._Macros)(True)
1437 except WrnExpression, Value:
1438 ValueList[0] = Value.result
1439 PcdValue = ValueList[0]
1440 else:
1441 #
1442 # Int*/Boolean VPD PCD
1443 # TokenSpace | PcdCName | Offset | [Value]
1444 #
1445 # VOID* VPD PCD
1446 # TokenSpace | PcdCName | Offset | [Size] | [Value]
1447 #
1448 if self._ItemType == MODEL_PCD_DYNAMIC_VPD:
1449 if len(ValueList) >= 4:
1450 PcdValue = ValueList[-1]
1451 else:
1452 PcdValue = ValueList[-1]
1453 #
1454 # For the VPD PCD, there may not have PcdValue data in DSC file
1455 #
1456 if PcdValue:
1457 try:
1458 ValueList[-1] = ValueExpression(PcdValue, self._Macros)(True)
1459 except WrnExpression, Value:
1460 ValueList[-1] = Value.result
1461
1462 if ValueList[-1] == 'True':
1463 ValueList[-1] = '1'
1464 if ValueList[-1] == 'False':
1465 ValueList[-1] = '0'
1466 PcdValue = ValueList[-1]
1467 if PcdValue and self._ItemType in [MODEL_PCD_FEATURE_FLAG, MODEL_PCD_FIXED_AT_BUILD]:
1468 GlobalData.gPlatformPcds[TAB_SPLIT.join(self._ValueList[0:2])] = PcdValue
1469 self._ValueList[2] = '|'.join(ValueList)
1470
1471 def __ProcessComponent(self):
1472 self._ValueList[0] = ReplaceMacro(self._ValueList[0], self._Macros)
1473
1474 def __ProcessSourceOverridePath(self):
1475 self._ValueList[0] = ReplaceMacro(self._ValueList[0], self._Macros)
1476
1477 def __ProcessBuildOption(self):
1478 self._ValueList = [ReplaceMacro(Value, self._Macros, RaiseError=False)
1479 for Value in self._ValueList]
1480
1481 _SectionParser = {
1482 MODEL_META_DATA_HEADER : _DefineParser,
1483 MODEL_EFI_SKU_ID : _SkuIdParser,
1484 MODEL_EFI_LIBRARY_INSTANCE : _LibraryInstanceParser,
1485 MODEL_EFI_LIBRARY_CLASS : _LibraryClassParser,
1486 MODEL_PCD_FIXED_AT_BUILD : _PcdParser,
1487 MODEL_PCD_PATCHABLE_IN_MODULE : _PcdParser,
1488 MODEL_PCD_FEATURE_FLAG : _PcdParser,
1489 MODEL_PCD_DYNAMIC_DEFAULT : _PcdParser,
1490 MODEL_PCD_DYNAMIC_HII : _PcdParser,
1491 MODEL_PCD_DYNAMIC_VPD : _PcdParser,
1492 MODEL_PCD_DYNAMIC_EX_DEFAULT : _PcdParser,
1493 MODEL_PCD_DYNAMIC_EX_HII : _PcdParser,
1494 MODEL_PCD_DYNAMIC_EX_VPD : _PcdParser,
1495 MODEL_META_DATA_COMPONENT : _ComponentParser,
1496 MODEL_META_DATA_COMPONENT_SOURCE_OVERRIDE_PATH : _CompponentSourceOverridePathParser,
1497 MODEL_META_DATA_BUILD_OPTION : _BuildOptionParser,
1498 MODEL_UNKNOWN : MetaFileParser._Skip,
1499 MODEL_META_DATA_USER_EXTENSION : MetaFileParser._Skip,
1500 MODEL_META_DATA_SECTION_HEADER : MetaFileParser._SectionHeaderParser,
1501 MODEL_META_DATA_SUBSECTION_HEADER : _SubsectionHeaderParser,
1502 }
1503
1504 _Macros = property(_GetMacros)
1505
1506 ## DEC file parser class
1507 #
1508 # @param FilePath The path of platform description file
1509 # @param FileType The raw data of DSC file
1510 # @param Table Database used to retrieve module/package information
1511 # @param Macros Macros used for replacement in file
1512 #
1513 class DecParser(MetaFileParser):
1514 # DEC file supported data types (one type per section)
1515 DataType = {
1516 TAB_DEC_DEFINES.upper() : MODEL_META_DATA_HEADER,
1517 TAB_DSC_DEFINES_DEFINE : MODEL_META_DATA_DEFINE,
1518 TAB_INCLUDES.upper() : MODEL_EFI_INCLUDE,
1519 TAB_LIBRARY_CLASSES.upper() : MODEL_EFI_LIBRARY_CLASS,
1520 TAB_GUIDS.upper() : MODEL_EFI_GUID,
1521 TAB_PPIS.upper() : MODEL_EFI_PPI,
1522 TAB_PROTOCOLS.upper() : MODEL_EFI_PROTOCOL,
1523 TAB_PCDS_FIXED_AT_BUILD_NULL.upper() : MODEL_PCD_FIXED_AT_BUILD,
1524 TAB_PCDS_PATCHABLE_IN_MODULE_NULL.upper() : MODEL_PCD_PATCHABLE_IN_MODULE,
1525 TAB_PCDS_FEATURE_FLAG_NULL.upper() : MODEL_PCD_FEATURE_FLAG,
1526 TAB_PCDS_DYNAMIC_NULL.upper() : MODEL_PCD_DYNAMIC,
1527 TAB_PCDS_DYNAMIC_EX_NULL.upper() : MODEL_PCD_DYNAMIC_EX,
1528 }
1529
1530 ## Constructor of DecParser
1531 #
1532 # Initialize object of DecParser
1533 #
1534 # @param FilePath The path of platform description file
1535 # @param FileType The raw data of DSC file
1536 # @param Table Database used to retrieve module/package information
1537 # @param Macros Macros used for replacement in file
1538 #
1539 def __init__(self, FilePath, FileType, Table):
1540 # prevent re-initialization
1541 if hasattr(self, "_Table"):
1542 return
1543 MetaFileParser.__init__(self, FilePath, FileType, Table, -1)
1544 self._Comments = []
1545 self._Version = 0x00010005 # Only EDK2 dec file is supported
1546
1547 ## Parser starter
1548 def Start(self):
1549 Content = ''
1550 try:
1551 Content = open(str(self.MetaFile), 'r').readlines()
1552 except:
1553 EdkLogger.error("Parser", FILE_READ_FAILURE, ExtraData=self.MetaFile)
1554
1555 for Index in range(0, len(Content)):
1556 Line, Comment = CleanString2(Content[Index])
1557 self._CurrentLine = Line
1558 self._LineIndex = Index
1559
1560 # save comment for later use
1561 if Comment:
1562 self._Comments.append((Comment, self._LineIndex+1))
1563 # skip empty line
1564 if Line == '':
1565 continue
1566
1567 # section header
1568 if Line[0] == TAB_SECTION_START and Line[-1] == TAB_SECTION_END:
1569 self._SectionHeaderParser()
1570 self._Comments = []
1571 continue
1572 elif len(self._SectionType) == 0:
1573 self._Comments = []
1574 continue
1575
1576 # section content
1577 self._ValueList = ['','','']
1578 self._SectionParser[self._SectionType[0]](self)
1579 if self._ValueList == None or self._ItemType == MODEL_META_DATA_DEFINE:
1580 self._ItemType = -1
1581 self._Comments = []
1582 continue
1583
1584 #
1585 # Model, Value1, Value2, Value3, Arch, BelongsToItem=-1, LineBegin=-1,
1586 # ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, FeatureFlag='', Enabled=-1
1587 #
1588 for Arch, ModuleType, Type in self._Scope:
1589 self._LastItem = self._Store(
1590 Type,
1591 self._ValueList[0],
1592 self._ValueList[1],
1593 self._ValueList[2],
1594 Arch,
1595 ModuleType,
1596 self._Owner[-1],
1597 self._LineIndex+1,
1598 -1,
1599 self._LineIndex+1,
1600 -1,
1601 0
1602 )
1603 for Comment, LineNo in self._Comments:
1604 self._Store(
1605 MODEL_META_DATA_COMMENT,
1606 Comment,
1607 self._ValueList[0],
1608 self._ValueList[1],
1609 Arch,
1610 ModuleType,
1611 self._LastItem,
1612 LineNo,
1613 -1,
1614 LineNo,
1615 -1,
1616 0
1617 )
1618 self._Comments = []
1619 self._Done()
1620
1621
1622 ## Section header parser
1623 #
1624 # The section header is always in following format:
1625 #
1626 # [section_name.arch<.platform|module_type>]
1627 #
1628 def _SectionHeaderParser(self):
1629 self._Scope = []
1630 self._SectionName = ''
1631 self._SectionType = []
1632 ArchList = set()
1633 for Item in GetSplitValueList(self._CurrentLine[1:-1], TAB_COMMA_SPLIT):
1634 if Item == '':
1635 continue
1636 ItemList = GetSplitValueList(Item, TAB_SPLIT)
1637
1638 # different types of PCD are permissible in one section
1639 self._SectionName = ItemList[0].upper()
1640 if self._SectionName in self.DataType:
1641 if self.DataType[self._SectionName] not in self._SectionType:
1642 self._SectionType.append(self.DataType[self._SectionName])
1643 else:
1644 EdkLogger.warn("Parser", "Unrecognized section", File=self.MetaFile,
1645 Line=self._LineIndex+1, ExtraData=self._CurrentLine)
1646 continue
1647
1648 if MODEL_PCD_FEATURE_FLAG in self._SectionType and len(self._SectionType) > 1:
1649 EdkLogger.error(
1650 'Parser',
1651 FORMAT_INVALID,
1652 "%s must not be in the same section of other types of PCD" % TAB_PCDS_FEATURE_FLAG_NULL,
1653 File=self.MetaFile,
1654 Line=self._LineIndex+1,
1655 ExtraData=self._CurrentLine
1656 )
1657 # S1 is always Arch
1658 if len(ItemList) > 1:
1659 S1 = ItemList[1].upper()
1660 else:
1661 S1 = 'COMMON'
1662 ArchList.add(S1)
1663 # S2 may be Platform or ModuleType
1664 if len(ItemList) > 2:
1665 S2 = ItemList[2].upper()
1666 else:
1667 S2 = 'COMMON'
1668 if [S1, S2, self.DataType[self._SectionName]] not in self._Scope:
1669 self._Scope.append([S1, S2, self.DataType[self._SectionName]])
1670
1671 # 'COMMON' must not be used with specific ARCHs at the same section
1672 if 'COMMON' in ArchList and len(ArchList) > 1:
1673 EdkLogger.error('Parser', FORMAT_INVALID, "'common' ARCH must not be used with specific ARCHs",
1674 File=self.MetaFile, Line=self._LineIndex+1, ExtraData=self._CurrentLine)
1675
1676 ## [guids], [ppis] and [protocols] section parser
1677 @ParseMacro
1678 def _GuidParser(self):
1679 TokenList = GetSplitValueList(self._CurrentLine, TAB_EQUAL_SPLIT, 1)
1680 if len(TokenList) < 2:
1681 EdkLogger.error('Parser', FORMAT_INVALID, "No GUID name or value specified",
1682 ExtraData=self._CurrentLine + " (<CName> = <GuidValueInCFormat>)",
1683 File=self.MetaFile, Line=self._LineIndex+1)
1684 if TokenList[0] == '':
1685 EdkLogger.error('Parser', FORMAT_INVALID, "No GUID name specified",
1686 ExtraData=self._CurrentLine + " (<CName> = <GuidValueInCFormat>)",
1687 File=self.MetaFile, Line=self._LineIndex+1)
1688 if TokenList[1] == '':
1689 EdkLogger.error('Parser', FORMAT_INVALID, "No GUID value specified",
1690 ExtraData=self._CurrentLine + " (<CName> = <GuidValueInCFormat>)",
1691 File=self.MetaFile, Line=self._LineIndex+1)
1692 if TokenList[1][0] != '{' or TokenList[1][-1] != '}' or GuidStructureStringToGuidString(TokenList[1]) == '':
1693 EdkLogger.error('Parser', FORMAT_INVALID, "Invalid GUID value format",
1694 ExtraData=self._CurrentLine + \
1695 " (<CName> = <GuidValueInCFormat:{8,4,4,{2,2,2,2,2,2,2,2}}>)",
1696 File=self.MetaFile, Line=self._LineIndex+1)
1697 self._ValueList[0] = TokenList[0]
1698 self._ValueList[1] = TokenList[1]
1699
1700 ## PCD sections parser
1701 #
1702 # [PcdsFixedAtBuild]
1703 # [PcdsPatchableInModule]
1704 # [PcdsFeatureFlag]
1705 # [PcdsDynamicEx
1706 # [PcdsDynamic]
1707 #
1708 @ParseMacro
1709 def _PcdParser(self):
1710 TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT, 1)
1711 self._ValueList[0:1] = GetSplitValueList(TokenList[0], TAB_SPLIT)
1712 # check PCD information
1713 if self._ValueList[0] == '' or self._ValueList[1] == '':
1714 EdkLogger.error('Parser', FORMAT_INVALID, "No token space GUID or PCD name specified",
1715 ExtraData=self._CurrentLine + \
1716 " (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
1717 File=self.MetaFile, Line=self._LineIndex+1)
1718 # check PCD datum information
1719 if len(TokenList) < 2 or TokenList[1] == '':
1720 EdkLogger.error('Parser', FORMAT_INVALID, "No PCD Datum information given",
1721 ExtraData=self._CurrentLine + \
1722 " (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
1723 File=self.MetaFile, Line=self._LineIndex+1)
1724
1725
1726 ValueRe = re.compile(r'^\s*L?\".*\|.*\"')
1727 PtrValue = ValueRe.findall(TokenList[1])
1728
1729 # Has VOID* type string, may contain "|" character in the string.
1730 if len(PtrValue) != 0:
1731 ptrValueList = re.sub(ValueRe, '', TokenList[1])
1732 ValueList = GetSplitValueList(ptrValueList)
1733 ValueList[0] = PtrValue[0]
1734 else:
1735 ValueList = GetSplitValueList(TokenList[1])
1736
1737
1738 # check if there's enough datum information given
1739 if len(ValueList) != 3:
1740 EdkLogger.error('Parser', FORMAT_INVALID, "Invalid PCD Datum information given",
1741 ExtraData=self._CurrentLine + \
1742 " (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
1743 File=self.MetaFile, Line=self._LineIndex+1)
1744 # check default value
1745 if ValueList[0] == '':
1746 EdkLogger.error('Parser', FORMAT_INVALID, "Missing DefaultValue in PCD Datum information",
1747 ExtraData=self._CurrentLine + \
1748 " (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
1749 File=self.MetaFile, Line=self._LineIndex+1)
1750 # check datum type
1751 if ValueList[1] == '':
1752 EdkLogger.error('Parser', FORMAT_INVALID, "Missing DatumType in PCD Datum information",
1753 ExtraData=self._CurrentLine + \
1754 " (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
1755 File=self.MetaFile, Line=self._LineIndex+1)
1756 # check token of the PCD
1757 if ValueList[2] == '':
1758 EdkLogger.error('Parser', FORMAT_INVALID, "Missing Token in PCD Datum information",
1759 ExtraData=self._CurrentLine + \
1760 " (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
1761 File=self.MetaFile, Line=self._LineIndex+1)
1762 # check format of default value against the datum type
1763 IsValid, Cause = CheckPcdDatum(ValueList[1], ValueList[0])
1764 if not IsValid:
1765 EdkLogger.error('Parser', FORMAT_INVALID, Cause, ExtraData=self._CurrentLine,
1766 File=self.MetaFile, Line=self._LineIndex+1)
1767
1768 if ValueList[0] in ['True', 'true', 'TRUE']:
1769 ValueList[0] = '1'
1770 elif ValueList[0] in ['False', 'false', 'FALSE']:
1771 ValueList[0] = '0'
1772
1773 self._ValueList[2] = ValueList[0].strip() + '|' + ValueList[1].strip() + '|' + ValueList[2].strip()
1774
1775 _SectionParser = {
1776 MODEL_META_DATA_HEADER : MetaFileParser._DefineParser,
1777 MODEL_EFI_INCLUDE : MetaFileParser._PathParser,
1778 MODEL_EFI_LIBRARY_CLASS : MetaFileParser._PathParser,
1779 MODEL_EFI_GUID : _GuidParser,
1780 MODEL_EFI_PPI : _GuidParser,
1781 MODEL_EFI_PROTOCOL : _GuidParser,
1782 MODEL_PCD_FIXED_AT_BUILD : _PcdParser,
1783 MODEL_PCD_PATCHABLE_IN_MODULE : _PcdParser,
1784 MODEL_PCD_FEATURE_FLAG : _PcdParser,
1785 MODEL_PCD_DYNAMIC : _PcdParser,
1786 MODEL_PCD_DYNAMIC_EX : _PcdParser,
1787 MODEL_UNKNOWN : MetaFileParser._Skip,
1788 MODEL_META_DATA_USER_EXTENSION : MetaFileParser._Skip,
1789 }
1790
1791 ##
1792 #
1793 # This acts like the main() function for the script, unless it is 'import'ed into another
1794 # script.
1795 #
1796 if __name__ == '__main__':
1797 pass
1798