]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/BPDG/GenVpd.py
BaseTools: change the Division Operator in the expression
[mirror_edk2.git] / BaseTools / Source / Python / BPDG / GenVpd.py
1 ## @file
2 # This file include GenVpd class for fix the Vpd type PCD offset, and PcdEntry for describe
3 # and process each entry of vpd type PCD.
4 #
5 # Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.<BR>
6 #
7 # This program and the accompanying materials
8 # are licensed and made available under the terms and conditions of the BSD License
9 # which accompanies this distribution. The full text of the license may be found at
10 # http://opensource.org/licenses/bsd-license.php
11 #
12 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14 #
15
16 import Common.LongFilePathOs as os
17 from io import BytesIO
18 from . import StringTable as st
19 import array
20 import re
21 from Common.LongFilePathSupport import OpenLongFilePath as open
22 from struct import *
23 from Common.DataType import MAX_SIZE_TYPE, MAX_VAL_TYPE
24 import Common.EdkLogger as EdkLogger
25 import Common.BuildToolError as BuildToolError
26
27 _FORMAT_CHAR = {1: 'B',
28 2: 'H',
29 4: 'I',
30 8: 'Q'
31 }
32
33 ## The VPD PCD data structure for store and process each VPD PCD entry.
34 #
35 # This class contain method to format and pack pcd's value.
36 #
37 class PcdEntry:
38 def __init__(self, PcdCName, SkuId,PcdOffset, PcdSize, PcdValue, Lineno=None, FileName=None, PcdUnpackValue=None,
39 PcdBinOffset=None, PcdBinSize=None, Alignment=None):
40 self.PcdCName = PcdCName.strip()
41 self.SkuId = SkuId.strip()
42 self.PcdOffset = PcdOffset.strip()
43 self.PcdSize = PcdSize.strip()
44 self.PcdValue = PcdValue.strip()
45 self.Lineno = Lineno.strip()
46 self.FileName = FileName.strip()
47 self.PcdUnpackValue = PcdUnpackValue
48 self.PcdBinOffset = PcdBinOffset
49 self.PcdBinSize = PcdBinSize
50 self.Alignment = Alignment
51
52 if self.PcdValue == '' :
53 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
54 "Invalid PCD format(Name: %s File: %s line: %s) , no Value specified!" % (self.PcdCName, self.FileName, self.Lineno))
55
56 if self.PcdOffset == '' :
57 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
58 "Invalid PCD format(Name: %s File: %s Line: %s) , no Offset specified!" % (self.PcdCName, self.FileName, self.Lineno))
59
60 if self.PcdSize == '' :
61 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
62 "Invalid PCD format(Name: %s File: %s Line: %s), no PcdSize specified!" % (self.PcdCName, self.FileName, self.Lineno))
63
64 self._GenOffsetValue ()
65
66 ## Analyze the string value to judge the PCD's datum type equal to Boolean or not.
67 #
68 # @param ValueString PCD's value
69 # @param Size PCD's size
70 #
71 # @retval True PCD's datum type is Boolean
72 # @retval False PCD's datum type is not Boolean.
73 #
74 def _IsBoolean(self, ValueString, Size):
75 if (Size == "1"):
76 if ValueString.upper() in ["TRUE", "FALSE"]:
77 return True
78 elif ValueString in ["0", "1", "0x0", "0x1", "0x00", "0x01"]:
79 return True
80
81 return False
82
83 ## Convert the PCD's value from string to integer.
84 #
85 # This function will try to convert the Offset value form string to integer
86 # for both hexadecimal and decimal.
87 #
88 def _GenOffsetValue(self):
89 if self.PcdOffset != "*" :
90 try:
91 self.PcdBinOffset = int (self.PcdOffset)
92 except:
93 try:
94 self.PcdBinOffset = int(self.PcdOffset, 16)
95 except:
96 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
97 "Invalid offset value %s for PCD %s (File: %s Line: %s)" % (self.PcdOffset, self.PcdCName, self.FileName, self.Lineno))
98
99 ## Pack Boolean type VPD PCD's value form string to binary type.
100 #
101 # @param ValueString The boolean type string for pack.
102 #
103 #
104 def _PackBooleanValue(self, ValueString):
105 if ValueString.upper() == "TRUE" or ValueString in ["1", "0x1", "0x01"]:
106 try:
107 self.PcdValue = pack(_FORMAT_CHAR[1], 1)
108 except:
109 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
110 "Invalid size or value for PCD %s to pack(File: %s Line: %s)." % (self.PcdCName, self.FileName, self.Lineno))
111 else:
112 try:
113 self.PcdValue = pack(_FORMAT_CHAR[1], 0)
114 except:
115 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
116 "Invalid size or value for PCD %s to pack(File: %s Line: %s)." % (self.PcdCName, self.FileName, self.Lineno))
117
118 ## Pack Integer type VPD PCD's value form string to binary type.
119 #
120 # @param ValueString The Integer type string for pack.
121 #
122 #
123 def _PackIntValue(self, IntValue, Size):
124 if Size not in _FORMAT_CHAR:
125 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
126 "Invalid size %d for PCD %s in integer datum size(File: %s Line: %s)." % (Size, self.PcdCName, self.FileName, self.Lineno))
127
128 for Type, MaxSize in MAX_SIZE_TYPE.items():
129 if Type == 'BOOLEAN':
130 continue
131 if Size == MaxSize:
132 if IntValue < 0:
133 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
134 "PCD can't be set to negative value %d for PCD %s in %s datum type(File: %s Line: %s)." % (
135 IntValue, self.PcdCName, Type, self.FileName, self.Lineno))
136 elif IntValue > MAX_VAL_TYPE[Type]:
137 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
138 "Too large PCD value %d for datum type %s for PCD %s(File: %s Line: %s)." % (
139 IntValue, Type, self.PcdCName, self.FileName, self.Lineno))
140
141 try:
142 self.PcdValue = pack(_FORMAT_CHAR[Size], IntValue)
143 except:
144 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
145 "Invalid size or value for PCD %s to pack(File: %s Line: %s)." % (self.PcdCName, self.FileName, self.Lineno))
146
147 ## Pack VOID* type VPD PCD's value form string to binary type.
148 #
149 # The VOID* type of string divided into 3 sub-type:
150 # 1: L"String"/L'String', Unicode type string.
151 # 2: "String"/'String', Ascii type string.
152 # 3: {bytearray}, only support byte-array.
153 #
154 # @param ValueString The Integer type string for pack.
155 #
156 def _PackPtrValue(self, ValueString, Size):
157 if ValueString.startswith('L"') or ValueString.startswith("L'"):
158 self._PackUnicode(ValueString, Size)
159 elif ValueString.startswith('{') and ValueString.endswith('}'):
160 self._PackByteArray(ValueString, Size)
161 elif (ValueString.startswith('"') and ValueString.endswith('"')) or (ValueString.startswith("'") and ValueString.endswith("'")):
162 self._PackString(ValueString, Size)
163 else:
164 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
165 "Invalid VOID* type PCD %s value %s (File: %s Line: %s)" % (self.PcdCName, ValueString, self.FileName, self.Lineno))
166
167 ## Pack an Ascii PCD value.
168 #
169 # An Ascii string for a PCD should be in format as ""/''.
170 #
171 def _PackString(self, ValueString, Size):
172 if (Size < 0):
173 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
174 "Invalid parameter Size %s of PCD %s!(File: %s Line: %s)" % (self.PcdBinSize, self.PcdCName, self.FileName, self.Lineno))
175 if (ValueString == ""):
176 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID, "Invalid parameter ValueString %s of PCD %s!(File: %s Line: %s)" % (self.PcdUnpackValue, self.PcdCName, self.FileName, self.Lineno))
177
178 QuotedFlag = True
179 if ValueString.startswith("'"):
180 QuotedFlag = False
181
182 ValueString = ValueString[1:-1]
183 # No null-terminator in 'string'
184 if (QuotedFlag and len(ValueString) + 1 > Size) or (not QuotedFlag and len(ValueString) > Size):
185 EdkLogger.error("BPDG", BuildToolError.RESOURCE_OVERFLOW,
186 "PCD value string %s is exceed to size %d(File: %s Line: %s)" % (ValueString, Size, self.FileName, self.Lineno))
187 try:
188 self.PcdValue = pack('%ds' % Size, bytes(ValueString, 'utf-8'))
189 except:
190 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
191 "Invalid size or value for PCD %s to pack(File: %s Line: %s)." % (self.PcdCName, self.FileName, self.Lineno))
192
193 ## Pack a byte-array PCD value.
194 #
195 # A byte-array for a PCD should be in format as {0x01, 0x02, ...}.
196 #
197 def _PackByteArray(self, ValueString, Size):
198 if (Size < 0):
199 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID, "Invalid parameter Size %s of PCD %s!(File: %s Line: %s)" % (self.PcdBinSize, self.PcdCName, self.FileName, self.Lineno))
200 if (ValueString == ""):
201 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID, "Invalid parameter ValueString %s of PCD %s!(File: %s Line: %s)" % (self.PcdUnpackValue, self.PcdCName, self.FileName, self.Lineno))
202
203 ValueString = ValueString.strip()
204 ValueString = ValueString.lstrip('{').strip('}')
205 ValueList = ValueString.split(',')
206 ValueList = [item.strip() for item in ValueList]
207
208 if len(ValueList) > Size:
209 EdkLogger.error("BPDG", BuildToolError.RESOURCE_OVERFLOW,
210 "The byte array %s is too large for size %d(File: %s Line: %s)" % (ValueString, Size, self.FileName, self.Lineno))
211
212 ReturnArray = array.array('B')
213
214 for Index in range(len(ValueList)):
215 Value = None
216 if ValueList[Index].lower().startswith('0x'):
217 # translate hex value
218 try:
219 Value = int(ValueList[Index], 16)
220 except:
221 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
222 "The value item %s in byte array %s is an invalid HEX value.(File: %s Line: %s)" % \
223 (ValueList[Index], ValueString, self.FileName, self.Lineno))
224 else:
225 # translate decimal value
226 try:
227 Value = int(ValueList[Index], 10)
228 except:
229 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
230 "The value item %s in byte array %s is an invalid DECIMAL value.(File: %s Line: %s)" % \
231 (ValueList[Index], ValueString, self.FileName, self.Lineno))
232
233 if Value > 255:
234 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
235 "The value item %s in byte array %s do not in range 0 ~ 0xFF(File: %s Line: %s)" % \
236 (ValueList[Index], ValueString, self.FileName, self.Lineno))
237
238 ReturnArray.append(Value)
239
240 for Index in range(len(ValueList), Size):
241 ReturnArray.append(0)
242
243 self.PcdValue = ReturnArray.tolist()
244
245 ## Pack a unicode PCD value into byte array.
246 #
247 # A unicode string for a PCD should be in format as L""/L''.
248 #
249 def _PackUnicode(self, UnicodeString, Size):
250 if (Size < 0):
251 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID, "Invalid parameter Size %s of PCD %s!(File: %s Line: %s)" % \
252 (self.PcdBinSize, self.PcdCName, self.FileName, self.Lineno))
253
254 QuotedFlag = True
255 if UnicodeString.startswith("L'"):
256 QuotedFlag = False
257 UnicodeString = UnicodeString[2:-1]
258
259 # No null-terminator in L'string'
260 if (QuotedFlag and (len(UnicodeString) + 1) * 2 > Size) or (not QuotedFlag and len(UnicodeString) * 2 > Size):
261 EdkLogger.error("BPDG", BuildToolError.RESOURCE_OVERFLOW,
262 "The size of unicode string %s is too larger for size %s(File: %s Line: %s)" % \
263 (UnicodeString, Size, self.FileName, self.Lineno))
264
265 ReturnArray = array.array('B')
266 for Value in UnicodeString:
267 try:
268 ReturnArray.append(ord(Value))
269 ReturnArray.append(0)
270 except:
271 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID,
272 "Invalid unicode character %s in unicode string %s(File: %s Line: %s)" % \
273 (Value, UnicodeString, self.FileName, self.Lineno))
274
275 for Index in range(len(UnicodeString) * 2, Size):
276 ReturnArray.append(0)
277
278 self.PcdValue = ReturnArray.tolist()
279
280
281
282 ## The class implementing the BPDG VPD PCD offset fix process
283 #
284 # The VPD PCD offset fix process includes:
285 # 1. Parse the input guided.txt file and store it in the data structure;
286 # 2. Format the input file data to remove unused lines;
287 # 3. Fixed offset if needed;
288 # 4. Generate output file, including guided.map and guided.bin file;
289 #
290 class GenVPD :
291 ## Constructor of DscBuildData
292 #
293 # Initialize object of GenVPD
294 # @Param InputFileName The filename include the vpd type pcd information
295 # @param MapFileName The filename of map file that stores vpd type pcd information.
296 # This file will be generated by the BPDG tool after fix the offset
297 # and adjust the offset to make the pcd data aligned.
298 # @param VpdFileName The filename of Vpd file that hold vpd pcd information.
299 #
300 def __init__(self, InputFileName, MapFileName, VpdFileName):
301 self.InputFileName = InputFileName
302 self.MapFileName = MapFileName
303 self.VpdFileName = VpdFileName
304 self.FileLinesList = []
305 self.PcdFixedOffsetSizeList = []
306 self.PcdUnknownOffsetList = []
307 try:
308 fInputfile = open(InputFileName, "r")
309 try:
310 self.FileLinesList = fInputfile.readlines()
311 except:
312 EdkLogger.error("BPDG", BuildToolError.FILE_READ_FAILURE, "File read failed for %s" % InputFileName, None)
313 finally:
314 fInputfile.close()
315 except:
316 EdkLogger.error("BPDG", BuildToolError.FILE_OPEN_FAILURE, "File open failed for %s" % InputFileName, None)
317
318 ##
319 # Parser the input file which is generated by the build tool. Convert the value of each pcd's
320 # from string to it's real format. Also remove the useless line in the input file.
321 #
322 def ParserInputFile (self):
323 count = 0
324 for line in self.FileLinesList:
325 # Strip "\r\n" generated by readlines ().
326 line = line.strip()
327 line = line.rstrip(os.linesep)
328
329 # Skip the comment line
330 if (not line.startswith("#")) and len(line) > 1 :
331 #
332 # Enhanced for support "|" character in the string.
333 #
334 ValueList = ['', '', '', '', '']
335
336 ValueRe = re.compile(r'\s*L?\".*\|.*\"\s*$')
337 PtrValue = ValueRe.findall(line)
338
339 ValueUpdateFlag = False
340
341 if len(PtrValue) >= 1:
342 line = re.sub(ValueRe, '', line)
343 ValueUpdateFlag = True
344
345 TokenList = line.split('|')
346 ValueList[0:len(TokenList)] = TokenList
347
348 if ValueUpdateFlag:
349 ValueList[4] = PtrValue[0]
350 self.FileLinesList[count] = ValueList
351 # Store the line number
352 self.FileLinesList[count].append(str(count + 1))
353 elif len(line) <= 1 :
354 # Set the blank line to "None"
355 self.FileLinesList[count] = None
356 else :
357 # Set the comment line to "None"
358 self.FileLinesList[count] = None
359 count += 1
360
361 # The line count contain usage information
362 count = 0
363 # Delete useless lines
364 while (True) :
365 try :
366 if (self.FileLinesList[count] is None) :
367 del(self.FileLinesList[count])
368 else :
369 count += 1
370 except :
371 break
372 #
373 # After remove the useless line, if there are no data remain in the file line list,
374 # Report warning messages to user's.
375 #
376 if len(self.FileLinesList) == 0 :
377 EdkLogger.warn('BPDG', BuildToolError.RESOURCE_NOT_AVAILABLE,
378 "There are no VPD type pcds defined in DSC file, Please check it.")
379
380 # Process the pcds one by one base on the pcd's value and size
381 count = 0
382 for line in self.FileLinesList:
383 if line is not None :
384 PCD = PcdEntry(line[0], line[1], line[2], line[3], line[4], line[5], self.InputFileName)
385 # Strip the space char
386 PCD.PcdCName = PCD.PcdCName.strip(' ')
387 PCD.SkuId = PCD.SkuId.strip(' ')
388 PCD.PcdOffset = PCD.PcdOffset.strip(' ')
389 PCD.PcdSize = PCD.PcdSize.strip(' ')
390 PCD.PcdValue = PCD.PcdValue.strip(' ')
391 PCD.Lineno = PCD.Lineno.strip(' ')
392
393 #
394 # Store the original pcd value.
395 # This information will be useful while generate the output map file.
396 #
397 PCD.PcdUnpackValue = str(PCD.PcdValue)
398
399 #
400 # Translate PCD size string to an integer value.
401 PackSize = None
402 try:
403 PackSize = int(PCD.PcdSize, 10)
404 PCD.PcdBinSize = PackSize
405 except:
406 try:
407 PackSize = int(PCD.PcdSize, 16)
408 PCD.PcdBinSize = PackSize
409 except:
410 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID, "Invalid PCD size value %s at file: %s line: %s" % (PCD.PcdSize, self.InputFileName, PCD.Lineno))
411
412 #
413 # If value is Unicode string (e.g. L""), then use 2-byte alignment
414 # If value is byte array (e.g. {}), then use 8-byte alignment
415 #
416 PCD.PcdOccupySize = PCD.PcdBinSize
417 if PCD.PcdUnpackValue.startswith("{"):
418 Alignment = 8
419 elif PCD.PcdUnpackValue.startswith("L"):
420 Alignment = 2
421 else:
422 Alignment = 1
423
424 PCD.Alignment = Alignment
425 if PCD.PcdOffset != '*':
426 if PCD.PcdOccupySize % Alignment != 0:
427 if PCD.PcdUnpackValue.startswith("{"):
428 EdkLogger.warn("BPDG", "The offset value of PCD %s is not 8-byte aligned!" %(PCD.PcdCName), File=self.InputFileName)
429 else:
430 EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID, 'The offset value of PCD %s should be %s-byte aligned.' % (PCD.PcdCName, Alignment))
431 else:
432 if PCD.PcdOccupySize % Alignment != 0:
433 PCD.PcdOccupySize = (PCD.PcdOccupySize // Alignment + 1) * Alignment
434
435 PackSize = PCD.PcdOccupySize
436 if PCD._IsBoolean(PCD.PcdValue, PCD.PcdSize):
437 PCD._PackBooleanValue(PCD.PcdValue)
438 self.FileLinesList[count] = PCD
439 count += 1
440 continue
441 #
442 # Try to translate value to an integer firstly.
443 #
444 IsInteger = True
445 PackValue = None
446 try:
447 PackValue = int(PCD.PcdValue)
448 except:
449 try:
450 PackValue = int(PCD.PcdValue, 16)
451 except:
452 IsInteger = False
453
454 if IsInteger:
455 PCD._PackIntValue(PackValue, PackSize)
456 else:
457 PCD._PackPtrValue(PCD.PcdValue, PackSize)
458
459 self.FileLinesList[count] = PCD
460 count += 1
461 else :
462 continue
463
464 ##
465 # This function used to create a clean list only contain useful information and reorganized to make it
466 # easy to be sorted
467 #
468 def FormatFileLine (self) :
469
470 for eachPcd in self.FileLinesList :
471 if eachPcd.PcdOffset != '*' :
472 # Use pcd's Offset value as key, and pcd's Value as value
473 self.PcdFixedOffsetSizeList.append(eachPcd)
474 else :
475 # Use pcd's CName as key, and pcd's Size as value
476 self.PcdUnknownOffsetList.append(eachPcd)
477
478
479 ##
480 # This function is use to fix the offset value which the not specified in the map file.
481 # Usually it use the star (meaning any offset) character in the offset field
482 #
483 def FixVpdOffset (self):
484 # At first, the offset should start at 0
485 # Sort fixed offset list in order to find out where has free spaces for the pcd's offset
486 # value is "*" to insert into.
487
488 self.PcdFixedOffsetSizeList.sort(key=lambda x: x.PcdBinOffset)
489
490 #
491 # Sort the un-fixed pcd's offset by it's size.
492 #
493 self.PcdUnknownOffsetList.sort(key=lambda x: x.PcdBinSize)
494
495 index =0
496 for pcd in self.PcdUnknownOffsetList:
497 index += 1
498 if pcd.PcdCName == ".".join(("gEfiMdeModulePkgTokenSpaceGuid", "PcdNvStoreDefaultValueBuffer")):
499 if index != len(self.PcdUnknownOffsetList):
500 for i in range(len(self.PcdUnknownOffsetList) - index):
501 self.PcdUnknownOffsetList[index+i -1 ], self.PcdUnknownOffsetList[index+i] = self.PcdUnknownOffsetList[index+i], self.PcdUnknownOffsetList[index+i -1]
502
503 #
504 # Process all Offset value are "*"
505 #
506 if (len(self.PcdFixedOffsetSizeList) == 0) and (len(self.PcdUnknownOffsetList) != 0) :
507 # The offset start from 0
508 NowOffset = 0
509 for Pcd in self.PcdUnknownOffsetList :
510 if NowOffset % Pcd.Alignment != 0:
511 NowOffset = (NowOffset // Pcd.Alignment + 1) * Pcd.Alignment
512 Pcd.PcdBinOffset = NowOffset
513 Pcd.PcdOffset = str(hex(Pcd.PcdBinOffset))
514 NowOffset += Pcd.PcdOccupySize
515
516 self.PcdFixedOffsetSizeList = self.PcdUnknownOffsetList
517 return
518
519 # Check the offset of VPD type pcd's offset start from 0.
520 if self.PcdFixedOffsetSizeList[0].PcdBinOffset != 0 :
521 EdkLogger.warn("BPDG", "The offset of VPD type pcd should start with 0, please check it.",
522 None)
523
524 # Judge whether the offset in fixed pcd offset list is overlapped or not.
525 lenOfList = len(self.PcdFixedOffsetSizeList)
526 count = 0
527 while (count < lenOfList - 1) :
528 PcdNow = self.PcdFixedOffsetSizeList[count]
529 PcdNext = self.PcdFixedOffsetSizeList[count+1]
530 # Two pcd's offset is same
531 if PcdNow.PcdBinOffset == PcdNext.PcdBinOffset :
532 EdkLogger.error("BPDG", BuildToolError.ATTRIBUTE_GET_FAILURE,
533 "The offset of %s at line: %s is same with %s at line: %s in file %s" % \
534 (PcdNow.PcdCName, PcdNow.Lineno, PcdNext.PcdCName, PcdNext.Lineno, PcdNext.FileName),
535 None)
536
537 # Overlapped
538 if PcdNow.PcdBinOffset + PcdNow.PcdOccupySize > PcdNext.PcdBinOffset :
539 EdkLogger.error("BPDG", BuildToolError.ATTRIBUTE_GET_FAILURE,
540 "The offset of %s at line: %s is overlapped with %s at line: %s in file %s" % \
541 (PcdNow.PcdCName, PcdNow.Lineno, PcdNext.PcdCName, PcdNext.Lineno, PcdNext.FileName),
542 None)
543
544 # Has free space, raise a warning message
545 if PcdNow.PcdBinOffset + PcdNow.PcdOccupySize < PcdNext.PcdBinOffset :
546 EdkLogger.warn("BPDG", BuildToolError.ATTRIBUTE_GET_FAILURE,
547 "The offsets have free space of between %s at line: %s and %s at line: %s in file %s" % \
548 (PcdNow.PcdCName, PcdNow.Lineno, PcdNext.PcdCName, PcdNext.Lineno, PcdNext.FileName),
549 None)
550 count += 1
551
552 LastOffset = self.PcdFixedOffsetSizeList[0].PcdBinOffset
553 FixOffsetSizeListCount = 0
554 lenOfList = len(self.PcdFixedOffsetSizeList)
555 lenOfUnfixedList = len(self.PcdUnknownOffsetList)
556
557 ##
558 # Insert the un-fixed offset pcd's list into fixed offset pcd's list if has free space between those pcds.
559 #
560 while (FixOffsetSizeListCount < lenOfList) :
561
562 eachFixedPcd = self.PcdFixedOffsetSizeList[FixOffsetSizeListCount]
563 NowOffset = eachFixedPcd.PcdBinOffset
564
565 # Has free space
566 if LastOffset < NowOffset :
567 if lenOfUnfixedList != 0 :
568 countOfUnfixedList = 0
569 while(countOfUnfixedList < lenOfUnfixedList) :
570 eachUnfixedPcd = self.PcdUnknownOffsetList[countOfUnfixedList]
571 needFixPcdSize = eachUnfixedPcd.PcdOccupySize
572 # Not been fixed
573 if eachUnfixedPcd.PcdOffset == '*' :
574 if LastOffset % eachUnfixedPcd.Alignment != 0:
575 LastOffset = (LastOffset // eachUnfixedPcd.Alignment + 1) * eachUnfixedPcd.Alignment
576 # The offset un-fixed pcd can write into this free space
577 if needFixPcdSize <= (NowOffset - LastOffset) :
578 # Change the offset value of un-fixed pcd
579 eachUnfixedPcd.PcdOffset = str(hex(LastOffset))
580 eachUnfixedPcd.PcdBinOffset = LastOffset
581 # Insert this pcd into fixed offset pcd list.
582 self.PcdFixedOffsetSizeList.insert(FixOffsetSizeListCount, eachUnfixedPcd)
583
584 # Delete the item's offset that has been fixed and added into fixed offset list
585 self.PcdUnknownOffsetList.pop(countOfUnfixedList)
586
587 # After item added, should enlarge the length of fixed pcd offset list
588 lenOfList += 1
589 FixOffsetSizeListCount += 1
590
591 # Decrease the un-fixed pcd offset list's length
592 lenOfUnfixedList -= 1
593
594 # Modify the last offset value
595 LastOffset += needFixPcdSize
596 else :
597 # It can not insert into those two pcds, need to check still has other space can store it.
598 LastOffset = NowOffset + self.PcdFixedOffsetSizeList[FixOffsetSizeListCount].PcdOccupySize
599 FixOffsetSizeListCount += 1
600 break
601
602 # Set the FixOffsetSizeListCount = lenOfList for quit the loop
603 else :
604 FixOffsetSizeListCount = lenOfList
605
606 # No free space, smoothly connect with previous pcd.
607 elif LastOffset == NowOffset :
608 LastOffset = NowOffset + eachFixedPcd.PcdOccupySize
609 FixOffsetSizeListCount += 1
610 # Usually it will not enter into this thunk, if so, means it overlapped.
611 else :
612 EdkLogger.error("BPDG", BuildToolError.ATTRIBUTE_NOT_AVAILABLE,
613 "The offset value definition has overlapped at pcd: %s, it's offset is: %s, in file: %s line: %s" % \
614 (eachFixedPcd.PcdCName, eachFixedPcd.PcdOffset, eachFixedPcd.InputFileName, eachFixedPcd.Lineno),
615 None)
616 FixOffsetSizeListCount += 1
617
618 # Continue to process the un-fixed offset pcd's list, add this time, just append them behind the fixed pcd's offset list.
619 lenOfUnfixedList = len(self.PcdUnknownOffsetList)
620 lenOfList = len(self.PcdFixedOffsetSizeList)
621 while (lenOfUnfixedList > 0) :
622 # Still has items need to process
623 # The last pcd instance
624 LastPcd = self.PcdFixedOffsetSizeList[lenOfList-1]
625 NeedFixPcd = self.PcdUnknownOffsetList[0]
626
627 NeedFixPcd.PcdBinOffset = LastPcd.PcdBinOffset + LastPcd.PcdOccupySize
628 if NeedFixPcd.PcdBinOffset % NeedFixPcd.Alignment != 0:
629 NeedFixPcd.PcdBinOffset = (NeedFixPcd.PcdBinOffset // NeedFixPcd.Alignment + 1) * NeedFixPcd.Alignment
630
631 NeedFixPcd.PcdOffset = str(hex(NeedFixPcd.PcdBinOffset))
632
633 # Insert this pcd into fixed offset pcd list's tail.
634 self.PcdFixedOffsetSizeList.insert(lenOfList, NeedFixPcd)
635 # Delete the item's offset that has been fixed and added into fixed offset list
636 self.PcdUnknownOffsetList.pop(0)
637
638 lenOfList += 1
639 lenOfUnfixedList -= 1
640 ##
641 # Write the final data into output files.
642 #
643 def GenerateVpdFile (self, MapFileName, BinFileName):
644 #Open an VPD file to process
645
646 try:
647 fVpdFile = open(BinFileName, "wb", 0)
648 except:
649 # Open failed
650 EdkLogger.error("BPDG", BuildToolError.FILE_OPEN_FAILURE, "File open failed for %s" % self.VpdFileName, None)
651
652 try :
653 fMapFile = open(MapFileName, "w")
654 except:
655 # Open failed
656 EdkLogger.error("BPDG", BuildToolError.FILE_OPEN_FAILURE, "File open failed for %s" % self.MapFileName, None)
657
658 # Use a instance of BytesIO to cache data
659 fStringIO = BytesIO()
660
661 # Write the header of map file.
662 try :
663 fMapFile.write (st.MAP_FILE_COMMENT_TEMPLATE + "\n")
664 except:
665 EdkLogger.error("BPDG", BuildToolError.FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the file been locked or using by other applications." % self.MapFileName, None)
666
667 for eachPcd in self.PcdFixedOffsetSizeList :
668 # write map file
669 try :
670 fMapFile.write("%s | %s | %s | %s | %s \n" % (eachPcd.PcdCName, eachPcd.SkuId, eachPcd.PcdOffset, eachPcd.PcdSize, eachPcd.PcdUnpackValue))
671 except:
672 EdkLogger.error("BPDG", BuildToolError.FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the file been locked or using by other applications." % self.MapFileName, None)
673
674 # Write Vpd binary file
675 fStringIO.seek (eachPcd.PcdBinOffset)
676 if isinstance(eachPcd.PcdValue, list):
677 fStringIO.write(bytes(eachPcd.PcdValue))
678 else:
679 fStringIO.write (eachPcd.PcdValue)
680
681 try :
682 fVpdFile.write (fStringIO.getvalue())
683 except:
684 EdkLogger.error("BPDG", BuildToolError.FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the file been locked or using by other applications." % self.VpdFileName, None)
685
686 fStringIO.close ()
687 fVpdFile.close ()
688 fMapFile.close ()
689