]> git.proxmox.com Git - mirror_edk2.git/blob - IntelFsp2Pkg/Tools/GenCfgOpt.py
6dc1b10b34697c7b7fb490135c6cf9c767b0c628
[mirror_edk2.git] / IntelFsp2Pkg / Tools / GenCfgOpt.py
1 ## @ GenCfgOpt.py
2 #
3 # Copyright (c) 2014 - 2017, Intel Corporation. All rights reserved.<BR>
4 # This program and the accompanying materials are licensed and made available under
5 # the terms and conditions of the BSD License that accompanies this distribution.
6 # The full text of the license may be found at
7 # http://opensource.org/licenses/bsd-license.php.
8 #
9 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11 #
12 ##
13
14 import os
15 import re
16 import sys
17 import struct
18 from datetime import date
19
20 # Generated file copyright header
21
22 __copyright_txt__ = """## @file
23 #
24 # THIS IS AUTO-GENERATED FILE BY BUILD TOOLS AND PLEASE DO NOT MAKE MODIFICATION.
25 #
26 # This file lists all VPD informations for a platform collected by build.exe.
27 #
28 # Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>
29 # This program and the accompanying materials
30 # are licensed and made available under the terms and conditions of the BSD License
31 # which accompanies this distribution. The full text of the license may be found at
32 # http://opensource.org/licenses/bsd-license.php
33 #
34 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
35 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
36 #
37 """
38
39 __copyright_bsf__ = """/** @file
40
41 Boot Setting File for Platform Configuration.
42
43 Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>
44 This program and the accompanying materials
45 are licensed and made available under the terms and conditions of the BSD License
46 which accompanies this distribution. The full text of the license may be found at
47 http://opensource.org/licenses/bsd-license.php
48
49 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
50 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
51
52 This file is automatically generated. Please do NOT modify !!!
53
54 **/
55
56 """
57
58 __copyright_h__ = """/** @file
59
60 Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>
61
62 Redistribution and use in source and binary forms, with or without modification,
63 are permitted provided that the following conditions are met:
64
65 * Redistributions of source code must retain the above copyright notice, this
66 list of conditions and the following disclaimer.
67 * Redistributions in binary form must reproduce the above copyright notice, this
68 list of conditions and the following disclaimer in the documentation and/or
69 other materials provided with the distribution.
70 * Neither the name of Intel Corporation nor the names of its contributors may
71 be used to endorse or promote products derived from this software without
72 specific prior written permission.
73
74 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
75 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
76 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
77 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
78 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
79 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
80 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
81 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
82 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
83 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
84 THE POSSIBILITY OF SUCH DAMAGE.
85
86 This file is automatically generated. Please do NOT modify !!!
87
88 **/
89 """
90
91 class CLogicalExpression:
92 def __init__(self):
93 self.index = 0
94 self.string = ''
95
96 def errExit(self, err = ''):
97 print "ERROR: Express parsing for:"
98 print " %s" % self.string
99 print " %s^" % (' ' * self.index)
100 if err:
101 print "INFO : %s" % err
102 raise SystemExit
103
104 def getNonNumber (self, n1, n2):
105 if not n1.isdigit():
106 return n1
107 if not n2.isdigit():
108 return n2
109 return None
110
111 def getCurr(self, lens = 1):
112 try:
113 if lens == -1:
114 return self.string[self.index :]
115 else:
116 if self.index + lens > len(self.string):
117 lens = len(self.string) - self.index
118 return self.string[self.index : self.index + lens]
119 except Exception:
120 return ''
121
122 def isLast(self):
123 return self.index == len(self.string)
124
125 def moveNext(self, len = 1):
126 self.index += len
127
128 def skipSpace(self):
129 while not self.isLast():
130 if self.getCurr() in ' \t':
131 self.moveNext()
132 else:
133 return
134
135 def normNumber (self, val):
136 return True if val else False
137
138 def getNumber(self, var):
139 var = var.strip()
140 if re.match('^0x[a-fA-F0-9]+$', var):
141 value = int(var, 16)
142 elif re.match('^[+-]?\d+$', var):
143 value = int(var, 10)
144 else:
145 value = None
146 return value
147
148 def parseValue(self):
149 self.skipSpace()
150 var = ''
151 while not self.isLast():
152 char = self.getCurr()
153 if re.match('^[\w.]', char):
154 var += char
155 self.moveNext()
156 else:
157 break
158 val = self.getNumber(var)
159 if val is None:
160 value = var
161 else:
162 value = "%d" % val
163 return value
164
165 def parseSingleOp(self):
166 self.skipSpace()
167 if re.match('^NOT\W', self.getCurr(-1)):
168 self.moveNext(3)
169 op = self.parseBrace()
170 val = self.getNumber (op)
171 if val is None:
172 self.errExit ("'%s' is not a number" % op)
173 return "%d" % (not self.normNumber(int(op)))
174 else:
175 return self.parseValue()
176
177 def parseBrace(self):
178 self.skipSpace()
179 char = self.getCurr()
180 if char == '(':
181 self.moveNext()
182 value = self.parseExpr()
183 self.skipSpace()
184 if self.getCurr() != ')':
185 self.errExit ("Expecting closing brace or operator")
186 self.moveNext()
187 return value
188 else:
189 value = self.parseSingleOp()
190 return value
191
192 def parseCompare(self):
193 value = self.parseBrace()
194 while True:
195 self.skipSpace()
196 char = self.getCurr()
197 if char in ['<', '>']:
198 self.moveNext()
199 next = self.getCurr()
200 if next == '=':
201 op = char + next
202 self.moveNext()
203 else:
204 op = char
205 result = self.parseBrace()
206 test = self.getNonNumber(result, value)
207 if test is None:
208 value = "%d" % self.normNumber(eval (value + op + result))
209 else:
210 self.errExit ("'%s' is not a valid number for comparision" % test)
211 elif char in ['=', '!']:
212 op = self.getCurr(2)
213 if op in ['==', '!=']:
214 self.moveNext(2)
215 result = self.parseBrace()
216 test = self.getNonNumber(result, value)
217 if test is None:
218 value = "%d" % self.normNumber((eval (value + op + result)))
219 else:
220 value = "%d" % self.normNumber(eval ("'" + value + "'" + op + "'" + result + "'"))
221 else:
222 break
223 else:
224 break
225 return value
226
227 def parseAnd(self):
228 value = self.parseCompare()
229 while True:
230 self.skipSpace()
231 if re.match('^AND\W', self.getCurr(-1)):
232 self.moveNext(3)
233 result = self.parseCompare()
234 test = self.getNonNumber(result, value)
235 if test is None:
236 value = "%d" % self.normNumber(int(value) & int(result))
237 else:
238 self.errExit ("'%s' is not a valid op number for AND" % test)
239 else:
240 break
241 return value
242
243 def parseOrXor(self):
244 value = self.parseAnd()
245 op = None
246 while True:
247 self.skipSpace()
248 op = None
249 if re.match('^XOR\W', self.getCurr(-1)):
250 self.moveNext(3)
251 op = '^'
252 elif re.match('^OR\W', self.getCurr(-1)):
253 self.moveNext(2)
254 op = '|'
255 else:
256 break
257 if op:
258 result = self.parseAnd()
259 test = self.getNonNumber(result, value)
260 if test is None:
261 value = "%d" % self.normNumber(eval (value + op + result))
262 else:
263 self.errExit ("'%s' is not a valid op number for XOR/OR" % test)
264 return value
265
266 def parseExpr(self):
267 return self.parseOrXor()
268
269 def getResult(self):
270 value = self.parseExpr()
271 self.skipSpace()
272 if not self.isLast():
273 self.errExit ("Unexpected character found '%s'" % self.getCurr())
274 test = self.getNumber(value)
275 if test is None:
276 self.errExit ("Result '%s' is not a number" % value)
277 return int(value)
278
279 def evaluateExpress (self, Expr):
280 self.index = 0
281 self.string = Expr
282 if self.getResult():
283 Result = True
284 else:
285 Result = False
286 return Result
287
288 class CGenCfgOpt:
289 def __init__(self):
290 self.Debug = False
291 self.Error = ''
292 self.ReleaseMode = True
293
294 self._GlobalDataDef = """
295 GlobalDataDef
296 SKUID = 0, "DEFAULT"
297 EndGlobalData
298
299 """
300 self._BuidinOptionTxt = """
301 List &EN_DIS
302 Selection 0x1 , "Enabled"
303 Selection 0x0 , "Disabled"
304 EndList
305
306 """
307
308 self._BsfKeyList = ['FIND','NAME','HELP','TYPE','PAGE','OPTION','ORDER']
309 self._HdrKeyList = ['HEADER','STRUCT', 'EMBED', 'COMMENT']
310 self._BuidinOption = {'$EN_DIS' : 'EN_DIS'}
311
312 self._MacroDict = {}
313 self._PcdsDict = {}
314 self._CfgBlkDict = {}
315 self._CfgPageDict = {}
316 self._CfgItemList = []
317 self._DscFile = ''
318 self._FvDir = ''
319 self._MapVer = 0
320
321 def ParseBuildMode (self, OutputStr):
322 if "RELEASE_" in OutputStr:
323 self.ReleaseMode = True
324 if "DEBUG_" in OutputStr:
325 self.ReleaseMode = False
326 return
327
328 def ParseMacros (self, MacroDefStr):
329 # ['-DABC=1', '-D', 'CFG_DEBUG=1', '-D', 'CFG_OUTDIR=Build']
330 self._MacroDict = {}
331 IsExpression = False
332 for Macro in MacroDefStr:
333 if Macro.startswith('-D'):
334 IsExpression = True
335 if len(Macro) > 2:
336 Macro = Macro[2:]
337 else :
338 continue
339 if IsExpression:
340 IsExpression = False
341 Match = re.match("(\w+)=(.+)", Macro)
342 if Match:
343 self._MacroDict[Match.group(1)] = Match.group(2)
344 else:
345 Match = re.match("(\w+)", Macro)
346 if Match:
347 self._MacroDict[Match.group(1)] = ''
348 if len(self._MacroDict) == 0:
349 Error = 1
350 else:
351 Error = 0
352 if self.Debug:
353 print "INFO : Macro dictionary:"
354 for Each in self._MacroDict:
355 print " $(%s) = [ %s ]" % (Each , self._MacroDict[Each])
356 return Error
357
358 def EvaulateIfdef (self, Macro):
359 Result = Macro in self._MacroDict
360 if self.Debug:
361 print "INFO : Eval Ifdef [%s] : %s" % (Macro, Result)
362 return Result
363
364 def ExpandMacros (self, Input):
365 Line = Input
366 Match = re.findall("\$\(\w+\)", Input)
367 if Match:
368 for Each in Match:
369 Variable = Each[2:-1]
370 if Variable in self._MacroDict:
371 Line = Line.replace(Each, self._MacroDict[Variable])
372 else:
373 if self.Debug:
374 print "WARN : %s is not defined" % Each
375 Line = Line.replace(Each, Each[2:-1])
376 return Line
377
378 def ExpandPcds (self, Input):
379 Line = Input
380 Match = re.findall("(\w+\.\w+)", Input)
381 if Match:
382 for PcdName in Match:
383 if PcdName in self._PcdsDict:
384 Line = Line.replace(PcdName, self._PcdsDict[PcdName])
385 else:
386 if self.Debug:
387 print "WARN : %s is not defined" % PcdName
388 return Line
389
390 def EvaluateExpress (self, Expr):
391 ExpExpr = self.ExpandPcds(Expr)
392 ExpExpr = self.ExpandMacros(ExpExpr)
393 LogExpr = CLogicalExpression()
394 Result = LogExpr.evaluateExpress (ExpExpr)
395 if self.Debug:
396 print "INFO : Eval Express [%s] : %s" % (Expr, Result)
397 return Result
398
399 def FormatListValue(self, ConfigDict):
400 Struct = ConfigDict['struct']
401 if Struct not in ['UINT8','UINT16','UINT32','UINT64']:
402 return
403
404 dataarray = []
405 binlist = ConfigDict['value'][1:-1].split(',')
406 for each in binlist:
407 each = each.strip()
408 if each.startswith('0x'):
409 value = int(each, 16)
410 else:
411 value = int(each)
412 dataarray.append(value)
413
414 unit = int(Struct[4:]) / 8
415 if int(ConfigDict['length']) != unit * len(dataarray):
416 raise Exception("Array size is not proper for '%s' !" % ConfigDict['cname'])
417
418 bytearray = []
419 for each in dataarray:
420 value = each
421 for loop in xrange(unit):
422 bytearray.append("0x%02X" % (value & 0xFF))
423 value = value >> 8
424 newvalue = '{' + ','.join(bytearray) + '}'
425 ConfigDict['value'] = newvalue
426 return ""
427
428 def ParseDscFile (self, DscFile, FvDir):
429 self._CfgItemList = []
430 self._CfgPageDict = {}
431 self._CfgBlkDict = {}
432 self._DscFile = DscFile
433 self._FvDir = FvDir
434
435 IsDefSect = False
436 IsPcdSect = False
437 IsUpdSect = False
438 IsVpdSect = False
439
440 IfStack = []
441 ElifStack = []
442 Error = 0
443 ConfigDict = {}
444
445 DscFd = open(DscFile, "r")
446 DscLines = DscFd.readlines()
447 DscFd.close()
448
449 while len(DscLines):
450 DscLine = DscLines.pop(0).strip()
451 Handle = False
452 Match = re.match("^\[(.+)\]", DscLine)
453 if Match is not None:
454 IsDefSect = False
455 IsPcdSect = False
456 IsVpdSect = False
457 IsUpdSect = False
458 if Match.group(1).lower() == "Defines".lower():
459 IsDefSect = True
460 if Match.group(1).lower() == "PcdsFeatureFlag".lower():
461 IsPcdSect = True
462 elif Match.group(1).lower() == "PcdsDynamicVpd.Upd".lower():
463 ConfigDict = {}
464 ConfigDict['header'] = 'ON'
465 ConfigDict['region'] = 'UPD'
466 ConfigDict['order'] = -1
467 ConfigDict['page'] = ''
468 ConfigDict['name'] = ''
469 ConfigDict['find'] = ''
470 ConfigDict['struct'] = ''
471 ConfigDict['embed'] = ''
472 ConfigDict['comment'] = ''
473 ConfigDict['subreg'] = []
474 IsUpdSect = True
475 else:
476 if IsDefSect or IsPcdSect or IsUpdSect or IsVpdSect:
477 if re.match("^!else($|\s+#.+)", DscLine):
478 if IfStack:
479 IfStack[-1] = not IfStack[-1]
480 else:
481 print("ERROR: No paired '!if' found for '!else' for line '%s'" % DscLine)
482 raise SystemExit
483 elif re.match("^!endif($|\s+#.+)", DscLine):
484 if IfStack:
485 IfStack.pop()
486 Level = ElifStack.pop()
487 if Level > 0:
488 del IfStack[-Level:]
489 else:
490 print("ERROR: No paired '!if' found for '!endif' for line '%s'" % DscLine)
491 raise SystemExit
492 else:
493 Result = False
494 Match = re.match("!(ifdef|ifndef)\s+(.+)", DscLine)
495 if Match:
496 Result = self.EvaulateIfdef (Match.group(2))
497 if Match.group(1) == 'ifndef':
498 Result = not Result
499 IfStack.append(Result)
500 ElifStack.append(0)
501 else:
502 Match = re.match("!(if|elseif)\s+(.+)", DscLine)
503 if Match:
504 Result = self.EvaluateExpress(Match.group(2))
505 if Match.group(1) == "if":
506 ElifStack.append(0)
507 IfStack.append(Result)
508 else: #elseif
509 if IfStack:
510 IfStack[-1] = not IfStack[-1]
511 IfStack.append(Result)
512 ElifStack[-1] = ElifStack[-1] + 1
513 else:
514 print("ERROR: No paired '!if' found for '!elif' for line '%s'" % DscLine)
515 raise SystemExit
516 else:
517 if IfStack:
518 Handle = reduce(lambda x,y: x and y, IfStack)
519 else:
520 Handle = True
521 if Handle:
522 Match = re.match("!include\s+(.+)", DscLine)
523 if Match:
524 IncludeFilePath = Match.group(1)
525 IncludeFilePath = self.ExpandMacros(IncludeFilePath)
526 PackagesPath = os.getenv("PACKAGES_PATH")
527 if PackagesPath:
528 for PackagePath in PackagesPath.split(os.pathsep):
529 IncludeFilePathAbs = os.path.join(os.path.normpath(PackagePath), os.path.normpath(IncludeFilePath))
530 if os.path.exists(IncludeFilePathAbs):
531 IncludeDsc = open(IncludeFilePathAbs, "r")
532 break
533 else:
534 IncludeDsc = open(IncludeFilePath, "r")
535 if IncludeDsc == None:
536 print("ERROR: Cannot open file '%s'" % IncludeFilePath)
537 raise SystemExit
538 NewDscLines = IncludeDsc.readlines()
539 IncludeDsc.close()
540 DscLines = NewDscLines + DscLines
541 else:
542 if DscLine.startswith('!'):
543 print("ERROR: Unrecoginized directive for line '%s'" % DscLine)
544 raise SystemExit
545 if not Handle:
546 continue
547
548 if IsDefSect:
549 #DEFINE UPD_TOOL_GUID = 8C3D856A-9BE6-468E-850A-24F7A8D38E09
550 #DEFINE FSP_T_UPD_TOOL_GUID = 34686CA3-34F9-4901-B82A-BA630F0714C6
551 #DEFINE FSP_M_UPD_TOOL_GUID = 39A250DB-E465-4DD1-A2AC-E2BD3C0E2385
552 #DEFINE FSP_S_UPD_TOOL_GUID = CAE3605B-5B34-4C85-B3D7-27D54273C40F
553 Match = re.match("^\s*(?:DEFINE\s+)*(\w+)\s*=\s*([-.\w]+)", DscLine)
554 if Match:
555 self._MacroDict[Match.group(1)] = Match.group(2)
556 if self.Debug:
557 print "INFO : DEFINE %s = [ %s ]" % (Match.group(1), Match.group(2))
558 elif IsPcdSect:
559 #gSiPkgTokenSpaceGuid.PcdTxtEnable|FALSE
560 #gSiPkgTokenSpaceGuid.PcdOverclockEnable|TRUE
561 Match = re.match("^\s*([\w\.]+)\s*\|\s*(\w+)", DscLine)
562 if Match:
563 self._PcdsDict[Match.group(1)] = Match.group(2)
564 if self.Debug:
565 print "INFO : PCD %s = [ %s ]" % (Match.group(1), Match.group(2))
566 else:
567 Match = re.match("^\s*#\s+(!BSF|@Bsf|!HDR)\s+(.+)", DscLine)
568 if Match:
569 Remaining = Match.group(2)
570 if Match.group(1) == '!BSF' or Match.group(1) == '@Bsf':
571 Match = re.match("(?:^|.+\s+)PAGES:{(.+?)}", Remaining)
572 if Match:
573 # !BSF PAGES:{HSW:"Haswell System Agent", LPT:"Lynx Point PCH"}
574 PageList = Match.group(1).split(',')
575 for Page in PageList:
576 Page = Page.strip()
577 Match = re.match("(\w+):\"(.+)\"", Page)
578 self._CfgPageDict[Match.group(1)] = Match.group(2)
579
580 Match = re.match("(?:^|.+\s+)BLOCK:{NAME:\"(.+)\"\s*,\s*VER:\"(.+)\"\s*}", Remaining)
581 if Match:
582 self._CfgBlkDict['name'] = Match.group(1)
583 self._CfgBlkDict['ver'] = Match.group(2)
584
585 for Key in self._BsfKeyList:
586 Match = re.match("(?:^|.+\s+)%s:{(.+?)}" % Key, Remaining)
587 if Match:
588 if Key in ['NAME', 'HELP', 'OPTION'] and Match.group(1).startswith('+'):
589 ConfigDict[Key.lower()] += Match.group(1)[1:]
590 else:
591 ConfigDict[Key.lower()] = Match.group(1)
592 else:
593 for Key in self._HdrKeyList:
594 Match = re.match("(?:^|.+\s+)%s:{(.+?)}" % Key, Remaining)
595 if Match:
596 ConfigDict[Key.lower()] = Match.group(1)
597
598 Match = re.match("^\s*#\s+@Prompt\s+(.+)", DscLine)
599 if Match:
600 ConfigDict['name'] = Match.group(1)
601
602 Match = re.match("^\s*#\s*@ValidList\s*(.+)\s*\|\s*(.+)\s*\|\s*(.+)\s*", DscLine)
603 if Match:
604 if Match.group(2).strip() in self._BuidinOption:
605 ConfigDict['option'] = Match.group(2).strip()
606 else:
607 OptionValueList = Match.group(2).split(',')
608 OptionStringList = Match.group(3).split(',')
609 Index = 0
610 for Option in OptionValueList:
611 Option = Option.strip()
612 ConfigDict['option'] = ConfigDict['option'] + str(Option) + ':' + OptionStringList[Index].strip()
613 Index += 1
614 if Index in range(len(OptionValueList)):
615 ConfigDict['option'] += ', '
616 ConfigDict['type'] = "Combo"
617
618 Match = re.match("^\s*#\s*@ValidRange\s*(.+)\s*\|\s*(.+)\s*-\s*(.+)\s*", DscLine)
619 if Match:
620 if "0x" in Match.group(2) or "0x" in Match.group(3):
621 ConfigDict['type'] = "EditNum, HEX, (%s,%s)" % (Match.group(2), Match.group(3))
622 else:
623 ConfigDict['type'] = "EditNum, DEC, (%s,%s)" % (Match.group(2), Match.group(3))
624
625 Match = re.match("^\s*##\s+(.+)", DscLine)
626 if Match:
627 ConfigDict['help'] = Match.group(1)
628
629 # Check VPD/UPD
630 if IsUpdSect:
631 Match = re.match("^([_a-zA-Z0-9]+).([_a-zA-Z0-9]+)\s*\|\s*(0x[0-9A-F]+)\s*\|\s*(\d+|0x[0-9a-fA-F]+)\s*\|\s*(.+)",DscLine)
632 else:
633 Match = re.match("^([_a-zA-Z0-9]+).([_a-zA-Z0-9]+)\s*\|\s*(0x[0-9A-F]+)(?:\s*\|\s*(.+))?", DscLine)
634 if Match:
635 ConfigDict['space'] = Match.group(1)
636 ConfigDict['cname'] = Match.group(2)
637 ConfigDict['offset'] = int (Match.group(3), 16)
638 if ConfigDict['order'] == -1:
639 ConfigDict['order'] = ConfigDict['offset'] << 8
640 else:
641 (Major, Minor) = ConfigDict['order'].split('.')
642 ConfigDict['order'] = (int (Major, 16) << 8 ) + int (Minor, 16)
643 if IsUpdSect:
644 Value = Match.group(5).strip()
645 if Match.group(4).startswith("0x"):
646 Length = int (Match.group(4), 16)
647 else :
648 Length = int (Match.group(4))
649 else:
650 Value = Match.group(4)
651 if Value is None:
652 Value = ''
653 Value = Value.strip()
654 if '|' in Value:
655 Match = re.match("^.+\s*\|\s*(.+)", Value)
656 if Match:
657 Value = Match.group(1)
658 Length = -1
659
660 ConfigDict['length'] = Length
661 Match = re.match("\$\((\w+)\)", Value)
662 if Match:
663 if Match.group(1) in self._MacroDict:
664 Value = self._MacroDict[Match.group(1)]
665
666 ConfigDict['value'] = Value
667 if (len(Value) > 0) and (Value[0] == '{'):
668 Value = self.FormatListValue(ConfigDict)
669
670 if ConfigDict['name'] == '':
671 # Clear BSF specific items
672 ConfigDict['bsfname'] = ''
673 ConfigDict['help'] = ''
674 ConfigDict['type'] = ''
675 ConfigDict['option'] = ''
676
677 self._CfgItemList.append(ConfigDict.copy())
678 ConfigDict['name'] = ''
679 ConfigDict['find'] = ''
680 ConfigDict['struct'] = ''
681 ConfigDict['embed'] = ''
682 ConfigDict['comment'] = ''
683 ConfigDict['order'] = -1
684 ConfigDict['subreg'] = []
685 ConfigDict['option'] = ''
686 else:
687 # It could be a virtual item as below
688 # !BSF FIELD:{SerialDebugPortAddress0:1}
689 # or
690 # @Bsf FIELD:{SerialDebugPortAddress0:1b}
691 Match = re.match("^\s*#\s+(!BSF|@Bsf)\s+FIELD:{(.+):(\d+)([Bb])?}", DscLine)
692 if Match:
693 SubCfgDict = ConfigDict.copy()
694 if (Match.group(4) == None) or (Match.group(4) == 'B'):
695 UnitBitLen = 8
696 elif Match.group(4) == 'b':
697 UnitBitLen = 1
698 else:
699 print("ERROR: Invalide BSF FIELD length for line '%s'" % DscLine)
700 raise SystemExit
701 SubCfgDict['cname'] = Match.group(2)
702 SubCfgDict['bitlength'] = int (Match.group(3)) * UnitBitLen
703 if SubCfgDict['bitlength'] > 0:
704 LastItem = self._CfgItemList[-1]
705 if len(LastItem['subreg']) == 0:
706 SubOffset = 0
707 else:
708 SubOffset = LastItem['subreg'][-1]['bitoffset'] + LastItem['subreg'][-1]['bitlength']
709 SubCfgDict['bitoffset'] = SubOffset
710 LastItem['subreg'].append (SubCfgDict.copy())
711 ConfigDict['name'] = ''
712 return Error
713
714 def GetBsfBitFields (self, subitem, bytes):
715 start = subitem['bitoffset']
716 end = start + subitem['bitlength']
717 bitsvalue = ''.join('{0:08b}'.format(i) for i in bytes[::-1])
718 bitsvalue = bitsvalue[::-1]
719 bitslen = len(bitsvalue)
720 if start > bitslen or end > bitslen:
721 print "Invalid bits offset [%d,%d] for %s" % (start, end, subitem['name'])
722 raise SystemExit
723 return hex(int(bitsvalue[start:end][::-1], 2))
724
725 def UpdateSubRegionDefaultValue (self):
726 Error = 0
727 for Item in self._CfgItemList:
728 if len(Item['subreg']) == 0:
729 continue
730 bytearray = []
731 if Item['value'][0] == '{':
732 binlist = Item['value'][1:-1].split(',')
733 for each in binlist:
734 each = each.strip()
735 if each.startswith('0x'):
736 value = int(each, 16)
737 else:
738 value = int(each)
739 bytearray.append(value)
740 else:
741 if Item['value'].startswith('0x'):
742 value = int(Item['value'], 16)
743 else:
744 value = int(Item['value'])
745 idx = 0
746 while idx < Item['length']:
747 bytearray.append(value & 0xFF)
748 value = value >> 8
749 idx = idx + 1
750 for SubItem in Item['subreg']:
751 valuestr = self.GetBsfBitFields(SubItem, bytearray)
752 SubItem['value'] = valuestr
753 return Error
754
755 def CreateSplitUpdTxt (self, UpdTxtFile):
756 GuidList = ['FSP_T_UPD_TOOL_GUID','FSP_M_UPD_TOOL_GUID','FSP_S_UPD_TOOL_GUID']
757 SignatureList = ['0x545F', '0x4D5F','0x535F'] # _T, _M, and _S signature for FSPT, FSPM, FSPS
758 for Index in range(len(GuidList)):
759 UpdTxtFile = ''
760 FvDir = self._FvDir
761 if GuidList[Index] not in self._MacroDict:
762 self.Error = "%s definition is missing in DSC file" % (GuidList[Index])
763 return 1
764
765 if UpdTxtFile == '':
766 UpdTxtFile = os.path.join(FvDir, self._MacroDict[GuidList[Index]] + '.txt')
767
768 ReCreate = False
769 if not os.path.exists(UpdTxtFile):
770 ReCreate = True
771 else:
772 DscTime = os.path.getmtime(self._DscFile)
773 TxtTime = os.path.getmtime(UpdTxtFile)
774 if DscTime > TxtTime:
775 ReCreate = True
776
777 if not ReCreate:
778 # DSC has not been modified yet
779 # So don't have to re-generate other files
780 self.Error = 'No DSC file change, skip to create UPD TXT file'
781 return 256
782
783 TxtFd = open(UpdTxtFile, "w")
784 TxtFd.write("%s\n" % (__copyright_txt__ % date.today().year))
785
786 NextOffset = 0
787 SpaceIdx = 0
788 StartAddr = 0
789 EndAddr = 0
790 Default = 'DEFAULT|'
791 InRange = False
792 for Item in self._CfgItemList:
793 if Item['cname'] == 'Signature' and str(Item['value'])[0:6] == SignatureList[Index]:
794 StartAddr = Item['offset']
795 NextOffset = StartAddr
796 InRange = True
797 if Item['cname'] == 'UpdTerminator' and InRange == True:
798 EndAddr = Item['offset']
799 InRange = False
800 InRange = False
801 for Item in self._CfgItemList:
802 if Item['cname'] == 'Signature' and str(Item['value'])[0:6] == SignatureList[Index]:
803 InRange = True
804 if InRange != True:
805 continue
806 if Item['cname'] == 'UpdTerminator':
807 InRange = False
808 if Item['region'] != 'UPD':
809 continue
810 Offset = Item['offset']
811 if StartAddr > Offset or EndAddr < Offset:
812 continue
813 if NextOffset < Offset:
814 # insert one line
815 TxtFd.write("%s.UnusedUpdSpace%d|%s0x%04X|0x%04X|{0}\n" % (Item['space'], SpaceIdx, Default, NextOffset - StartAddr, Offset - NextOffset))
816 SpaceIdx = SpaceIdx + 1
817 NextOffset = Offset + Item['length']
818 if Item['cname'] == 'PcdSerialIoUartDebugEnable':
819 if self.ReleaseMode == False:
820 Item['value'] = 0x01
821 TxtFd.write("%s.%s|%s0x%04X|%s|%s\n" % (Item['space'],Item['cname'],Default,Item['offset'] - StartAddr,Item['length'],Item['value']))
822 TxtFd.close()
823 return 0
824
825 def ProcessMultilines (self, String, MaxCharLength):
826 Multilines = ''
827 StringLength = len(String)
828 CurrentStringStart = 0
829 StringOffset = 0
830 BreakLineDict = []
831 if len(String) <= MaxCharLength:
832 while (StringOffset < StringLength):
833 if StringOffset >= 1:
834 if String[StringOffset - 1] == '\\' and String[StringOffset] == 'n':
835 BreakLineDict.append (StringOffset + 1)
836 StringOffset += 1
837 if BreakLineDict != []:
838 for Each in BreakLineDict:
839 Multilines += " %s\n" % String[CurrentStringStart:Each].lstrip()
840 CurrentStringStart = Each
841 if StringLength - CurrentStringStart > 0:
842 Multilines += " %s\n" % String[CurrentStringStart:].lstrip()
843 else:
844 Multilines = " %s\n" % String
845 else:
846 NewLineStart = 0
847 NewLineCount = 0
848 FoundSpaceChar = False
849 while (StringOffset < StringLength):
850 if StringOffset >= 1:
851 if NewLineCount >= MaxCharLength - 1:
852 if String[StringOffset] == ' ' and StringLength - StringOffset > 10:
853 BreakLineDict.append (NewLineStart + NewLineCount)
854 NewLineStart = NewLineStart + NewLineCount
855 NewLineCount = 0
856 FoundSpaceChar = True
857 elif StringOffset == StringLength - 1 and FoundSpaceChar == False:
858 BreakLineDict.append (0)
859 if String[StringOffset - 1] == '\\' and String[StringOffset] == 'n':
860 BreakLineDict.append (StringOffset + 1)
861 NewLineStart = StringOffset + 1
862 NewLineCount = 0
863 StringOffset += 1
864 NewLineCount += 1
865 if BreakLineDict != []:
866 BreakLineDict.sort ()
867 for Each in BreakLineDict:
868 if Each > 0:
869 Multilines += " %s\n" % String[CurrentStringStart:Each].lstrip()
870 CurrentStringStart = Each
871 if StringLength - CurrentStringStart > 0:
872 Multilines += " %s\n" % String[CurrentStringStart:].lstrip()
873 return Multilines
874
875 def CreateField (self, Item, Name, Length, Offset, Struct, BsfName, Help, Option):
876 PosName = 28
877 PosComment = 30
878 NameLine=''
879 HelpLine=''
880 OptionLine=''
881
882 IsArray = False
883 if Length in [1,2,4,8]:
884 Type = "UINT%d" % (Length * 8)
885 if Name.startswith("UnusedUpdSpace") and Length != 1:
886 IsArray = True
887 Type = "UINT8"
888 else:
889 IsArray = True
890 Type = "UINT8"
891
892 if Item and Item['value'].startswith('{'):
893 Type = "UINT8"
894 IsArray = True
895
896 if Struct != '':
897 Type = Struct
898 if Struct in ['UINT8','UINT16','UINT32','UINT64']:
899 IsArray = True
900 Unit = int(Type[4:]) / 8
901 Length = Length / Unit
902 else:
903 IsArray = False
904
905 if IsArray:
906 Name = Name + '[%d]' % Length
907
908 if len(Type) < PosName:
909 Space1 = PosName - len(Type)
910 else:
911 Space1 = 1
912
913 if BsfName != '':
914 NameLine=" - %s\n" % BsfName
915 else:
916 NameLine="\n"
917
918 if Help != '':
919 HelpLine = self.ProcessMultilines (Help, 80)
920
921 if Option != '':
922 OptionLine = self.ProcessMultilines (Option, 80)
923
924 if Offset is None:
925 OffsetStr = '????'
926 else:
927 OffsetStr = '0x%04X' % Offset
928
929 return "\n/** Offset %s%s%s%s**/\n %s%s%s;\n" % (OffsetStr, NameLine, HelpLine, OptionLine, Type, ' ' * Space1, Name,)
930
931 def PostProcessBody (self, TextBody):
932 NewTextBody = []
933 OldTextBody = []
934 IncludeLine = False
935 StructName = ''
936 VariableName = ''
937 IsUpdHdrDefined = False
938 IsUpdHeader = False
939 for Line in TextBody:
940 SplitToLines = Line.splitlines()
941 MatchComment = re.match("^/\*\sCOMMENT:(\w+):([\w|\W|\s]+)\s\*/\s([\s\S]*)", SplitToLines[0])
942 if MatchComment:
943 if MatchComment.group(1) == 'FSP_UPD_HEADER':
944 IsUpdHeader = True
945 else:
946 IsUpdHeader = False
947 if IsUpdHdrDefined != True or IsUpdHeader != True:
948 CommentLine = " " + MatchComment.group(2) + "\n"
949 NewTextBody.append("/**" + CommentLine + "**/\n")
950 Line = Line[(len(SplitToLines[0]) + 1):]
951
952 Match = re.match("^/\*\sEMBED_STRUCT:(\w+):(\w+):(START|END)\s\*/\s([\s\S]*)", Line)
953 if Match:
954 Line = Match.group(4)
955 if Match.group(1) == 'FSP_UPD_HEADER':
956 IsUpdHeader = True
957 else:
958 IsUpdHeader = False
959
960 if Match and Match.group(3) == 'START':
961 if IsUpdHdrDefined != True or IsUpdHeader != True:
962 NewTextBody.append ('typedef struct {\n')
963 StructName = Match.group(1)
964 VariableName = Match.group(2)
965 MatchOffset = re.search('/\*\*\sOffset\s0x([a-fA-F0-9]+)', Line)
966 if MatchOffset:
967 Offset = int(MatchOffset.group(1), 16)
968 else:
969 Offset = None
970 Line
971 IncludeLine = True
972 OldTextBody.append (self.CreateField (None, VariableName, 0, Offset, StructName, '', '', ''))
973 if IncludeLine:
974 if IsUpdHdrDefined != True or IsUpdHeader != True:
975 NewTextBody.append (Line)
976 else:
977 OldTextBody.append (Line)
978
979 if Match and Match.group(3) == 'END':
980 if (StructName != Match.group(1)) or (VariableName != Match.group(2)):
981 print "Unmatched struct name '%s' and '%s' !" % (StructName, Match.group(1))
982 else:
983 if IsUpdHdrDefined != True or IsUpdHeader != True:
984 NewTextBody.append ('} %s;\n\n' % StructName)
985 IsUpdHdrDefined = True
986 IncludeLine = False
987 NewTextBody.extend(OldTextBody)
988 return NewTextBody
989
990 def CreateHeaderFile (self, InputHeaderFile):
991 FvDir = self._FvDir
992
993 HeaderFileName = 'FspUpd.h'
994 HeaderFile = os.path.join(FvDir, HeaderFileName)
995
996 # Check if header needs to be recreated
997 ReCreate = False
998
999 TxtBody = []
1000 for Item in self._CfgItemList:
1001 if str(Item['cname']) == 'Signature' and Item['length'] == 8:
1002 Value = int(Item['value'], 16)
1003 Chars = []
1004 while Value != 0x0:
1005 Chars.append(chr(Value & 0xFF))
1006 Value = Value >> 8
1007 SignatureStr = ''.join(Chars)
1008 # Signature will be _T / _M / _S for FSPT / FSPM / FSPS accordingly
1009 if '_T' in SignatureStr[6:6+2]:
1010 TxtBody.append("#define FSPT_UPD_SIGNATURE %s /* '%s' */\n\n" % (Item['value'], SignatureStr))
1011 elif '_M' in SignatureStr[6:6+2]:
1012 TxtBody.append("#define FSPM_UPD_SIGNATURE %s /* '%s' */\n\n" % (Item['value'], SignatureStr))
1013 elif '_S' in SignatureStr[6:6+2]:
1014 TxtBody.append("#define FSPS_UPD_SIGNATURE %s /* '%s' */\n\n" % (Item['value'], SignatureStr))
1015 TxtBody.append("\n")
1016
1017 for Region in ['UPD']:
1018 UpdOffsetTable = []
1019 UpdSignature = ['0x545F', '0x4D5F', '0x535F'] #['_T', '_M', '_S'] signature for FSPT, FSPM, FSPS
1020 UpdStructure = ['FSPT_UPD', 'FSPM_UPD', 'FSPS_UPD']
1021 for Item in self._CfgItemList:
1022 if Item["cname"] == 'Signature' and Item["value"][0:6] in UpdSignature:
1023 UpdOffsetTable.append (Item["offset"])
1024
1025 for UpdIdx in range(len(UpdOffsetTable)):
1026 CommentLine = ""
1027 for Item in self._CfgItemList:
1028 if Item["comment"] != '' and Item["offset"] >= UpdOffsetTable[UpdIdx]:
1029 MatchComment = re.match("^(U|V)PD_DATA_REGION:([\w|\W|\s]+)", Item["comment"])
1030 if MatchComment and MatchComment.group(1) == Region[0]:
1031 CommentLine = " " + MatchComment.group(2) + "\n"
1032 TxtBody.append("/**" + CommentLine + "**/\n")
1033 elif Item["offset"] >= UpdOffsetTable[UpdIdx] and Item["comment"] == '':
1034 Match = re.match("^FSP([\w|\W|\s])_UPD", UpdStructure[UpdIdx])
1035 if Match:
1036 TxtBody.append("/** Fsp " + Match.group(1) + " UPD Configuration\n**/\n")
1037 TxtBody.append("typedef struct {\n")
1038 NextOffset = 0
1039 SpaceIdx = 0
1040 Offset = 0
1041
1042 LastVisible = True
1043 ResvOffset = 0
1044 ResvIdx = 0
1045 LineBuffer = []
1046 InRange = False
1047 for Item in self._CfgItemList:
1048 if Item['cname'] == 'Signature' and str(Item['value'])[0:6] == UpdSignature[UpdIdx] or Region[0] == 'V':
1049 InRange = True
1050 if InRange != True:
1051 continue
1052 if Item['cname'] == 'UpdTerminator':
1053 InRange = False
1054
1055 if Item['region'] != Region:
1056 continue
1057
1058 if Item["offset"] < UpdOffsetTable[UpdIdx]:
1059 continue
1060
1061 NextVisible = LastVisible
1062
1063 if LastVisible and (Item['header'] == 'OFF'):
1064 NextVisible = False
1065 ResvOffset = Item['offset']
1066 elif (not LastVisible) and Item['header'] == 'ON':
1067 NextVisible = True
1068 Name = "Reserved" + Region[0] + "pdSpace%d" % ResvIdx
1069 ResvIdx = ResvIdx + 1
1070 TxtBody.append(self.CreateField (Item, Name, Item["offset"] - ResvOffset, ResvOffset, '', '', '', ''))
1071
1072 if Offset < Item["offset"]:
1073 if LastVisible:
1074 Name = "Unused" + Region[0] + "pdSpace%d" % SpaceIdx
1075 LineBuffer.append(self.CreateField (Item, Name, Item["offset"] - Offset, Offset, '', '', '', ''))
1076 SpaceIdx = SpaceIdx + 1
1077 Offset = Item["offset"]
1078
1079 LastVisible = NextVisible
1080
1081 Offset = Offset + Item["length"]
1082 if LastVisible:
1083 for Each in LineBuffer:
1084 TxtBody.append (Each)
1085 LineBuffer = []
1086 Comment = Item["comment"]
1087 Embed = Item["embed"].upper()
1088 if Embed.endswith(':START') or Embed.endswith(':END'):
1089 if not Comment == '' and Embed.endswith(':START'):
1090 Marker = '/* COMMENT:%s */ \n' % Item["comment"]
1091 Marker = Marker + '/* EMBED_STRUCT:%s */ ' % Item["embed"]
1092 else:
1093 Marker = '/* EMBED_STRUCT:%s */ ' % Item["embed"]
1094 else:
1095 if Embed == '':
1096 Marker = ''
1097 else:
1098 self.Error = "Invalid embedded structure format '%s'!\n" % Item["embed"]
1099 return 4
1100 Line = Marker + self.CreateField (Item, Item["cname"], Item["length"], Item["offset"], Item['struct'], Item['name'], Item['help'], Item['option'])
1101 TxtBody.append(Line)
1102 if Item['cname'] == 'UpdTerminator':
1103 break
1104 TxtBody.append("} " + UpdStructure[UpdIdx] + ";\n\n")
1105
1106 # Handle the embedded data structure
1107 TxtBody = self.PostProcessBody (TxtBody)
1108
1109 HeaderTFileName = 'FsptUpd.h'
1110 HeaderMFileName = 'FspmUpd.h'
1111 HeaderSFileName = 'FspsUpd.h'
1112
1113 UpdRegionCheck = ['FSPT', 'FSPM', 'FSPS'] # FSPX_UPD_REGION
1114 UpdConfigCheck = ['FSP_T', 'FSP_M', 'FSP_S'] # FSP_X_CONFIG, FSP_X_TEST_CONFIG, FSP_X_RESTRICTED_CONFIG
1115 UpdSignatureCheck = ['FSPT_UPD_SIGNATURE', 'FSPM_UPD_SIGNATURE', 'FSPS_UPD_SIGNATURE']
1116 ExcludedSpecificUpd = 'FSPM_ARCH_UPD'
1117
1118 if InputHeaderFile != '':
1119 if not os.path.exists(InputHeaderFile):
1120 self.Error = "Input header file '%s' does not exist" % InputHeaderFile
1121 return 6
1122
1123 InFd = open(InputHeaderFile, "r")
1124 IncLines = InFd.readlines()
1125 InFd.close()
1126
1127 for item in range(len(UpdRegionCheck)):
1128 if UpdRegionCheck[item] == 'FSPT':
1129 HeaderFd = open(os.path.join(FvDir, HeaderTFileName), "w")
1130 FileBase = os.path.basename(os.path.join(FvDir, HeaderTFileName))
1131 elif UpdRegionCheck[item] == 'FSPM':
1132 HeaderFd = open(os.path.join(FvDir, HeaderMFileName), "w")
1133 FileBase = os.path.basename(os.path.join(FvDir, HeaderMFileName))
1134 elif UpdRegionCheck[item] == 'FSPS':
1135 HeaderFd = open(os.path.join(FvDir, HeaderSFileName), "w")
1136 FileBase = os.path.basename(os.path.join(FvDir, HeaderSFileName))
1137 FileName = FileBase.replace(".", "_").upper()
1138 HeaderFd.write("%s\n" % (__copyright_h__ % date.today().year))
1139 HeaderFd.write("#ifndef __%s__\n" % FileName)
1140 HeaderFd.write("#define __%s__\n\n" % FileName)
1141 HeaderFd.write("#include <%s>\n\n" % HeaderFileName)
1142 HeaderFd.write("#pragma pack(1)\n\n")
1143
1144 Export = False
1145 for Line in IncLines:
1146 Match = re.search ("!EXPORT\s+([A-Z]+)\s+EXTERNAL_BOOTLOADER_STRUCT_(BEGIN|END)\s+", Line)
1147 if Match:
1148 if Match.group(2) == "BEGIN" and Match.group(1) == UpdRegionCheck[item]:
1149 Export = True
1150 continue
1151 else:
1152 Export = False
1153 continue
1154 if Export:
1155 HeaderFd.write(Line)
1156 HeaderFd.write("\n")
1157
1158 Index = 0
1159 StartIndex = 0
1160 EndIndex = 0
1161 StructStart = []
1162 StructStartWithComment = []
1163 StructEnd = []
1164 for Line in TxtBody:
1165 Index += 1
1166 Match = re.match("(typedef struct {)", Line)
1167 if Match:
1168 StartIndex = Index - 1
1169 Match = re.match("}\s([_A-Z0-9]+);", Line)
1170 if Match and (UpdRegionCheck[item] in Match.group(1) or UpdConfigCheck[item] in Match.group(1)) and (ExcludedSpecificUpd not in Match.group(1)):
1171 EndIndex = Index
1172 StructStart.append(StartIndex)
1173 StructEnd.append(EndIndex)
1174 Index = 0
1175 for Line in TxtBody:
1176 Index += 1
1177 for Item in range(len(StructStart)):
1178 if Index == StructStart[Item]:
1179 Match = re.match("^(/\*\*\s*)", Line)
1180 if Match:
1181 StructStartWithComment.append(StructStart[Item])
1182 else:
1183 StructStartWithComment.append(StructStart[Item] + 1)
1184 Index = 0
1185 for Line in TxtBody:
1186 Index += 1
1187 for Item in range(len(StructStart)):
1188 if Index >= StructStartWithComment[Item] and Index <= StructEnd[Item]:
1189 HeaderFd.write (Line)
1190 HeaderFd.write("#pragma pack()\n\n")
1191 HeaderFd.write("#endif\n")
1192 HeaderFd.close()
1193
1194 HeaderFd = open(HeaderFile, "w")
1195 FileBase = os.path.basename(HeaderFile)
1196 FileName = FileBase.replace(".", "_").upper()
1197 HeaderFd.write("%s\n" % (__copyright_h__ % date.today().year))
1198 HeaderFd.write("#ifndef __%s__\n" % FileName)
1199 HeaderFd.write("#define __%s__\n\n" % FileName)
1200 HeaderFd.write("#include <FspEas.h>\n\n")
1201 HeaderFd.write("#pragma pack(1)\n\n")
1202
1203 for item in range(len(UpdRegionCheck)):
1204 Index = 0
1205 StartIndex = 0
1206 EndIndex = 0
1207 StructStart = []
1208 StructStartWithComment = []
1209 StructEnd = []
1210 for Line in TxtBody:
1211 Index += 1
1212 Match = re.match("(typedef struct {)", Line)
1213 if Match:
1214 StartIndex = Index - 1
1215 Match = re.match("#define\s([_A-Z0-9]+)\s*", Line)
1216 if Match and (UpdSignatureCheck[item] in Match.group(1) or UpdSignatureCheck[item] in Match.group(1)):
1217 StructStart.append(Index - 1)
1218 StructEnd.append(Index)
1219 Index = 0
1220 for Line in TxtBody:
1221 Index += 1
1222 for Item in range(len(StructStart)):
1223 if Index == StructStart[Item]:
1224 Match = re.match("^(/\*\*\s*)", Line)
1225 if Match:
1226 StructStartWithComment.append(StructStart[Item])
1227 else:
1228 StructStartWithComment.append(StructStart[Item] + 1)
1229 Index = 0
1230 for Line in TxtBody:
1231 Index += 1
1232 for Item in range(len(StructStart)):
1233 if Index >= StructStartWithComment[Item] and Index <= StructEnd[Item]:
1234 HeaderFd.write (Line)
1235 HeaderFd.write("#pragma pack()\n\n")
1236 HeaderFd.write("#endif\n")
1237 HeaderFd.close()
1238
1239 return 0
1240
1241 def WriteBsfStruct (self, BsfFd, Item):
1242 LogExpr = CLogicalExpression()
1243 if Item['type'] == "None":
1244 Space = "gPlatformFspPkgTokenSpaceGuid"
1245 else:
1246 Space = Item['space']
1247 Line = " $%s_%s" % (Space, Item['cname'])
1248 Match = re.match("\s*\{([x0-9a-fA-F,\s]+)\}\s*", Item['value'])
1249 if Match:
1250 DefaultValue = Match.group(1).strip()
1251 else:
1252 DefaultValue = Item['value'].strip()
1253 if 'bitlength' in Item:
1254 BsfFd.write(" %s%s%4d bits $_DEFAULT_ = %s\n" % (Line, ' ' * (64 - len(Line)), Item['bitlength'], DefaultValue))
1255 else:
1256 BsfFd.write(" %s%s%4d bytes $_DEFAULT_ = %s\n" % (Line, ' ' * (64 - len(Line)), Item['length'], DefaultValue))
1257 TmpList = []
1258 if Item['type'] == "Combo":
1259 if not Item['option'] in self._BuidinOption:
1260 OptList = Item['option'].split(',')
1261 for Option in OptList:
1262 Option = Option.strip()
1263 (OpVal, OpStr) = Option.split(':')
1264 test = LogExpr.getNumber (OpVal)
1265 if test is None:
1266 raise Exception("Selection Index '%s' is not a number" % OpVal)
1267 TmpList.append((OpVal, OpStr))
1268 return TmpList
1269
1270 def WriteBsfOption (self, BsfFd, Item):
1271 PcdName = Item['space'] + '_' + Item['cname']
1272 WriteHelp = 0
1273 if Item['type'] == "Combo":
1274 if Item['option'] in self._BuidinOption:
1275 Options = self._BuidinOption[Item['option']]
1276 else:
1277 Options = PcdName
1278 BsfFd.write(' %s $%s, "%s", &%s,\n' % (Item['type'], PcdName, Item['name'], Options))
1279 WriteHelp = 1
1280 elif Item['type'].startswith("EditNum"):
1281 Match = re.match("EditNum\s*,\s*(HEX|DEC)\s*,\s*\((\d+|0x[0-9A-Fa-f]+)\s*,\s*(\d+|0x[0-9A-Fa-f]+)\)", Item['type'])
1282 if Match:
1283 BsfFd.write(' EditNum $%s, "%s", %s,\n' % (PcdName, Item['name'], Match.group(1)))
1284 WriteHelp = 2
1285 elif Item['type'].startswith("EditText"):
1286 BsfFd.write(' %s $%s, "%s",\n' % (Item['type'], PcdName, Item['name']))
1287 WriteHelp = 1
1288 elif Item['type'] == "Table":
1289 Columns = Item['option'].split(',')
1290 if len(Columns) != 0:
1291 BsfFd.write(' %s $%s "%s",' % (Item['type'], PcdName, Item['name']))
1292 for Col in Columns:
1293 Fmt = Col.split(':')
1294 if len(Fmt) != 3:
1295 raise Exception("Column format '%s' is invalid !" % Fmt)
1296 try:
1297 Dtype = int(Fmt[1].strip())
1298 except:
1299 raise Exception("Column size '%s' is invalid !" % Fmt[1])
1300 BsfFd.write('\n Column "%s", %d bytes, %s' % (Fmt[0].strip(), Dtype, Fmt[2].strip()))
1301 BsfFd.write(',\n')
1302 WriteHelp = 1
1303
1304 if WriteHelp > 0:
1305 HelpLines = Item['help'].split('\\n\\r')
1306 FirstLine = True
1307 for HelpLine in HelpLines:
1308 if FirstLine:
1309 FirstLine = False
1310 BsfFd.write(' Help "%s"\n' % (HelpLine))
1311 else:
1312 BsfFd.write(' "%s"\n' % (HelpLine))
1313 if WriteHelp == 2:
1314 BsfFd.write(' "Valid range: %s ~ %s"\n' % (Match.group(2), Match.group(3)))
1315
1316 def GenerateBsfFile (self, BsfFile):
1317
1318 if BsfFile == '':
1319 self.Error = "BSF output file '%s' is invalid" % BsfFile
1320 return 1
1321
1322 Error = 0
1323 OptionDict = {}
1324 BsfFd = open(BsfFile, "w")
1325 BsfFd.write("%s\n" % (__copyright_bsf__ % date.today().year))
1326 BsfFd.write("%s\n" % self._GlobalDataDef)
1327 BsfFd.write("StructDef\n")
1328 NextOffset = -1
1329 for Item in self._CfgItemList:
1330 if Item['find'] != '':
1331 BsfFd.write('\n Find "%s"\n' % Item['find'])
1332 NextOffset = Item['offset'] + Item['length']
1333 if Item['name'] != '':
1334 if NextOffset != Item['offset']:
1335 BsfFd.write(" Skip %d bytes\n" % (Item['offset'] - NextOffset))
1336 if len(Item['subreg']) > 0:
1337 NextOffset = Item['offset']
1338 BitsOffset = NextOffset * 8
1339 for SubItem in Item['subreg']:
1340 BitsOffset += SubItem['bitlength']
1341 if SubItem['name'] == '':
1342 if 'bitlength' in SubItem:
1343 BsfFd.write(" Skip %d bits\n" % (SubItem['bitlength']))
1344 else:
1345 BsfFd.write(" Skip %d bytes\n" % (SubItem['length']))
1346 else:
1347 Options = self.WriteBsfStruct(BsfFd, SubItem)
1348 if len(Options) > 0:
1349 OptionDict[SubItem['space']+'_'+SubItem['cname']] = Options
1350
1351 NextBitsOffset = (Item['offset'] + Item['length']) * 8
1352 if NextBitsOffset > BitsOffset:
1353 BitsGap = NextBitsOffset - BitsOffset
1354 BitsRemain = BitsGap % 8
1355 if BitsRemain:
1356 BsfFd.write(" Skip %d bits\n" % BitsRemain)
1357 BitsGap -= BitsRemain
1358 BytesRemain = BitsGap / 8
1359 if BytesRemain:
1360 BsfFd.write(" Skip %d bytes\n" % BytesRemain)
1361 NextOffset = Item['offset'] + Item['length']
1362 else:
1363 NextOffset = Item['offset'] + Item['length']
1364 Options = self.WriteBsfStruct(BsfFd, Item)
1365 if len(Options) > 0:
1366 OptionDict[Item['space']+'_'+Item['cname']] = Options
1367 BsfFd.write("\nEndStruct\n\n")
1368
1369 BsfFd.write("%s" % self._BuidinOptionTxt)
1370
1371 for Each in OptionDict:
1372 BsfFd.write("List &%s\n" % Each)
1373 for Item in OptionDict[Each]:
1374 BsfFd.write(' Selection %s , "%s"\n' % (Item[0], Item[1]))
1375 BsfFd.write("EndList\n\n")
1376
1377 BsfFd.write("BeginInfoBlock\n")
1378 BsfFd.write(' PPVer "%s"\n' % (self._CfgBlkDict['ver']))
1379 BsfFd.write(' Description "%s"\n' % (self._CfgBlkDict['name']))
1380 BsfFd.write("EndInfoBlock\n\n")
1381
1382 for Each in self._CfgPageDict:
1383 BsfFd.write('Page "%s"\n' % self._CfgPageDict[Each])
1384 BsfItems = []
1385 for Item in self._CfgItemList:
1386 if Item['name'] != '':
1387 if Item['page'] != Each:
1388 continue
1389 if len(Item['subreg']) > 0:
1390 for SubItem in Item['subreg']:
1391 if SubItem['name'] != '':
1392 BsfItems.append(SubItem)
1393 else:
1394 BsfItems.append(Item)
1395
1396 BsfItems.sort(key=lambda x: x['order'])
1397
1398 for Item in BsfItems:
1399 self.WriteBsfOption (BsfFd, Item)
1400 BsfFd.write("EndPage\n\n")
1401
1402 BsfFd.close()
1403 return Error
1404
1405
1406 def Usage():
1407 print "GenCfgOpt Version 0.52"
1408 print "Usage:"
1409 print " GenCfgOpt UPDTXT PlatformDscFile BuildFvDir [-D Macros]"
1410 print " GenCfgOpt HEADER PlatformDscFile BuildFvDir InputHFile [-D Macros]"
1411 print " GenCfgOpt GENBSF PlatformDscFile BuildFvDir BsfOutFile [-D Macros]"
1412
1413 def Main():
1414 #
1415 # Parse the options and args
1416 #
1417 GenCfgOpt = CGenCfgOpt()
1418 argc = len(sys.argv)
1419 if argc < 4:
1420 Usage()
1421 return 1
1422 else:
1423 DscFile = sys.argv[2]
1424 if not os.path.exists(DscFile):
1425 print "ERROR: Cannot open DSC file '%s' !" % DscFile
1426 return 2
1427
1428 OutFile = ''
1429 if argc > 4:
1430 if sys.argv[4][0] == '-':
1431 Start = 4
1432 else:
1433 OutFile = sys.argv[4]
1434 Start = 5
1435 if argc > Start:
1436 if GenCfgOpt.ParseMacros(sys.argv[Start:]) != 0:
1437 print "ERROR: Macro parsing failed !"
1438 return 3
1439
1440 GenCfgOpt.ParseBuildMode(sys.argv[3])
1441 FvDir = sys.argv[3]
1442 if not os.path.exists(FvDir):
1443 os.makedirs(FvDir)
1444
1445 if GenCfgOpt.ParseDscFile(DscFile, FvDir) != 0:
1446 print "ERROR: %s !" % GenCfgOpt.Error
1447 return 5
1448
1449 if GenCfgOpt.UpdateSubRegionDefaultValue() != 0:
1450 print "ERROR: %s !" % GenCfgOpt.Error
1451 return 7
1452
1453 if sys.argv[1] == "UPDTXT":
1454 Ret = GenCfgOpt.CreateSplitUpdTxt(OutFile)
1455 if Ret != 0:
1456 # No change is detected
1457 if Ret == 256:
1458 print "INFO: %s !" % (GenCfgOpt.Error)
1459 else :
1460 print "ERROR: %s !" % (GenCfgOpt.Error)
1461 return Ret
1462 elif sys.argv[1] == "HEADER":
1463 if GenCfgOpt.CreateHeaderFile(OutFile) != 0:
1464 print "ERROR: %s !" % GenCfgOpt.Error
1465 return 8
1466 elif sys.argv[1] == "GENBSF":
1467 if GenCfgOpt.GenerateBsfFile(OutFile) != 0:
1468 print "ERROR: %s !" % GenCfgOpt.Error
1469 return 9
1470 else:
1471 if argc < 5:
1472 Usage()
1473 return 1
1474 print "ERROR: Unknown command '%s' !" % sys.argv[1]
1475 Usage()
1476 return 1
1477 return 0
1478 return 0
1479
1480
1481 if __name__ == '__main__':
1482 sys.exit(Main())