]>
git.proxmox.com Git - mirror_edk2.git/blob - IntelFspPkg/Tools/PatchFv.py
3 # Copyright (c) 2014 - 2015, Intel Corporation. All rights reserved.<BR>
4 # This program and the accompanying materials are licensed and made available under
5 # the terms and conditions of the BSD License that accompanies this distribution.
6 # The full text of the license may be found at
7 # http://opensource.org/licenses/bsd-license.php.
9 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
21 # param [in] binfile Binary file
22 # param [in] offset Offset
23 # param [in] len Length
27 def readDataFromFile (binfile
, offset
, len=1):
28 fd
= open(binfile
, "r+b")
29 fsize
= os
.path
.getsize(binfile
)
30 offval
= offset
& 0xFFFFFFFF
31 if (offval
& 0x80000000):
32 offval
= fsize
- (0xFFFFFFFF - offval
+ 1)
34 bytearray
= [ord(b
) for b
in fd
.read(len)]
38 value
= value
<< 8 | bytearray
[idx
]
44 # Check FSP header is valid or not
46 # param [in] binfile Binary file
48 # retval boolean True: valid; False: invalid
50 def IsFspHeaderValid (binfile
):
51 fd
= open (binfile
, "rb")
52 bindat
= fd
.read(0x200) # only read first 0x200 bytes
54 HeaderList
= ['FSPH' , 'FSPP' , 'FSPE'] # Check 'FSPH', 'FSPP', and 'FSPE' in the FSP header
56 for each
in HeaderList
:
58 idx
= bindat
.index(each
)
61 OffsetList
.append(idx
)
62 if not OffsetList
[0] or not OffsetList
[1]: # If 'FSPH' or 'FSPP' is missing, it will return false
64 Revision
= ord(bindat
[OffsetList
[0] + 0x0B])
66 # if revision is bigger than 1, it means it is FSP v1.1 or greater revision, which must contain 'FSPE'.
68 if Revision
> 1 and not OffsetList
[2]:
69 return False # If FSP v1.1 or greater without 'FSPE', then return false
75 # param [in] binfile Binary file
76 # param [in] offset Offset
77 # param [in] value Patch value
78 # param [in] len Length
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)
91 bytearray
.append(value
& 0xFF)
95 fd
.write("".join(chr(b
) for b
in bytearray
))
102 self
.dictSymbolAddress
= {}
103 self
.dictGuidNameXref
= {}
104 self
.dictFfsOffset
= {}
105 self
.dictVariable
= {}
106 self
.dictModBase
= {}
109 self
.fdBase
= 0xFFFFFFFF
112 self
.parenthesisOpenSet
= '([{<'
113 self
.parenthesisCloseSet
= ')]}>'
118 # retval self.fdFile Retrieve FD file
120 def getFdFile (self
):
126 # retval self.fdSize Retrieve the size of FD file
128 def getFdSize (self
):
132 # Create dictionaries
134 # param [in] fvDir FV's directory
135 # param [in] fvNames All FV's names
137 # retval 0 Created dictionaries successfully
139 def createDicts (self
, fvDir
, fvNames
):
141 # If the fvDir is not a dirctory, then raise an exception
143 if not os
.path
.isdir(fvDir
):
144 raise Exception ("'%s' is not a valid directory!" % FvDir
)
147 # If the Guid.xref is not existing in fvDir, then raise an exception
149 xrefFile
= os
.path
.join(fvDir
, "Guid.xref")
150 if not os
.path
.exists(xrefFile
):
151 raise Exception("Cannot open GUID Xref file '%s'!" % xrefFile
)
154 # Add GUID reference to dictionary
156 self
.dictGuidNameXref
= {}
157 self
.parseGuidXrefFile(xrefFile
)
160 # Split up each FV from fvNames and get the fdBase
162 fvList
= fvNames
.split(":")
163 fdBase
= fvList
.pop()
165 fvList
.append(fdBase
)
168 # If the FD file is not existing, then raise an exception
170 fdFile
= os
.path
.join(fvDir
, fdBase
.strip() + ".fd")
171 if not os
.path
.exists(fdFile
):
172 raise Exception("Cannot open FD file '%s'!" % fdFile
)
175 # Get the size of the FD file
178 self
.fdSize
= os
.path
.getsize(fdFile
)
181 # If the INF file, which is the first element of fvList, is not existing, then raise an exception
183 infFile
= os
.path
.join(fvDir
, fvList
[0].strip()) + ".inf"
184 if not os
.path
.exists(infFile
):
185 raise Exception("Cannot open INF file '%s'!" % infFile
)
188 # Parse INF file in order to get fdBase and then assign those values to dictVariable
190 self
.parseInfFile(infFile
)
191 self
.dictVariable
= {}
192 self
.dictVariable
["FDSIZE"] = self
.fdSize
193 self
.dictVariable
["FDBASE"] = self
.fdBase
196 # Collect information from FV MAP file and FV TXT file then
197 # put them into dictionaries
199 self
.dictSymbolAddress
= {}
200 self
.dictFfsOffset
= {}
204 # If the .Fv.map file is not existing, then raise an exception.
205 # Otherwise, parse FV MAP file
207 fvFile
= os
.path
.join(fvDir
, file.strip()) + ".Fv"
208 mapFile
= fvFile
+ ".map"
209 if not os
.path
.exists(mapFile
):
210 raise Exception("Cannot open MAP file '%s'!" % mapFile
)
212 self
.parseFvMapFile(mapFile
)
215 # If the .Fv.txt file is not existing, then raise an exception.
216 # Otherwise, parse FV TXT file
218 fvTxtFile
= fvFile
+ ".txt"
219 if not os
.path
.exists(fvTxtFile
):
220 raise Exception("Cannot open FV TXT file '%s'!" % fvTxtFile
)
222 self
.parseFvTxtFile(fvTxtFile
)
225 # Search all MAP files in FFS directory if it exists then parse MOD MAP file
227 ffsDir
= os
.path
.join(fvDir
, "Ffs")
228 if (os
.path
.isdir(ffsDir
)):
229 for item
in os
.listdir(ffsDir
):
230 if len(item
) <= 0x24:
232 mapFile
=os
.path
.join(ffsDir
, item
, "%s.map" % item
[0:0x24])
233 if not os
.path
.exists(mapFile
):
235 self
.parseModMapFile(item
[0x24:], mapFile
)
240 # Get FV offset in FD file
242 # param [in] fvFile FV file
244 # retval offset Got FV offset successfully
246 def getFvOffsetInFd(self
, fvFile
):
248 # Check if the first 0x70 bytes of fvFile can be found in fdFile
250 fvHandle
= open(fvFile
, "r+b")
251 fdHandle
= open(self
.fdFile
, "r+b")
252 offset
= fdHandle
.read().find(fvHandle
.read(0x70))
256 raise Exception("Could not locate FV file %s in FD!" % fvFile
)
262 # param [in] infFile INF file
264 # retval 0 Parsed INF file successfully
266 def parseInfFile(self
, infFile
):
268 # Get FV offset and search EFI_BASE_ADDRESS in the FD file
269 # then assign the value of EFI_BASE_ADDRESS to fdBase
271 fvOffset
= self
.getFvOffsetInFd(infFile
[0:-4] + ".Fv")
272 fdIn
= open(infFile
, "r")
273 rptLine
= fdIn
.readline()
274 self
.fdBase
= 0xFFFFFFFF
275 while (rptLine
!= "" ):
276 #EFI_BASE_ADDRESS = 0xFFFDF400
277 match
= re
.match("^EFI_BASE_ADDRESS\s*=\s*(0x[a-fA-F0-9]+)", rptLine
)
278 if match
is not None:
279 self
.fdBase
= int(match
.group(1), 16) - fvOffset
280 rptLine
= fdIn
.readline()
282 if self
.fdBase
== 0xFFFFFFFF:
283 raise Exception("Could not find EFI_BASE_ADDRESS in INF file!" % fvFile
)
289 # param [in] fvTxtFile .Fv.txt file
291 # retval 0 Parsed FV TXT file successfully
293 def parseFvTxtFile(self
, fvTxtFile
):
295 # Get information from .Fv.txt in order to create a dictionary
297 # self.dictFfsOffset[912740BE-2284-4734-B971-84B027353F0C] = 0x000D4078
299 fvOffset
= self
.getFvOffsetInFd(fvTxtFile
[0:-4])
300 fdIn
= open(fvTxtFile
, "r")
301 rptLine
= fdIn
.readline()
302 while (rptLine
!= "" ):
303 match
= re
.match("(0x[a-fA-F0-9]+)\s([0-9a-fA-F\-]+)", rptLine
)
304 if match
is not None:
305 self
.dictFfsOffset
[match
.group(2)] = "0x%08X" % (int(match
.group(1), 16) + fvOffset
)
306 rptLine
= fdIn
.readline()
313 # param [in] mapFile .Fv.map file
315 # retval 0 Parsed FV MAP file successfully
317 def parseFvMapFile(self
, mapFile
):
319 # Get information from .Fv.map in order to create dictionaries
321 # self.dictModBase[FspSecCore:BASE] = 4294592776 (0xfffa4908)
322 # self.dictModBase[FspSecCore:ENTRY] = 4294606552 (0xfffa7ed8)
323 # self.dictModBase[FspSecCore:TEXT] = 4294593080 (0xfffa4a38)
324 # self.dictModBase[FspSecCore:DATA] = 4294612280 (0xfffa9538)
325 # self.dictSymbolAddress[FspSecCore:_SecStartup] = 0x00fffa4a38
327 fdIn
= open(mapFile
, "r")
328 rptLine
= fdIn
.readline()
330 while (rptLine
!= "" ):
331 if rptLine
[0] != ' ':
332 #DxeIpl (Fixed Flash Address, BaseAddress=0x00fffb4310, EntryPoint=0x00fffb4958)
333 #(GUID=86D70125-BAA3-4296-A62F-602BEBBB9081 .textbaseaddress=0x00fffb4398 .databaseaddress=0x00fffb4178)
334 match
= re
.match("([_a-zA-Z0-9\-]+)\s\(.+BaseAddress=(0x[0-9a-fA-F]+),\s+EntryPoint=(0x[0-9a-fA-F]+)\)", rptLine
)
335 if match
is not None:
336 modName
= match
.group(1)
337 if len(modName
) == 36:
338 modName
= self
.dictGuidNameXref
[modName
.upper()]
339 self
.dictModBase
['%s:BASE' % modName
] = int (match
.group(2), 16)
340 self
.dictModBase
['%s:ENTRY' % modName
] = int (match
.group(3), 16)
341 match
= re
.match("\(GUID=([A-Z0-9\-]+)\s+\.textbaseaddress=(0x[0-9a-fA-F]+)\s+\.databaseaddress=(0x[0-9a-fA-F]+)\)", rptLine
)
342 if match
is not None:
343 modName
= match
.group(1)
344 if len(modName
) == 36:
345 modName
= self
.dictGuidNameXref
[modName
.upper()]
346 self
.dictModBase
['%s:TEXT' % modName
] = int (match
.group(2), 16)
347 self
.dictModBase
['%s:DATA' % modName
] = int (match
.group(3), 16)
349 # 0x00fff8016c __ModuleEntryPoint
350 match
= re
.match("^\s+(0x[a-z0-9]+)\s+([_a-zA-Z0-9]+)", rptLine
)
351 if match
is not None:
352 self
.dictSymbolAddress
["%s:%s"%(modName
, match
.group(2))] = match
.group(1)
353 rptLine
= fdIn
.readline()
360 # param [in] moduleName Module name
361 # param [in] mapFile .Fv.map file
363 # retval 0 Parsed MOD MAP file successfully
364 # retval 1 There is no moduleEntryPoint in modSymbols
366 def parseModMapFile(self
, moduleName
, mapFile
):
368 # Get information from mapFile by moduleName in order to create a dictionary
370 # self.dictSymbolAddress[FspSecCore:___guard_fids_count] = 0x00fffa4778
373 fdIn
= open(mapFile
, "r")
374 reportLines
= fdIn
.readlines()
377 moduleEntryPoint
= "__ModuleEntryPoint"
378 reportLine
= reportLines
[0]
379 if reportLine
.strip().find("Archive member included") != -1:
381 # 0x0000000000001d55 IoRead8
382 patchMapFileMatchString
= "\s+(0x[0-9a-fA-F]{16})\s+([^\s][^0x][_a-zA-Z0-9\-]+)\s"
383 matchKeyGroupIndex
= 2
384 matchSymbolGroupIndex
= 1
388 #0003:00000190 _gComBase 00007a50 SerialPo
389 patchMapFileMatchString
= "^\s[0-9a-fA-F]{4}:[0-9a-fA-F]{8}\s+(\w+)\s+([0-9a-fA-F]{8}\s+)"
390 matchKeyGroupIndex
= 1
391 matchSymbolGroupIndex
= 2
394 for reportLine
in reportLines
:
395 match
= re
.match(patchMapFileMatchString
, reportLine
)
396 if match
is not None:
397 modSymbols
[prefix
+ match
.group(matchKeyGroupIndex
)] = match
.group(matchSymbolGroupIndex
)
399 # Handle extra module patchable PCD variable in Linux map since it might have different format
400 # .data._gPcd_BinaryPatch_PcdVpdBaseAddress
401 # 0x0000000000003714 0x4 /tmp/ccmytayk.ltrans1.ltrans.o
403 if matchSymbolGroupIndex
== 1:
404 for reportLine
in reportLines
:
407 pcdName
= match
.group(1)
408 match
= re
.match("\s+(0x[0-9a-fA-F]{16})\s+", reportLine
)
409 if match
is not None:
410 modSymbols
[prefix
+ pcdName
] = match
.group(1)
412 match
= re
.match("^\s\.data\.(_gPcd_BinaryPatch[_a-zA-Z0-9\-]+)", reportLine
)
413 if match
is not None:
417 if not moduleEntryPoint
in modSymbols
:
420 modEntry
= '%s:%s' % (moduleName
,moduleEntryPoint
)
421 if not modEntry
in self
.dictSymbolAddress
:
422 modKey
= '%s:ENTRY' % moduleName
423 if modKey
in self
.dictModBase
:
424 baseOffset
= self
.dictModBase
['%s:ENTRY' % moduleName
] - int(modSymbols
[moduleEntryPoint
], 16)
428 baseOffset
= int(self
.dictSymbolAddress
[modEntry
], 16) - int(modSymbols
[moduleEntryPoint
], 16)
429 for symbol
in modSymbols
:
430 fullSym
= "%s:%s" % (moduleName
, symbol
)
431 if not fullSym
in self
.dictSymbolAddress
:
432 self
.dictSymbolAddress
[fullSym
] = "0x00%08x" % (baseOffset
+ int(modSymbols
[symbol
], 16))
436 # Parse Guid.xref file
438 # param [in] xrefFile the full directory of Guid.xref file
440 # retval 0 Parsed Guid.xref file successfully
442 def parseGuidXrefFile(self
, xrefFile
):
444 # Get information from Guid.xref in order to create a GuidNameXref dictionary
445 # The dictGuidNameXref, for example, will be like
446 # dictGuidNameXref [1BA0062E-C779-4582-8566-336AE8F78F09] = FspSecCore
448 fdIn
= open(xrefFile
, "r")
449 rptLine
= fdIn
.readline()
450 while (rptLine
!= "" ):
451 match
= re
.match("([0-9a-fA-F\-]+)\s([_a-zA-Z0-9]+)", rptLine
)
452 if match
is not None:
453 self
.dictGuidNameXref
[match
.group(1).upper()] = match
.group(2)
454 rptLine
= fdIn
.readline()
459 # Get current character
461 # retval elf.string[self.index]
462 # retval '' Exception
466 return self
.string
[self
.index
]
471 # Check to see if it is last index
476 return self
.index
== len(self
.string
)
488 while not self
.isLast():
489 if self
.getCurr() in ' \t':
499 def parseValue(self
):
502 while not self
.isLast():
503 char
= self
.getCurr()
504 if char
.lower() in '_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:-':
511 partList
= var
.split(':')
512 if len(partList
) != 2:
513 raise Exception("Unrecognized expression %s" % var
)
514 modName
= partList
[0]
516 if ('-' not in modName
) and (modOff
[0] in '0123456789'):
518 var
= self
.getModGuid(modName
) + ":" + modOff
519 if '-' in var
: # GUID:OFFSET
520 value
= self
.getGuidOff(var
)
522 value
= self
.getSymbols(var
)
525 if var
[0] in '0123456789':
526 value
= self
.getNumber(var
)
528 value
= self
.getVariable(var
)
532 # Parse single operation
534 # retval ~self.parseBrace() or self.parseValue()
536 def parseSingleOp(self
):
538 char
= self
.getCurr()
541 return ~self
.parseBrace()
543 return self
.parseValue()
546 # Parse symbol of Brace([, {, <)
548 # retval value or self.parseSingleOp()
550 def parseBrace(self
):
552 char
= self
.getCurr()
553 parenthesisType
= self
.parenthesisOpenSet
.find(char
)
554 if parenthesisType
>= 0:
556 value
= self
.parseExpr()
558 if self
.getCurr() != self
.parenthesisCloseSet
[parenthesisType
]:
559 raise Exception("No closing brace")
561 if parenthesisType
== 1: # [ : Get content
562 value
= self
.getContent(value
)
563 elif parenthesisType
== 2: # { : To address
564 value
= self
.toAddress(value
)
565 elif parenthesisType
== 3: # < : To offset
566 value
= self
.toOffset(value
)
569 return self
.parseSingleOp()
572 # Parse symbol of Multiplier(*)
574 # retval value or self.parseSingleOp()
577 values
= [self
.parseBrace()]
580 char
= self
.getCurr()
583 values
.append(self
.parseBrace())
592 # Parse symbol of And(&) and Or(|)
596 def parseAndOr(self
):
597 values
= [self
.parseMul()]
602 char
= self
.getCurr()
605 values
.append(self
.parseMul())
608 div_index
= self
.index
610 values
.append(self
.parseMul())
625 # Parse symbol of Add(+) and Minus(-)
629 def parseAddMinus(self
):
630 values
= [self
.parseAndOr()]
633 char
= self
.getCurr()
636 values
.append(self
.parseAndOr())
639 values
.append(-1 * self
.parseAndOr())
647 # retval self.parseAddMinus()
650 return self
.parseAddMinus()
658 value
= self
.parseExpr()
660 if not self
.isLast():
661 raise Exception("Unexpected character found '%s'" % self
.getCurr())
669 def getModGuid(self
, var
):
670 guid
= (guid
for guid
,name
in self
.dictGuidNameXref
.items() if name
==var
)
674 raise Exception("Unknown module name %s !" % var
)
682 def getVariable(self
, var
):
683 value
= self
.dictVariable
.get(var
, None)
685 raise Exception("Unrecognized variable '%s'" % var
)
693 def getNumber(self
, var
):
695 if var
.startswith('0x'): # HEX
708 def getContent(self
, value
):
709 if (value
>= self
.fdBase
) and (value
< self
.fdBase
+ self
.fdSize
):
710 value
= value
- self
.fdBase
711 if value
>= self
.fdSize
:
712 raise Exception("Invalid file offset 0x%08x !" % value
)
713 return readDataFromFile (self
.fdFile
, value
, 4)
716 # Change value to address
722 def toAddress(self
, value
):
723 if value
< self
.fdSize
:
724 value
= value
+ self
.fdBase
728 # Change value to offset
734 def toOffset(self
, value
):
735 if value
> self
.fdBase
:
736 value
= value
- self
.fdBase
746 def getGuidOff(self
, value
):
748 symbolName
= value
.split(':')
749 if len(symbolName
) == 2 and self
.dictFfsOffset
.has_key(symbolName
[0]):
750 value
= (int(self
.dictFfsOffset
[symbolName
[0]], 16) + int(symbolName
[1], 16)) & 0xFFFFFFFF
752 raise Exception("Unknown GUID %s !" % value
)
762 def getSymbols(self
, value
):
763 if self
.dictSymbolAddress
.has_key(value
):
765 ret
= int (self
.dictSymbolAddress
[value
], 16)
767 raise Exception("Unknown symbol %s !" % value
)
773 # param [in] expression
774 # param [in] isOffset
776 # retval value & 0xFFFFFFFF
778 def evaluate(self
, expression
, isOffset
):
781 self
.string
= expression
782 value
= self
.getResult()
785 # Consider it as an address first
786 if (value
>= self
.fdBase
) and (value
< self
.fdBase
+ self
.fdSize
):
787 value
= value
- self
.fdBase
788 if value
& 0x80000000:
789 # Consider it as a negative offset next
790 offset
= (~value
& 0xFFFFFFFF) + 1
791 if offset
< self
.fdSize
:
792 value
= self
.fdSize
- offset
793 if value
>= self
.fdSize
:
794 raise Exception("Invalid offset expression !")
795 return value
& 0xFFFFFFFF
798 # Print out the usage
801 print "Usage: \n\tPatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch \"Offset, Value\""
805 # Parse the options and args
807 symTables
= Symbols()
810 # If the arguments are less than 4, then return an error.
812 if len(sys
.argv
) < 4:
817 # If it fails to create dictionaries, then return an error.
819 if symTables
.createDicts(sys
.argv
[1], sys
.argv
[2]) != 0:
820 print "ERROR: Failed to create symbol dictionary!!"
824 # Get FD file and size
826 fdFile
= symTables
.getFdFile()
827 fdSize
= symTables
.getFdSize()
831 # Check to see if FSP header is valid
833 ret
= IsFspHeaderValid(fdFile
)
835 raise Exception ("The FSP header is not valid. Stop patching FD.")
837 for fvFile
in sys
.argv
[3:]:
839 # Check to see if it has enough arguments
841 items
= fvFile
.split(",")
843 raise Exception("Expect more arguments for '%s'!" % fvFile
)
850 if item
.startswith("@"):
852 elif item
.startswith("$"):
860 # Parse symbols then append it to params
862 params
.append (symTables
.evaluate(item
, isOffset
))
865 # Patch a new value into FD file if it is not a command
869 if len (params
) == 2:
872 oldvalue
= readDataFromFile(fdFile
, offset
, 4)
873 ret
= patchDataInFile (fdFile
, offset
, value
, 4) - 4
875 raise Exception ("Patch command needs 2 parameters !")
878 raise Exception ("Patch failed for offset 0x%08X" % offset
)
880 print "Patched offset 0x%08X:[%08X] with value 0x%08X # %s" % (offset
, oldvalue
, value
, comment
)
882 elif command
== "COPY":
884 # Copy binary block from source to destination
886 if len (params
) == 3:
887 src
= symTables
.toOffset(params
[0])
888 dest
= symTables
.toOffset(params
[1])
889 clen
= symTables
.toOffset(params
[2])
890 if (dest
+ clen
<= fdSize
) and (src
+ clen
<= fdSize
):
891 oldvalue
= readDataFromFile(fdFile
, src
, clen
)
892 ret
= patchDataInFile (fdFile
, dest
, oldvalue
, clen
) - clen
894 raise Exception ("Copy command OFFSET or LENGTH parameter is invalid !")
896 raise Exception ("Copy command needs 3 parameters !")
899 raise Exception ("Copy failed from offset 0x%08X to offset 0x%08X!" % (src
, dest
))
901 print "Copied %d bytes from offset 0x%08X ~ offset 0x%08X # %s" % (clen
, src
, dest
, comment
)
903 raise Exception ("Unknown command %s!" % command
)
906 except Exception as (ex
):
907 print "ERROR: %s" % ex
910 if __name__
== '__main__':