GenCfgOpt.py 66 KB

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