PatchFv.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. ## @ PatchFv.py
  2. #
  3. # Copyright (c) 2014 - 2021, 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. #
  11. # Read data from file
  12. #
  13. # param [in] binfile Binary file
  14. # param [in] offset Offset
  15. # param [in] len Length
  16. #
  17. # retval value Value
  18. #
  19. def readDataFromFile (binfile, offset, len=1):
  20. fd = open(binfile, "r+b")
  21. fsize = os.path.getsize(binfile)
  22. offval = offset & 0xFFFFFFFF
  23. if (offval & 0x80000000):
  24. offval = fsize - (0xFFFFFFFF - offval + 1)
  25. fd.seek(offval)
  26. if sys.version_info[0] < 3:
  27. bytearray = [ord(b) for b in fd.read(len)]
  28. else:
  29. bytearray = [b for b in fd.read(len)]
  30. value = 0
  31. idx = len - 1
  32. while idx >= 0:
  33. value = value << 8 | bytearray[idx]
  34. idx = idx - 1
  35. fd.close()
  36. return value
  37. #
  38. # Check FSP header is valid or not
  39. #
  40. # param [in] binfile Binary file
  41. #
  42. # retval boolean True: valid; False: invalid
  43. #
  44. def IsFspHeaderValid (binfile):
  45. fd = open (binfile, "rb")
  46. bindat = fd.read(0x200) # only read first 0x200 bytes
  47. fd.close()
  48. HeaderList = [b'FSPH' , b'FSPP' , b'FSPE'] # Check 'FSPH', 'FSPP', and 'FSPE' in the FSP header
  49. OffsetList = []
  50. for each in HeaderList:
  51. if each in bindat:
  52. idx = bindat.index(each)
  53. else:
  54. idx = 0
  55. OffsetList.append(idx)
  56. if not OffsetList[0] or not OffsetList[1]: # If 'FSPH' or 'FSPP' is missing, it will return false
  57. return False
  58. if sys.version_info[0] < 3:
  59. Revision = ord(bindat[OffsetList[0] + 0x0B])
  60. else:
  61. Revision = bindat[OffsetList[0] + 0x0B]
  62. #
  63. # if revision is bigger than 1, it means it is FSP v1.1 or greater revision, which must contain 'FSPE'.
  64. #
  65. if Revision > 1 and not OffsetList[2]:
  66. return False # If FSP v1.1 or greater without 'FSPE', then return false
  67. return True
  68. #
  69. # Patch data in file
  70. #
  71. # param [in] binfile Binary file
  72. # param [in] offset Offset
  73. # param [in] value Patch value
  74. # param [in] len Length
  75. #
  76. # retval len Length
  77. #
  78. def patchDataInFile (binfile, offset, value, len=1):
  79. fd = open(binfile, "r+b")
  80. fsize = os.path.getsize(binfile)
  81. offval = offset & 0xFFFFFFFF
  82. if (offval & 0x80000000):
  83. offval = fsize - (0xFFFFFFFF - offval + 1)
  84. bytearray = []
  85. idx = 0
  86. while idx < len:
  87. bytearray.append(value & 0xFF)
  88. value = value >> 8
  89. idx = idx + 1
  90. fd.seek(offval)
  91. if sys.version_info[0] < 3:
  92. fd.write("".join(chr(b) for b in bytearray))
  93. else:
  94. fd.write(bytes(bytearray))
  95. fd.close()
  96. return len
  97. class Symbols:
  98. def __init__(self):
  99. self.dictSymbolAddress = {}
  100. self.dictGuidNameXref = {}
  101. self.dictFfsOffset = {}
  102. self.dictVariable = {}
  103. self.dictModBase = {}
  104. self.fdFile = None
  105. self.string = ""
  106. self.fdBase = 0xFFFFFFFF
  107. self.fdSize = 0
  108. self.index = 0
  109. self.fvList = []
  110. self.parenthesisOpenSet = '([{<'
  111. self.parenthesisCloseSet = ')]}>'
  112. #
  113. # Get FD file
  114. #
  115. # retval self.fdFile Retrieve FD file
  116. #
  117. def getFdFile (self):
  118. return self.fdFile
  119. #
  120. # Get FD size
  121. #
  122. # retval self.fdSize Retrieve the size of FD file
  123. #
  124. def getFdSize (self):
  125. return self.fdSize
  126. def parseFvInfFile (self, infFile):
  127. fvInfo = {}
  128. fvFile = infFile[0:-4] + ".Fv"
  129. fvInfo['Name'] = os.path.splitext(os.path.basename(infFile))[0]
  130. fvInfo['Offset'] = self.getFvOffsetInFd(fvFile)
  131. fvInfo['Size'] = readDataFromFile (fvFile, 0x20, 4)
  132. fdIn = open(infFile, "r")
  133. rptLines = fdIn.readlines()
  134. fdIn.close()
  135. fvInfo['Base'] = 0
  136. for rptLine in rptLines:
  137. match = re.match("^EFI_BASE_ADDRESS\s*=\s*(0x[a-fA-F0-9]+)", rptLine)
  138. if match:
  139. fvInfo['Base'] = int(match.group(1), 16)
  140. break
  141. self.fvList.append(dict(fvInfo))
  142. return 0
  143. #
  144. # Create dictionaries
  145. #
  146. # param [in] fvDir FV's directory
  147. # param [in] fvNames All FV's names
  148. #
  149. # retval 0 Created dictionaries successfully
  150. #
  151. def createDicts (self, fvDir, fvNames):
  152. #
  153. # If the fvDir is not a directory, then raise an exception
  154. #
  155. if not os.path.isdir(fvDir):
  156. raise Exception ("'%s' is not a valid directory!" % fvDir)
  157. #
  158. # If the Guid.xref is not existing in fvDir, then raise an exception
  159. #
  160. xrefFile = os.path.join(fvDir, "Guid.xref")
  161. if not os.path.exists(xrefFile):
  162. raise Exception("Cannot open GUID Xref file '%s'!" % xrefFile)
  163. #
  164. # Add GUID reference to dictionary
  165. #
  166. self.dictGuidNameXref = {}
  167. self.parseGuidXrefFile(xrefFile)
  168. #
  169. # Split up each FV from fvNames and get the fdBase
  170. #
  171. fvList = fvNames.split(":")
  172. fdBase = fvList.pop()
  173. if len(fvList) == 0:
  174. fvList.append(fdBase)
  175. #
  176. # If the FD file is not existing, then raise an exception
  177. #
  178. fdFile = os.path.join(fvDir, fdBase.strip() + ".fd")
  179. if not os.path.exists(fdFile):
  180. raise Exception("Cannot open FD file '%s'!" % fdFile)
  181. #
  182. # Get the size of the FD file
  183. #
  184. self.fdFile = fdFile
  185. self.fdSize = os.path.getsize(fdFile)
  186. #
  187. # If the INF file, which is the first element of fvList, is not existing, then raise an exception
  188. #
  189. infFile = os.path.join(fvDir, fvList[0].strip()) + ".inf"
  190. if not os.path.exists(infFile):
  191. raise Exception("Cannot open INF file '%s'!" % infFile)
  192. #
  193. # Parse INF file in order to get fdBase and then assign those values to dictVariable
  194. #
  195. self.parseInfFile(infFile)
  196. self.dictVariable = {}
  197. self.dictVariable["FDSIZE"] = self.fdSize
  198. self.dictVariable["FDBASE"] = self.fdBase
  199. #
  200. # Collect information from FV MAP file and FV TXT file then
  201. # put them into dictionaries
  202. #
  203. self.fvList = []
  204. self.dictSymbolAddress = {}
  205. self.dictFfsOffset = {}
  206. for file in fvList:
  207. #
  208. # If the .Fv.map file is not existing, then raise an exception.
  209. # Otherwise, parse FV MAP file
  210. #
  211. fvFile = os.path.join(fvDir, file.strip()) + ".Fv"
  212. mapFile = fvFile + ".map"
  213. if not os.path.exists(mapFile):
  214. raise Exception("Cannot open MAP file '%s'!" % mapFile)
  215. infFile = fvFile[0:-3] + ".inf"
  216. self.parseFvInfFile(infFile)
  217. self.parseFvMapFile(mapFile)
  218. #
  219. # If the .Fv.txt file is not existing, then raise an exception.
  220. # Otherwise, parse FV TXT file
  221. #
  222. fvTxtFile = fvFile + ".txt"
  223. if not os.path.exists(fvTxtFile):
  224. raise Exception("Cannot open FV TXT file '%s'!" % fvTxtFile)
  225. self.parseFvTxtFile(fvTxtFile)
  226. for fv in self.fvList:
  227. self.dictVariable['_BASE_%s_' % fv['Name']] = fv['Base']
  228. #
  229. # Search all MAP files in FFS directory if it exists then parse MOD MAP file
  230. #
  231. ffsDir = os.path.join(fvDir, "Ffs")
  232. if (os.path.isdir(ffsDir)):
  233. for item in os.listdir(ffsDir):
  234. if len(item) <= 0x24:
  235. continue
  236. mapFile =os.path.join(ffsDir, item, "%s.map" % item[0:0x24])
  237. if not os.path.exists(mapFile):
  238. continue
  239. self.parseModMapFile(item[0x24:], mapFile)
  240. return 0
  241. #
  242. # Get FV offset in FD file
  243. #
  244. # param [in] fvFile FV file
  245. #
  246. # retval offset Got FV offset successfully
  247. #
  248. def getFvOffsetInFd(self, fvFile):
  249. #
  250. # Check if the first 0x70 bytes of fvFile can be found in fdFile
  251. #
  252. fvHandle = open(fvFile, "r+b")
  253. fdHandle = open(self.fdFile, "r+b")
  254. offset = fdHandle.read().find(fvHandle.read(0x70))
  255. fvHandle.close()
  256. fdHandle.close()
  257. if offset == -1:
  258. raise Exception("Could not locate FV file %s in FD!" % fvFile)
  259. return offset
  260. #
  261. # Parse INF file
  262. #
  263. # param [in] infFile INF file
  264. #
  265. # retval 0 Parsed INF file successfully
  266. #
  267. def parseInfFile(self, infFile):
  268. #
  269. # Get FV offset and search EFI_BASE_ADDRESS in the FD file
  270. # then assign the value of EFI_BASE_ADDRESS to fdBase
  271. #
  272. fvOffset = self.getFvOffsetInFd(infFile[0:-4] + ".Fv")
  273. fdIn = open(infFile, "r")
  274. rptLine = fdIn.readline()
  275. self.fdBase = 0xFFFFFFFF
  276. while (rptLine != "" ):
  277. #EFI_BASE_ADDRESS = 0xFFFDF400
  278. match = re.match("^EFI_BASE_ADDRESS\s*=\s*(0x[a-fA-F0-9]+)", rptLine)
  279. if match is not None:
  280. self.fdBase = int(match.group(1), 16) - fvOffset
  281. break
  282. rptLine = fdIn.readline()
  283. fdIn.close()
  284. if self.fdBase == 0xFFFFFFFF:
  285. raise Exception("Could not find EFI_BASE_ADDRESS in INF file!" % infFile)
  286. return 0
  287. #
  288. # Parse FV TXT file
  289. #
  290. # param [in] fvTxtFile .Fv.txt file
  291. #
  292. # retval 0 Parsed FV TXT file successfully
  293. #
  294. def parseFvTxtFile(self, fvTxtFile):
  295. fvName = os.path.basename(fvTxtFile)[0:-7].upper()
  296. #
  297. # Get information from .Fv.txt in order to create a dictionary
  298. # For example,
  299. # self.dictFfsOffset[912740BE-2284-4734-B971-84B027353F0C] = 0x000D4078
  300. #
  301. fvOffset = self.getFvOffsetInFd(fvTxtFile[0:-4])
  302. fdIn = open(fvTxtFile, "r")
  303. rptLine = fdIn.readline()
  304. while (rptLine != "" ):
  305. match = re.match("(0x[a-fA-F0-9]+)\s([0-9a-fA-F\-]+)", rptLine)
  306. if match is not None:
  307. if match.group(2) in self.dictFfsOffset:
  308. self.dictFfsOffset[fvName + ':' + match.group(2)] = "0x%08X" % (int(match.group(1), 16) + fvOffset)
  309. else:
  310. self.dictFfsOffset[match.group(2)] = "0x%08X" % (int(match.group(1), 16) + fvOffset)
  311. rptLine = fdIn.readline()
  312. fdIn.close()
  313. return 0
  314. #
  315. # Parse FV MAP file
  316. #
  317. # param [in] mapFile .Fv.map file
  318. #
  319. # retval 0 Parsed FV MAP file successfully
  320. #
  321. def parseFvMapFile(self, mapFile):
  322. #
  323. # Get information from .Fv.map in order to create dictionaries
  324. # For example,
  325. # self.dictModBase[FspSecCore:BASE] = 4294592776 (0xfffa4908)
  326. # self.dictModBase[FspSecCore:ENTRY] = 4294606552 (0xfffa7ed8)
  327. # self.dictModBase[FspSecCore:TEXT] = 4294593080 (0xfffa4a38)
  328. # self.dictModBase[FspSecCore:DATA] = 4294612280 (0xfffa9538)
  329. # self.dictSymbolAddress[FspSecCore:_SecStartup] = 0x00fffa4a38
  330. #
  331. fdIn = open(mapFile, "r")
  332. rptLine = fdIn.readline()
  333. modName = ""
  334. foundModHdr = False
  335. while (rptLine != "" ):
  336. if rptLine[0] != ' ':
  337. #DxeIpl (Fixed Flash Address, BaseAddress=0x00fffb4310, EntryPoint=0x00fffb4958,Type=PE)
  338. match = re.match("([_a-zA-Z0-9\-]+)\s\(.+BaseAddress=(0x[0-9a-fA-F]+),\s+EntryPoint=(0x[0-9a-fA-F]+),\s*Type=\w+\)", rptLine)
  339. if match is None:
  340. #DxeIpl (Fixed Flash Address, BaseAddress=0x00fffb4310, EntryPoint=0x00fffb4958)
  341. match = re.match("([_a-zA-Z0-9\-]+)\s\(.+BaseAddress=(0x[0-9a-fA-F]+),\s+EntryPoint=(0x[0-9a-fA-F]+)\)", rptLine)
  342. if match is not None:
  343. foundModHdr = True
  344. modName = match.group(1)
  345. if len(modName) == 36:
  346. modName = self.dictGuidNameXref[modName.upper()]
  347. self.dictModBase['%s:BASE' % modName] = int (match.group(2), 16)
  348. self.dictModBase['%s:ENTRY' % modName] = int (match.group(3), 16)
  349. #(GUID=86D70125-BAA3-4296-A62F-602BEBBB9081 .textbaseaddress=0x00fffb4398 .databaseaddress=0x00fffb4178)
  350. match = re.match("\(GUID=([A-Z0-9\-]+)\s+\.textbaseaddress=(0x[0-9a-fA-F]+)\s+\.databaseaddress=(0x[0-9a-fA-F]+)\)", rptLine)
  351. if match is not None:
  352. if foundModHdr:
  353. foundModHdr = False
  354. else:
  355. modName = match.group(1)
  356. if len(modName) == 36:
  357. modName = self.dictGuidNameXref[modName.upper()]
  358. self.dictModBase['%s:TEXT' % modName] = int (match.group(2), 16)
  359. self.dictModBase['%s:DATA' % modName] = int (match.group(3), 16)
  360. else:
  361. # 0x00fff8016c __ModuleEntryPoint
  362. foundModHdr = False
  363. match = re.match("^\s+(0x[a-z0-9]+)\s+([_a-zA-Z0-9]+)", rptLine)
  364. if match is not None:
  365. self.dictSymbolAddress["%s:%s"%(modName, match.group(2))] = match.group(1)
  366. rptLine = fdIn.readline()
  367. fdIn.close()
  368. return 0
  369. #
  370. # Parse MOD MAP file
  371. #
  372. # param [in] moduleName Module name
  373. # param [in] mapFile .Fv.map file
  374. #
  375. # retval 0 Parsed MOD MAP file successfully
  376. # retval 1 There is no moduleEntryPoint in modSymbols
  377. # retval 2 There is no offset for moduleEntryPoint in modSymbols
  378. #
  379. def parseModMapFile(self, moduleName, mapFile):
  380. #
  381. # Get information from mapFile by moduleName in order to create a dictionary
  382. # For example,
  383. # self.dictSymbolAddress[FspSecCore:___guard_fids_count] = 0x00fffa4778
  384. #
  385. modSymbols = {}
  386. fdIn = open(mapFile, "r")
  387. reportLines = fdIn.readlines()
  388. fdIn.close()
  389. moduleEntryPoint = "__ModuleEntryPoint"
  390. reportLine = reportLines[0]
  391. if reportLine.strip().find("Archive member included") != -1:
  392. #GCC
  393. # 0x0000000000001d55 IoRead8
  394. patchMapFileMatchString = "\s+(0x[0-9a-fA-F]{16})\s+([^\s][^0x][_a-zA-Z0-9\-]+)\s"
  395. matchKeyGroupIndex = 2
  396. matchSymbolGroupIndex = 1
  397. prefix = '_'
  398. else:
  399. #MSFT
  400. #0003:00000190 _gComBase 00007a50 SerialPo
  401. patchMapFileMatchString = "^\s[0-9a-fA-F]{4}:[0-9a-fA-F]{8}\s+(\w+)\s+([0-9a-fA-F]{8,16}\s+)"
  402. matchKeyGroupIndex = 1
  403. matchSymbolGroupIndex = 2
  404. prefix = ''
  405. for reportLine in reportLines:
  406. match = re.match(patchMapFileMatchString, reportLine)
  407. if match is not None:
  408. modSymbols[prefix + match.group(matchKeyGroupIndex)] = match.group(matchSymbolGroupIndex)
  409. # Handle extra module patchable PCD variable in Linux map since it might have different format
  410. # .data._gPcd_BinaryPatch_PcdVpdBaseAddress
  411. # 0x0000000000003714 0x4 /tmp/ccmytayk.ltrans1.ltrans.o
  412. handleNext = False
  413. if matchSymbolGroupIndex == 1:
  414. for reportLine in reportLines:
  415. if handleNext:
  416. handleNext = False
  417. pcdName = match.group(1)
  418. match = re.match("\s+(0x[0-9a-fA-F]{16})\s+", reportLine)
  419. if match is not None:
  420. modSymbols[prefix + pcdName] = match.group(1)
  421. else:
  422. match = re.match("^\s\.data\.(_gPcd_BinaryPatch[_a-zA-Z0-9\-]+)", reportLine)
  423. if match is not None:
  424. handleNext = True
  425. continue
  426. if not moduleEntryPoint in modSymbols:
  427. if matchSymbolGroupIndex == 2:
  428. if not '_ModuleEntryPoint' in modSymbols:
  429. return 1
  430. else:
  431. moduleEntryPoint = "_ModuleEntryPoint"
  432. else:
  433. return 1
  434. modEntry = '%s:%s' % (moduleName,moduleEntryPoint)
  435. if not modEntry in self.dictSymbolAddress:
  436. modKey = '%s:ENTRY' % moduleName
  437. if modKey in self.dictModBase:
  438. baseOffset = self.dictModBase['%s:ENTRY' % moduleName] - int(modSymbols[moduleEntryPoint], 16)
  439. else:
  440. return 2
  441. else:
  442. baseOffset = int(self.dictSymbolAddress[modEntry], 16) - int(modSymbols[moduleEntryPoint], 16)
  443. for symbol in modSymbols:
  444. fullSym = "%s:%s" % (moduleName, symbol)
  445. if not fullSym in self.dictSymbolAddress:
  446. self.dictSymbolAddress[fullSym] = "0x00%08x" % (baseOffset+ int(modSymbols[symbol], 16))
  447. return 0
  448. #
  449. # Parse Guid.xref file
  450. #
  451. # param [in] xrefFile the full directory of Guid.xref file
  452. #
  453. # retval 0 Parsed Guid.xref file successfully
  454. #
  455. def parseGuidXrefFile(self, xrefFile):
  456. #
  457. # Get information from Guid.xref in order to create a GuidNameXref dictionary
  458. # The dictGuidNameXref, for example, will be like
  459. # dictGuidNameXref [1BA0062E-C779-4582-8566-336AE8F78F09] = FspSecCore
  460. #
  461. fdIn = open(xrefFile, "r")
  462. rptLine = fdIn.readline()
  463. while (rptLine != "" ):
  464. match = re.match("([0-9a-fA-F\-]+)\s([_a-zA-Z0-9]+)", rptLine)
  465. if match is not None:
  466. self.dictGuidNameXref[match.group(1).upper()] = match.group(2)
  467. rptLine = fdIn.readline()
  468. fdIn.close()
  469. return 0
  470. #
  471. # Get current character
  472. #
  473. # retval self.string[self.index]
  474. # retval '' Exception
  475. #
  476. def getCurr(self):
  477. try:
  478. return self.string[self.index]
  479. except Exception:
  480. return ''
  481. #
  482. # Check to see if it is last index
  483. #
  484. # retval self.index
  485. #
  486. def isLast(self):
  487. return self.index == len(self.string)
  488. #
  489. # Move to next index
  490. #
  491. def moveNext(self):
  492. self.index += 1
  493. #
  494. # Skip space
  495. #
  496. def skipSpace(self):
  497. while not self.isLast():
  498. if self.getCurr() in ' \t':
  499. self.moveNext()
  500. else:
  501. return
  502. #
  503. # Parse value
  504. #
  505. # retval value
  506. #
  507. def parseValue(self):
  508. self.skipSpace()
  509. var = ''
  510. while not self.isLast():
  511. char = self.getCurr()
  512. if char.lower() in '_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:-':
  513. var += char
  514. self.moveNext()
  515. else:
  516. break
  517. if ':' in var:
  518. partList = var.split(':')
  519. lenList = len(partList)
  520. if lenList != 2 and lenList != 3:
  521. raise Exception("Unrecognized expression %s" % var)
  522. modName = partList[lenList-2]
  523. modOff = partList[lenList-1]
  524. if ('-' not in modName) and (modOff[0] in '0123456789'):
  525. # MOD: OFFSET
  526. var = self.getModGuid(modName) + ":" + modOff
  527. if '-' in var: # GUID:OFFSET
  528. value = self.getGuidOff(var)
  529. else:
  530. value = self.getSymbols(var)
  531. self.synUsed = True
  532. else:
  533. if var[0] in '0123456789':
  534. value = self.getNumber(var)
  535. else:
  536. value = self.getVariable(var)
  537. return int(value)
  538. #
  539. # Parse single operation
  540. #
  541. # retval ~self.parseBrace() or self.parseValue()
  542. #
  543. def parseSingleOp(self):
  544. self.skipSpace()
  545. char = self.getCurr()
  546. if char == '~':
  547. self.moveNext()
  548. return ~self.parseBrace()
  549. else:
  550. return self.parseValue()
  551. #
  552. # Parse symbol of Brace([, {, <)
  553. #
  554. # retval value or self.parseSingleOp()
  555. #
  556. def parseBrace(self):
  557. self.skipSpace()
  558. char = self.getCurr()
  559. parenthesisType = self.parenthesisOpenSet.find(char)
  560. if parenthesisType >= 0:
  561. self.moveNext()
  562. value = self.parseExpr()
  563. self.skipSpace()
  564. if self.getCurr() != self.parenthesisCloseSet[parenthesisType]:
  565. raise Exception("No closing brace")
  566. self.moveNext()
  567. if parenthesisType == 1: # [ : Get content
  568. value = self.getContent(value)
  569. elif parenthesisType == 2: # { : To address
  570. value = self.toAddress(value)
  571. elif parenthesisType == 3: # < : To offset
  572. value = self.toOffset(value)
  573. return value
  574. else:
  575. return self.parseSingleOp()
  576. #
  577. # Parse symbol of Multiplier(*)
  578. #
  579. # retval value or self.parseSingleOp()
  580. #
  581. def parseMul(self):
  582. values = [self.parseBrace()]
  583. while True:
  584. self.skipSpace()
  585. char = self.getCurr()
  586. if char == '*':
  587. self.moveNext()
  588. values.append(self.parseBrace())
  589. else:
  590. break
  591. value = 1
  592. for each in values:
  593. value *= each
  594. return value
  595. #
  596. # Parse symbol of And(&) and Or(|)
  597. #
  598. # retval value
  599. #
  600. def parseAndOr(self):
  601. value = self.parseMul()
  602. op = None
  603. while True:
  604. self.skipSpace()
  605. char = self.getCurr()
  606. if char == '&':
  607. self.moveNext()
  608. value &= self.parseMul()
  609. elif char == '|':
  610. div_index = self.index
  611. self.moveNext()
  612. value |= self.parseMul()
  613. else:
  614. break
  615. return value
  616. #
  617. # Parse symbol of Add(+) and Minus(-)
  618. #
  619. # retval sum(values)
  620. #
  621. def parseAddMinus(self):
  622. values = [self.parseAndOr()]
  623. while True:
  624. self.skipSpace()
  625. char = self.getCurr()
  626. if char == '+':
  627. self.moveNext()
  628. values.append(self.parseAndOr())
  629. elif char == '-':
  630. self.moveNext()
  631. values.append(-1 * self.parseAndOr())
  632. else:
  633. break
  634. return sum(values)
  635. #
  636. # Parse expression
  637. #
  638. # retval self.parseAddMinus()
  639. #
  640. def parseExpr(self):
  641. return self.parseAddMinus()
  642. #
  643. # Get result
  644. #
  645. # retval value
  646. #
  647. def getResult(self):
  648. value = self.parseExpr()
  649. self.skipSpace()
  650. if not self.isLast():
  651. raise Exception("Unexpected character found '%s'" % self.getCurr())
  652. return value
  653. #
  654. # Get module GUID
  655. #
  656. # retval value
  657. #
  658. def getModGuid(self, var):
  659. guid = (guid for guid,name in self.dictGuidNameXref.items() if name==var)
  660. try:
  661. value = guid.next()
  662. except Exception:
  663. raise Exception("Unknown module name %s !" % var)
  664. return value
  665. #
  666. # Get variable
  667. #
  668. # retval value
  669. #
  670. def getVariable(self, var):
  671. value = self.dictVariable.get(var, None)
  672. if value == None:
  673. raise Exception("Unrecognized variable '%s'" % var)
  674. return value
  675. #
  676. # Get number
  677. #
  678. # retval value
  679. #
  680. def getNumber(self, var):
  681. var = var.strip()
  682. if var.startswith('0x'): # HEX
  683. value = int(var, 16)
  684. else:
  685. value = int(var, 10)
  686. return value
  687. #
  688. # Get content
  689. #
  690. # param [in] value
  691. #
  692. # retval value
  693. #
  694. def getContent(self, value):
  695. return readDataFromFile (self.fdFile, self.toOffset(value), 4)
  696. #
  697. # Change value to address
  698. #
  699. # param [in] value
  700. #
  701. # retval value
  702. #
  703. def toAddress(self, value):
  704. if value < self.fdSize:
  705. value = value + self.fdBase
  706. return value
  707. #
  708. # Change value to offset
  709. #
  710. # param [in] value
  711. #
  712. # retval value
  713. #
  714. def toOffset(self, value):
  715. offset = None
  716. for fvInfo in self.fvList:
  717. if (value >= fvInfo['Base']) and (value < fvInfo['Base'] + fvInfo['Size']):
  718. offset = value - fvInfo['Base'] + fvInfo['Offset']
  719. if not offset:
  720. if (value >= self.fdBase) and (value < self.fdBase + self.fdSize):
  721. offset = value - self.fdBase
  722. else:
  723. offset = value
  724. if offset >= self.fdSize:
  725. raise Exception("Invalid file offset 0x%08x !" % value)
  726. return offset
  727. #
  728. # Get GUID offset
  729. #
  730. # param [in] value
  731. #
  732. # retval value
  733. #
  734. def getGuidOff(self, value):
  735. # GUID:Offset
  736. symbolName = value.split(':')
  737. if len(symbolName) == 3:
  738. fvName = symbolName[0].upper()
  739. keyName = '%s:%s' % (fvName, symbolName[1])
  740. offStr = symbolName[2]
  741. elif len(symbolName) == 2:
  742. keyName = symbolName[0]
  743. offStr = symbolName[1]
  744. if keyName in self.dictFfsOffset:
  745. value = (int(self.dictFfsOffset[keyName], 16) + int(offStr, 16)) & 0xFFFFFFFF
  746. else:
  747. raise Exception("Unknown GUID %s !" % value)
  748. return value
  749. #
  750. # Get symbols
  751. #
  752. # param [in] value
  753. #
  754. # retval ret
  755. #
  756. def getSymbols(self, value):
  757. if value in self.dictSymbolAddress:
  758. # Module:Function
  759. ret = int (self.dictSymbolAddress[value], 16)
  760. else:
  761. raise Exception("Unknown symbol %s !" % value)
  762. return ret
  763. #
  764. # Evaluate symbols
  765. #
  766. # param [in] expression
  767. # param [in] isOffset
  768. #
  769. # retval value & 0xFFFFFFFF
  770. #
  771. def evaluate(self, expression, isOffset):
  772. self.index = 0
  773. self.synUsed = False
  774. self.string = expression
  775. value = self.getResult()
  776. if isOffset:
  777. if self.synUsed:
  778. # Consider it as an address first
  779. value = self.toOffset(value)
  780. if value & 0x80000000:
  781. # Consider it as a negative offset next
  782. offset = (~value & 0xFFFFFFFF) + 1
  783. if offset < self.fdSize:
  784. value = self.fdSize - offset
  785. if value >= self.fdSize:
  786. raise Exception("Invalid offset expression !")
  787. return value & 0xFFFFFFFF
  788. #
  789. # Print out the usage
  790. #
  791. def Usage():
  792. print ("PatchFv Version 0.50")
  793. print ("Usage: \n\tPatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch \"Offset, Value\"")
  794. def main():
  795. #
  796. # Parse the options and args
  797. #
  798. symTables = Symbols()
  799. #
  800. # If the arguments are less than 4, then return an error.
  801. #
  802. if len(sys.argv) < 4:
  803. Usage()
  804. return 1
  805. #
  806. # If it fails to create dictionaries, then return an error.
  807. #
  808. if symTables.createDicts(sys.argv[1], sys.argv[2]) != 0:
  809. print ("ERROR: Failed to create symbol dictionary!!")
  810. return 2
  811. #
  812. # Get FD file and size
  813. #
  814. fdFile = symTables.getFdFile()
  815. fdSize = symTables.getFdSize()
  816. try:
  817. #
  818. # Check to see if FSP header is valid
  819. #
  820. ret = IsFspHeaderValid(fdFile)
  821. if ret == False:
  822. raise Exception ("The FSP header is not valid. Stop patching FD.")
  823. comment = ""
  824. for fvFile in sys.argv[3:]:
  825. #
  826. # Check to see if it has enough arguments
  827. #
  828. items = fvFile.split(",")
  829. if len (items) < 2:
  830. raise Exception("Expect more arguments for '%s'!" % fvFile)
  831. comment = ""
  832. command = ""
  833. params = []
  834. for item in items:
  835. item = item.strip()
  836. if item.startswith("@"):
  837. comment = item[1:]
  838. elif item.startswith("$"):
  839. command = item[1:]
  840. else:
  841. if len(params) == 0:
  842. isOffset = True
  843. else :
  844. isOffset = False
  845. #
  846. # Parse symbols then append it to params
  847. #
  848. params.append (symTables.evaluate(item, isOffset))
  849. #
  850. # Patch a new value into FD file if it is not a command
  851. #
  852. if command == "":
  853. # Patch a DWORD
  854. if len (params) == 2:
  855. offset = params[0]
  856. value = params[1]
  857. oldvalue = readDataFromFile(fdFile, offset, 4)
  858. ret = patchDataInFile (fdFile, offset, value, 4) - 4
  859. else:
  860. raise Exception ("Patch command needs 2 parameters !")
  861. if ret:
  862. raise Exception ("Patch failed for offset 0x%08X" % offset)
  863. else:
  864. print ("Patched offset 0x%08X:[%08X] with value 0x%08X # %s" % (offset, oldvalue, value, comment))
  865. elif command == "COPY":
  866. #
  867. # Copy binary block from source to destination
  868. #
  869. if len (params) == 3:
  870. src = symTables.toOffset(params[0])
  871. dest = symTables.toOffset(params[1])
  872. clen = symTables.toOffset(params[2])
  873. if (dest + clen <= fdSize) and (src + clen <= fdSize):
  874. oldvalue = readDataFromFile(fdFile, src, clen)
  875. ret = patchDataInFile (fdFile, dest, oldvalue, clen) - clen
  876. else:
  877. raise Exception ("Copy command OFFSET or LENGTH parameter is invalid !")
  878. else:
  879. raise Exception ("Copy command needs 3 parameters !")
  880. if ret:
  881. raise Exception ("Copy failed from offset 0x%08X to offset 0x%08X!" % (src, dest))
  882. else :
  883. print ("Copied %d bytes from offset 0x%08X ~ offset 0x%08X # %s" % (clen, src, dest, comment))
  884. else:
  885. raise Exception ("Unknown command %s!" % command)
  886. return 0
  887. except Exception as ex:
  888. print ("ERROR: %s" % ex)
  889. return 1
  890. if __name__ == '__main__':
  891. sys.exit(main())