]>
git.proxmox.com Git - mirror_edk2.git/blob - IntelFsp2Pkg/Tools/GenCfgOpt.py
bcced590ce02555c60c6ab0a3af12fb251315ff1
3 # Copyright (c) 2014 - 2020, Intel Corporation. All rights reserved.<BR>
4 # SPDX-License-Identifier: BSD-2-Clause-Patent
12 from datetime
import date
13 from functools
import reduce
15 # Generated file copyright header
17 __copyright_txt__
= """## @file
19 # THIS IS AUTO-GENERATED FILE BY BUILD TOOLS AND PLEASE DO NOT MAKE MODIFICATION.
21 # This file lists all VPD informations for a platform collected by build.exe.
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
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.
34 __copyright_bsf__
= """/** @file
36 Boot Setting File for Platform Configuration.
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
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.
47 This file is automatically generated. Please do NOT modify !!!
53 __copyright_h__
= """/** @file
55 Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>
57 Redistribution and use in source and binary forms, with or without modification,
58 are permitted provided that the following conditions are met:
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.
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.
81 This file is automatically generated. Please do NOT modify !!!
88 class CLogicalExpression
:
93 def errExit(self
, err
= ''):
94 print ("ERROR: Express parsing for:")
95 print (" %s" % self
.string
)
96 print (" %s^" % (' ' * self
.index
))
98 print ("INFO : %s" % err
)
101 def getNonNumber (self
, n1
, n2
):
108 def getCurr(self
, lens
= 1):
111 return self
.string
[self
.index
:]
113 if self
.index
+ lens
> len(self
.string
):
114 lens
= len(self
.string
) - self
.index
115 return self
.string
[self
.index
: self
.index
+ lens
]
120 return self
.index
== len(self
.string
)
122 def moveNext(self
, len = 1):
126 while not self
.isLast():
127 if self
.getCurr() in ' \t':
132 def normNumber (self
, val
):
133 return True if val
else False
135 def getNumber(self
, var
):
137 if re
.match('^0x[a-fA-F0-9]+$', var
):
139 elif re
.match('^[+-]?\d+$', var
):
145 def parseValue(self
):
148 while not self
.isLast():
149 char
= self
.getCurr()
150 if re
.match('^[\w.]', char
):
155 val
= self
.getNumber(var
)
162 def parseSingleOp(self
):
164 if re
.match('^NOT\W', self
.getCurr(-1)):
166 op
= self
.parseBrace()
167 val
= self
.getNumber (op
)
169 self
.errExit ("'%s' is not a number" % op
)
170 return "%d" % (not self
.normNumber(int(op
)))
172 return self
.parseValue()
174 def parseBrace(self
):
176 char
= self
.getCurr()
179 value
= self
.parseExpr()
181 if self
.getCurr() != ')':
182 self
.errExit ("Expecting closing brace or operator")
186 value
= self
.parseSingleOp()
189 def parseCompare(self
):
190 value
= self
.parseBrace()
193 char
= self
.getCurr()
194 if char
in ['<', '>']:
196 next
= self
.getCurr()
202 result
= self
.parseBrace()
203 test
= self
.getNonNumber(result
, value
)
205 value
= "%d" % self
.normNumber(eval (value
+ op
+ result
))
207 self
.errExit ("'%s' is not a valid number for comparision" % test
)
208 elif char
in ['=', '!']:
210 if op
in ['==', '!=']:
212 result
= self
.parseBrace()
213 test
= self
.getNonNumber(result
, value
)
215 value
= "%d" % self
.normNumber((eval (value
+ op
+ result
)))
217 value
= "%d" % self
.normNumber(eval ("'" + value
+ "'" + op
+ "'" + result
+ "'"))
225 value
= self
.parseCompare()
228 if re
.match('^AND\W', self
.getCurr(-1)):
230 result
= self
.parseCompare()
231 test
= self
.getNonNumber(result
, value
)
233 value
= "%d" % self
.normNumber(int(value
) & int(result
))
235 self
.errExit ("'%s' is not a valid op number for AND" % test
)
240 def parseOrXor(self
):
241 value
= self
.parseAnd()
246 if re
.match('^XOR\W', self
.getCurr(-1)):
249 elif re
.match('^OR\W', self
.getCurr(-1)):
255 result
= self
.parseAnd()
256 test
= self
.getNonNumber(result
, value
)
258 value
= "%d" % self
.normNumber(eval (value
+ op
+ result
))
260 self
.errExit ("'%s' is not a valid op number for XOR/OR" % test
)
264 return self
.parseOrXor()
267 value
= self
.parseExpr()
269 if not self
.isLast():
270 self
.errExit ("Unexpected character found '%s'" % self
.getCurr())
271 test
= self
.getNumber(value
)
273 self
.errExit ("Result '%s' is not a number" % value
)
276 def evaluateExpress (self
, Expr
):
290 self
._GlobalDataDef
= """
296 self
._BuidinOptionTxt
= """
298 Selection 0x1 , "Enabled"
299 Selection 0x0 , "Disabled"
304 self
._BsfKeyList
= ['FIND','NAME','HELP','TYPE','PAGE','OPTION','ORDER']
305 self
._HdrKeyList
= ['HEADER','STRUCT', 'EMBED', 'COMMENT']
306 self
._BuidinOption
= {'$EN_DIS' : 'EN_DIS'}
310 self
._CfgBlkDict
= {}
311 self
._CfgPageDict
= {}
312 self
._CfgItemList
= []
317 def ParseMacros (self
, MacroDefStr
):
318 # ['-DABC=1', '-D', 'CFG_DEBUG=1', '-D', 'CFG_OUTDIR=Build']
321 for Macro
in MacroDefStr
:
322 if Macro
.startswith('-D'):
330 Match
= re
.match("(\w+)=(.+)", Macro
)
332 self
._MacroDict
[Match
.group(1)] = Match
.group(2)
334 Match
= re
.match("(\w+)", Macro
)
336 self
._MacroDict
[Match
.group(1)] = ''
337 if len(self
._MacroDict
) == 0:
342 print ("INFO : Macro dictionary:")
343 for Each
in self
._MacroDict
:
344 print (" $(%s) = [ %s ]" % (Each
, self
._MacroDict
[Each
]))
347 def EvaulateIfdef (self
, Macro
):
348 Result
= Macro
in self
._MacroDict
350 print ("INFO : Eval Ifdef [%s] : %s" % (Macro
, Result
))
353 def ExpandMacros (self
, Input
):
355 Match
= re
.findall("\$\(\w+\)", Input
)
358 Variable
= Each
[2:-1]
359 if Variable
in self
._MacroDict
:
360 Line
= Line
.replace(Each
, self
._MacroDict
[Variable
])
363 print ("WARN : %s is not defined" % Each
)
364 Line
= Line
.replace(Each
, Each
[2:-1])
367 def ExpandPcds (self
, Input
):
369 Match
= re
.findall("(\w+\.\w+)", Input
)
371 for PcdName
in Match
:
372 if PcdName
in self
._PcdsDict
:
373 Line
= Line
.replace(PcdName
, self
._PcdsDict
[PcdName
])
376 print ("WARN : %s is not defined" % PcdName
)
379 def EvaluateExpress (self
, Expr
):
380 ExpExpr
= self
.ExpandPcds(Expr
)
381 ExpExpr
= self
.ExpandMacros(ExpExpr
)
382 LogExpr
= CLogicalExpression()
383 Result
= LogExpr
.evaluateExpress (ExpExpr
)
385 print ("INFO : Eval Express [%s] : %s" % (Expr
, Result
))
388 def FormatListValue(self
, ConfigDict
):
389 Struct
= ConfigDict
['struct']
390 if Struct
not in ['UINT8','UINT16','UINT32','UINT64']:
394 binlist
= ConfigDict
['value'][1:-1].split(',')
397 if each
.startswith('0x'):
398 value
= int(each
, 16)
401 dataarray
.append(value
)
403 unit
= int(Struct
[4:]) / 8
404 if int(ConfigDict
['length']) != unit
* len(dataarray
):
405 raise Exception("Array size is not proper for '%s' !" % ConfigDict
['cname'])
408 for each
in dataarray
:
410 for loop
in range(int(unit
)):
411 bytearray
.append("0x%02X" % (value
& 0xFF))
413 newvalue
= '{' + ','.join(bytearray
) + '}'
414 ConfigDict
['value'] = newvalue
417 def ParseDscFile (self
, DscFile
, FvDir
):
420 self
._CfgItemList
= []
421 self
._CfgPageDict
= {}
422 self
._CfgBlkDict
= {}
423 self
._DscFile
= DscFile
436 DscFd
= open(DscFile
, "r")
437 DscLines
= DscFd
.readlines()
440 MaxAlign
= 32 #Default align to 32, but if there are 64 bit unit, align to 64
441 SizeAlign
= 0 #record the struct max align
442 Base
= 0 #Starting offset of sub-structure.
444 DscLine
= DscLines
.pop(0).strip()
446 Match
= re
.match("^\[(.+)\]", DscLine
)
447 if Match
is not None:
452 if Match
.group(1).lower() == "Defines".lower():
454 if (Match
.group(1).lower() == "PcdsFeatureFlag".lower() or Match
.group(1).lower() == "PcdsFixedAtBuild".lower()):
456 elif Match
.group(1).lower() == "PcdsDynamicVpd.Upd".lower():
458 ConfigDict
['header'] = 'ON'
459 ConfigDict
['region'] = 'UPD'
460 ConfigDict
['order'] = -1
461 ConfigDict
['page'] = ''
462 ConfigDict
['name'] = ''
463 ConfigDict
['find'] = ''
464 ConfigDict
['struct'] = ''
465 ConfigDict
['embed'] = ''
466 ConfigDict
['comment'] = ''
467 ConfigDict
['subreg'] = []
471 if IsDefSect
or IsPcdSect
or IsUpdSect
or IsVpdSect
:
472 if re
.match("^!else($|\s+#.+)", DscLine
):
474 IfStack
[-1] = not IfStack
[-1]
476 print("ERROR: No paired '!if' found for '!else' for line '%s'" % DscLine
)
478 elif re
.match("^!endif($|\s+#.+)", DscLine
):
481 Level
= ElifStack
.pop()
485 print("ERROR: No paired '!if' found for '!endif' for line '%s'" % DscLine
)
489 Match
= re
.match("!(ifdef|ifndef)\s+(.+)", DscLine
)
491 Result
= self
.EvaulateIfdef (Match
.group(2))
492 if Match
.group(1) == 'ifndef':
494 IfStack
.append(Result
)
497 Match
= re
.match("!(if|elseif)\s+(.+)", DscLine
.split("#")[0])
499 Result
= self
.EvaluateExpress(Match
.group(2))
500 if Match
.group(1) == "if":
502 IfStack
.append(Result
)
505 IfStack
[-1] = not IfStack
[-1]
506 IfStack
.append(Result
)
507 ElifStack
[-1] = ElifStack
[-1] + 1
509 print("ERROR: No paired '!if' found for '!elif' for line '%s'" % DscLine
)
513 Handle
= reduce(lambda x
,y
: x
and y
, IfStack
)
517 Match
= re
.match("!include\s+(.+)", DscLine
)
519 IncludeFilePath
= Match
.group(1)
520 IncludeFilePath
= self
.ExpandMacros(IncludeFilePath
)
521 PackagesPath
= os
.getenv("PACKAGES_PATH")
523 for PackagePath
in PackagesPath
.split(os
.pathsep
):
524 IncludeFilePathAbs
= os
.path
.join(os
.path
.normpath(PackagePath
), os
.path
.normpath(IncludeFilePath
))
525 if os
.path
.exists(IncludeFilePathAbs
):
526 IncludeDsc
= open(IncludeFilePathAbs
, "r")
529 IncludeDsc
= open(IncludeFilePath
, "r")
530 if IncludeDsc
== None:
531 print("ERROR: Cannot open file '%s'" % IncludeFilePath
)
533 NewDscLines
= IncludeDsc
.readlines()
535 DscLines
= NewDscLines
+ DscLines
538 if DscLine
.startswith('!'):
539 print("ERROR: Unrecognized directive for line '%s'" % DscLine
)
545 #DEFINE UPD_TOOL_GUID = 8C3D856A-9BE6-468E-850A-24F7A8D38E09
546 #DEFINE FSP_T_UPD_TOOL_GUID = 34686CA3-34F9-4901-B82A-BA630F0714C6
547 #DEFINE FSP_M_UPD_TOOL_GUID = 39A250DB-E465-4DD1-A2AC-E2BD3C0E2385
548 #DEFINE FSP_S_UPD_TOOL_GUID = CAE3605B-5B34-4C85-B3D7-27D54273C40F
549 Match
= re
.match("^\s*(?:DEFINE\s+)*(\w+)\s*=\s*([/$()-.\w]+)", DscLine
)
551 self
._MacroDict
[Match
.group(1)] = self
.ExpandMacros(Match
.group(2))
553 print ("INFO : DEFINE %s = [ %s ]" % (Match
.group(1), self
.ExpandMacros(Match
.group(2))))
555 #gSiPkgTokenSpaceGuid.PcdTxtEnable|FALSE
556 #gSiPkgTokenSpaceGuid.PcdOverclockEnable|TRUE
557 Match
= re
.match("^\s*([\w\.]+)\s*\|\s*(\w+)", DscLine
)
559 self
._PcdsDict
[Match
.group(1)] = Match
.group(2)
561 print ("INFO : PCD %s = [ %s ]" % (Match
.group(1), Match
.group(2)))
563 while i
< len(BuildOptionPcd
):
564 Match
= re
.match("\s*([\w\.]+)\s*\=\s*(\w+)", BuildOptionPcd
[i
])
566 self
._PcdsDict
[Match
.group(1)] = Match
.group(2)
569 Match
= re
.match("^\s*#\s+(!BSF|@Bsf|!HDR)\s+(.+)", DscLine
)
571 Remaining
= Match
.group(2)
572 if Match
.group(1) == '!BSF' or Match
.group(1) == '@Bsf':
573 Match
= re
.match("(?:^|.+\s+)PAGES:{(.+?)}", Remaining
)
575 # !BSF PAGES:{HSW:"Haswell System Agent", LPT:"Lynx Point PCH"}
576 PageList
= Match
.group(1).split(',')
577 for Page
in PageList
:
579 Match
= re
.match("(\w+):\"(.+)\"", Page
)
580 self
._CfgPageDict
[Match
.group(1)] = Match
.group(2)
582 Match
= re
.match("(?:^|.+\s+)BLOCK:{NAME:\"(.+)\"\s*,\s*VER:\"(.+)\"\s*}", Remaining
)
584 self
._CfgBlkDict
['name'] = Match
.group(1)
585 self
._CfgBlkDict
['ver'] = Match
.group(2)
587 for Key
in self
._BsfKeyList
:
588 Match
= re
.match("(?:^|.+\s+)%s:{(.+?)}" % Key
, Remaining
)
590 if Key
in ['NAME', 'HELP', 'OPTION'] and Match
.group(1).startswith('+'):
591 ConfigDict
[Key
.lower()] += Match
.group(1)[1:]
593 ConfigDict
[Key
.lower()] = Match
.group(1)
595 for Key
in self
._HdrKeyList
:
596 Match
= re
.match("(?:^|.+\s+)%s:{(.+?)}" % Key
, Remaining
)
598 ConfigDict
[Key
.lower()] = Match
.group(1)
600 Match
= re
.match("^\s*#\s+@Prompt\s+(.+)", DscLine
)
602 ConfigDict
['name'] = Match
.group(1)
604 Match
= re
.match("^\s*#\s*@ValidList\s*(.+)\s*\|\s*(.+)\s*\|\s*(.+)\s*", DscLine
)
606 if Match
.group(2).strip() in self
._BuidinOption
:
607 ConfigDict
['option'] = Match
.group(2).strip()
609 OptionValueList
= Match
.group(2).split(',')
610 OptionStringList
= Match
.group(3).split(',')
612 for Option
in OptionValueList
:
613 Option
= Option
.strip()
614 ConfigDict
['option'] = ConfigDict
['option'] + str(Option
) + ':' + OptionStringList
[Index
].strip()
616 if Index
in range(len(OptionValueList
)):
617 ConfigDict
['option'] += ', '
618 ConfigDict
['type'] = "Combo"
620 Match
= re
.match("^\s*#\s*@ValidRange\s*(.+)\s*\|\s*(.+)\s*-\s*(.+)\s*", DscLine
)
622 if "0x" in Match
.group(2) or "0x" in Match
.group(3):
623 ConfigDict
['type'] = "EditNum, HEX, (%s,%s)" % (Match
.group(2), Match
.group(3))
625 ConfigDict
['type'] = "EditNum, DEC, (%s,%s)" % (Match
.group(2), Match
.group(3))
627 Match
= re
.match("^\s*##\s+(.+)", DscLine
)
629 ConfigDict
['help'] = Match
.group(1)
633 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
)
635 Match
= re
.match("^([_a-zA-Z0-9]+).([_a-zA-Z0-9]+)\s*\|\s*(0x[0-9A-F]+)(?:\s*\|\s*(.+))?", DscLine
)
637 ConfigDict
['space'] = Match
.group(1)
638 ConfigDict
['cname'] = Match
.group(2)
639 if Match
.group(3) != '*':
641 Offset
= int (Match
.group(3), 16)
645 if Hardcode
and AutoAlign
:
646 print("Hardcode and auto-align mixed mode is not supported by GenCfgOpt")
648 ConfigDict
['offset'] = Offset
649 if ConfigDict
['order'] == -1:
650 ConfigDict
['order'] = ConfigDict
['offset'] << 8
652 (Major
, Minor
) = ConfigDict
['order'].split('.')
653 ConfigDict
['order'] = (int (Major
, 16) << 8 ) + int (Minor
, 16)
655 Value
= Match
.group(5).strip()
656 if Match
.group(4).startswith("0x"):
657 Length
= int (Match
.group(4), 16)
659 Length
= int (Match
.group(4))
662 Value
= Match
.group(4)
665 Value
= Value
.strip()
667 Match
= re
.match("^.+\s*\|\s*(.+)", Value
)
669 Value
= Match
.group(1)
672 ConfigDict
['length'] = Length
673 Match
= re
.match("\$\((\w+)\)", Value
)
675 if Match
.group(1) in self
._MacroDict
:
676 Value
= self
._MacroDict
[Match
.group(1)]
678 ConfigDict
['value'] = Value
679 if (len(Value
) > 0) and (Value
[0] == '{'):
680 Value
= self
.FormatListValue(ConfigDict
)
682 if ConfigDict
['name'] == '':
683 # Clear BSF specific items
684 ConfigDict
['bsfname'] = ''
685 ConfigDict
['help'] = ''
686 ConfigDict
['type'] = ''
687 ConfigDict
['option'] = ''
688 if IsUpdSect
and AutoAlign
:
689 ItemLength
= int(ConfigDict
['length'])
690 ItemOffset
= int(ConfigDict
['offset'])
691 ItemStruct
= ConfigDict
['struct']
693 if ItemLength
in [1, 2, 4, 8] and not ConfigDict
['value'].startswith('{'):
695 # If there are 64 bit unit, align to 64
700 UnitDict
= {'UINT8':1, 'UINT16':2, 'UINT32':4, 'UINT64':8}
701 if ItemStruct
in ['UINT8', 'UINT16', 'UINT32', 'UINT64']:
702 Unit
= UnitDict
[ItemStruct
]
703 # If there are 64 bit unit, align to 64
706 SizeAlign
= max(SizeAlign
, Unit
)
707 if (ConfigDict
['embed'].find(':START') != -1):
709 SubOffset
= ItemOffset
- Base
710 SubRemainder
= SubOffset
% Unit
712 Diff
= Unit
- SubRemainder
713 Offset
= Offset
+ Diff
714 ItemOffset
= ItemOffset
+ Diff
716 if (ConfigDict
['embed'].find(':END') != -1):
717 Remainder
= Offset
% (MaxAlign
/8) # MaxAlign is either 32 or 64
719 Diff
= int((MaxAlign
/8) - Remainder
)
720 Offset
= Offset
+ Diff
721 ItemOffset
= ItemOffset
+ Diff
722 MaxAlign
= 32 # Reset to default 32 align when struct end
723 if (ConfigDict
['cname'] == 'UpdTerminator'):
724 # ItemLength is the size of UpdTerminator
725 # Itemlength might be 16, 32, or 64
726 # Struct align to 64 if UpdTerminator
727 # or struct size is 64 bit, else align to 32
728 Remainder
= Offset
% max(ItemLength
/8, 4, SizeAlign
)
729 Offset
= Offset
+ ItemLength
731 Diff
= int(max(ItemLength
/8, 4, SizeAlign
) - Remainder
)
732 ItemOffset
= ItemOffset
+ Diff
733 ConfigDict
['offset'] = ItemOffset
735 self
._CfgItemList
.append(ConfigDict
.copy())
736 ConfigDict
['name'] = ''
737 ConfigDict
['find'] = ''
738 ConfigDict
['struct'] = ''
739 ConfigDict
['embed'] = ''
740 ConfigDict
['comment'] = ''
741 ConfigDict
['order'] = -1
742 ConfigDict
['subreg'] = []
743 ConfigDict
['option'] = ''
745 # It could be a virtual item as below
746 # !BSF FIELD:{SerialDebugPortAddress0:1}
748 # @Bsf FIELD:{SerialDebugPortAddress0:1b}
749 Match
= re
.match("^\s*#\s+(!BSF|@Bsf)\s+FIELD:{(.+):(\d+)([Bb])?}", DscLine
)
751 SubCfgDict
= ConfigDict
.copy()
752 if (Match
.group(4) == None) or (Match
.group(4) == 'B'):
754 elif Match
.group(4) == 'b':
757 print("ERROR: Invalide BSF FIELD length for line '%s'" % DscLine
)
759 SubCfgDict
['cname'] = Match
.group(2)
760 SubCfgDict
['bitlength'] = int (Match
.group(3)) * UnitBitLen
761 if SubCfgDict
['bitlength'] > 0:
762 LastItem
= self
._CfgItemList
[-1]
763 if len(LastItem
['subreg']) == 0:
766 SubOffset
= LastItem
['subreg'][-1]['bitoffset'] + LastItem
['subreg'][-1]['bitlength']
767 SubCfgDict
['bitoffset'] = SubOffset
768 LastItem
['subreg'].append (SubCfgDict
.copy())
769 ConfigDict
['name'] = ''
772 def GetBsfBitFields (self
, subitem
, bytes
):
773 start
= subitem
['bitoffset']
774 end
= start
+ subitem
['bitlength']
775 bitsvalue
= ''.join('{0:08b}'.format(i
) for i
in bytes
[::-1])
776 bitsvalue
= bitsvalue
[::-1]
777 bitslen
= len(bitsvalue
)
778 if start
> bitslen
or end
> bitslen
:
779 print ("Invalid bits offset [%d,%d] for %s" % (start
, end
, subitem
['name']))
781 return hex(int(bitsvalue
[start
:end
][::-1], 2))
783 def UpdateSubRegionDefaultValue (self
):
785 for Item
in self
._CfgItemList
:
786 if len(Item
['subreg']) == 0:
789 if Item
['value'][0] == '{':
790 binlist
= Item
['value'][1:-1].split(',')
793 if each
.startswith('0x'):
794 value
= int(each
, 16)
797 bytearray
.append(value
)
799 if Item
['value'].startswith('0x'):
800 value
= int(Item
['value'], 16)
802 value
= int(Item
['value'])
804 while idx
< Item
['length']:
805 bytearray
.append(value
& 0xFF)
808 for SubItem
in Item
['subreg']:
809 valuestr
= self
.GetBsfBitFields(SubItem
, bytearray
)
810 SubItem
['value'] = valuestr
813 def CreateSplitUpdTxt (self
, UpdTxtFile
):
814 GuidList
= ['FSP_T_UPD_TOOL_GUID','FSP_M_UPD_TOOL_GUID','FSP_S_UPD_TOOL_GUID']
815 SignatureList
= ['0x545F', '0x4D5F','0x535F'] # _T, _M, and _S signature for FSPT, FSPM, FSPS
816 for Index
in range(len(GuidList
)):
819 if GuidList
[Index
] not in self
._MacroDict
:
820 self
.Error
= "%s definition is missing in DSC file" % (GuidList
[Index
])
824 UpdTxtFile
= os
.path
.join(FvDir
, self
._MacroDict
[GuidList
[Index
]] + '.txt')
827 if not os
.path
.exists(UpdTxtFile
):
830 DscTime
= os
.path
.getmtime(self
._DscFile
)
831 TxtTime
= os
.path
.getmtime(UpdTxtFile
)
832 if DscTime
> TxtTime
:
836 # DSC has not been modified yet
837 # So don't have to re-generate other files
838 self
.Error
= 'No DSC file change, skip to create UPD TXT file'
841 TxtFd
= open(UpdTxtFile
, "w")
842 TxtFd
.write("%s\n" % (__copyright_txt__
% date
.today().year
))
850 for Item
in self
._CfgItemList
:
851 if Item
['cname'] == 'Signature' and str(Item
['value'])[0:6] == SignatureList
[Index
]:
852 StartAddr
= Item
['offset']
853 NextOffset
= StartAddr
855 if Item
['cname'] == 'UpdTerminator' and InRange
== True:
856 EndAddr
= Item
['offset']
859 for Item
in self
._CfgItemList
:
860 if Item
['cname'] == 'Signature' and str(Item
['value'])[0:6] == SignatureList
[Index
]:
864 if Item
['cname'] == 'UpdTerminator':
866 if Item
['region'] != 'UPD':
868 Offset
= Item
['offset']
869 if StartAddr
> Offset
or EndAddr
< Offset
:
871 if NextOffset
< Offset
:
873 TxtFd
.write("%s.UnusedUpdSpace%d|%s0x%04X|0x%04X|{0}\n" % (Item
['space'], SpaceIdx
, Default
, NextOffset
- StartAddr
, Offset
- NextOffset
))
874 SpaceIdx
= SpaceIdx
+ 1
875 NextOffset
= Offset
+ Item
['length']
876 TxtFd
.write("%s.%s|%s0x%04X|%s|%s\n" % (Item
['space'],Item
['cname'],Default
,Item
['offset'] - StartAddr
,Item
['length'],Item
['value']))
880 def ProcessMultilines (self
, String
, MaxCharLength
):
882 StringLength
= len(String
)
883 CurrentStringStart
= 0
886 if len(String
) <= MaxCharLength
:
887 while (StringOffset
< StringLength
):
888 if StringOffset
>= 1:
889 if String
[StringOffset
- 1] == '\\' and String
[StringOffset
] == 'n':
890 BreakLineDict
.append (StringOffset
+ 1)
892 if BreakLineDict
!= []:
893 for Each
in BreakLineDict
:
894 Multilines
+= " %s\n" % String
[CurrentStringStart
:Each
].lstrip()
895 CurrentStringStart
= Each
896 if StringLength
- CurrentStringStart
> 0:
897 Multilines
+= " %s\n" % String
[CurrentStringStart
:].lstrip()
899 Multilines
= " %s\n" % String
903 FoundSpaceChar
= False
904 while (StringOffset
< StringLength
):
905 if StringOffset
>= 1:
906 if NewLineCount
>= MaxCharLength
- 1:
907 if String
[StringOffset
] == ' ' and StringLength
- StringOffset
> 10:
908 BreakLineDict
.append (NewLineStart
+ NewLineCount
)
909 NewLineStart
= NewLineStart
+ NewLineCount
911 FoundSpaceChar
= True
912 elif StringOffset
== StringLength
- 1 and FoundSpaceChar
== False:
913 BreakLineDict
.append (0)
914 if String
[StringOffset
- 1] == '\\' and String
[StringOffset
] == 'n':
915 BreakLineDict
.append (StringOffset
+ 1)
916 NewLineStart
= StringOffset
+ 1
920 if BreakLineDict
!= []:
921 BreakLineDict
.sort ()
922 for Each
in BreakLineDict
:
924 Multilines
+= " %s\n" % String
[CurrentStringStart
:Each
].lstrip()
925 CurrentStringStart
= Each
926 if StringLength
- CurrentStringStart
> 0:
927 Multilines
+= " %s\n" % String
[CurrentStringStart
:].lstrip()
930 def CreateField (self
, Item
, Name
, Length
, Offset
, Struct
, BsfName
, Help
, Option
):
938 if Length
in [1,2,4,8]:
939 Type
= "UINT%d" % (Length
* 8)
940 if Name
.startswith("UnusedUpdSpace") and Length
!= 1:
947 if Item
and Item
['value'].startswith('{'):
953 if Struct
in ['UINT8','UINT16','UINT32','UINT64']:
955 Unit
= int(Type
[4:]) / 8
956 Length
= Length
/ Unit
961 Name
= Name
+ '[%d]' % Length
963 if len(Type
) < PosName
:
964 Space1
= PosName
- len(Type
)
969 NameLine
=" - %s\n" % BsfName
974 HelpLine
= self
.ProcessMultilines (Help
, 80)
977 OptionLine
= self
.ProcessMultilines (Option
, 80)
982 OffsetStr
= '0x%04X' % Offset
984 return "\n/** Offset %s%s%s%s**/\n %s%s%s;\n" % (OffsetStr
, NameLine
, HelpLine
, OptionLine
, Type
, ' ' * Space1
, Name
,)
986 def PostProcessBody (self
, TextBody
):
992 IsUpdHdrDefined
= False
994 for Line
in TextBody
:
995 SplitToLines
= Line
.splitlines()
996 MatchComment
= re
.match("^/\*\sCOMMENT:(\w+):([\w|\W|\s]+)\s\*/\s([\s\S]*)", SplitToLines
[0])
998 if MatchComment
.group(1) == 'FSP_UPD_HEADER':
1002 if IsUpdHdrDefined
!= True or IsUpdHeader
!= True:
1003 CommentLine
= " " + MatchComment
.group(2) + "\n"
1004 NewTextBody
.append("/**" + CommentLine
+ "**/\n")
1005 Line
= Line
[(len(SplitToLines
[0]) + 1):]
1007 Match
= re
.match("^/\*\sEMBED_STRUCT:(\w+):(\w+):(START|END)\s\*/\s([\s\S]*)", Line
)
1009 Line
= Match
.group(4)
1010 if Match
.group(1) == 'FSP_UPD_HEADER':
1015 if Match
and Match
.group(3) == 'START':
1016 if IsUpdHdrDefined
!= True or IsUpdHeader
!= True:
1017 NewTextBody
.append ('typedef struct {\n')
1018 StructName
= Match
.group(1)
1019 VariableName
= Match
.group(2)
1020 MatchOffset
= re
.search('/\*\*\sOffset\s0x([a-fA-F0-9]+)', Line
)
1022 Offset
= int(MatchOffset
.group(1), 16)
1027 OldTextBody
.append (self
.CreateField (None, VariableName
, 0, Offset
, StructName
, '', '', ''))
1029 if IsUpdHdrDefined
!= True or IsUpdHeader
!= True:
1030 NewTextBody
.append (Line
)
1032 OldTextBody
.append (Line
)
1034 if Match
and Match
.group(3) == 'END':
1035 if (StructName
!= Match
.group(1)) or (VariableName
!= Match
.group(2)):
1036 print ("Unmatched struct name '%s' and '%s' !" % (StructName
, Match
.group(1)))
1038 if IsUpdHdrDefined
!= True or IsUpdHeader
!= True:
1039 NewTextBody
.append ('} %s;\n\n' % StructName
)
1040 IsUpdHdrDefined
= True
1042 NewTextBody
.extend(OldTextBody
)
1045 def WriteLinesWithoutTailingSpace (self
, HeaderFd
, Line
):
1046 TxtBody2
= Line
.splitlines(True)
1047 for Line2
in TxtBody2
:
1048 Line2
= Line2
.rstrip()
1050 HeaderFd
.write (Line2
)
1052 def CreateHeaderFile (self
, InputHeaderFile
):
1055 HeaderFileName
= 'FspUpd.h'
1056 HeaderFile
= os
.path
.join(FvDir
, HeaderFileName
)
1058 # Check if header needs to be recreated
1062 for Item
in self
._CfgItemList
:
1063 if str(Item
['cname']) == 'Signature' and Item
['length'] == 8:
1064 Value
= int(Item
['value'], 16)
1067 Chars
.append(chr(Value
& 0xFF))
1069 SignatureStr
= ''.join(Chars
)
1070 # Signature will be _T / _M / _S for FSPT / FSPM / FSPS accordingly
1071 if '_T' in SignatureStr
[6:6+2]:
1072 TxtBody
.append("#define FSPT_UPD_SIGNATURE %s /* '%s' */\n\n" % (Item
['value'], SignatureStr
))
1073 elif '_M' in SignatureStr
[6:6+2]:
1074 TxtBody
.append("#define FSPM_UPD_SIGNATURE %s /* '%s' */\n\n" % (Item
['value'], SignatureStr
))
1075 elif '_S' in SignatureStr
[6:6+2]:
1076 TxtBody
.append("#define FSPS_UPD_SIGNATURE %s /* '%s' */\n\n" % (Item
['value'], SignatureStr
))
1077 TxtBody
.append("\n")
1079 for Region
in ['UPD']:
1081 UpdSignature
= ['0x545F', '0x4D5F', '0x535F'] #['_T', '_M', '_S'] signature for FSPT, FSPM, FSPS
1082 UpdStructure
= ['FSPT_UPD', 'FSPM_UPD', 'FSPS_UPD']
1083 for Item
in self
._CfgItemList
:
1084 if Item
["cname"] == 'Signature' and Item
["value"][0:6] in UpdSignature
:
1085 UpdOffsetTable
.append (Item
["offset"])
1087 for UpdIdx
in range(len(UpdOffsetTable
)):
1089 for Item
in self
._CfgItemList
:
1090 if Item
["comment"] != '' and Item
["offset"] >= UpdOffsetTable
[UpdIdx
]:
1091 MatchComment
= re
.match("^(U|V)PD_DATA_REGION:([\w|\W|\s]+)", Item
["comment"])
1092 if MatchComment
and MatchComment
.group(1) == Region
[0]:
1093 CommentLine
= " " + MatchComment
.group(2) + "\n"
1094 TxtBody
.append("/**" + CommentLine
+ "**/\n")
1095 elif Item
["offset"] >= UpdOffsetTable
[UpdIdx
] and Item
["comment"] == '':
1096 Match
= re
.match("^FSP([\w|\W|\s])_UPD", UpdStructure
[UpdIdx
])
1098 TxtBody
.append("/** Fsp " + Match
.group(1) + " UPD Configuration\n**/\n")
1099 TxtBody
.append("typedef struct {\n")
1109 for Item
in self
._CfgItemList
:
1110 if Item
['cname'] == 'Signature' and str(Item
['value'])[0:6] == UpdSignature
[UpdIdx
] or Region
[0] == 'V':
1114 if Item
['cname'] == 'UpdTerminator':
1117 if Item
['region'] != Region
:
1120 if Item
["offset"] < UpdOffsetTable
[UpdIdx
]:
1123 NextVisible
= LastVisible
1125 if LastVisible
and (Item
['header'] == 'OFF'):
1127 ResvOffset
= Item
['offset']
1128 elif (not LastVisible
) and Item
['header'] == 'ON':
1130 Name
= "Reserved" + Region
[0] + "pdSpace%d" % ResvIdx
1131 ResvIdx
= ResvIdx
+ 1
1132 TxtBody
.append(self
.CreateField (Item
, Name
, Item
["offset"] - ResvOffset
, ResvOffset
, '', '', '', ''))
1134 if Offset
< Item
["offset"]:
1136 Name
= "Unused" + Region
[0] + "pdSpace%d" % SpaceIdx
1137 LineBuffer
.append(self
.CreateField (Item
, Name
, Item
["offset"] - Offset
, Offset
, '', '', '', ''))
1138 SpaceIdx
= SpaceIdx
+ 1
1139 Offset
= Item
["offset"]
1141 LastVisible
= NextVisible
1143 Offset
= Offset
+ Item
["length"]
1145 for Each
in LineBuffer
:
1146 TxtBody
.append (Each
)
1148 Comment
= Item
["comment"]
1149 Embed
= Item
["embed"].upper()
1150 if Embed
.endswith(':START') or Embed
.endswith(':END'):
1151 if not Comment
== '' and Embed
.endswith(':START'):
1152 Marker
= '/* COMMENT:%s */ \n' % Item
["comment"]
1153 Marker
= Marker
+ '/* EMBED_STRUCT:%s */ ' % Item
["embed"]
1155 Marker
= '/* EMBED_STRUCT:%s */ ' % Item
["embed"]
1160 self
.Error
= "Invalid embedded structure format '%s'!\n" % Item
["embed"]
1162 Line
= Marker
+ self
.CreateField (Item
, Item
["cname"], Item
["length"], Item
["offset"], Item
['struct'], Item
['name'], Item
['help'], Item
['option'])
1163 TxtBody
.append(Line
)
1164 if Item
['cname'] == 'UpdTerminator':
1166 TxtBody
.append("} " + UpdStructure
[UpdIdx
] + ";\n\n")
1168 # Handle the embedded data structure
1169 TxtBody
= self
.PostProcessBody (TxtBody
)
1171 HeaderTFileName
= 'FsptUpd.h'
1172 HeaderMFileName
= 'FspmUpd.h'
1173 HeaderSFileName
= 'FspsUpd.h'
1175 UpdRegionCheck
= ['FSPT', 'FSPM', 'FSPS'] # FSPX_UPD_REGION
1176 UpdConfigCheck
= ['FSP_T', 'FSP_M', 'FSP_S'] # FSP_X_CONFIG, FSP_X_TEST_CONFIG, FSP_X_RESTRICTED_CONFIG
1177 UpdSignatureCheck
= ['FSPT_UPD_SIGNATURE', 'FSPM_UPD_SIGNATURE', 'FSPS_UPD_SIGNATURE']
1178 ExcludedSpecificUpd
= ['FSPT_ARCH_UPD', 'FSPM_ARCH_UPD', 'FSPS_ARCH_UPD']
1181 if InputHeaderFile
!= '':
1182 if not os
.path
.exists(InputHeaderFile
):
1183 self
.Error
= "Input header file '%s' does not exist" % InputHeaderFile
1186 InFd
= open(InputHeaderFile
, "r")
1187 IncLines
= InFd
.readlines()
1190 for item
in range(len(UpdRegionCheck
)):
1191 if UpdRegionCheck
[item
] == 'FSPT':
1192 HeaderFd
= open(os
.path
.join(FvDir
, HeaderTFileName
), "w")
1193 FileBase
= os
.path
.basename(os
.path
.join(FvDir
, HeaderTFileName
))
1194 elif UpdRegionCheck
[item
] == 'FSPM':
1195 HeaderFd
= open(os
.path
.join(FvDir
, HeaderMFileName
), "w")
1196 FileBase
= os
.path
.basename(os
.path
.join(FvDir
, HeaderMFileName
))
1197 elif UpdRegionCheck
[item
] == 'FSPS':
1198 HeaderFd
= open(os
.path
.join(FvDir
, HeaderSFileName
), "w")
1199 FileBase
= os
.path
.basename(os
.path
.join(FvDir
, HeaderSFileName
))
1200 FileName
= FileBase
.replace(".", "_").upper()
1201 HeaderFd
.write("%s\n" % (__copyright_h__
% date
.today().year
))
1202 HeaderFd
.write("#ifndef __%s__\n" % FileName
)
1203 HeaderFd
.write("#define __%s__\n\n" % FileName
)
1204 HeaderFd
.write("#include <%s>\n\n" % HeaderFileName
)
1205 HeaderFd
.write("#pragma pack(1)\n\n")
1208 for Line
in IncLines
:
1209 Match
= re
.search ("!EXPORT\s+([A-Z]+)\s+EXTERNAL_BOOTLOADER_STRUCT_(BEGIN|END)\s+", Line
)
1211 if Match
.group(2) == "BEGIN" and Match
.group(1) == UpdRegionCheck
[item
]:
1218 HeaderFd
.write(Line
)
1219 HeaderFd
.write("\n")
1225 StructStartWithComment
= []
1227 for Line
in TxtBody
:
1229 Match
= re
.match("(typedef struct {)", Line
)
1231 StartIndex
= Index
- 1
1232 Match
= re
.match("}\s([_A-Z0-9]+);", Line
)
1233 if Match
and (UpdRegionCheck
[item
] in Match
.group(1) or UpdConfigCheck
[item
] in Match
.group(1)) and (ExcludedSpecificUpd
[item
] not in Match
.group(1)):
1235 StructStart
.append(StartIndex
)
1236 StructEnd
.append(EndIndex
)
1238 for Line
in TxtBody
:
1240 for Item
in range(len(StructStart
)):
1241 if Index
== StructStart
[Item
]:
1242 Match
= re
.match("^(/\*\*\s*)", Line
)
1244 StructStartWithComment
.append(StructStart
[Item
])
1246 StructStartWithComment
.append(StructStart
[Item
] + 1)
1248 for Line
in TxtBody
:
1250 for Item
in range(len(StructStart
)):
1251 if Index
>= StructStartWithComment
[Item
] and Index
<= StructEnd
[Item
]:
1252 self
.WriteLinesWithoutTailingSpace(HeaderFd
, Line
)
1253 HeaderFd
.write("#pragma pack()\n\n")
1254 HeaderFd
.write("#endif\n")
1257 HeaderFd
= open(HeaderFile
, "w")
1258 FileBase
= os
.path
.basename(HeaderFile
)
1259 FileName
= FileBase
.replace(".", "_").upper()
1260 HeaderFd
.write("%s\n" % (__copyright_h__
% date
.today().year
))
1261 HeaderFd
.write("#ifndef __%s__\n" % FileName
)
1262 HeaderFd
.write("#define __%s__\n\n" % FileName
)
1263 HeaderFd
.write("#include <FspEas.h>\n\n")
1264 HeaderFd
.write("#pragma pack(1)\n\n")
1266 for item
in range(len(UpdRegionCheck
)):
1271 StructStartWithComment
= []
1273 for Line
in TxtBody
:
1275 Match
= re
.match("(typedef struct {)", Line
)
1277 StartIndex
= Index
- 1
1278 Match
= re
.match("#define\s([_A-Z0-9]+)\s*", Line
)
1279 if Match
and (UpdSignatureCheck
[item
] in Match
.group(1) or UpdSignatureCheck
[item
] in Match
.group(1)):
1280 StructStart
.append(Index
- 1)
1281 StructEnd
.append(Index
)
1283 for Line
in TxtBody
:
1285 for Item
in range(len(StructStart
)):
1286 if Index
== StructStart
[Item
]:
1287 Match
= re
.match("^(/\*\*\s*)", Line
)
1289 StructStartWithComment
.append(StructStart
[Item
])
1291 StructStartWithComment
.append(StructStart
[Item
] + 1)
1293 for Line
in TxtBody
:
1295 for Item
in range(len(StructStart
)):
1296 if Index
>= StructStartWithComment
[Item
] and Index
<= StructEnd
[Item
]:
1297 self
.WriteLinesWithoutTailingSpace(HeaderFd
, Line
)
1298 HeaderFd
.write("#pragma pack()\n\n")
1299 HeaderFd
.write("#endif\n")
1304 def WriteBsfStruct (self
, BsfFd
, Item
):
1305 LogExpr
= CLogicalExpression()
1306 if Item
['type'] == "None":
1307 Space
= "gPlatformFspPkgTokenSpaceGuid"
1309 Space
= Item
['space']
1310 Line
= " $%s_%s" % (Space
, Item
['cname'])
1311 Match
= re
.match("\s*\{([x0-9a-fA-F,\s]+)\}\s*", Item
['value'])
1313 DefaultValue
= Match
.group(1).strip()
1315 DefaultValue
= Item
['value'].strip()
1316 if 'bitlength' in Item
:
1317 BsfFd
.write(" %s%s%4d bits $_DEFAULT_ = %s\n" % (Line
, ' ' * (64 - len(Line
)), Item
['bitlength'], DefaultValue
))
1319 BsfFd
.write(" %s%s%4d bytes $_DEFAULT_ = %s\n" % (Line
, ' ' * (64 - len(Line
)), Item
['length'], DefaultValue
))
1321 if Item
['type'] == "Combo":
1322 if not Item
['option'] in self
._BuidinOption
:
1323 OptList
= Item
['option'].split(',')
1324 for Option
in OptList
:
1325 Option
= Option
.strip()
1326 (OpVal
, OpStr
) = Option
.split(':')
1327 test
= LogExpr
.getNumber (OpVal
)
1329 raise Exception("Selection Index '%s' is not a number" % OpVal
)
1330 TmpList
.append((OpVal
, OpStr
))
1333 def WriteBsfOption (self
, BsfFd
, Item
):
1334 PcdName
= Item
['space'] + '_' + Item
['cname']
1336 if Item
['type'] == "Combo":
1337 if Item
['option'] in self
._BuidinOption
:
1338 Options
= self
._BuidinOption
[Item
['option']]
1341 BsfFd
.write(' %s $%s, "%s", &%s,\n' % (Item
['type'], PcdName
, Item
['name'], Options
))
1343 elif Item
['type'].startswith("EditNum"):
1344 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'])
1346 BsfFd
.write(' EditNum $%s, "%s", %s,\n' % (PcdName
, Item
['name'], Match
.group(1)))
1348 elif Item
['type'].startswith("EditText"):
1349 BsfFd
.write(' %s $%s, "%s",\n' % (Item
['type'], PcdName
, Item
['name']))
1351 elif Item
['type'] == "Table":
1352 Columns
= Item
['option'].split(',')
1353 if len(Columns
) != 0:
1354 BsfFd
.write(' %s $%s "%s",' % (Item
['type'], PcdName
, Item
['name']))
1356 Fmt
= Col
.split(':')
1358 raise Exception("Column format '%s' is invalid !" % Fmt
)
1360 Dtype
= int(Fmt
[1].strip())
1362 raise Exception("Column size '%s' is invalid !" % Fmt
[1])
1363 BsfFd
.write('\n Column "%s", %d bytes, %s' % (Fmt
[0].strip(), Dtype
, Fmt
[2].strip()))
1368 HelpLines
= Item
['help'].split('\\n\\r')
1370 for HelpLine
in HelpLines
:
1373 BsfFd
.write(' Help "%s"\n' % (HelpLine
))
1375 BsfFd
.write(' "%s"\n' % (HelpLine
))
1377 BsfFd
.write(' "Valid range: %s ~ %s"\n' % (Match
.group(2), Match
.group(3)))
1379 def GenerateBsfFile (self
, BsfFile
):
1382 self
.Error
= "BSF output file '%s' is invalid" % BsfFile
1387 BsfFd
= open(BsfFile
, "w")
1388 BsfFd
.write("%s\n" % (__copyright_bsf__
% date
.today().year
))
1389 BsfFd
.write("%s\n" % self
._GlobalDataDef
)
1390 BsfFd
.write("StructDef\n")
1392 for Item
in self
._CfgItemList
:
1393 if Item
['find'] != '':
1394 BsfFd
.write('\n Find "%s"\n' % Item
['find'])
1395 NextOffset
= Item
['offset'] + Item
['length']
1396 if Item
['name'] != '':
1397 if NextOffset
!= Item
['offset']:
1398 BsfFd
.write(" Skip %d bytes\n" % (Item
['offset'] - NextOffset
))
1399 if len(Item
['subreg']) > 0:
1400 NextOffset
= Item
['offset']
1401 BitsOffset
= NextOffset
* 8
1402 for SubItem
in Item
['subreg']:
1403 BitsOffset
+= SubItem
['bitlength']
1404 if SubItem
['name'] == '':
1405 if 'bitlength' in SubItem
:
1406 BsfFd
.write(" Skip %d bits\n" % (SubItem
['bitlength']))
1408 BsfFd
.write(" Skip %d bytes\n" % (SubItem
['length']))
1410 Options
= self
.WriteBsfStruct(BsfFd
, SubItem
)
1411 if len(Options
) > 0:
1412 OptionDict
[SubItem
['space']+'_'+SubItem
['cname']] = Options
1414 NextBitsOffset
= (Item
['offset'] + Item
['length']) * 8
1415 if NextBitsOffset
> BitsOffset
:
1416 BitsGap
= NextBitsOffset
- BitsOffset
1417 BitsRemain
= BitsGap
% 8
1419 BsfFd
.write(" Skip %d bits\n" % BitsRemain
)
1420 BitsGap
-= BitsRemain
1421 BytesRemain
= int(BitsGap
/ 8)
1423 BsfFd
.write(" Skip %d bytes\n" % BytesRemain
)
1424 NextOffset
= Item
['offset'] + Item
['length']
1426 NextOffset
= Item
['offset'] + Item
['length']
1427 Options
= self
.WriteBsfStruct(BsfFd
, Item
)
1428 if len(Options
) > 0:
1429 OptionDict
[Item
['space']+'_'+Item
['cname']] = Options
1430 BsfFd
.write("\nEndStruct\n\n")
1432 BsfFd
.write("%s" % self
._BuidinOptionTxt
)
1434 for Each
in OptionDict
:
1435 BsfFd
.write("List &%s\n" % Each
)
1436 for Item
in OptionDict
[Each
]:
1437 BsfFd
.write(' Selection %s , "%s"\n' % (Item
[0], Item
[1]))
1438 BsfFd
.write("EndList\n\n")
1440 BsfFd
.write("BeginInfoBlock\n")
1441 BsfFd
.write(' PPVer "%s"\n' % (self
._CfgBlkDict
['ver']))
1442 BsfFd
.write(' Description "%s"\n' % (self
._CfgBlkDict
['name']))
1443 BsfFd
.write("EndInfoBlock\n\n")
1445 for Each
in self
._CfgPageDict
:
1446 BsfFd
.write('Page "%s"\n' % self
._CfgPageDict
[Each
])
1448 for Item
in self
._CfgItemList
:
1449 if Item
['name'] != '':
1450 if Item
['page'] != Each
:
1452 if len(Item
['subreg']) > 0:
1453 for SubItem
in Item
['subreg']:
1454 if SubItem
['name'] != '':
1455 BsfItems
.append(SubItem
)
1457 BsfItems
.append(Item
)
1459 BsfItems
.sort(key
=lambda x
: x
['order'])
1461 for Item
in BsfItems
:
1462 self
.WriteBsfOption (BsfFd
, Item
)
1463 BsfFd
.write("EndPage\n\n")
1470 print ("GenCfgOpt Version 0.55")
1472 print (" GenCfgOpt UPDTXT PlatformDscFile BuildFvDir [-D Macros]")
1473 print (" GenCfgOpt HEADER PlatformDscFile BuildFvDir InputHFile [-D Macros]")
1474 print (" GenCfgOpt GENBSF PlatformDscFile BuildFvDir BsfOutFile [-D Macros]")
1478 # Parse the options and args
1482 GenCfgOpt
= CGenCfgOpt()
1483 while i
< len(sys
.argv
):
1484 if sys
.argv
[i
].strip().lower() == "--pcd":
1485 BuildOptionPcd
.append(sys
.argv
[i
+1])
1488 argc
= len(sys
.argv
)
1493 DscFile
= sys
.argv
[2]
1494 if not os
.path
.exists(DscFile
):
1495 print ("ERROR: Cannot open DSC file '%s' !" % DscFile
)
1500 if sys
.argv
[4][0] == '-':
1503 OutFile
= sys
.argv
[4]
1506 if GenCfgOpt
.ParseMacros(sys
.argv
[Start
:]) != 0:
1507 print ("ERROR: Macro parsing failed !")
1511 if not os
.path
.exists(FvDir
):
1514 if GenCfgOpt
.ParseDscFile(DscFile
, FvDir
) != 0:
1515 print ("ERROR: %s !" % GenCfgOpt
.Error
)
1518 if GenCfgOpt
.UpdateSubRegionDefaultValue() != 0:
1519 print ("ERROR: %s !" % GenCfgOpt
.Error
)
1522 if sys
.argv
[1] == "UPDTXT":
1523 Ret
= GenCfgOpt
.CreateSplitUpdTxt(OutFile
)
1525 # No change is detected
1527 print ("INFO: %s !" % (GenCfgOpt
.Error
))
1529 print ("ERROR: %s !" % (GenCfgOpt
.Error
))
1531 elif sys
.argv
[1] == "HEADER":
1532 if GenCfgOpt
.CreateHeaderFile(OutFile
) != 0:
1533 print ("ERROR: %s !" % GenCfgOpt
.Error
)
1535 elif sys
.argv
[1] == "GENBSF":
1536 if GenCfgOpt
.GenerateBsfFile(OutFile
) != 0:
1537 print ("ERROR: %s !" % GenCfgOpt
.Error
)
1543 print ("ERROR: Unknown command '%s' !" % sys
.argv
[1])
1550 if __name__
== '__main__':