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