summaryrefslogtreecommitdiffstats
path: root/BaseTools/Source/Python/GenFds/EfiSection.py
blob: 5bb1ae6f664c8649fbbb75e8befac7a70899d3ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
## @file
# process rule section generation
#
#  Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
#
#  This program and the accompanying materials
#  are licensed and made available under the terms and conditions of the BSD License
#  which accompanies this distribution.  The full text of the license may be found at
#  http://opensource.org/licenses/bsd-license.php
#
#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#

##
# Import Modules
#
from struct import *
import Section
from GenFdsGlobalVariable import GenFdsGlobalVariable
import subprocess
from Ffs import Ffs
import Common.LongFilePathOs as os
from CommonDataClass.FdfClass import EfiSectionClassObject
from Common import EdkLogger
from Common.BuildToolError import *
from Common.Misc import PeImageClass
from Common.LongFilePathSupport import OpenLongFilePath as open
from Common.LongFilePathSupport import CopyLongFilePath

## generate rule section
#
#
class EfiSection (EfiSectionClassObject):

    ## The constructor
    #
    #   @param  self        The object pointer
    #
    def __init__(self):
          EfiSectionClassObject.__init__(self)

    ## GenSection() method
    #
    #   Generate rule section
    #
    #   @param  self        The object pointer
    #   @param  OutputPath  Where to place output file
    #   @param  ModuleName  Which module this section belongs to
    #   @param  SecNum      Index of section
    #   @param  KeyStringList  Filter for inputs of section generation
    #   @param  FfsInf      FfsInfStatement object that contains this section data
    #   @param  Dict        dictionary contains macro and its value
    #   @retval tuple       (Generated file name list, section alignment)
    #
    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 ('SEC', 'PEI_CORE', 'PEIM') and SectionType in ('TE', '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 + '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 + '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 + '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 'UI'
        #
        elif SectionType == '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 + '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 + '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 + '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 + '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 == 'PE32' or SectionType == '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 == '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