]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/GenFds/Region.py
BaseTools: skip updating temporary variable.
[mirror_edk2.git] / BaseTools / Source / Python / GenFds / Region.py
1 ## @file
2 # process FD Region generation
3 #
4 # Copyright (c) 2007 - 2017, 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
30 ## generate Region
31 #
32 #
33 class Region(RegionClassObject):
34
35 ## The constructor
36 #
37 # @param self The object pointer
38 #
39 def __init__(self):
40 RegionClassObject.__init__(self)
41
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 PadData = ''.join(PadByte for i in xrange(0, Size))
60 Buffer.write(PadData)
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 VtfDict VTF objects
73 # @param MacroDict macro value pair
74 # @retval string Generated FV file path
75 #
76
77 def AddToBuffer(self, Buffer, BaseAddress, BlockSizeList, ErasePolarity, ImageBinDict, vtfDict=None, MacroDict={}, Flag=False):
78 Size = self.Size
79 if not Flag:
80 GenFdsGlobalVariable.InfLogger('\nGenerate Region at Offset 0x%X' % self.Offset)
81 GenFdsGlobalVariable.InfLogger(" Region Size = 0x%X" % Size)
82 GenFdsGlobalVariable.SharpCounter = 0
83 if Flag and (self.RegionType != 'FV'):
84 return
85
86 if self.RegionType == 'FV':
87 #
88 # Get Fv from FvDict
89 #
90 self.FvAddress = int(BaseAddress, 16) + self.Offset
91 FvBaseAddress = '0x%X' % self.FvAddress
92 FvOffset = 0
93 for RegionData in self.RegionDataList:
94 FileName = None
95 if RegionData.endswith(".fv"):
96 RegionData = GenFdsGlobalVariable.MacroExtend(RegionData, MacroDict)
97 if not Flag:
98 GenFdsGlobalVariable.InfLogger(' Region FV File Name = .fv : %s' % RegionData)
99 if RegionData[1] != ':' :
100 RegionData = mws.join (GenFdsGlobalVariable.WorkSpaceDir, RegionData)
101 if not os.path.exists(RegionData):
102 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=RegionData)
103
104 FileName = RegionData
105 elif RegionData.upper() + 'fv' in ImageBinDict.keys():
106 if not Flag:
107 GenFdsGlobalVariable.InfLogger(' Region Name = FV')
108 FileName = ImageBinDict[RegionData.upper() + 'fv']
109 else:
110 #
111 # Generate FvImage.
112 #
113 FvObj = None
114 if RegionData.upper() in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys():
115 FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(RegionData.upper())
116
117 if FvObj is not None :
118 if not Flag:
119 GenFdsGlobalVariable.InfLogger(' Region Name = FV')
120 #
121 # Call GenFv tool
122 #
123 self.BlockInfoOfRegion(BlockSizeList, FvObj)
124 self.FvAddress = self.FvAddress + FvOffset
125 FvAlignValue = self.GetFvAlignValue(FvObj.FvAlignment)
126 if self.FvAddress % FvAlignValue != 0:
127 EdkLogger.error("GenFds", GENFDS_ERROR,
128 "FV (%s) is NOT %s Aligned!" % (FvObj.UiFvName, FvObj.FvAlignment))
129 FvBuffer = StringIO.StringIO('')
130 FvBaseAddress = '0x%X' % self.FvAddress
131 BlockSize = None
132 BlockNum = None
133 FvObj.AddToBuffer(FvBuffer, FvBaseAddress, BlockSize, BlockNum, ErasePolarity, vtfDict, Flag=Flag)
134 if Flag:
135 continue
136
137 if FvBuffer.len > 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 + FvBuffer.len
147 Size = Size - FvBuffer.len
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.keys():
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.keys():
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 def GetFvAlignValue(self, Str):
278 AlignValue = 1
279 Granu = 1
280 Str = Str.strip().upper()
281 if Str.endswith('K'):
282 Granu = 1024
283 Str = Str[:-1]
284 elif Str.endswith('M'):
285 Granu = 1024 * 1024
286 Str = Str[:-1]
287 elif Str.endswith('G'):
288 Granu = 1024 * 1024 * 1024
289 Str = Str[:-1]
290 else:
291 pass
292
293 AlignValue = int(Str) * Granu
294 return AlignValue
295
296 ## BlockSizeOfRegion()
297 #
298 # @param BlockSizeList List of block information
299 # @param FvObj The object for FV
300 #
301 def BlockInfoOfRegion(self, BlockSizeList, FvObj):
302 Start = 0
303 End = 0
304 RemindingSize = self.Size
305 ExpectedList = []
306 for (BlockSize, BlockNum, pcd) in BlockSizeList:
307 End = Start + BlockSize * BlockNum
308 # region not started yet
309 if self.Offset >= End:
310 Start = End
311 continue
312 # region located in current blocks
313 else:
314 # region ended within current blocks
315 if self.Offset + self.Size <= End:
316 ExpectedList.append((BlockSize, (RemindingSize + BlockSize - 1) / BlockSize))
317 break
318 # region not ended yet
319 else:
320 # region not started in middle of current blocks
321 if self.Offset <= Start:
322 UsedBlockNum = BlockNum
323 # region started in middle of current blocks
324 else:
325 UsedBlockNum = (End - self.Offset) / BlockSize
326 Start = End
327 ExpectedList.append((BlockSize, UsedBlockNum))
328 RemindingSize -= BlockSize * UsedBlockNum
329
330 if FvObj.BlockSizeList == []:
331 FvObj.BlockSizeList = ExpectedList
332 else:
333 # first check whether FvObj.BlockSizeList items have only "BlockSize" or "NumBlocks",
334 # if so, use ExpectedList
335 for Item in FvObj.BlockSizeList:
336 if Item[0] is None or Item[1] is None:
337 FvObj.BlockSizeList = ExpectedList
338 break
339 # make sure region size is no smaller than the summed block size in FV
340 Sum = 0
341 for Item in FvObj.BlockSizeList:
342 Sum += Item[0] * Item[1]
343 if self.Size < Sum:
344 EdkLogger.error("GenFds", GENFDS_ERROR, "Total Size of FV %s 0x%x is larger than Region Size 0x%x "
345 % (FvObj.UiFvName, Sum, self.Size))
346 # check whether the BlockStatements in FV section is appropriate
347 ExpectedListData = ''
348 for Item in ExpectedList:
349 ExpectedListData += "BlockSize = 0x%x\n\tNumBlocks = 0x%x\n\t" % Item
350 Index = 0
351 for Item in FvObj.BlockSizeList:
352 if Item[0] != ExpectedList[Index][0]:
353 EdkLogger.error("GenFds", GENFDS_ERROR, "BlockStatements of FV %s are not align with FD's, suggested FV BlockStatement"
354 % FvObj.UiFvName, ExtraData=ExpectedListData)
355 elif Item[1] != ExpectedList[Index][1]:
356 if (Item[1] < ExpectedList[Index][1]) and (Index == len(FvObj.BlockSizeList) - 1):
357 break;
358 else:
359 EdkLogger.error("GenFds", GENFDS_ERROR, "BlockStatements of FV %s are not align with FD's, suggested FV BlockStatement"
360 % FvObj.UiFvName, ExtraData=ExpectedListData)
361 else:
362 Index += 1
363
364
365