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