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