예제 #1
0
def GetLanguageCode1766(LangName, File=None):
    return LangName

    length = len(LangName)
    if length == 2:
        if LangName.isalpha():
            for Key in gLANG_CONV_TABLE.keys():
                if gLANG_CONV_TABLE.get(Key) == LangName.lower():
                    return Key
    elif length == 3:
        if LangName.isalpha() and gLANG_CONV_TABLE.get(LangName.lower()):
            return LangName
        else:
            EdkLogger.Error("Unicode File Parser", ToolError.FORMAT_INVALID,
                            "Invalid RFC 1766 language code : %s" % LangName,
                            File)
    elif length == 5:
        if LangName[0:2].isalpha() and LangName[2] == '-':
            for Key in gLANG_CONV_TABLE.keys():
                if gLANG_CONV_TABLE.get(Key) == LangName[0:2].lower():
                    return Key
    elif length >= 6:
        if LangName[0:2].isalpha() and LangName[2] == '-':
            for Key in gLANG_CONV_TABLE.keys():
                if gLANG_CONV_TABLE.get(Key) == LangName[0:2].lower():
                    return Key
        if LangName[0:3].isalpha() and gLANG_CONV_TABLE.get(
                LangName.lower()) is None and LangName[3] == '-':
            for Key in gLANG_CONV_TABLE.keys():
                if Key == LangName[0:3].lower():
                    return Key

    EdkLogger.Error("Unicode File Parser", ToolError.FORMAT_INVALID,
                    "Invalid RFC 4646 language code : %s" % LangName, File)
예제 #2
0
def SaveFileOnChange(File, Content, IsBinaryFile=True):
    if os.path.exists(File):
        if IsBinaryFile:
            try:
                if Content == __FileHookOpen__(File, "rb").read():
                    return False
            except BaseException:
                Logger.Error(None, ToolError.FILE_OPEN_FAILURE, ExtraData=File)
        else:
            try:
                if Content == __FileHookOpen__(File, "r").read():
                    return False
            except BaseException:
                Logger.Error(None, ToolError.FILE_OPEN_FAILURE, ExtraData=File)

    CreateDirectory(os.path.dirname(File))
    if IsBinaryFile:
        try:
            FileFd = __FileHookOpen__(File, "wb")
            FileFd.write(Content)
            FileFd.close()
        except BaseException:
            Logger.Error(None, ToolError.FILE_CREATE_FAILURE, ExtraData=File)
    else:
        try:
            FileFd = __FileHookOpen__(File, "w")
            FileFd.write(Content)
            FileFd.close()
        except BaseException:
            Logger.Error(None, ToolError.FILE_CREATE_FAILURE, ExtraData=File)

    return True
예제 #3
0
def GetLanguageCode(LangName, IsCompatibleMode, File):
    length = len(LangName)
    if IsCompatibleMode:
        if length == 3 and LangName.isalpha():
            TempLangName = gLANG_CONV_TABLE.get(LangName.lower())
            if TempLangName is not None:
                return TempLangName
            return LangName
        else:
            EdkLogger.Error("Unicode File Parser", ToolError.FORMAT_INVALID,
                            "Invalid RFC 1766 language code : %s" % LangName,
                            File)
    if (LangName[0] == 'X' or LangName[0] == 'x') and LangName[1] == '-':
        return LangName
    if length == 2:
        if LangName.isalpha():
            return LangName
    elif length == 3:
        if LangName.isalpha() and gLANG_CONV_TABLE.get(
                LangName.lower()) is None:
            return LangName
    elif length == 5:
        if LangName[0:2].isalpha() and LangName[2] == '-':
            return LangName
    elif length >= 6:
        if LangName[0:2].isalpha() and LangName[2] == '-':
            return LangName
        if LangName[0:3].isalpha() and gLANG_CONV_TABLE.get(
                LangName.lower()) is None and LangName[3] == '-':
            return LangName

    EdkLogger.Error("Unicode File Parser", ToolError.FORMAT_INVALID,
                    "Invalid RFC 4646 language code : %s" % LangName, File)
예제 #4
0
def ParsePcdErrorCode(Value=None, ContainerFile=None, LineNum=None):
    try:
        if Value.strip().startswith((TAB_HEX_START, TAB_CAPHEX_START)):
            Base = 16
        else:
            Base = 10
        ErrorCode = int(Value, Base)
        if ErrorCode > PCD_ERR_CODE_MAX_SIZE or ErrorCode < 0:
            Logger.Error(
                'Parser',
                FORMAT_NOT_SUPPORTED,
                "The format %s of ErrorCode is not valid, should be UNIT32 type or long type"
                % Value,
                File=ContainerFile,
                Line=LineNum)
        ErrorCode = '0x%x' % ErrorCode
        return ErrorCode
    except ValueError as XStr:
        if XStr:
            pass
        Logger.Error(
            'Parser',
            FORMAT_NOT_SUPPORTED,
            "The format %s of ErrorCode is not valid, should be UNIT32 type or long type"
            % Value,
            File=ContainerFile,
            Line=LineNum)
