1 ## @file ParserValidate.py
3 # Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
5 # This program and the accompanying materials are licensed and made available
6 # under the terms and conditions of the BSD License which accompanies this
7 # distribution. The full text of the license may be found at
8 # http://opensource.org/licenses/bsd-license.php
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.
21 from Library
.DataType
import MODULE_LIST
22 from Library
.DataType
import COMPONENT_TYPE_LIST
23 from Library
.DataType
import PCD_USAGE_TYPE_LIST_OF_MODULE
24 from Library
.DataType
import TAB_SPACE_SPLIT
25 from Library
.String
import GetSplitValueList
26 from Library
.ExpressionValidate
import IsValidBareCString
27 from Library
.ExpressionValidate
import IsValidFeatureFlagExp
29 ## __HexDigit() method
31 # Whether char input is a Hex data bit
33 # @param TempChar: The char to test
35 def __HexDigit(TempChar
):
36 if (TempChar
>= 'a' and TempChar
<= 'f') or \
37 (TempChar
>= 'A' and TempChar
<= 'F') \
38 or (TempChar
>= '0' and TempChar
<= '9'):
43 ## IsValidHex() method
45 # Whether char input is a Hex data.
47 # @param TempChar: The char to test
49 def IsValidHex(HexStr
):
50 if not HexStr
.upper().startswith("0X"):
52 CharList
= [c
for c
in HexStr
[2:] if not __HexDigit(c
)]
53 if len(CharList
) == 0:
58 ## Judge the input string is valid bool type or not.
60 # <TRUE> ::= {"TRUE"} {"true"} {"True"} {"0x1"} {"0x01"}
61 # <FALSE> ::= {"FALSE"} {"false"} {"False"} {"0x0"} {"0x00"}
62 # <BoolType> ::= {<TRUE>} {<FALSE>}
64 # @param BoolString: A string contained the value need to be judged.
66 def IsValidBoolType(BoolString
):
70 if BoolString
== 'TRUE' or \
71 BoolString
== 'True' or \
72 BoolString
== 'true' or \
73 BoolString
== '0x1' or \
79 elif BoolString
== 'FALSE' or \
80 BoolString
== 'False' or \
81 BoolString
== 'false' or \
82 BoolString
== '0x0' or \
91 ## Is Valid Module Type List or not
93 # @param ModuleTypeList: A list contain ModuleType strings need to be
96 def IsValidInfMoudleTypeList(ModuleTypeList
):
97 for ModuleType
in ModuleTypeList
:
98 return IsValidInfMoudleType(ModuleType
)
100 ## Is Valid Module Type or not
102 # @param ModuleType: A string contain ModuleType need to be judged.
104 def IsValidInfMoudleType(ModuleType
):
105 if ModuleType
in MODULE_LIST
:
110 ## Is Valid Component Type or not
112 # @param ComponentType: A string contain ComponentType need to be judged.
114 def IsValidInfComponentType(ComponentType
):
115 if ComponentType
.upper() in COMPONENT_TYPE_LIST
:
121 ## Is valid Tool Family or not
123 # @param ToolFamily: A string contain Tool Family need to be judged.
124 # Famlily := [A-Z]([a-zA-Z0-9])*
126 def IsValidToolFamily(ToolFamily
):
127 ReIsValieFamily
= re
.compile(r
"^[A-Z]+[A-Za-z0-9]{0,}$", re
.DOTALL
)
128 if ReIsValieFamily
.match(ToolFamily
) == None:
132 ## Is valid Tool TagName or not
134 # The TagName sample is MYTOOLS and VS2005.
136 # @param TagName: A string contain Tool TagName need to be judged.
138 def IsValidToolTagName(TagName
):
139 if TagName
.strip() == '':
141 if TagName
.strip() == '*':
143 if not IsValidWord(TagName
):
147 ## Is valid arch or not
149 # @param Arch The arch string need to be validated
150 # <OA> ::= (a-zA-Z)(A-Za-z0-9){0,}
151 # <arch> ::= {"IA32"} {"X64"} {"IPF"} {"EBC"} {<OA>}
153 # @param Arch: Input arch
155 def IsValidArch(Arch
):
158 ReIsValieArch
= re
.compile(r
"^[a-zA-Z]+[a-zA-Z0-9]{0,}$", re
.DOTALL
)
159 if ReIsValieArch
.match(Arch
) == None:
163 ## Is valid family or not
165 # <Family> ::= {"MSFT"} {"GCC"} {"INTEL"} {<Usr>} {"*"}
166 # <Usr> ::= [A-Z][A-Za-z0-9]{0,}
168 # @param family: The family string need to be validated
170 def IsValidFamily(Family
):
171 Family
= Family
.strip()
178 ReIsValidFamily
= re
.compile(r
"^[A-Z]+[A-Za-z0-9]{0,}$", re
.DOTALL
)
179 if ReIsValidFamily
.match(Family
) == None:
183 ## Is valid build option name or not
185 # @param BuildOptionName: The BuildOptionName string need to be validated
187 def IsValidBuildOptionName(BuildOptionName
):
188 if not BuildOptionName
:
191 ToolOptionList
= GetSplitValueList(BuildOptionName
, '_', 4)
193 if len(ToolOptionList
) != 5:
196 ReIsValidBuildOption1
= re
.compile(r
"^\s*(\*)|([A-Z][a-zA-Z0-9]*)$")
197 ReIsValidBuildOption2
= re
.compile(r
"^\s*(\*)|([a-zA-Z][a-zA-Z0-9]*)$")
199 if ReIsValidBuildOption1
.match(ToolOptionList
[0]) == None:
202 if ReIsValidBuildOption1
.match(ToolOptionList
[1]) == None:
205 if ReIsValidBuildOption2
.match(ToolOptionList
[2]) == None:
208 if ToolOptionList
[3] == "*" and ToolOptionList
[4] not in ['FAMILY', 'DLL', 'DPATH']:
215 # Check if pattern string matches total token
217 # @param ReString: regular string
218 # @param Token: Token to be matched
220 def IsValidToken(ReString
, Token
):
221 Match
= re
.compile(ReString
).match(Token
)
222 return Match
and Match
.start() == 0 and Match
.end() == len(Token
)
226 # Check if path exist
228 # @param Path: Absolute path or relative path to be checked
229 # @param Root: Root path
231 def IsValidPath(Path
, Root
):
233 OrigPath
= Path
.replace('\\', '/')
235 Path
= os
.path
.normpath(Path
).replace('\\', '/')
236 Root
= os
.path
.normpath(Root
).replace('\\', '/')
237 FullPath
= os
.path
.normpath(os
.path
.join(Root
, Path
)).replace('\\', '/')
239 if not os
.path
.exists(FullPath
):
243 # If Path is absolute path.
244 # It should be in Root.
246 if os
.path
.isabs(Path
):
247 if not Path
.startswith(Root
):
252 # Check illegal character
254 for Rel
in ['/', './', '../']:
255 if OrigPath
.startswith(Rel
):
257 for Rel
in ['//', '/./', '/../']:
260 for Rel
in ['/.', '/..', '/']:
261 if OrigPath
.endswith(Rel
):
264 Path
= Path
.rstrip('/')
267 # Check relative path
269 for Word
in Path
.split('/'):
270 if not IsValidWord(Word
):
275 ## IsValidInstallPath
277 # Check if an install path valid or not.
279 # Absolute path or path starts with '.' or path contains '..' are invalid.
281 # @param Path: path to be checked
283 def IsValidInstallPath(Path
):
284 if os
.path
.isabs(Path
):
287 if Path
.startswith('.'):
290 if Path
.find('..') != -1:
296 ## IsValidCFormatGuid
298 # Check if GUID format has the from of {8,4,4,{2,2,2,2,2,2,2,2}}
300 # @param Guid: Guid to be checked
302 def IsValidCFormatGuid(Guid
):
304 # Valid: { 0xf0b11735, 0x87a0, 0x4193, {0xb2, 0x66, 0x53, 0x8c, 0x38,
305 # 0xaf, 0x48, 0xce }}
306 # Invalid: { 0xf0b11735, 0x87a0, 0x4193, {0xb2, 0x66, 0x53, 0x8c, 0x38,
307 # 0xaf, 0x48, 0xce }} 0x123
308 # Invalid: { 0xf0b1 1735, 0x87a0, 0x4193, {0xb2, 0x66, 0x53, 0x8c, 0x38,
309 # 0xaf, 0x48, 0xce }}
311 List
= ['{', 10, ',', 6, ',', 6, ',{', 4, ',', 4, ',', 4,
312 ',', 4, ',', 4, ',', 4, ',', 4, ',', 4, '}}']
317 if Char
not in '{},\t ':
323 # Index may out of bound
325 if not SepValue
or SepValue
!= List
[Index
]:
330 if not Value
.startswith('0x') and not Value
.startswith('0X'):
334 # Index may out of bound
336 if type(List
[Index
]) != type(1) or \
337 len(Value
) > List
[Index
] or len(Value
) < 3:
341 # Check if string can be converted to integer
342 # Throw exception if not
345 except BaseException
:
347 # Exception caught means invalid format
355 return SepValue
== '}}' and Value
== ''
359 # Check whether the PCD type is valid
361 # @param PcdTypeString: The PcdType string need to be checked.
363 def IsValidPcdType(PcdTypeString
):
364 if PcdTypeString
.upper() in PCD_USAGE_TYPE_LIST_OF_MODULE
:
371 # Check whether the word is valid.
372 # <Word> ::= (a-zA-Z0-9_)(a-zA-Z0-9_-){0,} Alphanumeric characters with
374 # dash "-" and/or underscore "_" characters. No whitespace
375 # characters are permitted.
377 # @param Word: The word string need to be checked.
379 def IsValidWord(Word
):
383 # The first char should be alpha, _ or Digit.
385 if not Word
[0].isalnum() and \
386 not Word
[0] == '_' and \
387 not Word
[0].isdigit():
391 for Char
in Word
[1:]:
392 if (not Char
.isalpha()) and \
393 (not Char
.isdigit()) and \
398 if Char
== '.' and LastChar
== '.':
407 # Check whether the SimpleWord is valid.
408 # <SimpleWord> ::= (a-zA-Z0-9)(a-zA-Z0-9_-){0,}
409 # A word that cannot contain a period character.
411 # @param Word: The word string need to be checked.
413 def IsValidSimpleWord(Word
):
414 ReIsValidSimpleWord
= \
415 re
.compile(r
"^[0-9A-Za-z][0-9A-Za-z\-_]*$", re
.DOTALL
)
420 if not ReIsValidSimpleWord
.match(Word
):
427 # Check whether the decimal version is valid.
428 # <DecVersion> ::= (0-9){1,} ["." (0-9){1,}]
430 # @param Word: The word string need to be checked.
432 def IsValidDecVersion(Word
):
433 if Word
.find('.') > -1:
434 ReIsValidDecVersion
= re
.compile(r
"[0-9]+\.?[0-9]+$")
436 ReIsValidDecVersion
= re
.compile(r
"[0-9]+$")
437 if ReIsValidDecVersion
.match(Word
) == None:
443 # Check whether the hex version is valid.
444 # <HexVersion> ::= "0x" <Major> <Minor>
445 # <Major> ::= <HexDigit>{4}
446 # <Minor> ::= <HexDigit>{4}
448 # @param Word: The word string need to be checked.
450 def IsValidHexVersion(Word
):
451 ReIsValidHexVersion
= re
.compile(r
"[0][xX][0-9A-Fa-f]{8}$", re
.DOTALL
)
452 if ReIsValidHexVersion
.match(Word
) == None:
457 ## IsValidBuildNumber
459 # Check whether the BUILD_NUMBER is valid.
460 # ["BUILD_NUMBER" "=" <Integer>{1,4} <EOL>]
462 # @param Word: The BUILD_NUMBER string need to be checked.
464 def IsValidBuildNumber(Word
):
465 ReIsValieBuildNumber
= re
.compile(r
"[0-9]{1,4}$", re
.DOTALL
)
466 if ReIsValieBuildNumber
.match(Word
) == None:
473 # Check whether the Depex is valid.
475 # @param Word: The Depex string need to be checked.
477 def IsValidDepex(Word
):
478 Index
= Word
.upper().find("PUSH")
480 return IsValidCFormatGuid(Word
[Index
+4:].strip())
482 ReIsValidCName
= re
.compile(r
"^[A-Za-z_][0-9A-Za-z_\s\.]*$", re
.DOTALL
)
483 if ReIsValidCName
.match(Word
) == None:
488 ## IsValidNormalizedString
491 # <NormalizedString> ::= <DblQuote> [{<Word>} {<Space>}]{1,} <DblQuote>
494 # @param String: string to be checked
496 def IsValidNormalizedString(String
):
504 StringList
= GetSplitValueList(String
, TAB_SPACE_SPLIT
)
506 for Item
in StringList
:
509 if not IsValidWord(Item
):
516 # Check whether the IdString is valid.
518 # @param IdString: The IdString need to be checked.
520 def IsValidIdString(String
):
521 if IsValidSimpleWord(String
.strip()):
524 if String
.strip().startswith('"') and \
525 String
.strip().endswith('"'):
526 String
= String
[1:-1]
527 if String
.strip() == "":
529 if IsValidNormalizedString(String
):
534 ## IsValidVersionString
536 # Check whether the VersionString is valid.
537 # <AsciiString> ::= [ [<WhiteSpace>]{0,} [<AsciiChars>]{0,} ] {0,}
538 # <WhiteSpace> ::= {<Tab>} {<Space>}
541 # <AsciiChars> ::= (0x21 - 0x7E)
543 # @param VersionString: The VersionString need to be checked.
545 def IsValidVersionString(VersionString
):
546 VersionString
= VersionString
.strip()
547 for Char
in VersionString
:
548 if not (Char
>= 0x21 and Char
<= 0x7E):
555 # Check whether the PcdValue is valid.
557 # @param VersionString: The PcdValue need to be checked.
559 def IsValidPcdValue(PcdValue
):
560 for Char
in PcdValue
:
561 if Char
== '\n' or Char
== '\t' or Char
== '\f':
567 if IsValidFeatureFlagExp(PcdValue
, True)[0]:
571 # <Number> ::= {<Integer>} {<HexNumber>}
572 # <Integer> ::= {(0-9)} {(1-9)(0-9){1,}}
573 # <HexNumber> ::= "0x" <HexDigit>{1,}
574 # <HexDigit> ::= (a-fA-F0-9)
576 if IsValidHex(PcdValue
):
579 ReIsValidIntegerSingle
= re
.compile(r
"^\s*[0-9]\s*$", re
.DOTALL
)
580 if ReIsValidIntegerSingle
.match(PcdValue
) != None:
583 ReIsValidIntegerMulti
= re
.compile(r
"^\s*[1-9][0-9]+\s*$", re
.DOTALL
)
584 if ReIsValidIntegerMulti
.match(PcdValue
) != None:
589 # <StringVal> ::= {<StringType>} {<Array>} {"$(" <MACRO> ")"}
590 # <StringType> ::= {<UnicodeString>} {<CString>}
592 ReIsValidStringType
= re
.compile(r
"^\s*[\"L
].*[\"]\s
*$
")
593 if ReIsValidStringType.match(PcdValue):
595 if PcdValue.strip().startswith('L\"'):
596 StringValue = PcdValue.strip().lstrip('L\"').rstrip('\"')
597 if IsValidBareCString(StringValue):
599 elif PcdValue.strip().startswith('\"'):
600 StringValue = PcdValue.strip().lstrip('\"').rstrip('\"')
601 if IsValidBareCString(StringValue):
607 # <Array> ::= {<CArray>} {<NList>} {<CFormatGUID>}
608 # <CArray> ::= "{" [<NList>] <CArray>{0,} "}"
609 # <NList> ::= <HexByte> ["," <HexByte>]{0,}
610 # <HexDigit> ::= (a-fA-F0-9)
611 # <HexByte> ::= "0x
" <HexDigit>{1,2}
613 if IsValidCFormatGuid(PcdValue):
616 ReIsValidByteHex = re.compile(r"^\s
*0x
[0-9a
-fA
-F
]{1,2}\s
*$
", re.DOTALL)
617 if PcdValue.strip().startswith('{') and PcdValue.strip().endswith('}') :
618 StringValue = PcdValue.strip().lstrip('{').rstrip('}')
619 ValueList = StringValue.split(',')
621 for ValueItem in ValueList:
622 if not ReIsValidByteHex.match(ValueItem.strip()):
632 ValueList = PcdValue.split(',')
633 for ValueItem in ValueList:
634 if not ReIsValidByteHex.match(ValueItem.strip()):
642 ## IsValidCVariableName
644 # Check whether the PcdValue is valid.
646 # @param VersionString: The PcdValue need to be checked.
648 def IsValidCVariableName(CName):
649 ReIsValidCName = re.compile(r"^
[A
-Za
-z_
][0-9A
-Za
-z_
]*$
", re.DOTALL)
650 if ReIsValidCName.match(CName) == None:
657 # <Identifier> ::= <NonDigit> <Chars>{0,}
658 # <Chars> ::= (a-zA-Z0-9_)
659 # <NonDigit> ::= (a-zA-Z_)
661 # @param Ident: identifier to be checked
663 def IsValidIdentifier(Ident):
664 ReIdent = re.compile(r"^
[A
-Za
-z_
][0-9A
-Za
-z_
]*$
", re.DOTALL)
665 if ReIdent.match(Ident) == None:
670 ## IsValidDecVersionVal
672 # {(0-9){1,} "." (0-99)}
674 # @param Ver: version to be checked
676 def IsValidDecVersionVal(Ver):
677 ReVersion = re.compile(r"[0-9]+(\
.[0-9]{1,2})$
")
679 if ReVersion.match(Ver) == None:
687 # (A-Z)(a-zA-Z0-9){0,} and could not be "NULL
"
689 def IsValidLibName(LibName):
690 if LibName == 'NULL':
692 ReLibName = re.compile("^
[A
-Z
]+[a
-zA
-Z0
-9]*$
")
693 if not ReLibName.match(LibName):
700 # <UserId> ::= (a-zA-Z)(a-zA-Z0-9_.){0,}
701 # Words that contain period "." must be encapsulated in double quotation marks.
703 def IsValidUserId(UserId):
704 UserId = UserId.strip()
706 if UserId.startswith('"') and UserId.endswith('"'):
708 UserId = UserId[1:-1]
709 if not UserId or not UserId[0].isalpha():
711 for Char in UserId[1:]:
712 if not Char.isalnum() and not Char in '_.':
714 if Char == '.' and not Quoted: