GenCfgOpt.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  1. ## @ GenCfgOpt.py
  2. #
  3. # Copyright (c) 2014 - 2015, 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. # Generated file copyright header
  13. __copyright_txt__ = """## @file
  14. #
  15. # THIS IS AUTO-GENERATED FILE BY BUILD TOOLS AND PLEASE DO NOT MAKE MODIFICATION.
  16. #
  17. # This file lists all VPD informations for a platform collected by build.exe.
  18. #
  19. # Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>
  20. # This program and the accompanying materials
  21. # are licensed and made available under the terms and conditions of the BSD License
  22. # which accompanies this distribution. The full text of the license may be found at
  23. # http://opensource.org/licenses/bsd-license.php
  24. #
  25. # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
  26. # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
  27. #
  28. """
  29. __copyright_bsf__ = """/** @file
  30. Boot Setting File for Platform Configuration.
  31. Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>
  32. This program and the accompanying materials
  33. are licensed and made available under the terms and conditions of the BSD License
  34. which accompanies this distribution. The full text of the license may be found at
  35. http://opensource.org/licenses/bsd-license.php
  36. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
  37. WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
  38. This file is automatically generated. Please do NOT modify !!!
  39. **/
  40. """
  41. __copyright_h__ = """/** @file
  42. Copyright (c) %4d, Intel Corporation. All rights reserved.<BR>
  43. Redistribution and use in source and binary forms, with or without modification,
  44. are permitted provided that the following conditions are met:
  45. * Redistributions of source code must retain the above copyright notice, this
  46. list of conditions and the following disclaimer.
  47. * Redistributions in binary form must reproduce the above copyright notice, this
  48. list of conditions and the following disclaimer in the documentation and/or
  49. other materials provided with the distribution.
  50. * Neither the name of Intel Corporation nor the names of its contributors may
  51. be used to endorse or promote products derived from this software without
  52. specific prior written permission.
  53. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  54. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  55. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  56. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  57. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  58. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  59. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  60. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  61. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  62. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  63. THE POSSIBILITY OF SUCH DAMAGE.
  64. This file is automatically generated. Please do NOT modify !!!
  65. **/
  66. """
  67. def UpdateMemSiUpdInitOffsetValue (DscFile):
  68. DscFd = open(DscFile, "r")
  69. DscLines = DscFd.readlines()
  70. DscFd.close()
  71. DscContent = []
  72. MemUpdInitOffset = 0
  73. SiUpdInitOffset = 0
  74. MemUpdInitOffsetValue = 0
  75. SiUpdInitOffsetValue = 0
  76. while len(DscLines):
  77. DscLine = DscLines.pop(0)
  78. DscContent.append(DscLine)
  79. DscLine = DscLine.strip()
  80. Match = re.match("^([_a-zA-Z0-9]+).(MemoryInitUpdOffset)\s*\|\s*(0x[0-9A-F]+)\s*\|\s*(\d+|0x[0-9a-fA-F]+)\s*\|\s*(.+)",DscLine)
  81. if Match:
  82. MemUpdInitOffsetValue = int(Match.group(5), 0)
  83. Match = re.match("^\s*([_a-zA-Z0-9]+).(SiliconInitUpdOffset)\s*\|\s*(0x[0-9A-F]+)\s*\|\s*(\d+|0x[0-9a-fA-F]+)\s*\|\s*(.+)",DscLine)
  84. if Match:
  85. SiUpdInitOffsetValue = int(Match.group(5), 0)
  86. 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*(0x244450554D454D24)",DscLine)
  87. if Match:
  88. MemUpdInitOffset = int(Match.group(3), 0)
  89. 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*(0x244450555F495324)",DscLine)
  90. if Match:
  91. SiUpdInitOffset = int(Match.group(3), 0)
  92. if MemUpdInitOffsetValue != MemUpdInitOffset or SiUpdInitOffsetValue != SiUpdInitOffset:
  93. MemUpdInitOffsetStr = "0x%08X" % MemUpdInitOffset
  94. SiUpdInitOffsetStr = "0x%08X" % SiUpdInitOffset
  95. DscFd = open(DscFile,"w")
  96. for DscLine in DscContent:
  97. Match = re.match("^\s*([_a-zA-Z0-9]+).(MemoryInitUpdOffset)\s*\|\s*(0x[0-9A-F]+)\s*\|\s*(\d+|0x[0-9a-fA-F]+)\s*\|\s*(.+)",DscLine)
  98. if Match:
  99. DscLine = re.sub(r'(?:[^\s]+\s*$)', MemUpdInitOffsetStr + '\n', DscLine)
  100. Match = re.match("^\s*([_a-zA-Z0-9]+).(SiliconInitUpdOffset)\s*\|\s*(0x[0-9A-F]+)\s*\|\s*(\d+|0x[0-9a-fA-F]+)\s*\|\s*(.+)",DscLine)
  101. if Match:
  102. DscLine = re.sub(r'(?:[^\s]+\s*$)', SiUpdInitOffsetStr + '\n', line)
  103. DscFd.writelines(DscLine)
  104. DscFd.close()
  105. class CLogicalExpression:
  106. def __init__(self):
  107. self.index = 0
  108. self.string = ''
  109. def errExit(self, err = ''):
  110. print "ERROR: Express parsing for:"
  111. print " %s" % self.string
  112. print " %s^" % (' ' * self.index)
  113. if err:
  114. print "INFO : %s" % err
  115. raise SystemExit
  116. def getNonNumber (self, n1, n2):
  117. if not n1.isdigit():
  118. return n1
  119. if not n2.isdigit():
  120. return n2
  121. return None
  122. def getCurr(self, lens = 1):
  123. try:
  124. if lens == -1:
  125. return self.string[self.index :]
  126. else:
  127. if self.index + lens > len(self.string):
  128. lens = len(self.string) - self.index
  129. return self.string[self.index : self.index + lens]
  130. except Exception:
  131. return ''
  132. def isLast(self):
  133. return self.index == len(self.string)
  134. def moveNext(self, len = 1):
  135. self.index += len
  136. def skipSpace(self):
  137. while not self.isLast():
  138. if self.getCurr() in ' \t':
  139. self.moveNext()
  140. else:
  141. return
  142. def normNumber (self, val):
  143. return True if val else False
  144. def getNumber(self, var):
  145. var = var.strip()
  146. if re.match('^0x[a-fA-F0-9]+$', var):
  147. value = int(var, 16)
  148. elif re.match('^[+-]?\d+$', var):
  149. value = int(var, 10)
  150. else:
  151. value = None
  152. return value
  153. def parseValue(self):
  154. self.skipSpace()
  155. var = ''
  156. while not self.isLast():
  157. char = self.getCurr()
  158. if re.match('^[\w.]', char):
  159. var += char
  160. self.moveNext()
  161. else:
  162. break
  163. val = self.getNumber(var)
  164. if val is None:
  165. value = var
  166. else:
  167. value = "%d" % val
  168. return value
  169. def parseSingleOp(self):
  170. self.skipSpace()
  171. if re.match('^NOT\W', self.getCurr(-1)):
  172. self.moveNext(3)
  173. op = self.parseBrace()
  174. val = self.getNumber (op)
  175. if val is None:
  176. self.errExit ("'%s' is not a number" % op)
  177. return "%d" % (not self.normNumber(int(op)))
  178. else:
  179. return self.parseValue()
  180. def parseBrace(self):
  181. self.skipSpace()
  182. char = self.getCurr()
  183. if char == '(':
  184. self.moveNext()
  185. value = self.parseExpr()
  186. self.skipSpace()
  187. if self.getCurr() != ')':
  188. self.errExit ("Expecting closing brace or operator")
  189. self.moveNext()
  190. return value
  191. else:
  192. value = self.parseSingleOp()
  193. return value
  194. def parseCompare(self):
  195. value = self.parseBrace()
  196. while True:
  197. self.skipSpace()
  198. char = self.getCurr()
  199. if char in ['<', '>']:
  200. self.moveNext()
  201. next = self.getCurr()
  202. if next == '=':
  203. op = char + next
  204. self.moveNext()
  205. else:
  206. op = char
  207. result = self.parseBrace()
  208. test = self.getNonNumber(result, value)
  209. if test is None:
  210. value = "%d" % self.normNumber(eval (value + op + result))
  211. else:
  212. self.errExit ("'%s' is not a valid number for comparision" % test)
  213. elif char in ['=', '!']:
  214. op = self.getCurr(2)
  215. if op in ['==', '!=']:
  216. self.moveNext(2)
  217. result = self.parseBrace()
  218. test = self.getNonNumber(result, value)
  219. if test is None:
  220. value = "%d" % self.normNumber((eval (value + op + result)))
  221. else:
  222. value = "%d" % self.normNumber(eval ("'" + value + "'" + op + "'" + result + "'"))
  223. else:
  224. break
  225. else:
  226. break
  227. return value
  228. def parseAnd(self):
  229. value = self.parseCompare()
  230. while True:
  231. self.skipSpace()
  232. if re.match('^AND\W', self.getCurr(-1)):
  233. self.moveNext(3)
  234. result = self.parseCompare()
  235. test = self.getNonNumber(result, value)
  236. if test is None:
  237. value = "%d" % self.normNumber(int(value) & int(result))
  238. else:
  239. self.errExit ("'%s' is not a valid op number for AND" % test)
  240. else:
  241. break
  242. return value
  243. def parseOrXor(self):
  244. value = self.parseAnd()
  245. op = None
  246. while True:
  247. self.skipSpace()
  248. op = None
  249. if re.match('^XOR\W', self.getCurr(-1)):
  250. self.moveNext(3)
  251. op = '^'
  252. elif re.match('^OR\W', self.getCurr(-1)):
  253. self.moveNext(2)
  254. op = '|'
  255. else:
  256. break
  257. if op:
  258. result = self.parseAnd()
  259. test = self.getNonNumber(result, value)
  260. if test is None:
  261. value = "%d" % self.normNumber(eval (value + op + result))
  262. else:
  263. self.errExit ("'%s' is not a valid op number for XOR/OR" % test)
  264. return value
  265. def parseExpr(self):
  266. return self.parseOrXor()
  267. def getResult(self):
  268. value = self.parseExpr()
  269. self.skipSpace()
  270. if not self.isLast():
  271. self.errExit ("Unexpected character found '%s'" % self.getCurr())
  272. test = self.getNumber(value)
  273. if test is None:
  274. self.errExit ("Result '%s' is not a number" % value)
  275. return int(value)
  276. def evaluateExpress (self, Expr):
  277. self.index = 0
  278. self.string = Expr
  279. if self.getResult():
  280. Result = True
  281. else:
  282. Result = False
  283. return Result
  284. class CGenCfgOpt:
  285. def __init__(self):
  286. self.Debug = False
  287. self.Error = ''
  288. self._GlobalDataDef = """
  289. GlobalDataDef
  290. SKUID = 0, "DEFAULT"
  291. EndGlobalData
  292. """
  293. self._BuidinOptionTxt = """
  294. List &EN_DIS
  295. Selection 0x1 , "Enabled"
  296. Selection 0x0 , "Disabled"
  297. EndList
  298. """
  299. self._BsfKeyList = ['FIND','NAME','HELP','TYPE','PAGE','OPTION','ORDER']
  300. self._HdrKeyList = ['HEADER','STRUCT', 'EMBED']
  301. self._BuidinOption = {'$EN_DIS' : 'EN_DIS'}
  302. self._MacroDict = {}
  303. self._CfgBlkDict = {}
  304. self._CfgPageDict = {}
  305. self._CfgItemList = []
  306. self._DscFile = ''
  307. self._FvDir = ''
  308. self._MapVer = 0
  309. def ParseMacros (self, MacroDefStr):
  310. # ['-DABC=1', '-D', 'CFG_DEBUG=1', '-D', 'CFG_OUTDIR=Build']
  311. self._MacroDict = {}
  312. IsExpression = False
  313. for Macro in MacroDefStr:
  314. if Macro.startswith('-D'):
  315. IsExpression = True
  316. if len(Macro) > 2:
  317. Macro = Macro[2:]
  318. else :
  319. continue
  320. if IsExpression:
  321. IsExpression = False
  322. Match = re.match("(\w+)=(.+)", Macro)
  323. if Match:
  324. self._MacroDict[Match.group(1)] = Match.group(2)
  325. else:
  326. Match = re.match("(\w+)", Macro)
  327. if Match:
  328. self._MacroDict[Match.group(1)] = ''
  329. if len(self._MacroDict) == 0:
  330. Error = 1
  331. else:
  332. Error = 0
  333. if self.Debug:
  334. print "INFO : Macro dictionary:"
  335. for Each in self._MacroDict:
  336. print " $(%s) = [ %s ]" % (Each , self._MacroDict[Each])
  337. return Error
  338. def EvaulateIfdef (self, Macro):
  339. Result = Macro in self._MacroDict
  340. if self.Debug:
  341. print "INFO : Eval Ifdef [%s] : %s" % (Macro, Result)
  342. return Result
  343. def ExpandMacros (self, Input):
  344. Line = Input
  345. Match = re.findall("\$\(\w+\)", Input)
  346. if Match:
  347. for Each in Match:
  348. Variable = Each[2:-1]
  349. if Variable in self._MacroDict:
  350. Line = Line.replace(Each, self._MacroDict[Variable])
  351. else:
  352. if self.Debug:
  353. print "WARN : %s is not defined" % Each
  354. Line = Line.replace(Each, Each[2:-1])
  355. return Line
  356. def EvaluateExpress (self, Expr):
  357. ExpExpr = self.ExpandMacros(Expr)
  358. LogExpr = CLogicalExpression()
  359. Result = LogExpr.evaluateExpress (ExpExpr)
  360. if self.Debug:
  361. print "INFO : Eval Express [%s] : %s" % (Expr, Result)
  362. return Result
  363. def FormatListValue(self, ConfigDict):
  364. Struct = ConfigDict['struct']
  365. if Struct not in ['UINT8','UINT16','UINT32','UINT64']:
  366. return
  367. dataarray = []
  368. binlist = ConfigDict['value'][1:-1].split(',')
  369. for each in binlist:
  370. each = each.strip()
  371. if each.startswith('0x'):
  372. value = int(each, 16)
  373. else:
  374. value = int(each)
  375. dataarray.append(value)
  376. unit = int(Struct[4:]) / 8
  377. if int(ConfigDict['length']) != unit * len(dataarray):
  378. raise Exception("Array size is not proper for '%s' !" % ConfigDict['cname'])
  379. bytearray = []
  380. for each in dataarray:
  381. value = each
  382. for loop in xrange(unit):
  383. bytearray.append("0x%02X" % (value & 0xFF))
  384. value = value >> 8
  385. newvalue = '{' + ','.join(bytearray) + '}'
  386. ConfigDict['value'] = newvalue
  387. return ""
  388. def ParseDscFile (self, DscFile, FvDir):
  389. self._CfgItemList = []
  390. self._CfgPageDict = {}
  391. self._CfgBlkDict = {}
  392. self._DscFile = DscFile
  393. self._FvDir = FvDir
  394. IsDefSect = False
  395. IsUpdSect = False
  396. IsVpdSect = False
  397. Found = False
  398. IfStack = []
  399. ElifStack = []
  400. Error = 0
  401. ConfigDict = {}
  402. DscFd = open(DscFile, "r")
  403. DscLines = DscFd.readlines()
  404. DscFd.close()
  405. while len(DscLines):
  406. DscLine = DscLines.pop(0).strip()
  407. Handle = False
  408. Match = re.match("^\[(.+)\]", DscLine)
  409. if Match is not None:
  410. if Match.group(1).lower() == "Defines".lower():
  411. IsDefSect = True
  412. IsVpdSect = False
  413. IsUpdSect = False
  414. elif Match.group(1).lower() == "PcdsDynamicVpd".lower():
  415. ConfigDict = {}
  416. ConfigDict['header'] = 'ON'
  417. ConfigDict['region'] = 'VPD'
  418. ConfigDict['order'] = -1
  419. ConfigDict['page'] = ''
  420. ConfigDict['name'] = ''
  421. ConfigDict['find'] = ''
  422. ConfigDict['struct'] = ''
  423. ConfigDict['embed'] = ''
  424. ConfigDict['subreg'] = []
  425. IsDefSect = False
  426. IsVpdSect = True
  427. IsUpdSect = False
  428. elif Match.group(1).lower() == "PcdsDynamicVpd.Upd".lower():
  429. ConfigDict = {}
  430. ConfigDict['header'] = 'ON'
  431. ConfigDict['region'] = 'UPD'
  432. ConfigDict['order'] = -1
  433. ConfigDict['page'] = ''
  434. ConfigDict['name'] = ''
  435. ConfigDict['find'] = ''
  436. ConfigDict['struct'] = ''
  437. ConfigDict['embed'] = ''
  438. ConfigDict['subreg'] = []
  439. IsDefSect = False
  440. IsUpdSect = True
  441. IsVpdSect = False
  442. Found = True
  443. else:
  444. IsDefSect = False
  445. IsUpdSect = False
  446. IsVpdSect = False
  447. else:
  448. if IsDefSect or IsUpdSect or IsVpdSect:
  449. if re.match("^!else($|\s+#.+)", DscLine):
  450. if IfStack:
  451. IfStack[-1] = not IfStack[-1]
  452. else:
  453. print("ERROR: No paired '!if' found for '!else' for line '%s'" % DscLine)
  454. raise SystemExit
  455. elif re.match("^!endif($|\s+#.+)", DscLine):
  456. if IfStack:
  457. IfStack.pop()
  458. Level = ElifStack.pop()
  459. if Level > 0:
  460. del IfStack[-Level:]
  461. else:
  462. print("ERROR: No paired '!if' found for '!endif' for line '%s'" % DscLine)
  463. raise SystemExit
  464. else:
  465. Result = False
  466. Match = re.match("!(ifdef|ifndef)\s+(.+)", DscLine)
  467. if Match:
  468. Result = self.EvaulateIfdef (Match.group(2))
  469. if Match.group(1) == 'ifndef':
  470. Result = not Result
  471. IfStack.append(Result)
  472. ElifStack.append(0)
  473. else:
  474. Match = re.match("!(if|elseif)\s+(.+)", DscLine)
  475. if Match:
  476. Result = self.EvaluateExpress(Match.group(2))
  477. if Match.group(1) == "if":
  478. ElifStack.append(0)
  479. IfStack.append(Result)
  480. else: #elseif
  481. if IfStack:
  482. IfStack[-1] = not IfStack[-1]
  483. IfStack.append(Result)
  484. ElifStack[-1] = ElifStack[-1] + 1
  485. else:
  486. print("ERROR: No paired '!if' found for '!elif' for line '%s'" % DscLine)
  487. raise SystemExit
  488. else:
  489. if IfStack:
  490. Handle = reduce(lambda x,y: x and y, IfStack)
  491. else:
  492. Handle = True
  493. if Handle:
  494. Match = re.match("!include\s+(.+)", DscLine)
  495. if Match:
  496. IncludeFilePath = Match.group(1)
  497. IncludeFilePath = self.ExpandMacros(IncludeFilePath)
  498. try:
  499. IncludeDsc = open(IncludeFilePath, "r")
  500. except:
  501. print("ERROR: Cannot open file '%s'" % IncludeFilePath)
  502. raise SystemExit
  503. NewDscLines = IncludeDsc.readlines()
  504. IncludeDsc.close()
  505. DscLines = NewDscLines + DscLines
  506. else:
  507. if DscLine.startswith('!'):
  508. print("ERROR: Unrecoginized directive for line '%s'" % DscLine)
  509. raise SystemExit
  510. if not Handle:
  511. continue
  512. if IsDefSect:
  513. #DEFINE UPD_TOOL_GUID = 8C3D856A-9BE6-468E-850A-24F7A8D38E09
  514. Match = re.match("^\s*(?:DEFINE\s+)*(\w+)\s*=\s*([-.\w]+)", DscLine)
  515. if Match:
  516. self._MacroDict[Match.group(1)] = Match.group(2)
  517. if self.Debug:
  518. print "INFO : DEFINE %s = [ %s ]" % (Match.group(1), Match.group(2))
  519. else:
  520. Match = re.match("^\s*#\s+!(BSF|HDR)\s+(.+)", DscLine)
  521. if Match:
  522. Remaining = Match.group(2)
  523. if Match.group(1) == 'BSF':
  524. Match = re.match("(?:^|.+\s+)PAGES:{(.+?)}", Remaining)
  525. if Match:
  526. # !BSF PAGES:{HSW:"Haswell System Agent", LPT:"Lynx Point PCH"}
  527. PageList = Match.group(1).split(',')
  528. for Page in PageList:
  529. Page = Page.strip()
  530. Match = re.match("(\w+):\"(.+)\"", Page)
  531. self._CfgPageDict[Match.group(1)] = Match.group(2)
  532. Match = re.match("(?:^|.+\s+)BLOCK:{NAME:\"(.+)\"\s*,\s*VER:\"(.+)\"\s*}", Remaining)
  533. if Match:
  534. self._CfgBlkDict['name'] = Match.group(1)
  535. self._CfgBlkDict['ver'] = Match.group(2)
  536. for Key in self._BsfKeyList:
  537. Match = re.match("(?:^|.+\s+)%s:{(.+?)}" % Key, Remaining)
  538. if Match:
  539. if Key in ['NAME', 'HELP', 'OPTION'] and Match.group(1).startswith('+'):
  540. ConfigDict[Key.lower()] += Match.group(1)[1:]
  541. else:
  542. ConfigDict[Key.lower()] = Match.group(1)
  543. else:
  544. for Key in self._HdrKeyList:
  545. Match = re.match("(?:^|.+\s+)%s:{(.+?)}" % Key, Remaining)
  546. if Match:
  547. ConfigDict[Key.lower()] = Match.group(1)
  548. # Check VPD/UPD
  549. if IsUpdSect:
  550. 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)
  551. else:
  552. Match = re.match("^([_a-zA-Z0-9]+).([_a-zA-Z0-9]+)\s*\|\s*(0x[0-9A-F]+)(?:\s*\|\s*(.+))?", DscLine)
  553. if Match:
  554. ConfigDict['space'] = Match.group(1)
  555. ConfigDict['cname'] = Match.group(2)
  556. ConfigDict['offset'] = int (Match.group(3), 16)
  557. if ConfigDict['order'] == -1:
  558. ConfigDict['order'] = ConfigDict['offset'] << 8
  559. else:
  560. (Major, Minor) = ConfigDict['order'].split('.')
  561. ConfigDict['order'] = (int (Major, 16) << 8 ) + int (Minor, 16)
  562. if IsUpdSect:
  563. Value = Match.group(5).strip()
  564. if Match.group(4).startswith("0x"):
  565. Length = int (Match.group(4), 16)
  566. else :
  567. Length = int (Match.group(4))
  568. else:
  569. Value = Match.group(4)
  570. if Value is None:
  571. Value = ''
  572. Value = Value.strip()
  573. if '|' in Value:
  574. Match = re.match("^.+\s*\|\s*(.+)", Value)
  575. if Match:
  576. Value = Match.group(1)
  577. Length = -1
  578. ConfigDict['length'] = Length
  579. Match = re.match("\$\((\w+)\)", Value)
  580. if Match:
  581. if Match.group(1) in self._MacroDict:
  582. Value = self._MacroDict[Match.group(1)]
  583. ConfigDict['value'] = Value
  584. if (len(Value) > 0) and (Value[0] == '{'):
  585. Value = self.FormatListValue(ConfigDict)
  586. if ConfigDict['name'] == '':
  587. # Clear BSF specific items
  588. ConfigDict['bsfname'] = ''
  589. ConfigDict['help'] = ''
  590. ConfigDict['type'] = ''
  591. ConfigDict['option'] = ''
  592. self._CfgItemList.append(ConfigDict.copy())
  593. ConfigDict['name'] = ''
  594. ConfigDict['find'] = ''
  595. ConfigDict['struct'] = ''
  596. ConfigDict['embed'] = ''
  597. ConfigDict['order'] = -1
  598. ConfigDict['subreg'] = []
  599. else:
  600. # It could be a virtual item as below
  601. # !BSF FIELD:{1:SerialDebugPortAddress0}
  602. Match = re.match("^\s*#\s+!BSF\s+FIELD:{(.+):(\d+)}", DscLine)
  603. if Match:
  604. SubCfgDict = ConfigDict
  605. SubCfgDict['cname'] = Match.group(1)
  606. SubCfgDict['length'] = int (Match.group(2))
  607. if SubCfgDict['length'] > 0:
  608. LastItem = self._CfgItemList[-1]
  609. if len(LastItem['subreg']) == 0:
  610. SubOffset = 0
  611. else:
  612. SubOffset += LastItem['subreg'][-1]['length']
  613. SubCfgDict['offset'] = SubOffset
  614. LastItem['subreg'].append (SubCfgDict.copy())
  615. ConfigDict['name'] = ''
  616. return Error
  617. def UpdateSubRegionDefaultValue (self):
  618. Error = 0
  619. for Item in self._CfgItemList:
  620. if len(Item['subreg']) == 0:
  621. continue
  622. bytearray = []
  623. if Item['value'][0] == '{':
  624. binlist = Item['value'][1:-1].split(',')
  625. for each in binlist:
  626. each = each.strip()
  627. if each.startswith('0x'):
  628. value = int(each, 16)
  629. else:
  630. value = int(each)
  631. bytearray.append(value)
  632. else:
  633. if Item['value'].startswith('0x'):
  634. value = int(Item['value'], 16)
  635. else:
  636. value = int(Item['value'])
  637. idx = 0;
  638. while idx < Item['length']:
  639. bytearray.append(value & 0xFF)
  640. value = value >> 8
  641. idx = idx + 1
  642. for SubItem in Item['subreg']:
  643. if SubItem['length'] in (1,2,4,8):
  644. valuelist = [b for b in bytearray[SubItem['offset']:SubItem['offset']+SubItem['length']]]
  645. valuelist.reverse()
  646. valuestr = "".join('%02X' % b for b in valuelist)
  647. SubItem['value'] = '0x%s' % valuestr
  648. else:
  649. valuestr = ",".join('0x%02X' % b for b in bytearray[SubItem['offset']:SubItem['offset']+SubItem['length']])
  650. SubItem['value'] = '{%s}' % valuestr
  651. return Error
  652. def UpdateVpdSizeField (self):
  653. FvDir = self._FvDir;
  654. if 'VPD_TOOL_GUID' not in self._MacroDict:
  655. self.Error = "VPD_TOOL_GUID definition is missing in DSC file"
  656. return 1
  657. VpdMapFile = os.path.join(FvDir, self._MacroDict['VPD_TOOL_GUID'] + '.map')
  658. if not os.path.exists(VpdMapFile):
  659. self.Error = "VPD MAP file '%s' does not exist" % VpdMapFile
  660. return 2
  661. MapFd = open(VpdMapFile, "r")
  662. MapLines = MapFd.readlines()
  663. MapFd.close()
  664. VpdDict = {}
  665. PcdDict = {}
  666. for MapLine in MapLines:
  667. #gPlatformFspPkgTokenSpaceGuid.PcdVpdRegionSign | DEFAULT | 0x0000 | 8 | 0x534450565F425346
  668. #gPlatformFspPkgTokenSpaceGuid.PcdVpdRegionSign | 0x0000 | 8 | 0x534450565F425346
  669. #gPlatformFspPkgTokenSpaceGuid.PcdTest | 0x0008 | 5 | {0x01,0x02,0x03,0x04,0x05}
  670. Match = re.match("([_a-zA-Z0-9]+).([_a-zA-Z0-9]+)(\s\|\sDEFAULT)?\s\|\s(0x[0-9A-F]{4})\s\|\s(\d+|0x[0-9a-fA-F]+)\s\|\s(\{?[x0-9a-fA-F,\s]+\}?)", MapLine)
  671. if Match:
  672. Space = Match.group(1)
  673. Name = Match.group(2)
  674. if (self._MapVer == 0) and (Match.group(3) != None):
  675. self._MapVer = 1
  676. Offset = int (Match.group(4), 16)
  677. if Match.group(5).startswith("0x"):
  678. Length = int (Match.group(5), 16)
  679. else :
  680. Length = int (Match.group(5))
  681. PcdDict["len"] = Length
  682. PcdDict["value"] = Match.group(6)
  683. VpdDict[Space+'.'+Name] = dict(PcdDict)
  684. for Item in self._CfgItemList:
  685. if Item['value'] == '':
  686. Item['value'] = VpdDict[Item['space']+'.'+Item['cname']]['value']
  687. if Item['length'] == -1:
  688. Item['length'] = VpdDict[Item['space']+'.'+Item['cname']]['len']
  689. if Item['struct'] != '':
  690. Type = Item['struct'].strip()
  691. if Type.endswith('*') and (Item['length'] != 4):
  692. self.Error = "Struct pointer '%s' has invalid size" % Type
  693. return 3
  694. return 0
  695. def CreateUpdTxtFile (self, UpdTxtFile):
  696. FvDir = self._FvDir
  697. if 'UPD_TOOL_GUID' not in self._MacroDict:
  698. self.Error = "UPD_TOOL_GUID definition is missing in DSC file"
  699. return 1
  700. if UpdTxtFile == '':
  701. UpdTxtFile = os.path.join(FvDir, self._MacroDict['UPD_TOOL_GUID'] + '.txt')
  702. ReCreate = False
  703. if not os.path.exists(UpdTxtFile):
  704. ReCreate = True
  705. else:
  706. DscTime = os.path.getmtime(self._DscFile)
  707. TxtTime = os.path.getmtime(UpdTxtFile)
  708. if DscTime > TxtTime:
  709. ReCreate = True
  710. if not ReCreate:
  711. # DSC has not been modified yet
  712. # So don't have to re-generate other files
  713. self.Error = 'No DSC file change, skip to create UPD TXT file'
  714. return 256
  715. TxtFd = open(UpdTxtFile, "w")
  716. TxtFd.write("%s\n" % (__copyright_txt__ % date.today().year))
  717. NextOffset = 0
  718. SpaceIdx = 0
  719. if self._MapVer == 1:
  720. Default = 'DEFAULT|'
  721. else:
  722. Default = ''
  723. for Item in self._CfgItemList:
  724. if Item['region'] != 'UPD':
  725. continue
  726. Offset = Item['offset']
  727. if NextOffset < Offset:
  728. # insert one line
  729. TxtFd.write("%s.UnusedUpdSpace%d|%s0x%04X|0x%04X|{0}\n" % (Item['space'], SpaceIdx, Default, NextOffset, Offset - NextOffset))
  730. SpaceIdx = SpaceIdx + 1
  731. NextOffset = Offset + Item['length']
  732. TxtFd.write("%s.%s|%s0x%04X|%s|%s\n" % (Item['space'],Item['cname'],Default,Item['offset'],Item['length'],Item['value']))
  733. TxtFd.close()
  734. return 0
  735. def CreateField (self, Item, Name, Length, Offset, Struct, BsfName, Help):
  736. PosName = 28
  737. PosComment = 30
  738. NameLine=''
  739. HelpLine=''
  740. IsArray = False
  741. if Length in [1,2,4,8]:
  742. Type = "UINT%d" % (Length * 8)
  743. else:
  744. IsArray = True
  745. Type = "UINT8"
  746. if Item and Item['value'].startswith('{'):
  747. Type = "UINT8"
  748. IsArray = True
  749. if Struct != '':
  750. Type = Struct
  751. if Struct in ['UINT8','UINT16','UINT32','UINT64']:
  752. IsArray = True
  753. Unit = int(Type[4:]) / 8
  754. Length = Length / Unit
  755. else:
  756. IsArray = False
  757. if IsArray:
  758. Name = Name + '[%d]' % Length
  759. if len(Type) < PosName:
  760. Space1 = PosName - len(Type)
  761. else:
  762. Space1 = 1
  763. if BsfName != '':
  764. NameLine=" %s\n" % BsfName
  765. if Help != '':
  766. HelpLine=" %s\n" % Help
  767. if Offset is None:
  768. OffsetStr = '????'
  769. else:
  770. OffsetStr = '0x%04X' % Offset
  771. return "/** Offset %s\n%s%s**/\n %s%s%s;\n" % (OffsetStr, NameLine, HelpLine, Type, ' ' * Space1, Name,)
  772. def PostProcessBody (self, TextBody):
  773. NewTextBody = []
  774. OldTextBody = []
  775. IncludeLine = False
  776. StructName = ''
  777. VariableName = ''
  778. for Line in TextBody:
  779. Match = re.match("^/\*\sEMBED_STRUCT:(\w+):(\w+):(START|END)\s\*/\s([\s\S]*)", Line)
  780. if Match:
  781. Line = Match.group(4)
  782. if Match and Match.group(3) == 'START':
  783. NewTextBody.append ('typedef struct {\n')
  784. StructName = Match.group(1)
  785. VariableName = Match.group(2)
  786. MatchOffset = re.search('/\*\*\sOffset\s0x([a-fA-F0-9]+)', Line)
  787. if MatchOffset:
  788. Offset = int(MatchOffset.group(1), 16)
  789. else:
  790. Offset = None
  791. Line
  792. IncludeLine = True
  793. OldTextBody.append (self.CreateField (None, VariableName, 0, Offset, StructName, '', ''))
  794. if IncludeLine:
  795. NewTextBody.append (Line)
  796. else:
  797. OldTextBody.append (Line)
  798. if Match and Match.group(3) == 'END':
  799. if (StructName != Match.group(1)) or (VariableName != Match.group(2)):
  800. print "Unmatched struct name '%s' and '%s' !" % (StructName, Match.group(1))
  801. else:
  802. NewTextBody.append ('} %s;\n\n' % StructName)
  803. IncludeLine = False
  804. NewTextBody.extend(OldTextBody)
  805. return NewTextBody
  806. def CreateHeaderFile (self, InputHeaderFile, IsInternal):
  807. FvDir = self._FvDir
  808. if IsInternal:
  809. HeaderFile = os.path.join(FvDir, 'FspUpdVpdInternal.h')
  810. else:
  811. HeaderFile = os.path.join(FvDir, 'FspUpdVpd.h')
  812. # Check if header needs to be recreated
  813. ReCreate = False
  814. if IsInternal:
  815. if not os.path.exists(HeaderFile):
  816. ReCreate = True
  817. else:
  818. DscTime = os.path.getmtime(self._DscFile)
  819. HeadTime = os.path.getmtime(HeaderFile)
  820. if not os.path.exists(InputHeaderFile):
  821. InpTime = HeadTime
  822. else:
  823. InpTime = os.path.getmtime(InputHeaderFile)
  824. if DscTime > HeadTime or InpTime > HeadTime:
  825. ReCreate = True
  826. if not ReCreate:
  827. self.Error = "No DSC or input header file is changed, skip the header file generating"
  828. return 256
  829. TxtBody = []
  830. for Item in self._CfgItemList:
  831. if str(Item['cname']) == 'Signature' and Item['length'] == 8:
  832. Value = int(Item['value'], 16)
  833. Chars = []
  834. while Value != 0x0:
  835. Chars.append(chr(Value & 0xFF))
  836. Value = Value >> 8
  837. SignatureStr = ''.join(Chars)
  838. if int(Item['offset']) == 0:
  839. TxtBody.append("#define FSP_UPD_SIGNATURE %s /* '%s' */\n" % (Item['value'], SignatureStr))
  840. elif 'MEM' in SignatureStr:
  841. TxtBody.append("#define FSP_MEMORY_INIT_UPD_SIGNATURE %s /* '%s' */\n" % (Item['value'], SignatureStr))
  842. else:
  843. TxtBody.append("#define FSP_SILICON_INIT_UPD_SIGNATURE %s /* '%s' */\n" % (Item['value'], SignatureStr))
  844. TxtBody.append("\n")
  845. for Region in ['UPD', 'VPD']:
  846. # Write PcdVpdRegionSign and PcdImageRevision
  847. if Region[0] == 'V':
  848. if 'VPD_TOOL_GUID' not in self._MacroDict:
  849. self.Error = "VPD_TOOL_GUID definition is missing in DSC file"
  850. return 1
  851. BinFile = os.path.join(FvDir, self._MacroDict['VPD_TOOL_GUID'] + ".bin")
  852. if not os.path.exists(BinFile):
  853. self.Error = "VPD binary file '%s' does not exist" % BinFile
  854. return 2
  855. BinFd = open(BinFile, "rb")
  856. IdStr = BinFd.read(0x08)
  857. ImageId = struct.unpack('<Q', IdStr)
  858. ImageRev = struct.unpack('<I', BinFd.read(0x04))
  859. BinFd.close()
  860. TxtBody.append("#define FSP_IMAGE_ID 0x%016X /* '%s' */\n" % (ImageId[0], IdStr))
  861. TxtBody.append("#define FSP_IMAGE_REV 0x%08X \n\n" % ImageRev[0])
  862. TxtBody.append("typedef struct _" + Region[0] + "PD_DATA_REGION {\n")
  863. NextOffset = 0
  864. SpaceIdx = 0
  865. Offset = 0
  866. LastVisible = True
  867. ResvOffset = 0
  868. ResvIdx = 0
  869. LineBuffer = []
  870. for Item in self._CfgItemList:
  871. if Item['region'] != Region:
  872. continue
  873. NextVisible = LastVisible
  874. if not IsInternal:
  875. if LastVisible and (Item['header'] == 'OFF'):
  876. NextVisible = False
  877. ResvOffset = Item['offset']
  878. elif (not LastVisible) and Item['header'] == 'ON':
  879. NextVisible = True
  880. Name = "Reserved" + Region[0] + "pdSpace%d" % ResvIdx
  881. ResvIdx = ResvIdx + 1
  882. TxtBody.append(self.CreateField (Item, Name, Item["offset"] - ResvOffset, ResvOffset, '', '', ''))
  883. if Offset < Item["offset"]:
  884. if IsInternal or LastVisible:
  885. Name = "Unused" + Region[0] + "pdSpace%d" % SpaceIdx
  886. LineBuffer.append(self.CreateField (Item, Name, Item["offset"] - Offset, Offset, '', '', ''))
  887. SpaceIdx = SpaceIdx + 1
  888. Offset = Item["offset"]
  889. if Offset != Item["offset"]:
  890. self.Error = "Unsorted offset 0x%04X\n" % Item["offset"]
  891. return 3
  892. LastVisible = NextVisible
  893. Offset = Offset + Item["length"]
  894. if IsInternal or LastVisible:
  895. for Each in LineBuffer:
  896. TxtBody.append (Each)
  897. LineBuffer = []
  898. Embed = Item["embed"].upper()
  899. if Embed.endswith(':START') or Embed.endswith(':END'):
  900. Marker = '/* EMBED_STRUCT:%s */ ' % Item["embed"]
  901. else:
  902. if Embed == '':
  903. Marker = '';
  904. else:
  905. self.Error = "Invalid embedded structure format '%s'!\n" % Item["embed"]
  906. return 4
  907. Line = Marker + self.CreateField (Item, Item["cname"], Item["length"], Item["offset"], Item['struct'], Item['name'], Item['help'])
  908. TxtBody.append(Line)
  909. TxtBody.append("} " + Region[0] + "PD_DATA_REGION;\n\n")
  910. # Handle the embedded data structure
  911. TxtBody = self.PostProcessBody (TxtBody)
  912. HeaderFd = open(HeaderFile, "w")
  913. FileBase = os.path.basename(HeaderFile)
  914. FileName = FileBase.replace(".", "_").upper()
  915. HeaderFd.write("%s\n" % (__copyright_h__ % date.today().year))
  916. HeaderFd.write("#ifndef __%s__\n" % FileName)
  917. HeaderFd.write("#define __%s__\n\n" % FileName)
  918. HeaderFd.write("#pragma pack(1)\n\n")
  919. if InputHeaderFile != '':
  920. if not os.path.exists(InputHeaderFile):
  921. self.Error = "Input header file '%s' does not exist" % InputHeaderFile
  922. return 6
  923. InFd = open(InputHeaderFile, "r")
  924. IncLines = InFd.readlines()
  925. InFd.close()
  926. Export = False
  927. for Line in IncLines:
  928. Match = re.search ("!EXPORT\s+EXTERNAL_BOOTLOADER_STRUCT_(BEGIN|END)\s+", Line)
  929. if Match:
  930. if Match.group(1) == "BEGIN":
  931. Export = True
  932. continue
  933. else:
  934. Export = False
  935. continue
  936. if Export:
  937. HeaderFd.write(Line)
  938. HeaderFd.write("\n\n")
  939. for Line in TxtBody:
  940. HeaderFd.write (Line)
  941. HeaderFd.write("#pragma pack()\n\n")
  942. HeaderFd.write("#endif\n")
  943. HeaderFd.close()
  944. return 0
  945. def WriteBsfStruct (self, BsfFd, Item):
  946. if Item['type'] == "None":
  947. Space = "gPlatformFspPkgTokenSpaceGuid"
  948. else:
  949. Space = Item['space']
  950. Line = " $%s_%s" % (Space, Item['cname'])
  951. Match = re.match("\s*\{([x0-9a-fA-F,\s]+)\}\s*", Item['value'])
  952. if Match:
  953. DefaultValue = Match.group(1).strip()
  954. else:
  955. DefaultValue = Item['value'].strip()
  956. BsfFd.write(" %s%s%4d bytes $_DEFAULT_ = %s\n" % (Line, ' ' * (64 - len(Line)), Item['length'], DefaultValue))
  957. TmpList = []
  958. if Item['type'] == "Combo":
  959. if not Item['option'] in self._BuidinOption:
  960. OptList = Item['option'].split(',')
  961. for Option in OptList:
  962. Option = Option.strip()
  963. (OpVal, OpStr) = Option.split(':')
  964. TmpList.append((OpVal, OpStr))
  965. return TmpList
  966. def WriteBsfOption (self, BsfFd, Item):
  967. PcdName = Item['space'] + '_' + Item['cname']
  968. WriteHelp = 0
  969. if Item['type'] == "Combo":
  970. if Item['option'] in self._BuidinOption:
  971. Options = self._BuidinOption[Item['option']]
  972. else:
  973. Options = PcdName
  974. BsfFd.write(' %s $%s, "%s", &%s,\n' % (Item['type'], PcdName, Item['name'], Options));
  975. WriteHelp = 1
  976. elif Item['type'].startswith("EditNum"):
  977. 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'])
  978. if Match:
  979. BsfFd.write(' EditNum $%s, "%s", %s,\n' % (PcdName, Item['name'], Match.group(1)));
  980. WriteHelp = 2
  981. elif Item['type'].startswith("EditText"):
  982. BsfFd.write(' %s $%s, "%s",\n' % (Item['type'], PcdName, Item['name']));
  983. WriteHelp = 1
  984. elif Item['type'] == "Table":
  985. Columns = Item['option'].split(',')
  986. if len(Columns) != 0:
  987. BsfFd.write(' %s $%s "%s",' % (Item['type'], PcdName, Item['name']));
  988. for Col in Columns:
  989. Fmt = Col.split(':')
  990. if len(Fmt) != 3:
  991. raise Exception("Column format '%s' is invalid !" % Fmt)
  992. try:
  993. Dtype = int(Fmt[1].strip())
  994. except:
  995. raise Exception("Column size '%s' is invalid !" % Fmt[1])
  996. BsfFd.write('\n Column "%s", %d bytes, %s' % (Fmt[0].strip(), Dtype, Fmt[2].strip()))
  997. BsfFd.write(',\n')
  998. WriteHelp = 1
  999. if WriteHelp > 0:
  1000. HelpLines = Item['help'].split('\\n\\r')
  1001. FirstLine = True
  1002. for HelpLine in HelpLines:
  1003. if FirstLine:
  1004. FirstLine = False
  1005. BsfFd.write(' Help "%s"\n' % (HelpLine));
  1006. else:
  1007. BsfFd.write(' "%s"\n' % (HelpLine));
  1008. if WriteHelp == 2:
  1009. BsfFd.write(' "Valid range: %s ~ %s"\n' % (Match.group(2), Match.group(3)));
  1010. def GenerateBsfFile (self, BsfFile):
  1011. if BsfFile == '':
  1012. self.Error = "BSF output file '%s' is invalid" % BsfFile
  1013. return 1
  1014. Error = 0
  1015. OptionDict = {}
  1016. BsfFd = open(BsfFile, "w")
  1017. BsfFd.write("%s\n" % (__copyright_bsf__ % date.today().year))
  1018. BsfFd.write("%s\n" % self._GlobalDataDef);
  1019. BsfFd.write("StructDef\n")
  1020. NextOffset = -1
  1021. for Item in self._CfgItemList:
  1022. if Item['find'] != '':
  1023. BsfFd.write('\n Find "%s"\n' % Item['find'])
  1024. NextOffset = Item['offset'] + Item['length']
  1025. if Item['name'] != '':
  1026. if NextOffset != Item['offset']:
  1027. BsfFd.write(" Skip %d bytes\n" % (Item['offset'] - NextOffset))
  1028. if len(Item['subreg']) > 0:
  1029. NextOffset = Item['offset']
  1030. for SubItem in Item['subreg']:
  1031. NextOffset += SubItem['length']
  1032. if SubItem['name'] == '':
  1033. BsfFd.write(" Skip %d bytes\n" % (SubItem['length']))
  1034. else:
  1035. Options = self.WriteBsfStruct(BsfFd, SubItem)
  1036. if len(Options) > 0:
  1037. OptionDict[SubItem['space']+'_'+SubItem['cname']] = Options
  1038. if (Item['offset'] + Item['length']) < NextOffset:
  1039. self.Error = "BSF sub region '%s' length does not match" % (Item['space']+'.'+Item['cname'])
  1040. return 2
  1041. else:
  1042. NextOffset = Item['offset'] + Item['length']
  1043. Options = self.WriteBsfStruct(BsfFd, Item)
  1044. if len(Options) > 0:
  1045. OptionDict[Item['space']+'_'+Item['cname']] = Options
  1046. BsfFd.write("\nEndStruct\n\n")
  1047. BsfFd.write("%s" % self._BuidinOptionTxt);
  1048. for Each in OptionDict:
  1049. BsfFd.write("List &%s\n" % Each);
  1050. for Item in OptionDict[Each]:
  1051. BsfFd.write(' Selection %s , "%s"\n' % (Item[0], Item[1]));
  1052. BsfFd.write("EndList\n\n");
  1053. BsfFd.write("BeginInfoBlock\n");
  1054. BsfFd.write(' PPVer "%s"\n' % (self._CfgBlkDict['ver']));
  1055. BsfFd.write(' Description "%s"\n' % (self._CfgBlkDict['name']));
  1056. BsfFd.write("EndInfoBlock\n\n");
  1057. for Each in self._CfgPageDict:
  1058. BsfFd.write('Page "%s"\n' % self._CfgPageDict[Each]);
  1059. BsfItems = []
  1060. for Item in self._CfgItemList:
  1061. if Item['name'] != '':
  1062. if Item['page'] != Each:
  1063. continue
  1064. if len(Item['subreg']) > 0:
  1065. for SubItem in Item['subreg']:
  1066. if SubItem['name'] != '':
  1067. BsfItems.append(SubItem)
  1068. else:
  1069. BsfItems.append(Item)
  1070. BsfItems.sort(key=lambda x: x['order'])
  1071. for Item in BsfItems:
  1072. self.WriteBsfOption (BsfFd, Item)
  1073. BsfFd.write("EndPage\n\n");
  1074. BsfFd.close()
  1075. return Error
  1076. def Usage():
  1077. print "GenCfgOpt Version 0.50"
  1078. print "Usage:"
  1079. print " GenCfgOpt UPDTXT PlatformDscFile BuildFvDir [TxtOutFile] [-D Macros]"
  1080. print " GenCfgOpt HEADER PlatformDscFile BuildFvDir [InputHFile] [-D Macros]"
  1081. print " GenCfgOpt GENBSF PlatformDscFile BuildFvDir BsfOutFile [-D Macros]"
  1082. def Main():
  1083. #
  1084. # Parse the options and args
  1085. #
  1086. GenCfgOpt = CGenCfgOpt()
  1087. argc = len(sys.argv)
  1088. if argc < 4:
  1089. Usage()
  1090. return 1
  1091. else:
  1092. DscFile = sys.argv[2]
  1093. if not os.path.exists(DscFile):
  1094. print "ERROR: Cannot open DSC file '%s' !" % DscFile
  1095. return 2
  1096. UpdateMemSiUpdInitOffsetValue(DscFile)
  1097. OutFile = ''
  1098. if argc > 4:
  1099. if sys.argv[4][0] == '-':
  1100. Start = 4
  1101. else:
  1102. OutFile = sys.argv[4]
  1103. Start = 5
  1104. if GenCfgOpt.ParseMacros(sys.argv[Start:]) != 0:
  1105. print "ERROR: Macro parsing failed !"
  1106. return 3
  1107. FvDir = sys.argv[3]
  1108. if not os.path.isdir(FvDir):
  1109. print "ERROR: FV folder '%s' is invalid !" % FvDir
  1110. return 4
  1111. if GenCfgOpt.ParseDscFile(DscFile, FvDir) != 0:
  1112. print "ERROR: %s !" % GenCfgOpt.Error
  1113. return 5
  1114. if GenCfgOpt.UpdateVpdSizeField() != 0:
  1115. print "ERROR: %s !" % GenCfgOpt.Error
  1116. return 6
  1117. if GenCfgOpt.UpdateSubRegionDefaultValue() != 0:
  1118. print "ERROR: %s !" % GenCfgOpt.Error
  1119. return 7
  1120. if sys.argv[1] == "UPDTXT":
  1121. Ret = GenCfgOpt.CreateUpdTxtFile(OutFile)
  1122. if Ret != 0:
  1123. # No change is detected
  1124. if Ret == 256:
  1125. print "INFO: %s !" % (GenCfgOpt.Error)
  1126. else :
  1127. print "ERROR: %s !" % (GenCfgOpt.Error)
  1128. return Ret
  1129. elif sys.argv[1] == "HEADER":
  1130. Ret = GenCfgOpt.CreateHeaderFile(OutFile, True)
  1131. if Ret != 0:
  1132. # No change is detected
  1133. if Ret == 256:
  1134. print "INFO: %s !" % (GenCfgOpt.Error)
  1135. else :
  1136. print "ERROR: %s !" % (GenCfgOpt.Error)
  1137. return Ret
  1138. if GenCfgOpt.CreateHeaderFile(OutFile, False) != 0:
  1139. print "ERROR: %s !" % GenCfgOpt.Error
  1140. return 8
  1141. elif sys.argv[1] == "GENBSF":
  1142. if GenCfgOpt.GenerateBsfFile(OutFile) != 0:
  1143. print "ERROR: %s !" % GenCfgOpt.Error
  1144. return 9
  1145. else:
  1146. if argc < 5:
  1147. Usage()
  1148. return 1
  1149. print "ERROR: Unknown command '%s' !" % sys.argv[1]
  1150. Usage()
  1151. return 1
  1152. return 0
  1153. return 0
  1154. if __name__ == '__main__':
  1155. sys.exit(Main())