예제 #5
0
def ValidateUNIFilePath(Path):
    Suffix = Path[Path.rfind(TAB_SPLIT):]

    #
    # Check if the suffix is one of the '.uni', '.UNI', '.Uni'
    #
    if Suffix not in TAB_UNI_FILE_SUFFIXS:
        Logger.Error("Unicode File Parser",
                     ToolError.FORMAT_INVALID,
                     Message=ST.ERR_UNI_FILE_SUFFIX_WRONG,
                     ExtraData=Path)

    #
    # Check if '..' in the file name(without suffix)
    #
    if (TAB_SPLIT + TAB_SPLIT) in Path:
        Logger.Error("Unicode File Parser",
                     ToolError.FORMAT_INVALID,
                     Message=ST.ERR_UNI_FILE_NAME_INVALID,
                     ExtraData=Path)

    #
    # Check if the file name is valid according to the DEC and INF specification
    #
    Pattern = '[a-zA-Z0-9_][a-zA-Z0-9_\-\.]*'
    FileName = Path.replace(Suffix, '')
    InvalidCh = re.sub(Pattern, '', FileName)
    if InvalidCh:
        Logger.Error("Unicode File Parser",
                     ToolError.FORMAT_INVALID,
                     Message=ST.ERR_INF_PARSER_FILE_NOT_EXIST_OR_NAME_INVALID,
                     ExtraData=Path)
예제 #6
0
def CheckFileList(QualifiedExt, FileList, ErrorStringExt, ErrorStringFullPath):
    if not FileList:
        return
    WorkspaceDir = GlobalData.gWORKSPACE
    WorkspaceDir = os.path.normpath(WorkspaceDir)
    for Item in FileList:
        Ext = os.path.splitext(Item)[1]
        if Ext.upper() != QualifiedExt.upper():
            Logger.Error("\nMkPkg", OPTION_VALUE_INVALID, \
                         ErrorStringExt % Item)

        Item = os.path.normpath(Item)
        Path = mws.join(WorkspaceDir, Item)
        if not os.path.exists(Path):
            Logger.Error("\nMkPkg", FILE_NOT_FOUND, ST.ERR_NOT_FOUND % Item)
        elif Item == Path:
            Logger.Error("\nMkPkg", OPTION_VALUE_INVALID,
                         ErrorStringFullPath % Item)
        elif not IsValidPath(Item, WorkspaceDir):
            Logger.Error("\nMkPkg", OPTION_VALUE_INVALID, \
                         ErrorStringExt % Item)

        if not os.path.split(Item)[0]:
            Logger.Error("\nMkPkg", OPTION_VALUE_INVALID, \
                         ST.ERR_INVALID_METAFILE_PATH % Item)
예제 #7
0
    def Extract(self, Which, ToDest):
        Which = os.path.normpath(Which)
        if Which not in self._Files:
            Logger.Error("PackagingTool", FILE_NOT_FOUND,
                            ExtraData="[%s] in %s" % (Which, self._FileName))
        try:
            FileContent = self._ZipFile.read(self._Files[Which])
        except BaseException as Xstr:
            Logger.Error("PackagingTool", FILE_DECOMPRESS_FAILURE,
                            ExtraData="[%s] in %s (%s)" % (Which, \
                                                           self._FileName, \
                                                           str(Xstr)))
        try:
            CreateDirectory(os.path.dirname(ToDest))
            if os.path.exists(ToDest) and not os.access(ToDest, os.W_OK):
                Logger.Warn("PackagingTool", \
                            ST.WRN_FILE_NOT_OVERWRITTEN % ToDest)
                return
            else:
                ToFile = __FileHookOpen__(ToDest, 'wb')
        except BaseException as Xstr:
            Logger.Error("PackagingTool", FILE_OPEN_FAILURE,
                            ExtraData="%s (%s)" % (ToDest, str(Xstr)))

        try:
            ToFile.write(FileContent)
            ToFile.close()
        except BaseException as Xstr:
            Logger.Error("PackagingTool", FILE_WRITE_FAILURE,
                            ExtraData="%s (%s)" % (ToDest, str(Xstr)))
예제 #8
0
def MacroParser(Line, FileName, SectionType, FileLocalMacros):
    MacroDefPattern = re.compile("^(DEFINE)[ \t]+")
    LineContent = Line[0]
    LineNo = Line[1]
    Match = MacroDefPattern.match(LineContent)
    if not Match:
        #
        # Not 'DEFINE/EDK_GLOBAL' statement, call decorated method
        #
        return None, None

    TokenList = GetSplitValueList(LineContent[Match.end(1):], \
                                  DataType.TAB_EQUAL_SPLIT, 1)
    #
    # Syntax check
    #
    if not TokenList[0]:
        Logger.Error('Parser', FORMAT_INVALID, ST.ERR_MACRONAME_NOGIVEN,
                        ExtraData=LineContent, File=FileName, Line=LineNo)
    if len(TokenList) < 2:
        Logger.Error('Parser', FORMAT_INVALID, ST.ERR_MACROVALUE_NOGIVEN,
                        ExtraData=LineContent, File=FileName, Line=LineNo)

    Name, Value = TokenList

    #
    # DEFINE defined macros
    #
    if SectionType == DataType.MODEL_META_DATA_HEADER:
        FileLocalMacros[Name] = Value

    ReIsValidMacroName = re.compile(r"^[A-Z][A-Z0-9_]*$", re.DOTALL)
    if ReIsValidMacroName.match(Name) is None:
        Logger.Error('Parser',
                     FORMAT_INVALID,
                     ST.ERR_MACRONAME_INVALID % (Name),
                     ExtraData=LineContent,
                     File=FileName,
                     Line=LineNo)

    # Validate MACRO Value
    #
    # <MacroDefinition> ::=  [<Comments>]{0,}
    #                       "DEFINE" <MACRO> "=" [{<PATH>} {<VALUE>}] <EOL>
    # <Value>           ::=  {<NumVal>} {<Boolean>} {<AsciiString>} {<GUID>}
    #                        {<CString>} {<UnicodeString>} {<CArray>}
    #
    # The definition of <NumVal>, <PATH>, <Boolean>, <GUID>, <CString>,
    # <UnicodeString>, <CArray> are subset of <AsciiString>.
    #
    ReIsValidMacroValue = re.compile(r"^[\x20-\x7e]*$", re.DOTALL)
    if ReIsValidMacroValue.match(Value) is None:
        Logger.Error('Parser',
                     FORMAT_INVALID,
                     ST.ERR_MACROVALUE_INVALID % (Value),
                     ExtraData=LineContent,
                     File=FileName,
                     Line=LineNo)

    return Name, Value
예제 #9
0
 def CheckRequiredFields(self):
     Ret = False
     if self.ItemObject.GetPackageSpecification() == '':
         Logger.Error(TOOL_NAME,
                      FILE_PARSE_FAILURE,
                      File=self._RawData.Filename,
                      ExtraData=ST.ERR_DECPARSE_DEFINE_REQUIRED %
                      DT.TAB_DEC_DEFINES_DEC_SPECIFICATION)
     elif self.ItemObject.GetPackageName() == '':
         Logger.Error(TOOL_NAME,
                      FILE_PARSE_FAILURE,
                      File=self._RawData.Filename,
                      ExtraData=ST.ERR_DECPARSE_DEFINE_REQUIRED %
                      DT.TAB_DEC_DEFINES_PACKAGE_NAME)
     elif self.ItemObject.GetPackageGuid() == '':
         Logger.Error(TOOL_NAME,
                      FILE_PARSE_FAILURE,
                      File=self._RawData.Filename,
                      ExtraData=ST.ERR_DECPARSE_DEFINE_REQUIRED %
                      DT.TAB_DEC_DEFINES_PACKAGE_GUID)
     elif self.ItemObject.GetPackageVersion() == '':
         Logger.Error(TOOL_NAME,
                      FILE_PARSE_FAILURE,
                      File=self._RawData.Filename,
                      ExtraData=ST.ERR_DECPARSE_DEFINE_REQUIRED %
                      DT.TAB_DEC_DEFINES_PACKAGE_VERSION)
     else:
         Ret = True
     return Ret
예제 #10
0
def SetPcdName(PcdItem, CurrentLineOfPcdItem, PcdItemObj):
    #
    # Only PCD Name specified
    # <PcdName> ::= <TokenSpaceGuidCName> "." <TokenCName>
    #
    PcdId = GetSplitValueList(PcdItem[0], DT.TAB_SPLIT)
    if len(PcdId) != 2:
        Logger.Error("InfParser",
                     ToolError.FORMAT_INVALID,
                     ST.ERR_INF_PARSER_PCD_NAME_FORMAT_ERROR,
                     File=CurrentLineOfPcdItem[2],
                     Line=CurrentLineOfPcdItem[1],
                     ExtraData=CurrentLineOfPcdItem[0])
    else:
        #
        # Validate PcdTokenSpaceGuidCName
        #
        if not IsValidCVariableName(PcdId[0]):
            Logger.Error("InfParser",
                         ToolError.FORMAT_INVALID,
                         ST.ERR_INF_PARSER_PCD_CVAR_GUID,
                         File=CurrentLineOfPcdItem[2],
                         Line=CurrentLineOfPcdItem[1],
                         ExtraData=PcdId[0])
        if not IsValidCVariableName(PcdId[1]):
            Logger.Error("InfParser",
                         ToolError.FORMAT_INVALID,
                         ST.ERR_INF_PARSER_PCD_CVAR_PCDCNAME,
                         File=CurrentLineOfPcdItem[2],
                         Line=CurrentLineOfPcdItem[1],
                         ExtraData=PcdId[1])
        PcdItemObj.SetTokenSpaceGuidCName(PcdId[0])
        PcdItemObj.SetCName(PcdId[1])

    return PcdItemObj
예제 #11
0
def UnZipDp(WorkspaceDir, DpPkgFileName, Index=1):
    ContentZipFile = None
    Logger.Quiet(ST.MSG_UZIP_PARSE_XML)
    DistFile = PackageFile(DpPkgFileName)

    DpDescFileName, ContentFileName = GetDPFile(DistFile.GetZipFile())

    TempDir = os.path.normpath(
        os.path.join(WorkspaceDir, "Conf/.tmp%s" % str(Index)))
    GlobalData.gUNPACK_DIR.append(TempDir)
    DistPkgFile = DistFile.UnpackFile(
        DpDescFileName, os.path.normpath(os.path.join(TempDir,
                                                      DpDescFileName)))
    if not DistPkgFile:
        Logger.Error("InstallPkg", FILE_NOT_FOUND,
                     ST.ERR_FILE_BROKEN % DpDescFileName)

    #
    # Generate distpkg
    #
    DistPkgObj = DistributionPackageXml()
    DistPkg = DistPkgObj.FromXml(DistPkgFile)
    if DistPkg.Header.RePackage == '':
        DistPkg.Header.RePackage = False
    if DistPkg.Header.ReadOnly == '':
        DistPkg.Header.ReadOnly = False

    #
    # unzip contents.zip file
    #
    ContentFile = DistFile.UnpackFile(
        ContentFileName,
        os.path.normpath(os.path.join(TempDir, ContentFileName)))
    if not ContentFile:
        Logger.Error("InstallPkg", FILE_NOT_FOUND,
                     ST.ERR_FILE_BROKEN % ContentFileName)

    #
    # Get file size
    #
    FileSize = os.path.getsize(ContentFile)

    if FileSize != 0:
        ContentZipFile = PackageFile(ContentFile)

    #
    # verify MD5 signature when existed
    #
    if DistPkg.Header.Signature != '':
        Md5Signature = md5(__FileHookOpen__(ContentFile, 'rb').read())
        if DistPkg.Header.Signature != Md5Signature.hexdigest():
            ContentZipFile.Close()
            Logger.Error("InstallPkg",
                         FILE_CHECKSUM_FAILURE,
                         ExtraData=ContentFile)

    return DistPkg, ContentZipFile, DpPkgFileName, DistFile
예제 #12
0
def Main(Options=None):

    try:
        DataBase = GlobalData.gDB
        if not Options.DistributionFile:
            Logger.Error("RmPkg",
                         OPTION_MISSING,
                         ExtraData=ST.ERR_SPECIFY_PACKAGE)
        WorkspaceDir = GlobalData.gWORKSPACE
        #
        # Prepare check dependency
        #
        Dep = DependencyRules(DataBase)

        #
        # Get the Dp information
        #
        StoredDistFile, Guid, Version = GetInstalledDpInfo(
            Options.DistributionFile, Dep, DataBase, WorkspaceDir)

        #
        # Check Dp depex
        #
        CheckDpDepex(Dep, Guid, Version, WorkspaceDir)

        #
        # remove distribution
        #
        RemoveDist(Guid, Version, StoredDistFile, DataBase, WorkspaceDir,
                   Options.Yes)

        Logger.Quiet(ST.MSG_FINISH)

        ReturnCode = 0

    except FatalError as XExcept:
        ReturnCode = XExcept.args[0]
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                         format_exc())
    except KeyboardInterrupt:
        ReturnCode = ABORT_ERROR
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                         format_exc())
    except:
        Logger.Error("\nRmPkg",
                     CODE_ERROR,
                     ST.ERR_UNKNOWN_FATAL_REMOVING_ERR,
                     ExtraData=ST.MSG_SEARCH_FOR_HELP % ST.MSG_EDKII_MAIL_ADDR,
                     RaiseError=False)
        Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                     format_exc())
        ReturnCode = CODE_ERROR
    return ReturnCode
    def InfAsBuiltLibraryParser(self, SectionString, InfSectionObject,
                                FileName):
        LibraryList = []
        LibInsFlag = False
        for Line in SectionString:
            LineContent = Line[0]
            LineNo = Line[1]

            if LineContent.strip() == '':
                LibInsFlag = False
                continue

            if not LineContent.strip().startswith("#"):
                Logger.Error('InfParser',
                             FORMAT_INVALID,
                             ST.ERR_LIB_CONTATIN_ASBUILD_AND_COMMON,
                             File=FileName,
                             Line=LineNo,
                             ExtraData=LineContent)

            if IsLibInstanceInfo(LineContent):
                LibInsFlag = True
                continue

            if LibInsFlag:
                LibGuid, LibVer = GetLibInstanceInfo(LineContent,
                                                     GlobalData.gWORKSPACE,
                                                     LineNo, FileName)
                #
                # If the VERSION_STRING is missing from the INF file, tool should default to "0".
                #
                if LibVer == '':
                    LibVer = '0'
                if LibGuid != '':
                    if (LibGuid, LibVer) not in LibraryList:
                        LibraryList.append((LibGuid, LibVer))

        #
        # Current section archs
        #
        KeyList = []
        Item = ['', '', '']
        for Item in self.LastSectionHeaderContent:
            if (Item[1], Item[2]) not in KeyList:
                KeyList.append((Item[1], Item[2]))

        if not InfSectionObject.SetLibraryClasses(LibraryList,
                                                  KeyList=KeyList):
            Logger.Error('InfParser',
                         FORMAT_INVALID,
                         ST.ERR_INF_PARSER_MODULE_SECTION_TYPE_ERROR %
                         ("[Library]"),
                         File=FileName,
                         Line=Item[3])
def GetGuidVerFormLibInstance(Guid, Version, WorkSpace, CurrentInfFileName):
    for InfFile in GetInfsFromWorkSpace(WorkSpace):
        try:
            if InfFile.strip().upper() == CurrentInfFileName.strip().upper():
                continue
            InfFile = InfFile.replace('\\', '/')
            if InfFile not in GlobalData.gLIBINSTANCEDICT:
                InfFileObj = open(InfFile, "r")
                GlobalData.gLIBINSTANCEDICT[InfFile] = InfFileObj
            else:
                InfFileObj = GlobalData.gLIBINSTANCEDICT[InfFile]

        except BaseException:
            Logger.Error("InfParser",
                         ToolError.FILE_READ_FAILURE,
                         ST.ERR_FILE_OPEN_FAILURE,
                         File=InfFile)
        try:
            FileLinesList = InfFileObj.readlines()
            FileLinesList = ProcessLineExtender(FileLinesList)

            ReFindFileGuidPattern = re.compile("^\s*FILE_GUID\s*=.*$")
            ReFindVerStringPattern = re.compile("^\s*VERSION_STRING\s*=.*$")

            for Line in FileLinesList:
                if ReFindFileGuidPattern.match(Line):
                    FileGuidString = Line
                if ReFindVerStringPattern.match(Line):
                    VerString = Line

            if FileGuidString:
                FileGuidString = GetSplitValueList(FileGuidString, '=', 1)[1]
            if VerString:
                VerString = GetSplitValueList(VerString, '=', 1)[1]

            if FileGuidString.strip().upper() == Guid.upper() and \
                VerString.strip().upper() == Version.upper():
                return Guid, Version

        except BaseException:
            Logger.Error("InfParser",
                         ToolError.FILE_READ_FAILURE,
                         ST.ERR_FILE_OPEN_FAILURE,
                         File=InfFile)
        finally:
            InfFileObj.close()

    return '', ''
예제 #15
0
def ParseDecPcdTailComment(TailCommentList, ContainerFile):
    assert (len(TailCommentList) == 1)
    TailComment = TailCommentList[0][0]
    LineNum = TailCommentList[0][1]

    Comment = TailComment.lstrip(" #")

    ReFindFirstWordRe = re.compile(r"""^([^ #]*)""", re.DOTALL)

    #
    # get first word and compare with SUP_MODULE_LIST
    #
    MatchObject = ReFindFirstWordRe.match(Comment)
    if not (MatchObject and MatchObject.group(1) in SUP_MODULE_LIST):
        return None, Comment

    #
    # parse line, it must have supported module type specified
    #
    if Comment.find(TAB_COMMENT_SPLIT) == -1:
        Comment += TAB_COMMENT_SPLIT
    SupMode, HelpStr = GetSplitValueList(Comment, TAB_COMMENT_SPLIT, 1)
    SupModuleList = []
    for Mod in GetSplitValueList(SupMode, TAB_SPACE_SPLIT):
        if not Mod:
            continue
        elif Mod not in SUP_MODULE_LIST:
            Logger.Error("UPT", FORMAT_INVALID,
                         ST.WRN_INVALID_MODULE_TYPE % Mod, ContainerFile,
                         LineNum)
        else:
            SupModuleList.append(Mod)

    return SupModuleList, HelpStr
예제 #16
0
    def InfHeaderParser(self,
                        Content,
                        InfHeaderObject2,
                        FileName,
                        IsBinaryHeader=False):
        if IsBinaryHeader:
            (Abstract, Description, Copyright,
             License) = ParseHeaderCommentSection(Content, FileName, True)
            if not Abstract or not Description or not Copyright or not License:
                Logger.Error('Parser',
                             FORMAT_INVALID,
                             ST.ERR_INVALID_BINARYHEADER_FORMAT,
                             File=FileName)
        else:
            (Abstract, Description, Copyright,
             License) = ParseHeaderCommentSection(Content, FileName)
        #
        # Not process file name now, for later usage.
        #
        if self.FileName:
            pass

        #
        # Insert Abstract, Description, CopyRight, License into header object
        #
        InfHeaderObject2.SetAbstract(Abstract)
        InfHeaderObject2.SetDescription(Description)
        InfHeaderObject2.SetCopyright(Copyright)
        InfHeaderObject2.SetLicense(License)
예제 #17
0
    def GetStringObject(self, Item):
        Language = ''
        Value = ''

        Name = Item.split()[1]
        # Check the string name is the upper character
        if Name != '':
            MatchString = re.match('[A-Z0-9_]+', Name, re.UNICODE)
            if MatchString is None or MatchString.end(0) != len(Name):
                EdkLogger.Error(
                    "Unicode File Parser", ToolError.FORMAT_INVALID,
                    'The string token name %s in UNI file %s must be upper case character.'
                    % (Name, self.File))
        LanguageList = Item.split(u'#language ')
        for IndexI in range(len(LanguageList)):
            if IndexI == 0:
                continue
            else:
                Language = LanguageList[IndexI].split()[0]
                #.replace(u'\r\n', u'')
                Value = \
                LanguageList[IndexI][LanguageList[IndexI].find(u'\"') + len(u'\"') : LanguageList[IndexI].rfind(u'\"')]
                Language = GetLanguageCode(Language, self.IsCompatibleMode,
                                           self.File)
                self.AddStringToList(Name, Language, Value)
예제 #18
0
    def Pack(self, Top, BaseDir):
        if not os.path.isdir(Top):
            Logger.Error("PackagingTool", FILE_UNKNOWN_ERROR, \
                         "%s is not a directory!" %Top)

        FilesToPack = []
        Cwd = os.getcwd()
        os.chdir(BaseDir)
        RelaDir = Top[Top.upper().find(BaseDir.upper()).\
                      join(len(BaseDir).join(1)):]

        for Root, Dirs, Files in os.walk(RelaDir):
            if 'CVS' in Dirs:
                Dirs.remove('CVS')
            if '.svn' in Dirs:
                Dirs.remove('.svn')

            for Dir in Dirs:
                if Dir.startswith('.'):
                    Dirs.remove(Dir)
            for File1 in Files:
                if File1.startswith('.'):
                    continue
                ExtName = os.path.splitext(File1)[1]
                #
                # skip '.dec', '.inf', '.dsc', '.fdf' files
                #
                if ExtName.lower() in ['.dec', '.inf', '.dsc', '.fdf']:
                    continue
                FilesToPack.append(os.path.join(Root, File1))
        self.PackFiles(FilesToPack)
        os.chdir(Cwd)
예제 #19
0
    def _GenPackages(self, Skip):
        Logger.Debug(2, "Generate %s ..." % DT.TAB_PACKAGES)
        #
        # Get all Packages
        #
        PackageObj = self.Parser.InfPackageSection.Packages
        #
        # Go through each arch
        #
        for PackageItemObj in PackageObj:
            #
            # Need package information for dependency check usage
            #
            PackageDependency = PackageDependencyObject()
            PackageDependency.SetPackageFilePath(NormPath(PackageItemObj.GetPackageName()))
            PackageDependency.SetSupArchList(ConvertArchList(PackageItemObj.GetSupArchList()))
            PackageDependency.SetFeatureFlag(PackageItemObj.GetFeatureFlagExp())

            PkgInfo = GetPkgInfoFromDec(mws.join(self.WorkSpace, NormPath(PackageItemObj.GetPackageName())))
            if PkgInfo[1] and PkgInfo[2]:
                PackageDependency.SetGuid(PkgInfo[1])
                PackageDependency.SetVersion(PkgInfo[2])
            elif Skip:
                continue
            else:
                Logger.Error("\nUPT", PARSER_ERROR,
                             ST.ERR_INF_GET_PKG_DEPENDENCY_FAIL % PackageItemObj.GetPackageName(), File=self.FullPath)

            PackageDependencyList = self.GetPackageDependencyList()
            PackageDependencyList.append(PackageDependency)
            self.SetPackageDependencyList(PackageDependencyList)
예제 #20
0
def Main(Options = None):
    if Options:
        pass

    try:
        DataBase = GlobalData.gDB
        InventoryDistInstalled(DataBase)
        ReturnCode = 0
    except FatalError as XExcept:
        ReturnCode = XExcept.args[0]
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + format_exc())
    except KeyboardInterrupt:
        ReturnCode = ABORT_ERROR
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + format_exc())
    except:
        ReturnCode = CODE_ERROR
        Logger.Error("\nInventoryWs",
                    CODE_ERROR,
                    ST.ERR_UNKNOWN_FATAL_INVENTORYWS_ERR,
                    ExtraData=ST.MSG_SEARCH_FOR_HELP % ST.MSG_EDKII_MAIL_ADDR,
                    RaiseError=False
                    )
        Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(),
            platform) + format_exc())

    if ReturnCode == 0:
        Logger.Quiet(ST.MSG_FINISH)

    return ReturnCode
예제 #21
0
def InstallFile(ContentZipFile, FromFile, ToFile, ReadOnly, Executable=False):
    if os.path.exists(os.path.normpath(ToFile)):
        pass
    else:
        if not ContentZipFile or not ContentZipFile.UnpackFile(
                FromFile, ToFile):
            Logger.Error("UPT", FILE_NOT_FOUND,
                         ST.ERR_INSTALL_FILE_FROM_EMPTY_CONTENT % FromFile)

        if ReadOnly:
            if not Executable:
                chmod(ToFile, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
            else:
                chmod(
                    ToFile, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
                    | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
        elif Executable:
            chmod(
                ToFile, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
                | stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH | stat.S_IEXEC
                | stat.S_IXGRP | stat.S_IXOTH)
        else:
            chmod(
                ToFile, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
                | stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)

    Md5Signature = md5(__FileHookOpen__(str(ToFile), 'rb').read())
    Md5Sum = Md5Signature.hexdigest()

    return Md5Sum
예제 #22
0
def CheckPcdNameRedefined(Module, DependentPcdNames):
    PcdObjs = []
    if not Module.GetBinaryFileList():
        PcdObjs += Module.GetPcdList()
    else:
        Binary = Module.GetBinaryFileList()[0]
        for AsBuild in Binary.GetAsBuiltList():
            PcdObjs += AsBuild.GetPatchPcdList() + AsBuild.GetPcdExList()

    for PcdObj in PcdObjs:
        PcdName = '.'.join(
            [PcdObj.GetTokenSpaceGuidCName(),
             PcdObj.GetCName()])
        IsPcdNameDefined = False
        for PcdNames in DependentPcdNames:
            if PcdName in PcdNames:
                if IsPcdNameDefined:
                    Logger.Error(
                        "\nUPT",
                        FORMAT_INVALID,
                        File=Module.GetFullPath(),
                        ExtraData=ST.ERR_INF_PARSER_ITEM_DUPLICATE_IN_DEC %
                        PcdName)
                else:
                    IsPcdNameDefined = True
예제 #23
0
 def _LoggerError(self, ErrorString):
     Logger.Error(TOOL_NAME,
                  FILE_PARSE_FAILURE,
                  File=self._RawData.Filename,
                  Line=self._RawData.LineIndex,
                  ExtraData=ErrorString +
                  ST.ERR_DECPARSE_LINE % self._RawData.CurrentLine)
예제 #24
0
def GetPkgInfoFromDec(Path):
    PkgName = None
    PkgGuid = None
    PkgVersion = None

    Path = Path.replace('\\', '/')

    if not os.path.exists(Path):
        Logger.Error("\nUPT", FILE_NOT_FOUND, File=Path)

    if Path in gPKG_INFO_DICT:
        return gPKG_INFO_DICT[Path]

    try:
        DecParser = None
        if Path not in GlobalData.gPackageDict:
            DecParser = Dec(Path)
            GlobalData.gPackageDict[Path] = DecParser
        else:
            DecParser = GlobalData.gPackageDict[Path]

        PkgName = DecParser.GetPackageName()
        PkgGuid = DecParser.GetPackageGuid()
        PkgVersion = DecParser.GetPackageVersion()
        gPKG_INFO_DICT[Path] = (PkgName, PkgGuid, PkgVersion)
        return PkgName, PkgGuid, PkgVersion
    except FatalError:
        return None, None, None
예제 #25
0
 def AssertChar(self, AssertChar, ErrorString, ErrorLineNum):
     if not self.Expect(AssertChar):
         Logger.Error(TOOL_NAME,
                      FILE_PARSE_FAILURE,
                      File=self._File,
                      Line=ErrorLineNum,
                      ExtraData=ErrorString)
예제 #26
0
    def _CheckSectionHeaders(self, Line, LineNo):
        if len(self.SectionHeaderContent) == 0:
            Logger.Error("InfParser",
                         FORMAT_INVALID,
                         ST.ERR_INF_PARSER_DEFINE_SECTION_HEADER_INVALID,
                         File=self.FullPath,
                         Line=LineNo, ExtraData=Line)
        else:
            for SectionItem in self.SectionHeaderContent:
                ArchList = []
                #
                # Not cover Depex/UserExtension section header
                # check.
                #
                if SectionItem[0].strip().upper() == DT.TAB_INF_FIXED_PCD.upper() or \
                    SectionItem[0].strip().upper() == DT.TAB_INF_PATCH_PCD.upper() or \
                    SectionItem[0].strip().upper() == DT.TAB_INF_PCD_EX.upper() or \
                    SectionItem[0].strip().upper() == DT.TAB_INF_PCD.upper() or \
                    SectionItem[0].strip().upper() == DT.TAB_INF_FEATURE_PCD.upper():
                    ArchList = GetSplitValueList(SectionItem[1].strip(), ' ')
                else:
                    ArchList = [SectionItem[1].strip()]

                for Arch in ArchList:
                    if (not IsValidArch(Arch)) and \
                        (SectionItem[0].strip().upper() != DT.TAB_DEPEX.upper()) and \
                        (SectionItem[0].strip().upper() != DT.TAB_USER_EXTENSIONS.upper()) and \
                        (SectionItem[0].strip().upper() != DT.TAB_COMMON_DEFINES.upper()):
                        Logger.Error("InfParser",
                                     FORMAT_INVALID,
                                     ST.ERR_INF_PARSER_DEFINE_FROMAT_INVALID%(SectionItem[1]),
                                     File=self.FullPath,
                                     Line=LineNo, ExtraData=Line)
                #
                # Check if the ModuleType is valid
                #
                ChkModSectionList = ['LIBRARYCLASSES']
                if (self.SectionHeaderContent[0][0].upper() in ChkModSectionList):
                    if SectionItem[2].strip().upper():
                        MoudleTypeList = GetSplitValueList(
                                    SectionItem[2].strip().upper())
                        if (not IsValidInfMoudleTypeList(MoudleTypeList)):
                            Logger.Error("InfParser",
                                         FORMAT_INVALID,
                                         ST.ERR_INF_PARSER_DEFINE_FROMAT_INVALID%(SectionItem[2]),
                                         File=self.FullPath, Line=LineNo,
                                         ExtraData=Line)
예제 #27
0
    def ReplaceForEval(self, ReplaceValue, IsRange=False, IsExpr=False):
        if self.FullPath:
            pass
        #
        # deal with "NOT EQ", "NOT LT", "NOT GT", "NOT LE", "NOT GE", "NOT NOT"
        #
        NOTNOT_Pattern = '[\t\s]*NOT[\t\s]+NOT[\t\s]*'
        NOTGE_Pattern = '[\t\s]*NOT[\t\s]+GE[\t\s]*'
        NOTLE_Pattern = '[\t\s]*NOT[\t\s]+LE[\t\s]*'
        NOTGT_Pattern = '[\t\s]*NOT[\t\s]+GT[\t\s]*'
        NOTLT_Pattern = '[\t\s]*NOT[\t\s]+LT[\t\s]*'
        NOTEQ_Pattern = '[\t\s]*NOT[\t\s]+EQ[\t\s]*'
        ReplaceValue = re.compile(NOTNOT_Pattern).sub('', ReplaceValue)
        ReplaceValue = re.compile(NOTLT_Pattern).sub('x >= ', ReplaceValue)
        ReplaceValue = re.compile(NOTGT_Pattern).sub('x <= ', ReplaceValue)
        ReplaceValue = re.compile(NOTLE_Pattern).sub('x > ', ReplaceValue)
        ReplaceValue = re.compile(NOTGE_Pattern).sub('x < ', ReplaceValue)
        ReplaceValue = re.compile(NOTEQ_Pattern).sub('x != ', ReplaceValue)

        if IsRange:
            ReplaceValue = ReplaceValue.replace('EQ', 'x ==')
            ReplaceValue = ReplaceValue.replace('LT', 'x <')
            ReplaceValue = ReplaceValue.replace('LE', 'x <=')
            ReplaceValue = ReplaceValue.replace('GT', 'x >')
            ReplaceValue = ReplaceValue.replace('GE', 'x >=')
            ReplaceValue = ReplaceValue.replace('XOR', 'x ^')
        elif IsExpr:
            ReplaceValue = ReplaceValue.replace('EQ', '==')
            ReplaceValue = ReplaceValue.replace('NE', '!=')
            ReplaceValue = ReplaceValue.replace('LT', '<')
            ReplaceValue = ReplaceValue.replace('LE', '<=')
            ReplaceValue = ReplaceValue.replace('GT', '>')
            ReplaceValue = ReplaceValue.replace('GE', '>=')
            ReplaceValue = ReplaceValue.replace('XOR', '^')

        ReplaceValue = ReplaceValue.replace('AND', 'and')
        ReplaceValue = ReplaceValue.replace('&&', ' and ')
        ReplaceValue = ReplaceValue.replace('xor', '^')
        ReplaceValue = ReplaceValue.replace('OR', 'or')
        ReplaceValue = ReplaceValue.replace('||', ' or ')
        ReplaceValue = ReplaceValue.replace('NOT', 'not')
        if ReplaceValue.find('!') >= 0 and ReplaceValue[ReplaceValue.index('!')
                                                        + 1] != '=':
            ReplaceValue = ReplaceValue.replace('!', ' not ')
        if '.' in ReplaceValue:
            Pattern = '[a-zA-Z0-9]{1,}\.[a-zA-Z0-9]{1,}'
            MatchedList = re.findall(Pattern, ReplaceValue)
            for MatchedItem in MatchedList:
                if MatchedItem not in self.PcdDefaultValueDict:
                    Logger.Error("Dec File Parser",
                                 FORMAT_INVALID,
                                 Message=ST.ERR_DECPARSE_PCD_NODEFINED %
                                 MatchedItem,
                                 File=self.FullPath)

                ReplaceValue = ReplaceValue.replace(
                    MatchedItem, self.PcdDefaultValueDict[MatchedItem])

        return ReplaceValue
예제 #28
0
 def AssertEnd(self, ErrorString, ErrorLineNum):
     self.__SkipWhitespace()
     if self._Index != self._StrLen:
         Logger.Error(TOOL_NAME,
                      FILE_PARSE_FAILURE,
                      File=self._File,
                      Line=ErrorLineNum,
                      ExtraData=ErrorString)
예제 #29
0
def RaiseParserError(Line, Section, File, Format='', LineNo= -1):
    if LineNo == -1:
        LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)
    ErrorMsg = ST.ERR_INVALID_NOTFOUND % (Line, Section)
    if Format != '':
        Format = "Correct format is " + Format
    Logger.Error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, \
                 ExtraData=Format, RaiseError=Logger.IS_RAISE_ERROR)
예제 #30
0
def GetSpecialStr2(ItemList, FileName, LineNo, SectionString):
    Str2 = ''
    #
    # S2 may be Platform or ModuleType
    #
    if len(ItemList) == 3:
        #
        # Except [LibraryClass], [Depex]
        # section can has more than 2 items in section header string,
        # others should report error.
        #
        if not (ItemList[0].upper() == DT.TAB_LIBRARY_CLASSES.upper() or \
                ItemList[0].upper() == DT.TAB_DEPEX.upper() or \
                ItemList[0].upper() == DT.TAB_USER_EXTENSIONS.upper()):
            if ItemList[2] != '':
                Logger.Error(
                    'Parser',
                    FORMAT_INVALID,
                    ST.ERR_INF_PARSER_SOURCE_SECTION_SECTIONNAME_INVALID %
                    (SectionString),
                    File=FileName,
                    Line=LineNo,
                    ExtraData=SectionString)
        Str2 = ItemList[2]
    elif len(ItemList) == 4:
        #
        # Except [UserExtension]
        # section can has 4 items in section header string,
        # others should report error.
        #
        if not ItemList[0].upper() == DT.TAB_USER_EXTENSIONS.upper(
        ) or ItemList[0].upper() == DT.TAB_DEPEX.upper():
            if ItemList[3] != '':
                Logger.Error('Parser', FORMAT_INVALID, ST.ERR_INF_PARSER_SOURCE_SECTION_SECTIONNAME_INVALID \
                             % (SectionString), File=FileName, Line=LineNo, ExtraData=SectionString)

        if not ItemList[0].upper() == DT.TAB_USER_EXTENSIONS.upper():
            Str2 = ItemList[2] + ' | ' + ItemList[3]
        else:
            Str2 = ItemList[2]

    elif len(ItemList) > 4:
        Logger.Error('Parser', FORMAT_INVALID, ST.ERR_INF_PARSER_SOURCE_SECTION_SECTIONNAME_INVALID \
                     % (SectionString), File=FileName, Line=LineNo, ExtraData=SectionString)

    return Str2