]>
git.proxmox.com Git - mirror_edk2.git/blob - IntelFspPkg/Tools/PatchFv.py
3 # Copyright (c) 2014 - 2015, Intel Corporation. All rights reserved.<BR>
4 # SPDX-License-Identifier: BSD-2-Clause-Patent
15 # param [in] binfile Binary file
16 # param [in] offset Offset
17 # param [in] len Length
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)
28 bytearray
= [ord(b
) for b
in fd
.read(len)]
32 value
= value
<< 8 | bytearray
[idx
]
38 # Check FSP header is valid or not
40 # param [in] binfile Binary file
42 # retval boolean True: valid; False: invalid
44 def IsFspHeaderValid (binfile
):
45 fd
= open (binfile
, "rb")
46 bindat
= fd
.read(0x200) # only read first 0x200 bytes
48 HeaderList
= ['FSPH' , 'FSPP' , 'FSPE'] # Check 'FSPH', 'FSPP', and 'FSPE' in the FSP header
50 for each
in HeaderList
:
52 idx
= bindat
.index(each
)
55 OffsetList
.append(idx
)
56 if not OffsetList
[0] or not OffsetList
[1]: # If 'FSPH' or 'FSPP' is missing, it will return false
58 Revision
= ord(bindat
[OffsetList
[0] + 0x0B])
60 # if revision is bigger than 1, it means it is FSP v1.1 or greater revision, which must contain 'FSPE'.
62 if Revision
> 1 and not OffsetList
[2]:
63 return False # If FSP v1.1 or greater without 'FSPE', then return false
69 # param [in] binfile Binary file
70 # param [in] offset Offset
71 # param [in] value Patch value
72 # param [in] len Length
76 def patchDataInFile (binfile
, offset
, value
, len=1):
77 fd
= open(binfile
, "r+b")
78 fsize
= os
.path
.getsize(binfile
)
79 offval
= offset
& 0xFFFFFFFF
80 if (offval
& 0x80000000):
81 offval
= fsize
- (0xFFFFFFFF - offval
+ 1)
85 bytearray
.append(value
& 0xFF)
89 fd
.write("".join(chr(b
) for b
in bytearray
))
96 self
.dictSymbolAddress
= {}
97 self
.dictGuidNameXref
= {}
98 self
.dictFfsOffset
= {}
99 self
.dictVariable
= {}
100 self
.dictModBase
= {}
103 self
.fdBase
= 0xFFFFFFFF
106 self
.parenthesisOpenSet
= '([{<'
107 self
.parenthesisCloseSet
= ')]}>'
112 # retval self.fdFile Retrieve FD file
114 def getFdFile (self
):
120 # retval self.fdSize Retrieve the size of FD file
122 def getFdSize (self
):
126 # Create dictionaries
128 # param [in] fvDir FV's directory
129 # param [in] fvNames All FV's names
131 # retval 0 Created dictionaries successfully
133 def createDicts (self
, fvDir
, fvNames
):
135 # If the fvDir is not a dirctory, then raise an exception
137 if not os
.path
.isdir(fvDir
):
138 raise Exception ("'%s' is not a valid directory!" % FvDir
)
141 # If the Guid.xref is not existing in fvDir, then raise an exception
143 xrefFile
= os
.path
.join(fvDir
, "Guid.xref")
144 if not os
.path
.exists(xrefFile
):
145 raise Exception("Cannot open GUID Xref file '%s'!" % xrefFile
)
148 # Add GUID reference to dictionary
150 self
.dictGuidNameXref
= {}
151 self
.parseGuidXrefFile(xrefFile
)
154 # Split up each FV from fvNames and get the fdBase
156 fvList
= fvNames
.split(":")
157 fdBase
= fvList
.pop()
159 fvList
.append(fdBase
)
162 # If the FD file is not existing, then raise an exception
164 fdFile
= os
.path
.join(fvDir
, fdBase
.strip() + ".fd")
165 if not os
.path
.exists(fdFile
):
166 raise Exception("Cannot open FD file '%s'!" % fdFile
)
169 # Get the size of the FD file
172 self
.fdSize
= os
.path
.getsize(fdFile
)
175 # If the INF file, which is the first element of fvList, is not existing, then raise an exception
177 infFile
= os
.path
.join(fvDir
, fvList
[0].strip()) + ".inf"
178 if not os
.path
.exists(infFile
):
179 raise Exception("Cannot open INF file '%s'!" % infFile
)
182 # Parse INF file in order to get fdBase and then assign those values to dictVariable
184 self
.parseInfFile(infFile
)
185 self
.dictVariable
= {}
186 self
.dictVariable
["FDSIZE"] = self
.fdSize
187 self
.dictVariable
["FDBASE"] = self
.fdBase
190 # Collect information from FV MAP file and FV TXT file then
191 # put them into dictionaries
193 self
.dictSymbolAddress
= {}
194 self
.dictFfsOffset
= {}
198 # If the .Fv.map file is not existing, then raise an exception.
199 # Otherwise, parse FV MAP file
201 fvFile
= os
.path
.join(fvDir
, file.strip()) + ".Fv"
202 mapFile
= fvFile
+ ".map"
203 if not os
.path
.exists(mapFile
):
204 raise Exception("Cannot open MAP file '%s'!" % mapFile
)
206 self
.parseFvMapFile(mapFile
)
209 # If the .Fv.txt file is not existing, then raise an exception.
210 # Otherwise, parse FV TXT file
212 fvTxtFile
= fvFile
+ ".txt"
213 if not os
.path
.exists(fvTxtFile
):
214 raise Exception("Cannot open FV TXT file '%s'!" % fvTxtFile
)
216 self
.parseFvTxtFile(fvTxtFile
)
219 # Search all MAP files in FFS directory if it exists then parse MOD MAP file
221 ffsDir
= os
.path
.join(fvDir
, "Ffs")
222 if (os
.path
.isdir(ffsDir
)):
223 for item
in os
.listdir(ffsDir
):
224 if len(item
) <= 0x24:
226 mapFile
=os
.path
.join(ffsDir
, item
, "%s.map" % item
[0:0x24])
227 if not os
.path
.exists(mapFile
):
229 self
.parseModMapFile(item
[0x24:], mapFile
)
234 # Get FV offset in FD file
236 # param [in] fvFile FV file
238 # retval offset Got FV offset successfully
240 def getFvOffsetInFd(self
, fvFile
):
242 # Check if the first 0x70 bytes of fvFile can be found in fdFile
244 fvHandle
= open(fvFile
, "r+b")
245 fdHandle
= open(self
.fdFile
, "r+b")
246 offset
= fdHandle
.read().find(fvHandle
.read(0x70))
250 raise Exception("Could not locate FV file %s in FD!" % fvFile
)
256 # param [in] infFile INF file
258 # retval 0 Parsed INF file successfully
260 def parseInfFile(self
, infFile
):
262 # Get FV offset and search EFI_BASE_ADDRESS in the FD file
263 # then assign the value of EFI_BASE_ADDRESS to fdBase
265 fvOffset
= self
.getFvOffsetInFd(infFile
[0:-4] + ".Fv")
266 fdIn
= open(infFile
, "r")
267 rptLine
= fdIn
.readline()
268 self
.fdBase
= 0xFFFFFFFF
269 while (rptLine
!= "" ):
270 #EFI_BASE_ADDRESS = 0xFFFDF400
271 match
= re
.match("^EFI_BASE_ADDRESS\s*=\s*(0x[a-fA-F0-9]+)", rptLine
)
272 if match
is not None:
273 self
.fdBase
= int(match
.group(1), 16) - fvOffset
274 rptLine
= fdIn
.readline()
276 if self
.fdBase
== 0xFFFFFFFF:
277 raise Exception("Could not find EFI_BASE_ADDRESS in INF file!" % fvFile
)
283 # param [in] fvTxtFile .Fv.txt file
285 # retval 0 Parsed FV TXT file successfully
287 def parseFvTxtFile(self
, fvTxtFile
):
289 # Get information from .Fv.txt in order to create a dictionary
291 # self.dictFfsOffset[912740BE-2284-4734-B971-84B027353F0C] = 0x000D4078
293 fvOffset
= self
.getFvOffsetInFd(fvTxtFile
[0:-4])
294 fdIn
= open(fvTxtFile
, "r")
295 rptLine
= fdIn
.readline()
296 while (rptLine
!= "" ):
297 match
= re
.match("(0x[a-fA-F0-9]+)\s([0-9a-fA-F\-]+)", rptLine
)
298 if match
is not None:
299 self
.dictFfsOffset
[match
.group(2)] = "0x%08X" % (int(match
.group(1), 16) + fvOffset
)
300 rptLine
= fdIn
.readline()
307 # param [in] mapFile .Fv.map file
309 # retval 0 Parsed FV MAP file successfully
311 def parseFvMapFile(self
, mapFile
):
313 # Get information from .Fv.map in order to create dictionaries
315 # self.dictModBase[FspSecCore:BASE] = 4294592776 (0xfffa4908)
316 # self.dictModBase[FspSecCore:ENTRY] = 4294606552 (0xfffa7ed8)
317 # self.dictModBase[FspSecCore:TEXT] = 4294593080 (0xfffa4a38)
318 # self.dictModBase[FspSecCore:DATA] = 4294612280 (0xfffa9538)
319 # self.dictSymbolAddress[FspSecCore:_SecStartup] = 0x00fffa4a38
321 fdIn
= open(mapFile
, "r")
322 rptLine
= fdIn
.readline()
324 while (rptLine
!= "" ):
325 if rptLine
[0] != ' ':
326 #DxeIpl (Fixed Flash Address, BaseAddress=0x00fffb4310, EntryPoint=0x00fffb4958)
327 #(GUID=86D70125-BAA3-4296-A62F-602BEBBB9081 .textbaseaddress=0x00fffb4398 .databaseaddress=0x00fffb4178)
328 match
= re
.match("([_a-zA-Z0-9\-]+)\s\(.+BaseAddress=(0x[0-9a-fA-F]+),\s+EntryPoint=(0x[0-9a-fA-F]+)\)", rptLine
)
329 if match
is not None:
330 modName
= match
.group(1)
331 if len(modName
) == 36:
332 modName
= self
.dictGuidNameXref
[modName
.upper()]
333 self
.dictModBase
['%s:BASE' % modName
] = int (match
.group(2), 16)
334 self
.dictModBase
['%s:ENTRY' % modName
] = int (match
.group(3), 16)
335 match
= re
.match("\(GUID=([A-Z0-9\-]+)\s+\.textbaseaddress=(0x[0-9a-fA-F]+)\s+\.databaseaddress=(0x[0-9a-fA-F]+)\)", rptLine
)
336 if match
is not None:
337 modName
= match
.group(1)
338 if len(modName
) == 36:
339 modName
= self
.dictGuidNameXref
[modName
.upper()]
340 self
.dictModBase
['%s:TEXT' % modName
] = int (match
.group(2), 16)
341 self
.dictModBase
['%s:DATA' % modName
] = int (match
.group(3), 16)
343 # 0x00fff8016c __ModuleEntryPoint
344 match
= re
.match("^\s+(0x[a-z0-9]+)\s+([_a-zA-Z0-9]+)", rptLine
)
345 if match
is not None:
346 self
.dictSymbolAddress
["%s:%s"%(modName
, match
.group(2))] = match
.group(1)
347 rptLine
= fdIn
.readline()
354 # param [in] moduleName Module name
355 # param [in] mapFile .Fv.map file
357 # retval 0 Parsed MOD MAP file successfully
358 # retval 1 There is no moduleEntryPoint in modSymbols
360 def parseModMapFile(self
, moduleName
, mapFile
):
362 # Get information from mapFile by moduleName in order to create a dictionary
364 # self.dictSymbolAddress[FspSecCore:___guard_fids_count] = 0x00fffa4778
367 fdIn
= open(mapFile
, "r")
368 reportLines
= fdIn
.readlines()
371 moduleEntryPoint
= "__ModuleEntryPoint"
372 reportLine
= reportLines
[0]
373 if reportLine
.strip().find("Archive member included") != -1:
375 # 0x0000000000001d55 IoRead8
376 patchMapFileMatchString
= "\s+(0x[0-9a-fA-F]{16})\s+([^\s][^0x][_a-zA-Z0-9\-]+)\s"
377 matchKeyGroupIndex
= 2
378 matchSymbolGroupIndex
= 1
382 #0003:00000190 _gComBase 00007a50 SerialPo
383 patchMapFileMatchString
= "^\s[0-9a-fA-F]{4}:[0-9a-fA-F]{8}\s+(\w+)\s+([0-9a-fA-F]{8}\s+)"
384 matchKeyGroupIndex
= 1
385 matchSymbolGroupIndex
= 2
388 for reportLine
in reportLines
:
389 match
= re
.match(patchMapFileMatchString
, reportLine
)
390 if match
is not None:
391 modSymbols
[prefix
+ match
.group(matchKeyGroupIndex
)] = match
.group(matchSymbolGroupIndex
)
393 # Handle extra module patchable PCD variable in Linux map since it might have different format
394 # .data._gPcd_BinaryPatch_PcdVpdBaseAddress
395 # 0x0000000000003714 0x4 /tmp/ccmytayk.ltrans1.ltrans.o
397 if matchSymbolGroupIndex
== 1:
398 for reportLine
in reportLines
:
401 pcdName
= match
.group(1)
402 match
= re
.match("\s+(0x[0-9a-fA-F]{16})\s+", reportLine
)
403 if match
is not None:
404 modSymbols
[prefix
+ pcdName
] = match
.group(1)
406 match
= re
.match("^\s\.data\.(_gPcd_BinaryPatch[_a-zA-Z0-9\-]+)", reportLine
)
407 if match
is not None:
411 if not moduleEntryPoint
in modSymbols
:
414 modEntry
= '%s:%s' % (moduleName
,moduleEntryPoint
)
415 if not modEntry
in self
.dictSymbolAddress
:
416 modKey
= '%s:ENTRY' % moduleName
417 if modKey
in self
.dictModBase
:
418 baseOffset
= self
.dictModBase
['%s:ENTRY' % moduleName
] - int(modSymbols
[moduleEntryPoint
], 16)
422 baseOffset
= int(self
.dictSymbolAddress
[modEntry
], 16) - int(modSymbols
[moduleEntryPoint
], 16)
423 for symbol
in modSymbols
:
424 fullSym
= "%s:%s" % (moduleName
, symbol
)
425 if not fullSym
in self
.dictSymbolAddress
:
426 self
.dictSymbolAddress
[fullSym
] = "0x00%08x" % (baseOffset
+ int(modSymbols
[symbol
], 16))
430 # Parse Guid.xref file
432 # param [in] xrefFile the full directory of Guid.xref file
434 # retval 0 Parsed Guid.xref file successfully
436 def parseGuidXrefFile(self
, xrefFile
):
438 # Get information from Guid.xref in order to create a GuidNameXref dictionary
439 # The dictGuidNameXref, for example, will be like
440 # dictGuidNameXref [1BA0062E-C779-4582-8566-336AE8F78F09] = FspSecCore
442 fdIn
= open(xrefFile
, "r")
443 rptLine
= fdIn
.readline()
444 while (rptLine
!= "" ):
445 match
= re
.match("([0-9a-fA-F\-]+)\s([_a-zA-Z0-9]+)", rptLine
)
446 if match
is not None:
447 self
.dictGuidNameXref
[match
.group(1).upper()] = match
.group(2)
448 rptLine
= fdIn
.readline()
453 # Get current character
455 # retval elf.string[self.index]
456 # retval '' Exception
460 return self
.string
[self
.index
]
465 # Check to see if it is last index
470 return self
.index
== len(self
.string
)
482 while not self
.isLast():
483 if self
.getCurr() in ' \t':
493 def parseValue(self
):
496 while not self
.isLast():
497 char
= self
.getCurr()
498 if char
.lower() in '_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:-':
505 partList
= var
.split(':')
506 if len(partList
) != 2:
507 raise Exception("Unrecognized expression %s" % var
)
508 modName
= partList
[0]
510 if ('-' not in modName
) and (modOff
[0] in '0123456789'):
512 var
= self
.getModGuid(modName
) + ":" + modOff
513 if '-' in var
: # GUID:OFFSET
514 value
= self
.getGuidOff(var
)
516 value
= self
.getSymbols(var
)
519 if var
[0] in '0123456789':
520 value
= self
.getNumber(var
)
522 value
= self
.getVariable(var
)
526 # Parse single operation
528 # retval ~self.parseBrace() or self.parseValue()
530 def parseSingleOp(self
):
532 char
= self
.getCurr()
535 return ~self
.parseBrace()
537 return self
.parseValue()
540 # Parse symbol of Brace([, {, <)
542 # retval value or self.parseSingleOp()
544 def parseBrace(self
):
546 char
= self
.getCurr()
547 parenthesisType
= self
.parenthesisOpenSet
.find(char
)
548 if parenthesisType
>= 0:
550 value
= self
.parseExpr()
552 if self
.getCurr() != self
.parenthesisCloseSet
[parenthesisType
]:
553 raise Exception("No closing brace")
555 if parenthesisType
== 1: # [ : Get content
556 value
= self
.getContent(value
)
557 elif parenthesisType
== 2: # { : To address
558 value
= self
.toAddress(value
)
559 elif parenthesisType
== 3: # < : To offset
560 value
= self
.toOffset(value
)
563 return self
.parseSingleOp()
566 # Parse symbol of Multiplier(*)
568 # retval value or self.parseSingleOp()
571 values
= [self
.parseBrace()]
574 char
= self
.getCurr()
577 values
.append(self
.parseBrace())
586 # Parse symbol of And(&) and Or(|)
590 def parseAndOr(self
):
591 values
= [self
.parseMul()]
596 char
= self
.getCurr()
599 values
.append(self
.parseMul())
602 div_index
= self
.index
604 values
.append(self
.parseMul())
619 # Parse symbol of Add(+) and Minus(-)
623 def parseAddMinus(self
):
624 values
= [self
.parseAndOr()]
627 char
= self
.getCurr()
630 values
.append(self
.parseAndOr())
633 values
.append(-1 * self
.parseAndOr())
641 # retval self.parseAddMinus()
644 return self
.parseAddMinus()
652 value
= self
.parseExpr()
654 if not self
.isLast():
655 raise Exception("Unexpected character found '%s'" % self
.getCurr())
663 def getModGuid(self
, var
):
664 guid
= (guid
for guid
,name
in self
.dictGuidNameXref
.items() if name
==var
)
668 raise Exception("Unknown module name %s !" % var
)
676 def getVariable(self
, var
):
677 value
= self
.dictVariable
.get(var
, None)
679 raise Exception("Unrecognized variable '%s'" % var
)
687 def getNumber(self
, var
):
689 if var
.startswith('0x'): # HEX
702 def getContent(self
, value
):
703 if (value
>= self
.fdBase
) and (value
< self
.fdBase
+ self
.fdSize
):
704 value
= value
- self
.fdBase
705 if value
>= self
.fdSize
:
706 raise Exception("Invalid file offset 0x%08x !" % value
)
707 return readDataFromFile (self
.fdFile
, value
, 4)
710 # Change value to address
716 def toAddress(self
, value
):
717 if value
< self
.fdSize
:
718 value
= value
+ self
.fdBase
722 # Change value to offset
728 def toOffset(self
, value
):
729 if value
> self
.fdBase
:
730 value
= value
- self
.fdBase
740 def getGuidOff(self
, value
):
742 symbolName
= value
.split(':')
743 if len(symbolName
) == 2 and self
.dictFfsOffset
.has_key(symbolName
[0]):
744 value
= (int(self
.dictFfsOffset
[symbolName
[0]], 16) + int(symbolName
[1], 16)) & 0xFFFFFFFF
746 raise Exception("Unknown GUID %s !" % value
)
756 def getSymbols(self
, value
):
757 if self
.dictSymbolAddress
.has_key(value
):
759 ret
= int (self
.dictSymbolAddress
[value
], 16)
761 raise Exception("Unknown symbol %s !" % value
)
767 # param [in] expression
768 # param [in] isOffset
770 # retval value & 0xFFFFFFFF
772 def evaluate(self
, expression
, isOffset
):
775 self
.string
= expression
776 value
= self
.getResult()
779 # Consider it as an address first
780 if (value
>= self
.fdBase
) and (value
< self
.fdBase
+ self
.fdSize
):
781 value
= value
- self
.fdBase
782 if value
& 0x80000000:
783 # Consider it as a negative offset next
784 offset
= (~value
& 0xFFFFFFFF) + 1
785 if offset
< self
.fdSize
:
786 value
= self
.fdSize
- offset
787 if value
>= self
.fdSize
:
788 raise Exception("Invalid offset expression !")
789 return value
& 0xFFFFFFFF
792 # Print out the usage
795 print "Usage: \n\tPatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch \"Offset, Value\""
799 # Parse the options and args
801 symTables
= Symbols()
804 # If the arguments are less than 4, then return an error.
806 if len(sys
.argv
) < 4:
811 # If it fails to create dictionaries, then return an error.
813 if symTables
.createDicts(sys
.argv
[1], sys
.argv
[2]) != 0:
814 print "ERROR: Failed to create symbol dictionary!!"
818 # Get FD file and size
820 fdFile
= symTables
.getFdFile()
821 fdSize
= symTables
.getFdSize()
825 # Check to see if FSP header is valid
827 ret
= IsFspHeaderValid(fdFile
)
829 raise Exception ("The FSP header is not valid. Stop patching FD.")
831 for fvFile
in sys
.argv
[3:]:
833 # Check to see if it has enough arguments
835 items
= fvFile
.split(",")
837 raise Exception("Expect more arguments for '%s'!" % fvFile
)
844 if item
.startswith("@"):
846 elif item
.startswith("$"):
854 # Parse symbols then append it to params
856 params
.append (symTables
.evaluate(item
, isOffset
))
859 # Patch a new value into FD file if it is not a command
863 if len (params
) == 2:
866 oldvalue
= readDataFromFile(fdFile
, offset
, 4)
867 ret
= patchDataInFile (fdFile
, offset
, value
, 4) - 4
869 raise Exception ("Patch command needs 2 parameters !")
872 raise Exception ("Patch failed for offset 0x%08X" % offset
)
874 print "Patched offset 0x%08X:[%08X] with value 0x%08X # %s" % (offset
, oldvalue
, value
, comment
)
876 elif command
== "COPY":
878 # Copy binary block from source to destination
880 if len (params
) == 3:
881 src
= symTables
.toOffset(params
[0])
882 dest
= symTables
.toOffset(params
[1])
883 clen
= symTables
.toOffset(params
[2])
884 if (dest
+ clen
<= fdSize
) and (src
+ clen
<= fdSize
):
885 oldvalue
= readDataFromFile(fdFile
, src
, clen
)
886 ret
= patchDataInFile (fdFile
, dest
, oldvalue
, clen
) - clen
888 raise Exception ("Copy command OFFSET or LENGTH parameter is invalid !")
890 raise Exception ("Copy command needs 3 parameters !")
893 raise Exception ("Copy failed from offset 0x%08X to offset 0x%08X!" % (src
, dest
))
895 print "Copied %d bytes from offset 0x%08X ~ offset 0x%08X # %s" % (clen
, src
, dest
, comment
)
897 raise Exception ("Unknown command %s!" % command
)
900 except Exception as (ex
):
901 print "ERROR: %s" % ex
904 if __name__
== '__main__':