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