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.
22 from Library
.DataType
import MODULE_LIST
23 from Library
.DataType
import COMPONENT_TYPE_LIST
24 from Library
.DataType
import PCD_USAGE_TYPE_LIST_OF_MODULE
25 from Library
.DataType
import TAB_SPACE_SPLIT
26 from Library
.String
import GetSplitValueList
27 from Library
.ExpressionValidate
import IsValidBareCString
28 from Library
.ExpressionValidate
import IsValidFeatureFlagExp
30 ## __HexDigit() method
32 # Whether char input is a Hex data bit
34 # @param TempChar: The char to test
36 def __HexDigit(TempChar
):
37 if (TempChar
>= 'a' and TempChar
<= 'f') or \
38 (TempChar
>= 'A' and TempChar
<= 'F') \
39 or (TempChar
>= '0' and TempChar
<= '9'):
44 ## IsValidHex() method
46 # Whether char input is a Hex data.
48 # @param TempChar: The char to test
50 def IsValidHex(HexStr
):
51 if not HexStr
.upper().startswith("0X"):
53 CharList
= [c
for c
in HexStr
[2:] if not __HexDigit(c
)]
54 if len(CharList
) == 0:
59 ## Judge the input string is valid bool type or not.
61 # <TRUE> ::= {"TRUE"} {"true"} {"True"} {"0x1"} {"0x01"}
62 # <FALSE> ::= {"FALSE"} {"false"} {"False"} {"0x0"} {"0x00"}
63 # <BoolType> ::= {<TRUE>} {<FALSE>}
65 # @param BoolString: A string contained the value need to be judged.
67 def IsValidBoolType(BoolString
):
71 if BoolString
== 'TRUE' or \
72 BoolString
== 'True' or \
73 BoolString
== 'true' or \
74 BoolString
== '0x1' or \
80 elif BoolString
== 'FALSE' or \
81 BoolString
== 'False' or \
82 BoolString
== 'false' or \
83 BoolString
== '0x0' or \
92 ## Is Valid Module Type List or not
94 # @param ModuleTypeList: A list contain ModuleType strings need to be
97 def IsValidInfMoudleTypeList(ModuleTypeList
):
98 for ModuleType
in ModuleTypeList
:
99 return IsValidInfMoudleType(ModuleType
)
101 ## Is Valid Module Type or not
103 # @param ModuleType: A string contain ModuleType need to be judged.
105 def IsValidInfMoudleType(ModuleType
):
106 if ModuleType
in MODULE_LIST
:
111 ## Is Valid Component Type or not
113 # @param ComponentType: A string contain ComponentType need to be judged.
115 def IsValidInfComponentType(ComponentType
):
116 if ComponentType
.upper() in COMPONENT_TYPE_LIST
:
122 ## Is valid Tool Family or not
124 # @param ToolFamily: A string contain Tool Family need to be judged.
125 # Famlily := [A-Z]([a-zA-Z0-9])*
127 def IsValidToolFamily(ToolFamily
):
128 ReIsValieFamily
= re
.compile(r
"^[A-Z]+[A-Za-z0-9]{0,}$", re
.DOTALL
)
129 if ReIsValieFamily
.match(ToolFamily
) == None:
133 ## Is valid Tool TagName or not
135 # The TagName sample is MYTOOLS and VS2005.
137 # @param TagName: A string contain Tool TagName need to be judged.
139 def IsValidToolTagName(TagName
):
140 if TagName
.strip() == '':
142 if TagName
.strip() == '*':
144 if not IsValidWord(TagName
):
148 ## Is valid arch or not
150 # @param Arch The arch string need to be validated
151 # <OA> ::= (a-zA-Z)(A-Za-z0-9){0,}
152 # <arch> ::= {"IA32"} {"X64"} {"IPF"} {"EBC"} {<OA>}
154 # @param Arch: Input arch
156 def IsValidArch(Arch
):
159 ReIsValieArch
= re
.compile(r
"^[a-zA-Z]+[a-zA-Z0-9]{0,}$", re
.DOTALL
)
160 if ReIsValieArch
.match(Arch
) == None:
164 ## Is valid family or not
166 # <Family> ::= {"MSFT"} {"GCC"} {"INTEL"} {<Usr>} {"*"}
167 # <Usr> ::= [A-Z][A-Za-z0-9]{0,}
169 # @param family: The family string need to be validated
171 def IsValidFamily(Family
):
172 Family
= Family
.strip()
179 ReIsValidFamily
= re
.compile(r
"^[A-Z]+[A-Za-z0-9]{0,}$", re
.DOTALL
)
180 if ReIsValidFamily
.match(Family
) == None:
184 ## Is valid build option name or not
186 # @param BuildOptionName: The BuildOptionName string need to be validated
188 def IsValidBuildOptionName(BuildOptionName
):
189 if not BuildOptionName
:
192 ToolOptionList
= GetSplitValueList(BuildOptionName
, '_', 4)
194 if len(ToolOptionList
) != 5:
197 ReIsValidBuildOption1
= re
.compile(r
"^\s*(\*)|([A-Z][a-zA-Z0-9]*)$")
198 ReIsValidBuildOption2
= re
.compile(r
"^\s*(\*)|([a-zA-Z][a-zA-Z0-9]*)$")
200 if ReIsValidBuildOption1
.match(ToolOptionList
[0]) == None:
203 if ReIsValidBuildOption1
.match(ToolOptionList
[1]) == None:
206 if ReIsValidBuildOption2
.match(ToolOptionList
[2]) == None:
209 if ToolOptionList
[3] == "*" and ToolOptionList
[4] not in ['FAMILY', 'DLL', 'DPATH']:
216 # Check if pattern string matches total token
218 # @param ReString: regular string
219 # @param Token: Token to be matched
221 def IsValidToken(ReString
, Token
):
222 Match
= re
.compile(ReString
).match(Token
)
223 return Match
and Match
.start() == 0 and Match
.end() == len(Token
)
227 # Check if path exist
229 # @param Path: Absolute path or relative path to be checked
230 # @param Root: Root path
232 def IsValidPath(Path
, Root
):
234 OrigPath
= Path
.replace('\\', '/')
236 Path
= os
.path
.normpath(Path
).replace('\\', '/')
237 Root
= os
.path
.normpath(Root
).replace('\\', '/')
238 FullPath
= os
.path
.normpath(os
.path
.join(Root
, Path
)).replace('\\', '/')
240 if not os
.path
.exists(FullPath
):
244 # If Path is absolute path.
245 # It should be in Root.
247 if os
.path
.isabs(Path
):
248 if not Path
.startswith(Root
):
253 # Check illegal character
255 for Rel
in ['/', './', '../']:
256 if OrigPath
.startswith(Rel
):
258 for Rel
in ['//', '/./', '/../']:
261 for Rel
in ['/.', '/..', '/']:
262 if OrigPath
.endswith(Rel
):
265 Path
= Path
.rstrip('/')
268 # Check relative path
270 for Word
in Path
.split('/'):
271 if not IsValidWord(Word
):
276 ## IsValidInstallPath
278 # Check if an install path valid or not.
280 # Absolute path or path starts with '.' or path contains '..' are invalid.
282 # @param Path: path to be checked
284 def IsValidInstallPath(Path
):
285 if platform
.platform().find("Windows") >= 0:
286 if os
.path
.isabs(Path
):
291 if os
.path
.isabs(Path
):
293 if Path
.startswith('.'):
296 if Path
.find('..') != -1:
302 ## IsValidCFormatGuid
304 # Check if GUID format has the from of {8,4,4,{2,2,2,2,2,2,2,2}}
306 # @param Guid: Guid to be checked
308 def IsValidCFormatGuid(Guid
):
310 # Valid: { 0xf0b11735, 0x87a0, 0x4193, {0xb2, 0x66, 0x53, 0x8c, 0x38,
311 # 0xaf, 0x48, 0xce }}
312 # Invalid: { 0xf0b11735, 0x87a0, 0x4193, {0xb2, 0x66, 0x53, 0x8c, 0x38,
313 # 0xaf, 0x48, 0xce }} 0x123
314 # Invalid: { 0xf0b1 1735, 0x87a0, 0x4193, {0xb2, 0x66, 0x53, 0x8c, 0x38,
315 # 0xaf, 0x48, 0xce }}
317 List
= ['{', 10, ',', 6, ',', 6, ',{', 4, ',', 4, ',', 4,
318 ',', 4, ',', 4, ',', 4, ',', 4, ',', 4, '}}']
323 if Char
not in '{},\t ':
329 # Index may out of bound
331 if not SepValue
or SepValue
!= List
[Index
]:
336 if not Value
.startswith('0x') and not Value
.startswith('0X'):
340 # Index may out of bound
342 if type(List
[Index
]) != type(1) or \
343 len(Value
) > List
[Index
] or len(Value
) < 3:
347 # Check if string can be converted to integer
348 # Throw exception if not
351 except BaseException
:
353 # Exception caught means invalid format
361 return SepValue
== '}}' and Value
== ''
365 # Check whether the PCD type is valid
367 # @param PcdTypeString: The PcdType string need to be checked.
369 def IsValidPcdType(PcdTypeString
):
370 if PcdTypeString
.upper() in PCD_USAGE_TYPE_LIST_OF_MODULE
:
377 # Check whether the word is valid.
378 # <Word> ::= (a-zA-Z0-9_)(a-zA-Z0-9_-){0,} Alphanumeric characters with
380 # dash "-" and/or underscore "_" characters. No whitespace
381 # characters are permitted.
383 # @param Word: The word string need to be checked.
385 def IsValidWord(Word
):
389 # The first char should be alpha, _ or Digit.
391 if not Word
[0].isalnum() and \
392 not Word
[0] == '_' and \
393 not Word
[0].isdigit():
397 for Char
in Word
[1:]:
398 if (not Char
.isalpha()) and \
399 (not Char
.isdigit()) and \
404 if Char
== '.' and LastChar
== '.':
413 # Check whether the SimpleWord is valid.
414 # <SimpleWord> ::= (a-zA-Z0-9)(a-zA-Z0-9_-){0,}
415 # A word that cannot contain a period character.
417 # @param Word: The word string need to be checked.
419 def IsValidSimpleWord(Word
):
420 ReIsValidSimpleWord
= \
421 re
.compile(r
"^[0-9A-Za-z][0-9A-Za-z\-_]*$", re
.DOTALL
)
426 if not ReIsValidSimpleWord
.match(Word
):
433 # Check whether the decimal version is valid.
434 # <DecVersion> ::= (0-9){1,} ["." (0-9){1,}]
436 # @param Word: The word string need to be checked.
438 def IsValidDecVersion(Word
):
439 if Word
.find('.') > -1:
440 ReIsValidDecVersion
= re
.compile(r
"[0-9]+\.?[0-9]+$")
442 ReIsValidDecVersion
= re
.compile(r
"[0-9]+$")
443 if ReIsValidDecVersion
.match(Word
) == None:
449 # Check whether the hex version is valid.
450 # <HexVersion> ::= "0x" <Major> <Minor>
451 # <Major> ::= <HexDigit>{4}
452 # <Minor> ::= <HexDigit>{4}
454 # @param Word: The word string need to be checked.
456 def IsValidHexVersion(Word
):
457 ReIsValidHexVersion
= re
.compile(r
"[0][xX][0-9A-Fa-f]{8}$", re
.DOTALL
)
458 if ReIsValidHexVersion
.match(Word
) == None:
463 ## IsValidBuildNumber
465 # Check whether the BUILD_NUMBER is valid.
466 # ["BUILD_NUMBER" "=" <Integer>{1,4} <EOL>]
468 # @param Word: The BUILD_NUMBER string need to be checked.
470 def IsValidBuildNumber(Word
):
471 ReIsValieBuildNumber
= re
.compile(r
"[0-9]{1,4}$", re
.DOTALL
)
472 if ReIsValieBuildNumber
.match(Word
) == None:
479 # Check whether the Depex is valid.
481 # @param Word: The Depex string need to be checked.
483 def IsValidDepex(Word
):
484 Index
= Word
.upper().find("PUSH")
486 return IsValidCFormatGuid(Word
[Index
+4:].strip())
488 ReIsValidCName
= re
.compile(r
"^[A-Za-z_][0-9A-Za-z_\s\.]*$", re
.DOTALL
)
489 if ReIsValidCName
.match(Word
) == None:
494 ## IsValidNormalizedString
497 # <NormalizedString> ::= <DblQuote> [{<Word>} {<Space>}]{1,} <DblQuote>
500 # @param String: string to be checked
502 def IsValidNormalizedString(String
):
510 StringList
= GetSplitValueList(String
, TAB_SPACE_SPLIT
)
512 for Item
in StringList
:
515 if not IsValidWord(Item
):
522 # Check whether the IdString is valid.
524 # @param IdString: The IdString need to be checked.
526 def IsValidIdString(String
):
527 if IsValidSimpleWord(String
.strip()):
530 if String
.strip().startswith('"') and \
531 String
.strip().endswith('"'):
532 String
= String
[1:-1]
533 if String
.strip() == "":
535 if IsValidNormalizedString(String
):
540 ## IsValidVersionString
542 # Check whether the VersionString is valid.
543 # <AsciiString> ::= [ [<WhiteSpace>]{0,} [<AsciiChars>]{0,} ] {0,}
544 # <WhiteSpace> ::= {<Tab>} {<Space>}
547 # <AsciiChars> ::= (0x21 - 0x7E)
549 # @param VersionString: The VersionString need to be checked.
551 def IsValidVersionString(VersionString
):
552 VersionString
= VersionString
.strip()
553 for Char
in VersionString
:
554 if not (Char
>= 0x21 and Char
<= 0x7E):
561 # Check whether the PcdValue is valid.
563 # @param VersionString: The PcdValue need to be checked.
565 def IsValidPcdValue(PcdValue
):
566 for Char
in PcdValue
:
567 if Char
== '\n' or Char
== '\t' or Char
== '\f':
573 if IsValidFeatureFlagExp(PcdValue
, True)[0]:
577 # <Number> ::= {<Integer>} {<HexNumber>}
578 # <Integer> ::= {(0-9)} {(1-9)(0-9){1,}}
579 # <HexNumber> ::= "0x" <HexDigit>{1,}
580 # <HexDigit> ::= (a-fA-F0-9)
582 if IsValidHex(PcdValue
):
585 ReIsValidIntegerSingle
= re
.compile(r
"^\s*[0-9]\s*$", re
.DOTALL
)
586 if ReIsValidIntegerSingle
.match(PcdValue
) != None:
589 ReIsValidIntegerMulti
= re
.compile(r
"^\s*[1-9][0-9]+\s*$", re
.DOTALL
)
590 if ReIsValidIntegerMulti
.match(PcdValue
) != None:
595 # <StringVal> ::= {<StringType>} {<Array>} {"$(" <MACRO> ")"}
596 # <StringType> ::= {<UnicodeString>} {<CString>}
598 ReIsValidStringType
= re
.compile(r
"^\s*[\"L
].*[\"]\s
*$
")
599 if ReIsValidStringType.match(PcdValue):
601 if PcdValue.strip().startswith('L\"'):
602 StringValue = PcdValue.strip().lstrip('L\"').rstrip('\"')
603 if IsValidBareCString(StringValue):
605 elif PcdValue.strip().startswith('\"'):
606 StringValue = PcdValue.strip().lstrip('\"').rstrip('\"')
607 if IsValidBareCString(StringValue):
613 # <Array> ::= {<CArray>} {<NList>} {<CFormatGUID>}
614 # <CArray> ::= "{" [<NList>] <CArray>{0,} "}"
615 # <NList> ::= <HexByte> ["," <HexByte>]{0,}
616 # <HexDigit> ::= (a-fA-F0-9)
617 # <HexByte> ::= "0x
" <HexDigit>{1,2}
619 if IsValidCFormatGuid(PcdValue):
622 ReIsValidByteHex = re.compile(r"^\s
*0x
[0-9a
-fA
-F
]{1,2}\s
*$
", re.DOTALL)
623 if PcdValue.strip().startswith('{') and PcdValue.strip().endswith('}') :
624 StringValue = PcdValue.strip().lstrip('{').rstrip('}')
625 ValueList = StringValue.split(',')
627 for ValueItem in ValueList:
628 if not ReIsValidByteHex.match(ValueItem.strip()):
638 ValueList = PcdValue.split(',')
639 for ValueItem in ValueList:
640 if not ReIsValidByteHex.match(ValueItem.strip()):
648 ## IsValidCVariableName
650 # Check whether the PcdValue is valid.
652 # @param VersionString: The PcdValue need to be checked.
654 def IsValidCVariableName(CName):
655 ReIsValidCName = re.compile(r"^
[A
-Za
-z_
][0-9A
-Za
-z_
]*$
", re.DOTALL)
656 if ReIsValidCName.match(CName) == None:
663 # <Identifier> ::= <NonDigit> <Chars>{0,}
664 # <Chars> ::= (a-zA-Z0-9_)
665 # <NonDigit> ::= (a-zA-Z_)
667 # @param Ident: identifier to be checked
669 def IsValidIdentifier(Ident):
670 ReIdent = re.compile(r"^
[A
-Za
-z_
][0-9A
-Za
-z_
]*$
", re.DOTALL)
671 if ReIdent.match(Ident) == None:
676 ## IsValidDecVersionVal
678 # {(0-9){1,} "." (0-99)}
680 # @param Ver: version to be checked
682 def IsValidDecVersionVal(Ver):
683 ReVersion = re.compile(r"[0-9]+(\
.[0-9]{1,2})$
")
685 if ReVersion.match(Ver) == None:
693 # (A-Z)(a-zA-Z0-9){0,} and could not be "NULL
"
695 def IsValidLibName(LibName):
696 if LibName == 'NULL':
698 ReLibName = re.compile("^
[A
-Z
]+[a
-zA
-Z0
-9]*$
")
699 if not ReLibName.match(LibName):
706 # <UserId> ::= (a-zA-Z)(a-zA-Z0-9_.){0,}
707 # Words that contain period "." must be encapsulated in double quotation marks.
709 def IsValidUserId(UserId):
710 UserId = UserId.strip()
712 if UserId.startswith('"') and UserId.endswith('"'):
714 UserId = UserId[1:-1]
715 if not UserId or not UserId[0].isalpha():
717 for Char in UserId[1:]:
718 if not Char.isalnum() and not Char in '_.':
720 if Char == '.' and not Quoted: