Пример #1
0
    def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf = None, Dict = {}):
        #
        # Prepare the parameter of GenSection
        #
        if FfsInf != None:
            self.Alignment = FfsInf.__ExtendMacro__(self.Alignment)
            self.StringData = FfsInf.__ExtendMacro__(self.StringData)
            self.FileName = FfsInf.__ExtendMacro__(self.FileName)

        OutputFile = os.path.join(OutputPath, ModuleName + 'SEC' + SecNum + Ffs.SectionSuffix.get('UI'))

        if self.StringData != None :
            NameString = self.StringData
        elif self.FileName != None:
            FileNameStr = GenFdsGlobalVariable.ReplaceWorkspaceMacro(self.FileName)
            FileNameStr = GenFdsGlobalVariable.MacroExtend(FileNameStr, Dict)
            FileObj = open(FileNameStr, 'r')
            NameString = FileObj.read()
            NameString = '\"' + NameString + "\""
            FileObj.close()
        else:
            NameString = ''

        GenFdsGlobalVariable.GenerateSection(OutputFile, None, 'EFI_SECTION_USER_INTERFACE', Ui=NameString)

        OutputFileList = []
        OutputFileList.append(OutputFile)
        return OutputFileList, self.Alignment
Пример #2
0
    def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf = None, Dict = {}):

        if FfsInf != None:
            self.CompType = FfsInf.__ExtendMacro__(self.CompType)
            self.Alignment = FfsInf.__ExtendMacro__(self.Alignment)

        SectFiles = tuple()
        Index = 0
        for Sect in self.SectionList:
            Index = Index + 1
            SecIndex = '%s.%d' %(SecNum, Index)
            ReturnSectList, AlignValue = Sect.GenSection(OutputPath, ModuleName, SecIndex, KeyStringList, FfsInf, Dict)
            if ReturnSectList != []:
                for FileData in ReturnSectList:
                   SectFiles += (FileData,)


        OutputFile = OutputPath + \
                     os.sep     + \
                     ModuleName + \
                     'SEC'      + \
                     SecNum     + \
                     Ffs.SectionSuffix['COMPRESS']
        OutputFile = os.path.normpath(OutputFile)

        GenFdsGlobalVariable.GenerateSection(OutputFile, SectFiles, Section.Section.SectionType['COMPRESS'],
                                             CompressionType=self.CompTypeDict[self.CompType])
        OutputFileList = []
        OutputFileList.append(OutputFile)
        return OutputFileList, self.Alignment
Пример #3
0
    def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf=None, Dict={}, IsMakefile = False):
        #
        # Prepare the parameter of GenSection
        #
        if FfsInf is not None:
            self.Alignment = FfsInf.__ExtendMacro__(self.Alignment)
            self.BuildNum = FfsInf.__ExtendMacro__(self.BuildNum)
            self.StringData = FfsInf.__ExtendMacro__(self.StringData)
            self.FileName = FfsInf.__ExtendMacro__(self.FileName)

        OutputFile = os.path.join(OutputPath,
                                  ModuleName + SUP_MODULE_SEC + SecNum + Ffs.SectionSuffix.get('VERSION'))
        OutputFile = os.path.normpath(OutputFile)

        # Get String Data
        StringData = ''
        if self.StringData is not None:
            StringData = self.StringData
        elif self.FileName is not None:
            FileNameStr = GenFdsGlobalVariable.ReplaceWorkspaceMacro(self.FileName)
            FileNameStr = GenFdsGlobalVariable.MacroExtend(FileNameStr, Dict)
            FileObj = open(FileNameStr, 'r')
            StringData = FileObj.read()
            StringData = '"' + StringData + '"'
            FileObj.close()
        else:
            StringData = ''
        GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',
                                             Ver=StringData, BuildNumber=self.BuildNum, IsMakefile=IsMakefile)
        OutputFileList = []
        OutputFileList.append(OutputFile)
        return OutputFileList, self.Alignment
Пример #4
0
    def GenSection(self,
                   OutputPath,
                   ModuleName,
                   SecNum,
                   keyStringList,
                   FfsFile=None,
                   Dict=None,
                   IsMakefile=False):
        if self.ExpressionProcessed == False:
            self.Expression = self.Expression.replace("\n",
                                                      " ").replace("\r", " ")
            ExpList = self.Expression.split()

            for Exp in ExpList:
                if Exp.upper() not in ('AND', 'OR', 'NOT', 'TRUE', 'FALSE',
                                       'SOR', 'BEFORE', 'AFTER', 'END'):
                    GuidStr = self.__FindGuidValue(Exp)
                    if GuidStr is None:
                        EdkLogger.error(
                            "GenFds", RESOURCE_NOT_AVAILABLE,
                            "Depex GUID %s could not be found in build DB! (ModuleName: %s)"
                            % (Exp, ModuleName))

                    self.Expression = self.Expression.replace(Exp, GuidStr)

            self.Expression = self.Expression.strip()
            self.ExpressionProcessed = True

        if self.DepexType == 'PEI_DEPEX_EXP':
            ModuleType = 'PEIM'
            SecType = 'PEI_DEPEX'
        elif self.DepexType == 'DXE_DEPEX_EXP':
            ModuleType = 'DXE_DRIVER'
            SecType = 'DXE_DEPEX'
        elif self.DepexType == 'SMM_DEPEX_EXP':
            ModuleType = 'DXE_SMM_DRIVER'
            SecType = 'SMM_DEPEX'
        else:
            EdkLogger.error(
                "GenFds", FORMAT_INVALID,
                "Depex type %s is not valid for module %s" %
                (self.DepexType, ModuleName))

        InputFile = os.path.join(OutputPath,
                                 ModuleName + 'SEC' + SecNum + '.depex')
        InputFile = os.path.normpath(InputFile)
        Depex = DependencyExpression(self.Expression, ModuleType)
        Depex.Generate(InputFile)

        OutputFile = os.path.join(OutputPath,
                                  ModuleName + 'SEC' + SecNum + '.dpx')
        OutputFile = os.path.normpath(OutputFile)

        GenFdsGlobalVariable.GenerateSection(
            OutputFile, [InputFile],
            Section.Section.SectionType.get(SecType),
            IsMakefile=IsMakefile)
        return [OutputFile], self.Alignment
Пример #5
0
    def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf = None, Dict = {}):

        OutputFileList = []
        if self.FvFileType != None:
            FileList, IsSect = Section.Section.GetFileList(FfsInf, self.FvFileType, self.FvFileExtension)
            if IsSect :
                return FileList, self.Alignment

            Num = SecNum

            for FileName in FileList:
                OutputFile = os.path.join(OutputPath, ModuleName + 'SEC' + Num + Ffs.SectionSuffix.get("FV_IMAGE"))
                GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileName], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE')
                OutputFileList.append(OutputFile)
            return OutputFileList, self.Alignment
        #
        # Generate Fv
        #
        if self.FvName != None:
            Buffer = StringIO.StringIO('')
            Fv = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(self.FvName)
            if Fv != None:
                self.Fv = Fv
                FvFileName = Fv.AddToBuffer(Buffer, self.FvAddr, MacroDict = Dict)
                if Fv.FvAlignment != None:
                    if self.Alignment == None:
                        self.Alignment = Fv.FvAlignment
                    else:
                        if GenFdsGlobalVariable.GetAlignment (Fv.FvAlignment) > GenFdsGlobalVariable.GetAlignment (self.Alignment):
                            self.Alignment = Fv.FvAlignment
            else:
                if self.FvFileName != None:
                    FvFileName = GenFdsGlobalVariable.ReplaceWorkspaceMacro(self.FvFileName)
                else:
                    EdkLogger.error("GenFds", GENFDS_ERROR, "FvImageSection Failed! %s NOT found in FDF" % self.FvName)

            #
            # Prepare the parameter of GenSection
            #
            OutputFile = os.path.join(OutputPath, ModuleName + 'SEC' + SecNum + Ffs.SectionSuffix.get("FV_IMAGE"))
            GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileName], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE')
            OutputFileList.append(OutputFile)

            return OutputFileList, self.Alignment
Пример #6
0
    def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf = None, Dict = {}, IsMakefile = False):

        if FfsInf is not None:
            self.CompType = FfsInf.__ExtendMacro__(self.CompType)
            self.Alignment = FfsInf.__ExtendMacro__(self.Alignment)

        SectFiles = tuple()
        SectAlign = []
        Index = 0
        MaxAlign = None
        for Sect in self.SectionList:
            Index = Index + 1
            SecIndex = '%s.%d' %(SecNum, Index)
            ReturnSectList, AlignValue = Sect.GenSection(OutputPath, ModuleName, SecIndex, KeyStringList, FfsInf, Dict, IsMakefile=IsMakefile)
            if AlignValue is not None:
                if MaxAlign is None:
                    MaxAlign = AlignValue
                if GenFdsGlobalVariable.GetAlignment (AlignValue) > GenFdsGlobalVariable.GetAlignment (MaxAlign):
                    MaxAlign = AlignValue
            if ReturnSectList != []:
                if AlignValue is None:
                    AlignValue = "1"
                for FileData in ReturnSectList:
                    SectFiles += (FileData,)
                    SectAlign.append(AlignValue)

        OutputFile = OutputPath + \
                     os.sep     + \
                     ModuleName + \
                     'SEC'      + \
                     SecNum     + \
                     Ffs.SectionSuffix['COMPRESS']
        OutputFile = os.path.normpath(OutputFile)
        DummyFile = OutputFile + '.dummy'
        GenFdsGlobalVariable.GenerateSection(DummyFile, SectFiles, InputAlign=SectAlign, IsMakefile=IsMakefile)

        GenFdsGlobalVariable.GenerateSection(OutputFile, [DummyFile], Section.Section.SectionType['COMPRESS'],
                                             CompressionType=self.CompTypeDict[self.CompType], IsMakefile=IsMakefile)
        OutputFileList = []
        OutputFileList.append(OutputFile)
        return OutputFileList, self.Alignment
Пример #7
0
    def GenSection(self,
                   OutputPath,
                   ModuleName,
                   SecNum,
                   KeyStringList,
                   FfsInf=None,
                   Dict={},
                   IsMakefile=False):
        #
        # Prepare the parameter of GenSection
        #
        if FfsInf is not None:
            self.Alignment = FfsInf.__ExtendMacro__(self.Alignment)
            self.StringData = FfsInf.__ExtendMacro__(self.StringData)
            self.FileName = FfsInf.__ExtendMacro__(self.FileName)

        OutputFile = os.path.join(
            OutputPath, ModuleName + SUP_MODULE_SEC + SecNum +
            Ffs.SectionSuffix.get(BINARY_FILE_TYPE_UI))

        if self.StringData is not None:
            NameString = self.StringData
        elif self.FileName is not None:
            FileNameStr = GenFdsGlobalVariable.ReplaceWorkspaceMacro(
                self.FileName)
            FileNameStr = GenFdsGlobalVariable.MacroExtend(FileNameStr, Dict)
            FileObj = open(FileNameStr, 'r')
            NameString = FileObj.read()
            FileObj.close()
        else:
            NameString = ''
        GenFdsGlobalVariable.GenerateSection(OutputFile,
                                             None,
                                             'EFI_SECTION_USER_INTERFACE',
                                             Ui=NameString,
                                             IsMakefile=IsMakefile)

        OutputFileList = []
        OutputFileList.append(OutputFile)
        return OutputFileList, self.Alignment
Пример #8
0
    def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf = None, Dict = {}, IsMakefile = False) :
        
        if self.FileName is not None and self.FileName.startswith('PCD('):
            self.FileName = GenFdsGlobalVariable.GetPcdValue(self.FileName)
        """Prepare the parameter of GenSection"""
        if FfsInf is not None :
            InfFileName = FfsInf.InfFileName
            SectionType = FfsInf.__ExtendMacro__(self.SectionType)
            Filename = FfsInf.__ExtendMacro__(self.FileName)
            BuildNum = FfsInf.__ExtendMacro__(self.BuildNum)
            StringData = FfsInf.__ExtendMacro__(self.StringData)
            ModuleNameStr = FfsInf.__ExtendMacro__('$(MODULE_NAME)')
            NoStrip = True
            if FfsInf.ModuleType in (SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MODULE_PEIM) and SectionType in (BINARY_FILE_TYPE_TE, BINARY_FILE_TYPE_PE32):
                if FfsInf.KeepReloc is not None:
                    NoStrip = FfsInf.KeepReloc
                elif FfsInf.KeepRelocFromRule is not None:
                    NoStrip = FfsInf.KeepRelocFromRule
                elif self.KeepReloc is not None:
                    NoStrip = self.KeepReloc
                elif FfsInf.ShadowFromInfFile is not None:
                    NoStrip = FfsInf.ShadowFromInfFile
        else:
            EdkLogger.error("GenFds", GENFDS_ERROR, "Module %s apply rule for None!" %ModuleName)

        """If the file name was pointed out, add it in FileList"""
        FileList = []
        if Filename is not None:
            Filename = GenFdsGlobalVariable.MacroExtend(Filename, Dict)
            # check if the path is absolute or relative
            if os.path.isabs(Filename):
                Filename = os.path.normpath(Filename)
            else:
                Filename = os.path.normpath(os.path.join(FfsInf.EfiOutputPath, Filename))

            if not self.Optional:
                FileList.append(Filename)
            elif os.path.exists(Filename):
                FileList.append(Filename)
            elif IsMakefile:
                SuffixMap = FfsInf.GetFinalTargetSuffixMap()
                if '.depex' in SuffixMap:
                    FileList.append(Filename)
        else:
            FileList, IsSect = Section.Section.GetFileList(FfsInf, self.FileType, self.FileExtension, Dict, IsMakefile=IsMakefile)
            if IsSect :
                return FileList, self.Alignment

        Index = 0
        Align = self.Alignment

        """ If Section type is 'VERSION'"""
        OutputFileList = []
        if SectionType == 'VERSION':

            InfOverrideVerString = False
            if FfsInf.Version is not None:
                #StringData = FfsInf.Version
                BuildNum = FfsInf.Version
                InfOverrideVerString = True

            if InfOverrideVerString:
                #VerTuple = ('-n', '"' + StringData + '"')
                if BuildNum is not None and BuildNum != '':
                    BuildNumTuple = ('-j', BuildNum)
                else:
                    BuildNumTuple = tuple()

                Num = SecNum
                OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType))
                GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',
                                                    #Ui=StringData,
                                                    Ver=BuildNum,
                                                    IsMakefile=IsMakefile)
                OutputFileList.append(OutputFile)

            elif FileList != []:
                for File in FileList:
                    Index = Index + 1
                    Num = '%s.%d' %(SecNum, Index)
                    OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType))
                    f = open(File, 'r')
                    VerString = f.read()
                    f.close()
                    BuildNum = VerString
                    if BuildNum is not None and BuildNum != '':
                        BuildNumTuple = ('-j', BuildNum)
                    GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',
                                                        #Ui=VerString,
                                                        Ver=BuildNum,
                                                        IsMakefile=IsMakefile)
                    OutputFileList.append(OutputFile)

            else:
                BuildNum = StringData
                if BuildNum is not None and BuildNum != '':
                    BuildNumTuple = ('-j', BuildNum)
                else:
                    BuildNumTuple = tuple()
                BuildNumString = ' ' + ' '.join(BuildNumTuple)

                #if VerString == '' and 
                if BuildNumString == '':
                    if self.Optional == True :
                        GenFdsGlobalVariable.VerboseLogger( "Optional Section don't exist!")
                        return [], None
                    else:
                        EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s miss Version Section value" %InfFileName)
                Num = SecNum
                OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType))
                GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',
                                                    #Ui=VerString,
                                                    Ver=BuildNum,
                                                    IsMakefile=IsMakefile)
                OutputFileList.append(OutputFile)

        #
        # If Section Type is BINARY_FILE_TYPE_UI
        #
        elif SectionType == BINARY_FILE_TYPE_UI:

            InfOverrideUiString = False
            if FfsInf.Ui is not None:
                StringData = FfsInf.Ui
                InfOverrideUiString = True

            if InfOverrideUiString:
                Num = SecNum
                if IsMakefile and StringData == ModuleNameStr:
                    StringData = "$(MODULE_NAME)"
                OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType))
                GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE',
                                                     Ui=StringData, IsMakefile=IsMakefile)
                OutputFileList.append(OutputFile)

            elif FileList != []:
                for File in FileList:
                    Index = Index + 1
                    Num = '%s.%d' %(SecNum, Index)
                    OutputFile = os.path.join(OutputPath, ModuleName + SUP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType))
                    f = open(File, 'r')
                    UiString = f.read()
                    f.close()
                    if IsMakefile and UiString == ModuleNameStr:
                        UiString = "$(MODULE_NAME)"
                    GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE',
                                                        Ui=UiString, IsMakefile=IsMakefile)
                    OutputFileList.append(OutputFile)
            else:
                if StringData is not None and len(StringData) > 0:
                    UiTuple = ('-n', '"' + StringData + '"')
                else:
                    UiTuple = tuple()

                    if self.Optional == True :
                        GenFdsGlobalVariable.VerboseLogger( "Optional Section don't exist!")
                        return '', None
                    else:
                        EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s miss UI Section value" %InfFileName)

                Num = SecNum
                if IsMakefile and StringData == ModuleNameStr:
                    StringData = "$(MODULE_NAME)"
                OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType))
                GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE',
                                                     Ui=StringData, IsMakefile=IsMakefile)
                OutputFileList.append(OutputFile)


        else:
            """If File List is empty"""
            if FileList == [] :
                if self.Optional == True:
                    GenFdsGlobalVariable.VerboseLogger("Optional Section don't exist!")
                    return [], None
                else:
                    EdkLogger.error("GenFds", GENFDS_ERROR, "Output file for %s section could not be found for %s" % (SectionType, InfFileName))

            else:
                """Convert the File to Section file one by one """
                for File in FileList:
                    """ Copy Map file to FFS output path """
                    Index = Index + 1
                    Num = '%s.%d' %(SecNum, Index)
                    OutputFile = os.path.join( OutputPath, ModuleName + SUP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType))
                    File = GenFdsGlobalVariable.MacroExtend(File, Dict)
                    
                    #Get PE Section alignment when align is set to AUTO
                    if self.Alignment == 'Auto' and (SectionType == BINARY_FILE_TYPE_PE32 or SectionType == BINARY_FILE_TYPE_TE):
                        ImageObj = PeImageClass (File)
                        if ImageObj.SectionAlignment < 0x400:
                            Align = str (ImageObj.SectionAlignment)
                        elif ImageObj.SectionAlignment < 0x100000:
                            Align = str (ImageObj.SectionAlignment / 0x400) + 'K'
                        else:
                            Align = str (ImageObj.SectionAlignment / 0x100000) + 'M'

                    if File[(len(File)-4):] == '.efi':
                        MapFile = File.replace('.efi', '.map')
                        CopyMapFile = os.path.join(OutputPath, ModuleName + '.map')
                        if IsMakefile:
                            if GenFdsGlobalVariable.CopyList == []:
                                GenFdsGlobalVariable.CopyList = [(MapFile, CopyMapFile)]
                            else:
                                GenFdsGlobalVariable.CopyList.append((MapFile, CopyMapFile))
                        else:
                            if os.path.exists(MapFile):
                                if not os.path.exists(CopyMapFile) or \
                                       (os.path.getmtime(MapFile) > os.path.getmtime(CopyMapFile)):
                                    CopyLongFilePath(MapFile, CopyMapFile)

                    if not NoStrip:
                        FileBeforeStrip = os.path.join(OutputPath, ModuleName + '.efi')
                        if IsMakefile:
                            if GenFdsGlobalVariable.CopyList == []:
                                GenFdsGlobalVariable.CopyList = [(File, FileBeforeStrip)]
                            else:
                                GenFdsGlobalVariable.CopyList.append((File, FileBeforeStrip))
                        else:
                            if not os.path.exists(FileBeforeStrip) or \
                                (os.path.getmtime(File) > os.path.getmtime(FileBeforeStrip)):
                                CopyLongFilePath(File, FileBeforeStrip)
                        StrippedFile = os.path.join(OutputPath, ModuleName + '.stripped')
                        GenFdsGlobalVariable.GenerateFirmwareImage(
                                StrippedFile,
                                [File],
                                Strip=True,
                                IsMakefile = IsMakefile
                            )
                        File = StrippedFile
                    
                    """For TE Section call GenFw to generate TE image"""

                    if SectionType == BINARY_FILE_TYPE_TE:
                        TeFile = os.path.join( OutputPath, ModuleName + 'Te.raw')
                        GenFdsGlobalVariable.GenerateFirmwareImage(
                                TeFile,
                                [File],
                                Type='te',
                                IsMakefile = IsMakefile
                            )
                        File = TeFile

                    """Call GenSection"""
                    GenFdsGlobalVariable.GenerateSection(OutputFile,
                                                        [File],
                                                        Section.Section.SectionType.get (SectionType),
                                                        IsMakefile=IsMakefile
                                                        )
                    OutputFileList.append(OutputFile)

        return OutputFileList, Align
    def GenSection(self,
                   OutputPath,
                   ModuleName,
                   SecNum,
                   keyStringList,
                   FfsFile=None,
                   Dict={}):
        #
        # Prepare the parameter of GenSection
        #
        if FfsFile != None:
            self.SectFileName = GenFdsGlobalVariable.ReplaceWorkspaceMacro(
                self.SectFileName)
            self.SectFileName = GenFdsGlobalVariable.MacroExtend(
                self.SectFileName, Dict, FfsFile.CurrentArch)
        else:
            self.SectFileName = GenFdsGlobalVariable.ReplaceWorkspaceMacro(
                self.SectFileName)
            self.SectFileName = GenFdsGlobalVariable.MacroExtend(
                self.SectFileName, Dict)
        """Check Section file exist or not !"""

        if not os.path.exists(self.SectFileName):
            self.SectFileName = os.path.join(GenFdsGlobalVariable.WorkSpaceDir,
                                             self.SectFileName)
        """Copy Map file to Ffs output"""
        Filename = GenFdsGlobalVariable.MacroExtend(self.SectFileName)
        if Filename[(len(Filename) - 4):] == '.efi':
            MapFile = Filename.replace('.efi', '.map')
            if os.path.exists(MapFile):
                CopyMapFile = os.path.join(OutputPath, ModuleName + '.map')
                if not os.path.exists(CopyMapFile) or (
                        os.path.getmtime(MapFile) >
                        os.path.getmtime(CopyMapFile)):
                    CopyLongFilePath(MapFile, CopyMapFile)

        #Get PE Section alignment when align is set to AUTO
        if self.Alignment == 'Auto' and self.SecType in ('TE', 'PE32'):
            ImageObj = PeImageClass(Filename)
            if ImageObj.SectionAlignment < 0x400:
                self.Alignment = str(ImageObj.SectionAlignment)
            elif ImageObj.SectionAlignment < 0x100000:
                self.Alignment = str(ImageObj.SectionAlignment / 0x400) + 'K'
            else:
                self.Alignment = str(
                    ImageObj.SectionAlignment / 0x100000) + 'M'

        NoStrip = True
        if self.SecType in ('TE', 'PE32'):
            if self.KeepReloc != None:
                NoStrip = self.KeepReloc

        if not NoStrip:
            FileBeforeStrip = os.path.join(OutputPath, ModuleName + '.efi')
            if not os.path.exists(FileBeforeStrip) or \
                (os.path.getmtime(self.SectFileName) > os.path.getmtime(FileBeforeStrip)):
                CopyLongFilePath(self.SectFileName, FileBeforeStrip)
            StrippedFile = os.path.join(OutputPath, ModuleName + '.stripped')
            GenFdsGlobalVariable.GenerateFirmwareImage(
                StrippedFile,
                [GenFdsGlobalVariable.MacroExtend(self.SectFileName, Dict)],
                Strip=True)
            self.SectFileName = StrippedFile

        if self.SecType == 'TE':
            TeFile = os.path.join(OutputPath, ModuleName + 'Te.raw')
            GenFdsGlobalVariable.GenerateFirmwareImage(
                TeFile,
                [GenFdsGlobalVariable.MacroExtend(self.SectFileName, Dict)],
                Type='te')
            self.SectFileName = TeFile

        OutputFile = os.path.join(
            OutputPath,
            ModuleName + 'SEC' + SecNum + Ffs.SectionSuffix.get(self.SecType))
        OutputFile = os.path.normpath(OutputFile)

        GenFdsGlobalVariable.GenerateSection(
            OutputFile, [self.SectFileName],
            Section.Section.SectionType.get(self.SecType))
        FileList = [OutputFile]
        return FileList, self.Alignment
Пример #10
0
    def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf = None, Dict = {}):
        #
        # Generate all section
        #
        self.KeyStringList = KeyStringList
        self.CurrentArchList = GenFdsGlobalVariable.ArchList
        if FfsInf != None:
            self.Alignment = FfsInf.__ExtendMacro__(self.Alignment)
            self.NameGuid = FfsInf.__ExtendMacro__(self.NameGuid)
            self.SectionType = FfsInf.__ExtendMacro__(self.SectionType)
            self.CurrentArchList = [FfsInf.CurrentArch]

        SectFile  = tuple()
        SectAlign = []
        Index = 0
        MaxAlign = None
        if self.FvAddr != []:
            FvAddrIsSet = True
        else:
            FvAddrIsSet = False
        
        if self.ProcessRequired in ("TRUE", "1"):
            if self.FvAddr != []:
                #no use FvAddr when the image is processed.
                self.FvAddr = []
            if self.FvParentAddr != None:
                #no use Parent Addr when the image is processed.
                self.FvParentAddr = None

        for Sect in self.SectionList:
            Index = Index + 1
            SecIndex = '%s.%d' %(SecNum,Index)
            # set base address for inside FvImage
            if isinstance(Sect, FvImageSection):
                if self.FvAddr != []:
                    Sect.FvAddr = self.FvAddr.pop(0)
                self.IncludeFvSection = True
            elif isinstance(Sect, GuidSection):
                Sect.FvAddr = self.FvAddr
                Sect.FvParentAddr = self.FvParentAddr
            ReturnSectList, align = Sect.GenSection(OutputPath, ModuleName, SecIndex, KeyStringList,FfsInf, Dict)
            if isinstance(Sect, GuidSection):
                if Sect.IncludeFvSection:
                    self.IncludeFvSection = Sect.IncludeFvSection

            if align != None:
                if MaxAlign == None:
                    MaxAlign = align
                if GenFdsGlobalVariable.GetAlignment (align) > GenFdsGlobalVariable.GetAlignment (MaxAlign):
                    MaxAlign = align
            if ReturnSectList != []:
                if align == None:
                    align = "1"
                for file in ReturnSectList:
                    SectFile += (file,)
                    SectAlign.append(align)

        if MaxAlign != None:
            if self.Alignment == None:
                self.Alignment = MaxAlign
            else:
                if GenFdsGlobalVariable.GetAlignment (MaxAlign) > GenFdsGlobalVariable.GetAlignment (self.Alignment):
                    self.Alignment = MaxAlign

        OutputFile = OutputPath + \
                     os.sep     + \
                     ModuleName + \
                     'SEC'      + \
                     SecNum     + \
                     Ffs.SectionSuffix['GUIDED']
        OutputFile = os.path.normpath(OutputFile)

        ExternalTool = None
        ExternalOption = None
        if self.NameGuid != None:
            ExternalTool, ExternalOption = self.__FindExtendTool__()

        #
        # If not have GUID , call default
        # GENCRC32 section
        #
        if self.NameGuid == None :
            GenFdsGlobalVariable.VerboseLogger( "Use GenSection function Generate CRC32 Section")
            GenFdsGlobalVariable.GenerateSection(OutputFile, SectFile, Section.Section.SectionType[self.SectionType], InputAlign=SectAlign)
            OutputFileList = []
            OutputFileList.append(OutputFile)
            return OutputFileList, self.Alignment
        #or GUID not in External Tool List
        elif ExternalTool == None:
            EdkLogger.error("GenFds", GENFDS_ERROR, "No tool found with GUID %s" % self.NameGuid)
        else:
            DummyFile = OutputFile+".dummy"
            #
            # Call GenSection with DUMMY section type.
            #
            GenFdsGlobalVariable.GenerateSection(DummyFile, SectFile, InputAlign=SectAlign)
            #
            # Use external tool process the Output
            #
            TempFile = OutputPath + \
                       os.sep     + \
                       ModuleName + \
                       'SEC'      + \
                       SecNum     + \
                       '.tmp'
            TempFile = os.path.normpath(TempFile)

            FirstCall = False
            CmdOption = '-e'
            if ExternalOption != None:
                CmdOption = CmdOption + ' ' + ExternalOption
            if self.ProcessRequired not in ("TRUE", "1") and self.IncludeFvSection and not FvAddrIsSet and self.FvParentAddr != None:
                #FirstCall is only set for the encapsulated flash FV image without process required attribute.
                FirstCall = True
            #
            # Call external tool
            #
            ReturnValue = [1]
            if FirstCall:
                #first try to call the guided tool with -z option and CmdOption for the no process required guided tool.
                GenFdsGlobalVariable.GuidTool(TempFile, [DummyFile], ExternalTool, '-z' + ' ' + CmdOption, ReturnValue)

            #
            # when no call or first call failed, ReturnValue are not 1.
            # Call the guided tool with CmdOption
            #
            if ReturnValue[0] != 0:
                FirstCall = False
                ReturnValue[0] = 0
                GenFdsGlobalVariable.GuidTool(TempFile, [DummyFile], ExternalTool, CmdOption)

            FileHandleIn = open(DummyFile,'rb')
            FileHandleIn.seek(0,2)
            InputFileSize = FileHandleIn.tell()
            
            FileHandleOut = open(TempFile,'rb')
            FileHandleOut.seek(0,2)
            TempFileSize = FileHandleOut.tell()

            Attribute = []
            HeaderLength = None
            if TempFileSize > InputFileSize and TempFileSize % 4 == 0:
                FileHandleIn.seek(0)
                BufferIn  = FileHandleIn.read()
                FileHandleOut.seek(0)
                BufferOut = FileHandleOut.read()
                if BufferIn == BufferOut[TempFileSize - InputFileSize:]:
                    HeaderLength = str(TempFileSize - InputFileSize)
            #auto sec guided attribute with process required
            if HeaderLength == None:
                Attribute.append('PROCESSING_REQUIRED')

            FileHandleIn.close()
            FileHandleOut.close()
            
            if FirstCall and 'PROCESSING_REQUIRED' in Attribute:
                # Guided data by -z option on first call is the process required data. Call the guided tool with the real option.
                GenFdsGlobalVariable.GuidTool(TempFile, [DummyFile], ExternalTool, CmdOption)
            
            #
            # Call Gensection Add Section Header
            #
            if self.ProcessRequired in ("TRUE", "1"):
                if 'PROCESSING_REQUIRED' not in Attribute:
                    Attribute.append('PROCESSING_REQUIRED')
                HeaderLength = None
            if self.AuthStatusValid in ("TRUE", "1"):
                Attribute.append('AUTH_STATUS_VALID')
            GenFdsGlobalVariable.GenerateSection(OutputFile, [TempFile], Section.Section.SectionType['GUIDED'],
                                                 Guid=self.NameGuid, GuidAttr=Attribute, GuidHdrLen=HeaderLength)
            OutputFileList = []
            OutputFileList.append(OutputFile)
            if 'PROCESSING_REQUIRED' in Attribute:
                # reset guided section alignment to none for the processed required guided data
                self.Alignment = None
                self.IncludeFvSection = False
                self.ProcessRequired = "TRUE"
            return OutputFileList, self.Alignment
Пример #11
0
    def GenFfs(self, FvName, Dict={}):
        DXE_GUID = "FC510EE7-FFDC-11D4-BD41-0080C73C8881"
        PEI_GUID = "1B45CC0A-156A-428A-AF62-49864DA0E6E6"
        Buffer = StringIO.StringIO('')
        AprioriFileGuid = DXE_GUID
        if self.AprioriType == "PEI":
            AprioriFileGuid = PEI_GUID
        OutputAprFilePath = os.path.join (GenFdsGlobalVariable.WorkSpaceDir, \
                                   GenFdsGlobalVariable.FfsDir,\
                                   AprioriFileGuid + FvName)
        if not os.path.exists(OutputAprFilePath):
            os.makedirs(OutputAprFilePath)

        OutputAprFileName = os.path.join( OutputAprFilePath, \
                                       AprioriFileGuid + FvName + '.Apri' )
        AprFfsFileName = os.path.join (OutputAprFilePath,\
                                    AprioriFileGuid + FvName + '.Ffs')

        Dict.update(self.DefineVarDict)
        for FfsObj in self.FfsList:
            Guid = ""
            if isinstance(FfsObj, FfsFileStatement.FileStatement):
                Guid = FfsObj.NameGuid
            else:
                InfFileName = NormPath(FfsObj.InfFileName)
                Arch = FfsObj.GetCurrentArch()

                if Arch != None:
                    Dict['$(ARCH)'] = Arch
                InfFileName = GenFdsGlobalVariable.MacroExtend(
                    InfFileName, Dict, Arch)

                if Arch != None:
                    Inf = GenFdsGlobalVariable.WorkSpace.BuildObject[
                        PathClass(InfFileName, GenFdsGlobalVariable.
                                  WorkSpaceDir), Arch,
                        GenFdsGlobalVariable.TargetName,
                        GenFdsGlobalVariable.ToolChainTag]
                    Guid = Inf.Guid

                else:
                    Inf = GenFdsGlobalVariable.WorkSpace.BuildObject[
                        PathClass(InfFileName, GenFdsGlobalVariable.
                                  WorkSpaceDir), 'COMMON',
                        GenFdsGlobalVariable.TargetName,
                        GenFdsGlobalVariable.ToolChainTag]
                    Guid = Inf.Guid

                    self.BinFileList = Inf.Module.Binaries
                    if self.BinFileList == []:
                        EdkLogger.error("GenFds", RESOURCE_NOT_AVAILABLE,
                                        "INF %s not found in build ARCH %s!" \
                                        % (InfFileName, GenFdsGlobalVariable.ArchList))

            GuidPart = Guid.split('-')
            Buffer.write(pack('I', long(GuidPart[0], 16)))
            Buffer.write(pack('H', int(GuidPart[1], 16)))
            Buffer.write(pack('H', int(GuidPart[2], 16)))

            for Num in range(2):
                Char = GuidPart[3][Num * 2:Num * 2 + 2]
                Buffer.write(pack('B', int(Char, 16)))

            for Num in range(6):
                Char = GuidPart[4][Num * 2:Num * 2 + 2]
                Buffer.write(pack('B', int(Char, 16)))

        SaveFileOnChange(OutputAprFileName, Buffer.getvalue())

        RawSectionFileName = os.path.join( OutputAprFilePath, \
                                       AprioriFileGuid + FvName + '.raw' )
        GenFdsGlobalVariable.GenerateSection(RawSectionFileName,
                                             [OutputAprFileName],
                                             'EFI_SECTION_RAW')
        GenFdsGlobalVariable.GenerateFfs(AprFfsFileName, [RawSectionFileName],
                                         'EFI_FV_FILETYPE_FREEFORM',
                                         AprioriFileGuid)

        return AprFfsFileName
Пример #12
0
    def GenSection(self,
                   OutputPath,
                   ModuleName,
                   SecNum,
                   KeyStringList,
                   FfsInf=None,
                   Dict={}):

        OutputFileList = []
        if self.FvFileType != None:
            FileList, IsSect = Section.Section.GetFileList(
                FfsInf, self.FvFileType, self.FvFileExtension)
            if IsSect:
                return FileList, self.Alignment

            Num = SecNum

            MaxFvAlignment = 0
            for FvFileName in FileList:
                FvAlignmentValue = 0
                if os.path.isfile(FvFileName):
                    FvFileObj = open(FvFileName, 'rb')
                    FvFileObj.seek(0)
                    # PI FvHeader is 0x48 byte
                    FvHeaderBuffer = FvFileObj.read(0x48)
                    # FV alignment position.
                    FvAlignmentValue = 1 << (ord(FvHeaderBuffer[0x2E]) & 0x1F)
                    FvFileObj.close()
                if FvAlignmentValue > MaxFvAlignment:
                    MaxFvAlignment = FvAlignmentValue

                OutputFile = os.path.join(
                    OutputPath, ModuleName + 'SEC' + Num +
                    Ffs.SectionSuffix.get("FV_IMAGE"))
                GenFdsGlobalVariable.GenerateSection(
                    OutputFile, [FvFileName],
                    'EFI_SECTION_FIRMWARE_VOLUME_IMAGE')
                OutputFileList.append(OutputFile)

            # MaxFvAlignment is larger than or equal to 1K
            if MaxFvAlignment >= 0x400:
                if MaxFvAlignment >= 0x100000:
                    #The max alignment supported by FFS is 16M.
                    if MaxFvAlignment >= 1000000:
                        self.Alignment = "16M"
                    else:
                        self.Alignment = str(MaxFvAlignment / 0x100000) + "M"
                else:
                    self.Alignment = str(MaxFvAlignment / 0x400) + "K"
            else:
                # MaxFvAlignment is less than 1K
                self.Alignment = str(MaxFvAlignment)

            return OutputFileList, self.Alignment
        #
        # Generate Fv
        #
        if self.FvName != None:
            Buffer = StringIO.StringIO('')
            Fv = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(self.FvName)
            if Fv != None:
                self.Fv = Fv
                FvFileName = Fv.AddToBuffer(Buffer,
                                            self.FvAddr,
                                            MacroDict=Dict)
                if Fv.FvAlignment != None:
                    if self.Alignment == None:
                        self.Alignment = Fv.FvAlignment
                    else:
                        if GenFdsGlobalVariable.GetAlignment(
                                Fv.FvAlignment
                        ) > GenFdsGlobalVariable.GetAlignment(self.Alignment):
                            self.Alignment = Fv.FvAlignment
            else:
                if self.FvFileName != None:
                    FvFileName = GenFdsGlobalVariable.ReplaceWorkspaceMacro(
                        self.FvFileName)
                    if os.path.isfile(FvFileName):
                        FvFileObj = open(FvFileName, 'rb')
                        FvFileObj.seek(0)
                        # PI FvHeader is 0x48 byte
                        FvHeaderBuffer = FvFileObj.read(0x48)
                        # FV alignment position.
                        FvAlignmentValue = 1 << (ord(FvHeaderBuffer[0x2E])
                                                 & 0x1F)
                        # FvAlignmentValue is larger than or equal to 1K
                        if FvAlignmentValue >= 0x400:
                            if FvAlignmentValue >= 0x100000:
                                #The max alignment supported by FFS is 16M.
                                if FvAlignmentValue >= 0x1000000:
                                    self.Alignment = "16M"
                                else:
                                    self.Alignment = str(
                                        FvAlignmentValue / 0x100000) + "M"
                            else:
                                self.Alignment = str(
                                    FvAlignmentValue / 0x400) + "K"
                        else:
                            # FvAlignmentValue is less than 1K
                            self.Alignment = str(FvAlignmentValue)
                        FvFileObj.close()
                else:
                    EdkLogger.error(
                        "GenFds", GENFDS_ERROR,
                        "FvImageSection Failed! %s NOT found in FDF" %
                        self.FvName)

            #
            # Prepare the parameter of GenSection
            #
            OutputFile = os.path.join(
                OutputPath, ModuleName + 'SEC' + SecNum +
                Ffs.SectionSuffix.get("FV_IMAGE"))
            GenFdsGlobalVariable.GenerateSection(
                OutputFile, [FvFileName], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE')
            OutputFileList.append(OutputFile)

            return OutputFileList, self.Alignment
Пример #13
0
 def __GenComplexFileSection__(self, Rule, FvChildAddr, FvParentAddr):
     if self.ModuleType in ('SEC', 'PEI_CORE', 'PEIM'):
         if Rule.KeepReloc != None:
             self.KeepRelocFromRule = Rule.KeepReloc
     SectFiles = []
     SectAlignments = []
     Index = 1
     HasGneratedFlag = False
     if self.PcdIsDriver == 'PEI_PCD_DRIVER':
         if self.IsBinaryModule:
             PcdExDbFileName = os.path.join(GenFdsGlobalVariable.FvDir, "PEIPcdDataBase.raw")
         else:
             PcdExDbFileName = os.path.join(self.EfiOutputPath, "PEIPcdDataBase.raw")
         PcdExDbSecName = os.path.join(self.OutputPath, "PEIPcdDataBaseSec.raw")
         GenFdsGlobalVariable.GenerateSection(PcdExDbSecName,
                                              [PcdExDbFileName],
                                              "EFI_SECTION_RAW",
                                              )
         SectFiles.append(PcdExDbSecName)
         SectAlignments.append(None)
     elif self.PcdIsDriver == 'DXE_PCD_DRIVER':
         if self.IsBinaryModule:
             PcdExDbFileName = os.path.join(GenFdsGlobalVariable.FvDir, "DXEPcdDataBase.raw")
         else:
             PcdExDbFileName = os.path.join(self.EfiOutputPath, "DXEPcdDataBase.raw")
         PcdExDbSecName = os.path.join(self.OutputPath, "DXEPcdDataBaseSec.raw")
         GenFdsGlobalVariable.GenerateSection(PcdExDbSecName,
                                              [PcdExDbFileName],
                                              "EFI_SECTION_RAW",
                                              )
         SectFiles.append(PcdExDbSecName)
         SectAlignments.append(None)
     for Sect in Rule.SectionList:
         SecIndex = '%d' %Index
         SectList  = []
         #
         # Convert Fv Section Type for PI1.1 SMM driver.
         #
         if self.ModuleType == 'DXE_SMM_DRIVER' and int(self.PiSpecVersion, 16) >= 0x0001000A:
             if Sect.SectionType == 'DXE_DEPEX':
                 Sect.SectionType = 'SMM_DEPEX'
         #
         # Framework SMM Driver has no SMM_DEPEX section type
         #
         if self.ModuleType == 'DXE_SMM_DRIVER' and int(self.PiSpecVersion, 16) < 0x0001000A:
             if Sect.SectionType == 'SMM_DEPEX':
                 EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Framework SMM module doesn't support SMM_DEPEX section type", File=self.InfFileName)
         #
         # process the inside FvImage from FvSection or GuidSection
         #
         if FvChildAddr != []:
             if isinstance(Sect, FvImageSection):
                 Sect.FvAddr = FvChildAddr.pop(0)
             elif isinstance(Sect, GuidSection):
                 Sect.FvAddr = FvChildAddr
         if FvParentAddr != None and isinstance(Sect, GuidSection):
             Sect.FvParentAddr = FvParentAddr
         
         if Rule.KeyStringList != []:
             SectList, Align = Sect.GenSection(self.OutputPath , self.ModuleGuid, SecIndex, Rule.KeyStringList, self)
         else :
             SectList, Align = Sect.GenSection(self.OutputPath , self.ModuleGuid, SecIndex, self.KeyStringList, self)
         
         if not HasGneratedFlag:
             UniVfrOffsetFileSection = ""    
             ModuleFileName = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, self.InfFileName)
             InfData = GenFdsGlobalVariable.WorkSpace.BuildObject[PathClass(ModuleFileName), self.CurrentArch]
             #
             # Search the source list in InfData to find if there are .vfr file exist.
             #
             VfrUniBaseName = {}
             VfrUniOffsetList = []
             for SourceFile in InfData.Sources:
                 if SourceFile.Type.upper() == ".VFR" :
                     #
                     # search the .map file to find the offset of vfr binary in the PE32+/TE file. 
                     #
                     VfrUniBaseName[SourceFile.BaseName] = (SourceFile.BaseName + "Bin")
                 if SourceFile.Type.upper() == ".UNI" :
                     #
                     # search the .map file to find the offset of Uni strings binary in the PE32+/TE file. 
                     #
                     VfrUniBaseName["UniOffsetName"] = (self.BaseName + "Strings")
                 
             
             if len(VfrUniBaseName) > 0:
                 VfrUniOffsetList = self.__GetBuildOutputMapFileVfrUniInfo(VfrUniBaseName)
                 #
                 # Generate the Raw data of raw section
                 #
                 os.path.join( self.OutputPath, self.BaseName + '.offset')
                 UniVfrOffsetFileName    =  os.path.join( self.OutputPath, self.BaseName + '.offset')
                 UniVfrOffsetFileSection =  os.path.join( self.OutputPath, self.BaseName + 'Offset' + '.raw')
                 
                 self.__GenUniVfrOffsetFile (VfrUniOffsetList, UniVfrOffsetFileName)
                 
                 UniVfrOffsetFileNameList = []
                 UniVfrOffsetFileNameList.append(UniVfrOffsetFileName)
                 """Call GenSection"""
                 GenFdsGlobalVariable.GenerateSection(UniVfrOffsetFileSection,
                                                      UniVfrOffsetFileNameList,
                                                      "EFI_SECTION_RAW"
                                                      )
                 os.remove(UniVfrOffsetFileName)         
                 SectList.append(UniVfrOffsetFileSection)
                 HasGneratedFlag = True
             
         for SecName in  SectList :
             SectFiles.append(SecName)
             SectAlignments.append(Align)
         Index = Index + 1
     return SectFiles, SectAlignments
Пример #14
0
    def __GenSimpleFileSection__(self, Rule):
        #
        # Prepare the parameter of GenSection
        #
        FileList = []
        OutputFileList = []
        GenSecInputFile = None
        if Rule.FileName != None:
            GenSecInputFile = self.__ExtendMacro__(Rule.FileName)
            if os.path.isabs(GenSecInputFile):
                GenSecInputFile = os.path.normpath(GenSecInputFile)
            else:
                GenSecInputFile = os.path.normpath(os.path.join(self.EfiOutputPath, GenSecInputFile))
        else:
            FileList, IsSect = Section.Section.GetFileList(self, '', Rule.FileExtension)

        Index = 1
        SectionType = Rule.SectionType
        #
        # Convert Fv Section Type for PI1.1 SMM driver.
        #
        if self.ModuleType == 'DXE_SMM_DRIVER' and int(self.PiSpecVersion, 16) >= 0x0001000A:
            if SectionType == 'DXE_DEPEX':
                SectionType = 'SMM_DEPEX'
        #
        # Framework SMM Driver has no SMM_DEPEX section type
        #
        if self.ModuleType == 'DXE_SMM_DRIVER' and int(self.PiSpecVersion, 16) < 0x0001000A:
            if SectionType == 'SMM_DEPEX':
                EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Framework SMM module doesn't support SMM_DEPEX section type", File=self.InfFileName)
        NoStrip = True
        if self.ModuleType in ('SEC', 'PEI_CORE', 'PEIM'):
            if self.KeepReloc != None:
                NoStrip = self.KeepReloc
            elif Rule.KeepReloc != None:
                NoStrip = Rule.KeepReloc
            elif self.ShadowFromInfFile != None:
                NoStrip = self.ShadowFromInfFile

        if FileList != [] :
            for File in FileList:

                SecNum = '%d' %Index
                GenSecOutputFile= self.__ExtendMacro__(Rule.NameGuid) + \
                              Ffs.Ffs.SectionSuffix[SectionType] + 'SEC' + SecNum
                Index = Index + 1
                OutputFile = os.path.join(self.OutputPath, GenSecOutputFile)
                File = GenFdsGlobalVariable.MacroExtend(File, Dict, self.CurrentArch)

                #Get PE Section alignment when align is set to AUTO
                if self.Alignment == 'Auto' and (SectionType == 'PE32' or SectionType == 'TE'):
                    ImageObj = PeImageClass (File)
                    if ImageObj.SectionAlignment < 0x400:
                        self.Alignment = str (ImageObj.SectionAlignment)
                    else:
                        self.Alignment = str (ImageObj.SectionAlignment / 0x400) + 'K'

                if not NoStrip:
                    FileBeforeStrip = os.path.join(self.OutputPath, ModuleName + '.reloc')
                    if not os.path.exists(FileBeforeStrip) or \
                           (os.path.getmtime(File) > os.path.getmtime(FileBeforeStrip)):
                        CopyLongFilePath(File, FileBeforeStrip)
                    StrippedFile = os.path.join(self.OutputPath, ModuleName + '.stipped')
                    GenFdsGlobalVariable.GenerateFirmwareImage(
                                            StrippedFile,
                                            [File],
                                            Strip=True
                                            )
                    File = StrippedFile

                if SectionType == 'TE':
                    TeFile = os.path.join( self.OutputPath, self.ModuleGuid + 'Te.raw')
                    GenFdsGlobalVariable.GenerateFirmwareImage(
                                            TeFile,
                                            [File],
                                            Type='te'
                                            )
                    File = TeFile

                GenFdsGlobalVariable.GenerateSection(OutputFile, [File], Section.Section.SectionType[SectionType])
                OutputFileList.append(OutputFile)
        else:
            SecNum = '%d' %Index
            GenSecOutputFile= self.__ExtendMacro__(Rule.NameGuid) + \
                              Ffs.Ffs.SectionSuffix[SectionType] + 'SEC' + SecNum
            OutputFile = os.path.join(self.OutputPath, GenSecOutputFile)
            GenSecInputFile = GenFdsGlobalVariable.MacroExtend(GenSecInputFile, Dict, self.CurrentArch)

            #Get PE Section alignment when align is set to AUTO
            if self.Alignment == 'Auto' and (SectionType == 'PE32' or SectionType == 'TE'):
                ImageObj = PeImageClass (GenSecInputFile)
                if ImageObj.SectionAlignment < 0x400:
                    self.Alignment = str (ImageObj.SectionAlignment)
                else:
                    self.Alignment = str (ImageObj.SectionAlignment / 0x400) + 'K'

            if not NoStrip:
                FileBeforeStrip = os.path.join(self.OutputPath, ModuleName + '.reloc')
                if not os.path.exists(FileBeforeStrip) or \
                       (os.path.getmtime(GenSecInputFile) > os.path.getmtime(FileBeforeStrip)):
                    CopyLongFilePath(GenSecInputFile, FileBeforeStrip)

                StrippedFile = os.path.join(self.OutputPath, ModuleName + '.stipped')
                GenFdsGlobalVariable.GenerateFirmwareImage(
                                        StrippedFile,
                                        [GenSecInputFile],
                                        Strip=True
                                        )
                GenSecInputFile = StrippedFile

            if SectionType == 'TE':
                TeFile = os.path.join( self.OutputPath, self.ModuleGuid + 'Te.raw')
                GenFdsGlobalVariable.GenerateFirmwareImage(
                                        TeFile,
                                        [GenSecInputFile],
                                        Type='te'
                                        )
                GenSecInputFile = TeFile

            GenFdsGlobalVariable.GenerateSection(OutputFile, [GenSecInputFile], Section.Section.SectionType[SectionType])
            OutputFileList.append(OutputFile)

        return OutputFileList
Пример #15
0
    def GenSection(self,
                   OutputPath,
                   ModuleName,
                   SecNum,
                   KeyStringList,
                   FfsInf=None,
                   Dict={},
                   IsMakefile=False):
        #
        # Generate all section
        #
        self.KeyStringList = KeyStringList
        self.CurrentArchList = GenFdsGlobalVariable.ArchList
        if FfsInf is not None:
            self.Alignment = FfsInf.__ExtendMacro__(self.Alignment)
            self.NameGuid = FfsInf.__ExtendMacro__(self.NameGuid)
            self.SectionType = FfsInf.__ExtendMacro__(self.SectionType)
            self.CurrentArchList = [FfsInf.CurrentArch]

        SectFile = tuple()
        SectAlign = []
        Index = 0
        MaxAlign = None
        if self.FvAddr != []:
            FvAddrIsSet = True
        else:
            FvAddrIsSet = False

        if self.ProcessRequired in ("TRUE", "1"):
            if self.FvAddr != []:
                #no use FvAddr when the image is processed.
                self.FvAddr = []
            if self.FvParentAddr is not None:
                #no use Parent Addr when the image is processed.
                self.FvParentAddr = None

        for Sect in self.SectionList:
            Index = Index + 1
            SecIndex = '%s.%d' % (SecNum, Index)
            # set base address for inside FvImage
            if isinstance(Sect, FvImageSection):
                if self.FvAddr != []:
                    Sect.FvAddr = self.FvAddr.pop(0)
                self.IncludeFvSection = True
            elif isinstance(Sect, GuidSection):
                Sect.FvAddr = self.FvAddr
                Sect.FvParentAddr = self.FvParentAddr
            ReturnSectList, align = Sect.GenSection(OutputPath,
                                                    ModuleName,
                                                    SecIndex,
                                                    KeyStringList,
                                                    FfsInf,
                                                    Dict,
                                                    IsMakefile=IsMakefile)
            if isinstance(Sect, GuidSection):
                if Sect.IncludeFvSection:
                    self.IncludeFvSection = Sect.IncludeFvSection

            if align is not None:
                if MaxAlign is None:
                    MaxAlign = align
                if GenFdsGlobalVariable.GetAlignment(
                        align) > GenFdsGlobalVariable.GetAlignment(MaxAlign):
                    MaxAlign = align
            if ReturnSectList != []:
                if align is None:
                    align = "1"
                for file in ReturnSectList:
                    SectFile += (file, )
                    SectAlign.append(align)

        if MaxAlign is not None:
            if self.Alignment is None:
                self.Alignment = MaxAlign
            else:
                if GenFdsGlobalVariable.GetAlignment(
                        MaxAlign) > GenFdsGlobalVariable.GetAlignment(
                            self.Alignment):
                    self.Alignment = MaxAlign

        OutputFile = OutputPath + \
                     os.sep + \
                     ModuleName + \
                     'SEC' + \
                     SecNum + \
                     Ffs.SectionSuffix['GUIDED']
        OutputFile = os.path.normpath(OutputFile)

        ExternalTool = None
        ExternalOption = None
        if self.NameGuid is not None:
            ExternalTool, ExternalOption = FindExtendTool(
                self.KeyStringList, self.CurrentArchList, self.NameGuid)

        #
        # If not have GUID , call default
        # GENCRC32 section
        #
        if self.NameGuid is None:
            GenFdsGlobalVariable.VerboseLogger(
                "Use GenSection function Generate CRC32 Section")
            GenFdsGlobalVariable.GenerateSection(
                OutputFile,
                SectFile,
                Section.Section.SectionType[self.SectionType],
                InputAlign=SectAlign,
                IsMakefile=IsMakefile)
            OutputFileList = []
            OutputFileList.append(OutputFile)
            return OutputFileList, self.Alignment
        #or GUID not in External Tool List
        elif ExternalTool is None:
            EdkLogger.error("GenFds", GENFDS_ERROR,
                            "No tool found with GUID %s" % self.NameGuid)
        else:
            DummyFile = OutputFile + ".dummy"
            #
            # Call GenSection with DUMMY section type.
            #
            GenFdsGlobalVariable.GenerateSection(DummyFile,
                                                 SectFile,
                                                 InputAlign=SectAlign,
                                                 IsMakefile=IsMakefile)
            #
            # Use external tool process the Output
            #
            TempFile = OutputPath + \
                       os.sep + \
                       ModuleName + \
                       'SEC' + \
                       SecNum + \
                       '.tmp'
            TempFile = os.path.normpath(TempFile)
            #
            # Remove temp file if its time stamp is older than dummy file
            # Just in case the external tool fails at this time but succeeded before
            # Error should be reported if the external tool does not generate a new output based on new input
            #
            if os.path.exists(TempFile) and os.path.exists(
                    DummyFile
            ) and os.path.getmtime(TempFile) < os.path.getmtime(DummyFile):
                os.remove(TempFile)

            FirstCall = False
            CmdOption = '-e'
            if ExternalOption is not None:
                CmdOption = CmdOption + ' ' + ExternalOption
            if not GenFdsGlobalVariable.EnableGenfdsMultiThread:
                if self.ProcessRequired not in (
                        "TRUE", "1"
                ) and self.IncludeFvSection and not FvAddrIsSet and self.FvParentAddr is not None:
                    #FirstCall is only set for the encapsulated flash FV image without process required attribute.
                    FirstCall = True
                #
                # Call external tool
                #
                ReturnValue = [1]
                if FirstCall:
                    #first try to call the guided tool with -z option and CmdOption for the no process required guided tool.
                    GenFdsGlobalVariable.GuidTool(TempFile, [DummyFile],
                                                  ExternalTool,
                                                  '-z' + ' ' + CmdOption,
                                                  ReturnValue)

                #
                # when no call or first call failed, ReturnValue are not 1.
                # Call the guided tool with CmdOption
                #
                if ReturnValue[0] != 0:
                    FirstCall = False
                    ReturnValue[0] = 0
                    GenFdsGlobalVariable.GuidTool(TempFile, [DummyFile],
                                                  ExternalTool, CmdOption)
                #
                # There is external tool which does not follow standard rule which return nonzero if tool fails
                # The output file has to be checked
                #

                if not os.path.exists(TempFile):
                    EdkLogger.error(
                        "GenFds", COMMAND_FAILURE,
                        'Fail to call %s, no output file was generated' %
                        ExternalTool)

                FileHandleIn = open(DummyFile, 'rb')
                FileHandleIn.seek(0, 2)
                InputFileSize = FileHandleIn.tell()

                FileHandleOut = open(TempFile, 'rb')
                FileHandleOut.seek(0, 2)
                TempFileSize = FileHandleOut.tell()

                Attribute = []
                HeaderLength = None
                if self.ExtraHeaderSize != -1:
                    HeaderLength = str(self.ExtraHeaderSize)

                if self.ProcessRequired == "NONE" and HeaderLength is None:
                    if TempFileSize > InputFileSize:
                        FileHandleIn.seek(0)
                        BufferIn = FileHandleIn.read()
                        FileHandleOut.seek(0)
                        BufferOut = FileHandleOut.read()
                        if BufferIn == BufferOut[TempFileSize -
                                                 InputFileSize:]:
                            HeaderLength = str(TempFileSize - InputFileSize)
                    #auto sec guided attribute with process required
                    if HeaderLength is None:
                        Attribute.append('PROCESSING_REQUIRED')

                FileHandleIn.close()
                FileHandleOut.close()

                if FirstCall and 'PROCESSING_REQUIRED' in Attribute:
                    # Guided data by -z option on first call is the process required data. Call the guided tool with the real option.
                    GenFdsGlobalVariable.GuidTool(TempFile, [DummyFile],
                                                  ExternalTool, CmdOption)

                #
                # Call Gensection Add Section Header
                #
                if self.ProcessRequired in ("TRUE", "1"):
                    if 'PROCESSING_REQUIRED' not in Attribute:
                        Attribute.append('PROCESSING_REQUIRED')

                if self.AuthStatusValid in ("TRUE", "1"):
                    Attribute.append('AUTH_STATUS_VALID')
                GenFdsGlobalVariable.GenerateSection(
                    OutputFile, [TempFile],
                    Section.Section.SectionType['GUIDED'],
                    Guid=self.NameGuid,
                    GuidAttr=Attribute,
                    GuidHdrLen=HeaderLength)

            else:
                #add input file for GenSec get PROCESSING_REQUIRED
                GenFdsGlobalVariable.GuidTool(TempFile, [DummyFile],
                                              ExternalTool,
                                              CmdOption,
                                              IsMakefile=IsMakefile)
                Attribute = []
                HeaderLength = None
                if self.ExtraHeaderSize != -1:
                    HeaderLength = str(self.ExtraHeaderSize)
                if self.AuthStatusValid in ("TRUE", "1"):
                    Attribute.append('AUTH_STATUS_VALID')
                if self.ProcessRequired == "NONE" and HeaderLength is None:
                    GenFdsGlobalVariable.GenerateSection(
                        OutputFile, [TempFile],
                        Section.Section.SectionType['GUIDED'],
                        Guid=self.NameGuid,
                        GuidAttr=Attribute,
                        GuidHdrLen=HeaderLength,
                        DummyFile=DummyFile,
                        IsMakefile=IsMakefile)
                else:
                    if self.ProcessRequired in ("TRUE", "1"):
                        if 'PROCESSING_REQUIRED' not in Attribute:
                            Attribute.append('PROCESSING_REQUIRED')
                    GenFdsGlobalVariable.GenerateSection(
                        OutputFile, [TempFile],
                        Section.Section.SectionType['GUIDED'],
                        Guid=self.NameGuid,
                        GuidAttr=Attribute,
                        GuidHdrLen=HeaderLength,
                        IsMakefile=IsMakefile)

            OutputFileList = []
            OutputFileList.append(OutputFile)
            if 'PROCESSING_REQUIRED' in Attribute:
                # reset guided section alignment to none for the processed required guided data
                self.Alignment = None
                self.IncludeFvSection = False
                self.ProcessRequired = "TRUE"
            if IsMakefile and self.Alignment.strip() == '0':
                self.Alignment = '1'
            return OutputFileList, self.Alignment