1## @file
2# process FD Region generation
3#
4#  Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
5#
6#  SPDX-License-Identifier: BSD-2-Clause-Patent
7#
8
9##
10# Import Modules
11#
12from __future__ import absolute_import
13from struct import *
14from .GenFdsGlobalVariable import GenFdsGlobalVariable
15from io import BytesIO
16import string
17import Common.LongFilePathOs as os
18from stat import *
19from Common import EdkLogger
20from Common.BuildToolError import *
21from Common.LongFilePathSupport import OpenLongFilePath as open
22from Common.MultipleWorkspace import MultipleWorkspace as mws
23from Common.DataType import BINARY_FILE_TYPE_FV
24
25## generate Region
26#
27#
28class Region(object):
29
30    ## The constructor
31    #
32    #   @param  self        The object pointer
33    #
34    def __init__(self):
35        self.Offset = None       # The begin position of the Region
36        self.Size = None         # The Size of the Region
37        self.PcdOffset = None
38        self.PcdSize = None
39        self.SetVarDict = {}
40        self.RegionType = None
41        self.RegionDataList = []
42
43    ## PadBuffer()
44    #
45    #   Add padding bytes to the Buffer
46    #
47    #   @param Buffer         The buffer the generated region data will be put
48    #                         in
49    #   @param ErasePolarity  Flash erase polarity
50    #   @param Size           Number of padding bytes requested
51    #
52
53    def PadBuffer(self, Buffer, ErasePolarity, Size):
54        if Size > 0:
55            if (ErasePolarity == '1') :
56                PadByte = pack('B', 0xFF)
57            else:
58                PadByte = pack('B', 0)
59            for i in range(0, Size):
60                Buffer.write(PadByte)
61
62    ## AddToBuffer()
63    #
64    #   Add region data to the Buffer
65    #
66    #   @param  self        The object pointer
67    #   @param  Buffer      The buffer generated region data will be put
68    #   @param  BaseAddress base address of region
69    #   @param  BlockSize   block size of region
70    #   @param  BlockNum    How many blocks in region
71    #   @param  ErasePolarity      Flash erase polarity
72    #   @param  MacroDict   macro value pair
73    #   @retval string      Generated FV file path
74    #
75
76    def AddToBuffer(self, Buffer, BaseAddress, BlockSizeList, ErasePolarity, ImageBinDict,  MacroDict={}, Flag=False):
77        Size = self.Size
78        if not Flag:
79            GenFdsGlobalVariable.InfLogger('\nGenerate Region at Offset 0x%X' % self.Offset)
80            GenFdsGlobalVariable.InfLogger("   Region Size = 0x%X" % Size)
81        GenFdsGlobalVariable.SharpCounter = 0
82        if Flag and (self.RegionType != BINARY_FILE_TYPE_FV):
83            return
84
85        if self.RegionType == BINARY_FILE_TYPE_FV:
86            #
87            # Get Fv from FvDict
88            #
89            self.FvAddress = int(BaseAddress, 16) + self.Offset
90            FvBaseAddress = '0x%X' % self.FvAddress
91            FvOffset = 0
92            for RegionData in self.RegionDataList:
93                FileName = None
94                if RegionData.endswith(".fv"):
95                    RegionData = GenFdsGlobalVariable.MacroExtend(RegionData, MacroDict)
96                    if not Flag:
97                        GenFdsGlobalVariable.InfLogger('   Region FV File Name = .fv : %s' % RegionData)
98                    if RegionData[1] != ':' :
99                        RegionData = mws.join (GenFdsGlobalVariable.WorkSpaceDir, RegionData)
100                    if not os.path.exists(RegionData):
101                        EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=RegionData)
102
103                    FileName = RegionData
104                elif RegionData.upper() + 'fv' in ImageBinDict:
105                    if not Flag:
106                        GenFdsGlobalVariable.InfLogger('   Region Name = FV')
107                    FileName = ImageBinDict[RegionData.upper() + 'fv']
108                else:
109                    #
110                    # Generate FvImage.
111                    #
112                    FvObj = None
113                    if RegionData.upper() in GenFdsGlobalVariable.FdfParser.Profile.FvDict:
114                        FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict[RegionData.upper()]
115
116                    if FvObj is not None :
117                        if not Flag:
118                            GenFdsGlobalVariable.InfLogger('   Region Name = FV')
119                        #
120                        # Call GenFv tool
121                        #
122                        self.BlockInfoOfRegion(BlockSizeList, FvObj)
123                        self.FvAddress = self.FvAddress + FvOffset
124                        FvAlignValue = GenFdsGlobalVariable.GetAlignment(FvObj.FvAlignment)
125                        if self.FvAddress % FvAlignValue != 0:
126                            EdkLogger.error("GenFds", GENFDS_ERROR,
127                                            "FV (%s) is NOT %s Aligned!" % (FvObj.UiFvName, FvObj.FvAlignment))
128                        FvBuffer = BytesIO()
129                        FvBaseAddress = '0x%X' % self.FvAddress
130                        BlockSize = None
131                        BlockNum = None
132                        FvObj.AddToBuffer(FvBuffer, FvBaseAddress, BlockSize, BlockNum, ErasePolarity, Flag=Flag)
133                        if Flag:
134                            continue
135
136                        FvBufferLen = len(FvBuffer.getvalue())
137                        if FvBufferLen > Size:
138                            FvBuffer.close()
139                            EdkLogger.error("GenFds", GENFDS_ERROR,
140                                            "Size of FV (%s) is larger than Region Size 0x%X specified." % (RegionData, Size))
141                        #
142                        # Put the generated image into FD buffer.
143                        #
144                        Buffer.write(FvBuffer.getvalue())
145                        FvBuffer.close()
146                        FvOffset = FvOffset + FvBufferLen
147                        Size = Size - FvBufferLen
148                        continue
149                    else:
150                        EdkLogger.error("GenFds", GENFDS_ERROR, "FV (%s) is NOT described in FDF file!" % (RegionData))
151                #
152                # Add the exist Fv image into FD buffer
153                #
154                if not Flag:
155                    if FileName is not None:
156                        FileLength = os.stat(FileName)[ST_SIZE]
157                        if FileLength > Size:
158                            EdkLogger.error("GenFds", GENFDS_ERROR,
159                                            "Size of FV File (%s) is larger than Region Size 0x%X specified." \
160                                            % (RegionData, Size))
161                        BinFile = open(FileName, 'rb')
162                        Buffer.write(BinFile.read())
163                        BinFile.close()
164                        Size = Size - FileLength
165            #
166            # Pad the left buffer
167            #
168            if not Flag:
169                self.PadBuffer(Buffer, ErasePolarity, Size)
170
171        if self.RegionType == 'CAPSULE':
172            #
173            # Get Capsule from Capsule Dict
174            #
175            for RegionData in self.RegionDataList:
176                if RegionData.endswith(".cap"):
177                    RegionData = GenFdsGlobalVariable.MacroExtend(RegionData, MacroDict)
178                    GenFdsGlobalVariable.InfLogger('   Region CAPSULE Image Name = .cap : %s' % RegionData)
179                    if RegionData[1] != ':' :
180                        RegionData = mws.join (GenFdsGlobalVariable.WorkSpaceDir, RegionData)
181                    if not os.path.exists(RegionData):
182                        EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=RegionData)
183
184                    FileName = RegionData
185                elif RegionData.upper() + 'cap' in ImageBinDict:
186                    GenFdsGlobalVariable.InfLogger('   Region Name = CAPSULE')
187                    FileName = ImageBinDict[RegionData.upper() + 'cap']
188                else:
189                    #
190                    # Generate Capsule image and Put it into FD buffer
191                    #
192                    CapsuleObj = None
193                    if RegionData.upper() in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict:
194                        CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict[RegionData.upper()]
195
196                    if CapsuleObj is not None :
197                        CapsuleObj.CapsuleName = RegionData.upper()
198                        GenFdsGlobalVariable.InfLogger('   Region Name = CAPSULE')
199                        #
200                        # Call GenFv tool to generate Capsule Image
201                        #
202                        FileName = CapsuleObj.GenCapsule()
203                        CapsuleObj.CapsuleName = None
204                    else:
205                        EdkLogger.error("GenFds", GENFDS_ERROR, "Capsule (%s) is NOT described in FDF file!" % (RegionData))
206
207                #
208                # Add the capsule image into FD buffer
209                #
210                FileLength = os.stat(FileName)[ST_SIZE]
211                if FileLength > Size:
212                    EdkLogger.error("GenFds", GENFDS_ERROR,
213                                    "Size 0x%X of Capsule File (%s) is larger than Region Size 0x%X specified." \
214                                    % (FileLength, RegionData, Size))
215                BinFile = open(FileName, 'rb')
216                Buffer.write(BinFile.read())
217                BinFile.close()
218                Size = Size - FileLength
219            #
220            # Pad the left buffer
221            #
222            self.PadBuffer(Buffer, ErasePolarity, Size)
223
224        if self.RegionType in ('FILE', 'INF'):
225            for RegionData in self.RegionDataList:
226                if self.RegionType == 'INF':
227                    RegionData.__InfParse__(None)
228                    if len(RegionData.BinFileList) != 1:
229                        EdkLogger.error('GenFds', GENFDS_ERROR, 'INF in FD region can only contain one binary: %s' % RegionData)
230                    File = RegionData.BinFileList[0]
231                    RegionData = RegionData.PatchEfiFile(File.Path, File.Type)
232                else:
233                    RegionData = GenFdsGlobalVariable.MacroExtend(RegionData, MacroDict)
234                    if RegionData[1] != ':' :
235                        RegionData = mws.join (GenFdsGlobalVariable.WorkSpaceDir, RegionData)
236                    if not os.path.exists(RegionData):
237                        EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=RegionData)
238                #
239                # Add the file image into FD buffer
240                #
241                FileLength = os.stat(RegionData)[ST_SIZE]
242                if FileLength > Size:
243                    EdkLogger.error("GenFds", GENFDS_ERROR,
244                                    "Size of File (%s) is larger than Region Size 0x%X specified." \
245                                    % (RegionData, Size))
246                GenFdsGlobalVariable.InfLogger('   Region File Name = %s' % RegionData)
247                BinFile = open(RegionData, 'rb')
248                Buffer.write(BinFile.read())
249                BinFile.close()
250                Size = Size - FileLength
251            #
252            # Pad the left buffer
253            #
254            self.PadBuffer(Buffer, ErasePolarity, Size)
255
256        if self.RegionType == 'DATA' :
257            GenFdsGlobalVariable.InfLogger('   Region Name = DATA')
258            DataSize = 0
259            for RegionData in self.RegionDataList:
260                Data = RegionData.split(',')
261                DataSize = DataSize + len(Data)
262                if DataSize > Size:
263                   EdkLogger.error("GenFds", GENFDS_ERROR, "Size of DATA is larger than Region Size ")
264                else:
265                    for item in Data :
266                        Buffer.write(pack('B', int(item, 16)))
267                Size = Size - DataSize
268            #
269            # Pad the left buffer
270            #
271            self.PadBuffer(Buffer, ErasePolarity, Size)
272
273        if self.RegionType is None:
274            GenFdsGlobalVariable.InfLogger('   Region Name = None')
275            self.PadBuffer(Buffer, ErasePolarity, Size)
276
277    ## BlockSizeOfRegion()
278    #
279    #   @param  BlockSizeList        List of block information
280    #   @param  FvObj                The object for FV
281    #
282    def BlockInfoOfRegion(self, BlockSizeList, FvObj):
283        Start = 0
284        End = 0
285        RemindingSize = self.Size
286        ExpectedList = []
287        for (BlockSize, BlockNum, pcd) in BlockSizeList:
288            End = Start + BlockSize * BlockNum
289            # region not started yet
290            if self.Offset >= End:
291                Start = End
292                continue
293            # region located in current blocks
294            else:
295                # region ended within current blocks
296                if self.Offset + self.Size <= End:
297                    ExpectedList.append((BlockSize, (RemindingSize + BlockSize - 1) // BlockSize))
298                    break
299                # region not ended yet
300                else:
301                    # region not started in middle of current blocks
302                    if self.Offset <= Start:
303                        UsedBlockNum = BlockNum
304                    # region started in middle of current blocks
305                    else:
306                        UsedBlockNum = (End - self.Offset) // BlockSize
307                    Start = End
308                    ExpectedList.append((BlockSize, UsedBlockNum))
309                    RemindingSize -= BlockSize * UsedBlockNum
310
311        if FvObj.BlockSizeList == []:
312            FvObj.BlockSizeList = ExpectedList
313        else:
314            # first check whether FvObj.BlockSizeList items have only "BlockSize" or "NumBlocks",
315            # if so, use ExpectedList
316            for Item in FvObj.BlockSizeList:
317                if Item[0] is None or Item[1] is None:
318                    FvObj.BlockSizeList = ExpectedList
319                    break
320            # make sure region size is no smaller than the summed block size in FV
321            Sum = 0
322            for Item in FvObj.BlockSizeList:
323                Sum += Item[0] * Item[1]
324            if self.Size < Sum:
325                EdkLogger.error("GenFds", GENFDS_ERROR, "Total Size of FV %s 0x%x is larger than Region Size 0x%x "
326                                % (FvObj.UiFvName, Sum, self.Size))
327            # check whether the BlockStatements in FV section is appropriate
328            ExpectedListData = ''
329            for Item in ExpectedList:
330                ExpectedListData += "BlockSize = 0x%x\n\tNumBlocks = 0x%x\n\t" % Item
331            Index = 0
332            for Item in FvObj.BlockSizeList:
333                if Item[0] != ExpectedList[Index][0]:
334                    EdkLogger.error("GenFds", GENFDS_ERROR, "BlockStatements of FV %s are not align with FD's, suggested FV BlockStatement"
335                                    % FvObj.UiFvName, ExtraData=ExpectedListData)
336                elif Item[1] != ExpectedList[Index][1]:
337                    if (Item[1] < ExpectedList[Index][1]) and (Index == len(FvObj.BlockSizeList) - 1):
338                        break;
339                    else:
340                        EdkLogger.error("GenFds", GENFDS_ERROR, "BlockStatements of FV %s are not align with FD's, suggested FV BlockStatement"
341                                        % FvObj.UiFvName, ExtraData=ExpectedListData)
342                else:
343                    Index += 1
344
345
346
347