]>
git.proxmox.com Git - mirror_edk2.git/blob - IntelFspPkg/Tools/PatchFv.py
3 # Copyright (c) 2014, 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.
18 def readDataFromFile (binfile
, offset
, len=1):
19 fd
= open(binfile
, "r+b")
20 fsize
= os
.path
.getsize(binfile
)
21 offval
= offset
& 0xFFFFFFFF
22 if (offval
& 0x80000000):
23 offval
= fsize
- (0xFFFFFFFF - offval
+ 1)
25 bytearray
= [ord(b
) for b
in fd
.read(len)]
29 value
= value
<< 8 | bytearray
[idx
]
34 def patchDataInFile (binfile
, offset
, value
, len=1):
35 fd
= open(binfile
, "r+b")
36 fsize
= os
.path
.getsize(binfile
)
37 offval
= offset
& 0xFFFFFFFF
38 if (offval
& 0x80000000):
39 offval
= fsize
- (0xFFFFFFFF - offval
+ 1)
43 bytearray
.append(value
& 0xFF)
47 fd
.write("".join(chr(b
) for b
in bytearray
))
54 self
.dictSymbolAddress
= {}
55 self
.dictGuidNameXref
= {}
56 self
.dictFfsOffset
= {}
57 self
.dictVariable
= {}
61 self
.fdBase
= 0xFFFFFFFF
64 self
.parenthesisOpenSet
= '([{<'
65 self
.parenthesisCloseSet
= ')]}>'
73 def createDicts (self
, fvDir
, fvNames
):
74 if not os
.path
.isdir(fvDir
):
75 raise Exception ("'%s' is not a valid directory!" % FvDir
)
77 xrefFile
= os
.path
.join(fvDir
, "Guid.xref")
78 if not os
.path
.exists(xrefFile
):
79 raise Exception("Cannot open GUID Xref file '%s'!" % xrefFile
)
81 self
.dictGuidNameXref
= {}
82 self
.parseGuidXrefFile(xrefFile
)
84 fvList
= fvNames
.split(":")
89 fdFile
= os
.path
.join(fvDir
, fdBase
.strip() + ".fd")
90 if not os
.path
.exists(fdFile
):
91 raise Exception("Cannot open FD file '%s'!" % fdFile
)
94 self
.fdSize
= os
.path
.getsize(fdFile
)
96 infFile
= os
.path
.join(fvDir
, fvList
[0].strip()) + ".inf"
97 if not os
.path
.exists(infFile
):
98 raise Exception("Cannot open INF file '%s'!" % infFile
)
100 self
.parseInfFile(infFile
)
102 self
.dictVariable
= {}
103 self
.dictVariable
["FDSIZE"] = self
.fdSize
104 self
.dictVariable
["FDBASE"] = self
.fdBase
106 self
.dictSymbolAddress
= {}
107 self
.dictFfsOffset
= {}
110 fvFile
= os
.path
.join(fvDir
, file.strip()) + ".Fv"
111 mapFile
= fvFile
+ ".map"
112 if not os
.path
.exists(mapFile
):
113 raise Exception("Cannot open MAP file '%s'!" % mapFile
)
115 self
.parseFvMapFile(mapFile
)
117 fvTxtFile
= fvFile
+ ".txt"
118 if not os
.path
.exists(fvTxtFile
):
119 raise Exception("Cannot open FV TXT file '%s'!" % fvTxtFile
)
121 self
.parseFvTxtFile(fvTxtFile
)
123 ffsDir
= os
.path
.join(fvDir
, "Ffs")
124 if (os
.path
.isdir(ffsDir
)):
125 for item
in os
.listdir(ffsDir
):
126 if len(item
) <= 0x24:
128 mapFile
=os
.path
.join(ffsDir
, item
, "%s.map" % item
[0:0x24])
129 if not os
.path
.exists(mapFile
):
131 self
.parseModMapFile(item
[0x24:], mapFile
)
135 def getFvOffsetInFd(self
, fvFile
):
136 fvHandle
= open(fvFile
, "r+b")
137 fdHandle
= open(self
.fdFile
, "r+b")
138 offset
= fdHandle
.read().find(fvHandle
.read(0x70))
142 raise Exception("Could not locate FV file %s in FD!" % fvFile
)
145 def parseInfFile(self
, infFile
):
146 fvOffset
= self
.getFvOffsetInFd(infFile
[0:-4] + ".Fv")
147 fdIn
= open(infFile
, "r")
148 rptLine
= fdIn
.readline()
149 self
.fdBase
= 0xFFFFFFFF
150 while (rptLine
!= "" ):
151 #EFI_BASE_ADDRESS = 0xFFFDF400
152 match
= re
.match("^EFI_BASE_ADDRESS\s*=\s*(0x[a-fA-F0-9]+)", rptLine
)
153 if match
is not None:
154 self
.fdBase
= int(match
.group(1), 16) - fvOffset
155 rptLine
= fdIn
.readline()
157 if self
.fdBase
== 0xFFFFFFFF:
158 raise Exception("Could not find EFI_BASE_ADDRESS in INF file!" % fvFile
)
161 def parseFvTxtFile(self
, fvTxtFile
):
162 fvOffset
= self
.getFvOffsetInFd(fvTxtFile
[0:-4])
163 fdIn
= open(fvTxtFile
, "r")
164 rptLine
= fdIn
.readline()
165 while (rptLine
!= "" ):
166 match
= re
.match("(0x[a-fA-F0-9]+)\s([0-9a-fA-F\-]+)", rptLine
)
167 if match
is not None:
168 self
.dictFfsOffset
[match
.group(2)] = "0x%08X" % (int(match
.group(1), 16) + fvOffset
)
169 rptLine
= fdIn
.readline()
173 def parseFvMapFile(self
, mapFile
):
174 fdIn
= open(mapFile
, "r")
175 rptLine
= fdIn
.readline()
177 while (rptLine
!= "" ):
178 if rptLine
[0] != ' ':
179 #DxeIpl (Fixed Flash Address, BaseAddress=0x00fffb4310, EntryPoint=0x00fffb4958)
180 #(GUID=86D70125-BAA3-4296-A62F-602BEBBB9081 .textbaseaddress=0x00fffb4398 .databaseaddress=0x00fffb4178)
181 match
= re
.match("([_a-zA-Z0-9\-]+)\s\(.+BaseAddress=(0x[0-9a-fA-F]+),\s+EntryPoint=(0x[0-9a-fA-F]+)\)", rptLine
)
182 if match
is not None:
183 modName
= match
.group(1)
184 if len(modName
) == 36:
185 modName
= self
.dictGuidNameXref
[modName
.upper()]
186 self
.dictModBase
['%s:BASE' % modName
] = int (match
.group(2), 16)
187 self
.dictModBase
['%s:ENTRY' % modName
] = int (match
.group(3), 16)
188 match
= re
.match("\(GUID=([A-Z0-9\-]+)\s+\.textbaseaddress=(0x[0-9a-fA-F]+)\s+\.databaseaddress=(0x[0-9a-fA-F]+)\)", rptLine
)
189 if match
is not None:
190 modName
= match
.group(1)
191 if len(modName
) == 36:
192 modName
= self
.dictGuidNameXref
[modName
.upper()]
193 self
.dictModBase
['%s:TEXT' % modName
] = int (match
.group(2), 16)
194 self
.dictModBase
['%s:DATA' % modName
] = int (match
.group(3), 16)
196 # 0x00fff8016c __ModuleEntryPoint
197 match
= re
.match("^\s+(0x[a-z0-9]+)\s+([_a-zA-Z0-9]+)", rptLine
)
198 if match
is not None:
199 self
.dictSymbolAddress
["%s:%s"%(modName
, match
.group(2))] = match
.group(1)
200 rptLine
= fdIn
.readline()
204 def parseModMapFile(self
, moduleName
, mapFile
):
206 fdIn
= open(mapFile
, "r")
207 reportLine
= fdIn
.readline()
208 if reportLine
.strip().find("Archive member included because of file (symbol)") != -1:
210 # 0x0000000000001d55 IoRead8
211 patchMapFileMatchString
= "\s+(0x[0-9a-fA-F]{16})\s+([^\s][^0x][_a-zA-Z0-9\-]+)\s"
212 matchKeyGroupIndex
= 2
213 matchSymbolGroupIndex
= 1
214 moduleEntryPoint
= "_ModuleEntryPoint"
217 #0003:00000190 _gComBase 00007a50 SerialPo
218 patchMapFileMatchString
= "^\s[0-9a-fA-F]{4}:[0-9a-fA-F]{8}\s+(\w+)\s+([0-9a-fA-F]{8}\s+)"
219 matchKeyGroupIndex
= 1
220 matchSymbolGroupIndex
= 2
221 moduleEntryPoint
= "__ModuleEntryPoint"
222 while (reportLine
!= "" ):
223 match
= re
.match(patchMapFileMatchString
, reportLine
)
224 if match
is not None:
225 modSymbols
[match
.group(matchKeyGroupIndex
)] = match
.group(matchSymbolGroupIndex
)
226 reportLine
= fdIn
.readline()
229 if not moduleEntryPoint
in modSymbols
:
232 modEntry
= '%s:%s' % (moduleName
,moduleEntryPoint
)
233 if not modEntry
in self
.dictSymbolAddress
:
234 modKey
= '%s:ENTRY' % moduleName
235 if modKey
in self
.dictModBase
:
236 baseOffset
= self
.dictModBase
['%s:ENTRY' % moduleName
] - int(modSymbols
[moduleEntryPoint
], 16)
240 baseOffset
= int(self
.dictSymbolAddress
[modEntry
], 16) - int(modSymbols
[moduleEntryPoint
], 16)
241 for symbol
in modSymbols
:
242 fullSym
= "%s:%s" % (moduleName
, symbol
)
243 if not fullSym
in self
.dictSymbolAddress
:
244 self
.dictSymbolAddress
[fullSym
] = "0x00%08x" % (baseOffset
+ int(modSymbols
[symbol
], 16))
247 def parseGuidXrefFile(self
, xrefFile
):
248 fdIn
= open(xrefFile
, "r")
249 rptLine
= fdIn
.readline()
250 while (rptLine
!= "" ):
251 match
= re
.match("([0-9a-fA-F\-]+)\s([_a-zA-Z0-9]+)", rptLine
)
252 if match
is not None:
253 self
.dictGuidNameXref
[match
.group(1).upper()] = match
.group(2)
254 rptLine
= fdIn
.readline()
260 return self
.string
[self
.index
]
265 return self
.index
== len(self
.string
)
271 while not self
.isLast():
272 if self
.getCurr() in ' \t':
277 def parseValue(self
):
280 while not self
.isLast():
281 char
= self
.getCurr()
282 if char
.lower() in '_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:-':
289 partList
= var
.split(':')
290 if len(partList
) != 2:
291 raise Exception("Unrecognized expression %s" % var
)
292 modName
= partList
[0]
294 if ('-' not in modName
) and (modOff
[0] in '0123456789'):
296 var
= self
.getModGuid(modName
) + ":" + modOff
297 if '-' in var
: # GUID:OFFSET
298 value
= self
.getGuidOff(var
)
300 value
= self
.getSymbols(var
)
303 if var
[0] in '0123456789':
304 value
= self
.getNumber(var
)
306 value
= self
.getVariable(var
)
309 def parseSingleOp(self
):
311 char
= self
.getCurr()
314 return ~self
.parseBrace()
316 return self
.parseValue()
318 def parseBrace(self
):
320 char
= self
.getCurr()
321 parenthesisType
= self
.parenthesisOpenSet
.find(char
)
322 if parenthesisType
>= 0:
324 value
= self
.parseExpr()
326 if self
.getCurr() != self
.parenthesisCloseSet
[parenthesisType
]:
327 raise Exception("No closing brace")
329 if parenthesisType
== 1: # [ : Get content
330 value
= self
.getContent(value
)
331 elif parenthesisType
== 2: # { : To address
332 value
= self
.toAddress(value
)
333 elif parenthesisType
== 3: # < : To offset
334 value
= self
.toOffset(value
)
337 return self
.parseSingleOp()
340 values
= [self
.parseBrace()]
343 char
= self
.getCurr()
346 values
.append(self
.parseBrace())
354 def parseAndOr(self
):
355 values
= [self
.parseMul()]
360 char
= self
.getCurr()
363 values
.append(self
.parseMul())
366 div_index
= self
.index
368 values
.append(self
.parseMul())
382 def parseAddMinus(self
):
383 values
= [self
.parseAndOr()]
386 char
= self
.getCurr()
389 values
.append(self
.parseAndOr())
392 values
.append(-1 * self
.parseAndOr())
398 return self
.parseAddMinus()
401 value
= self
.parseExpr()
403 if not self
.isLast():
404 raise Exception("Unexpected character found '%s'" % self
.getCurr())
407 def getModGuid(self
, var
):
408 guid
= (guid
for guid
,name
in self
.dictGuidNameXref
.items() if name
==var
)
412 raise Exception("Unknown module name %s !" % var
)
415 def getVariable(self
, var
):
416 value
= self
.dictVariable
.get(var
, None)
418 raise Exception("Unrecognized variable '%s'" % var
)
421 def getNumber(self
, var
):
423 if var
.startswith('0x'): # HEX
429 def getContent(self
, value
):
430 if (value
>= self
.fdBase
) and (value
< self
.fdBase
+ self
.fdSize
):
431 value
= value
- self
.fdBase
432 if value
>= self
.fdSize
:
433 raise Exception("Invalid file offset 0x%08x !" % value
)
434 return readDataFromFile (self
.fdFile
, value
, 4)
436 def toAddress(self
, value
):
437 if value
< self
.fdSize
:
438 value
= value
+ self
.fdBase
441 def toOffset(self
, value
):
442 if value
> self
.fdBase
:
443 value
= value
- self
.fdBase
446 def getGuidOff(self
, value
):
448 symbolName
= value
.split(':')
449 if len(symbolName
) == 2 and self
.dictFfsOffset
.has_key(symbolName
[0]):
450 value
= (int(self
.dictFfsOffset
[symbolName
[0]], 16) + int(symbolName
[1], 16)) & 0xFFFFFFFF
452 raise Exception("Unknown GUID %s !" % value
)
455 def getSymbols(self
, value
):
456 if self
.dictSymbolAddress
.has_key(value
):
458 ret
= int (self
.dictSymbolAddress
[value
], 16)
460 raise Exception("Unknown symbol %s !" % value
)
463 def evaluate(self
, expression
, isOffset
):
466 self
.string
= expression
467 value
= self
.getResult()
470 # Consider it as an address first
471 if (value
>= self
.fdBase
) and (value
< self
.fdBase
+ self
.fdSize
):
472 value
= value
- self
.fdBase
473 if value
& 0x80000000:
474 # Consider it as a negative offset next
475 offset
= (~value
& 0xFFFFFFFF) + 1
476 if offset
< self
.fdSize
:
477 value
= self
.fdSize
- offset
478 if value
>= self
.fdSize
:
479 raise Exception("Invalid offset expression !")
480 return value
& 0xFFFFFFFF
483 print "Usage: \n\tPatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch \"Offset, Value\""
487 # Parse the options and args
489 symTables
= Symbols()
491 if len(sys
.argv
) < 4:
495 if symTables
.createDicts(sys
.argv
[1], sys
.argv
[2]) != 0:
496 print "ERROR: Failed to create symbol dictionary!!"
499 fdFile
= symTables
.getFdFile()
500 fdSize
= symTables
.getFdSize()
504 for fvFile
in sys
.argv
[3:]:
505 items
= fvFile
.split(",")
507 raise Exception("Expect more arguments for '%s'!" % fvFile
)
514 if item
.startswith("@"):
516 elif item
.startswith("$"):
523 params
.append (symTables
.evaluate(item
, isOffset
))
527 if len (params
) == 2:
530 oldvalue
= readDataFromFile(fdFile
, offset
, 4)
531 ret
= patchDataInFile (fdFile
, offset
, value
, 4) - 4
533 raise Exception ("Patch command needs 2 parameters !")
536 raise Exception ("Patch failed for offset 0x%08X" % offset
)
538 print "Patched offset 0x%08X:[%08X] with value 0x%08X # %s" % (offset
, oldvalue
, value
, comment
)
540 elif command
== "COPY":
541 # Copy binary block from source to destination
542 if len (params
) == 3:
543 src
= symTables
.toOffset(params
[0])
544 dest
= symTables
.toOffset(params
[1])
545 clen
= symTables
.toOffset(params
[2])
546 if (dest
+ clen
<= fdSize
) and (src
+ clen
<= fdSize
):
547 oldvalue
= readDataFromFile(fdFile
, src
, clen
)
548 ret
= patchDataInFile (fdFile
, dest
, oldvalue
, clen
) - clen
550 raise Exception ("Copy command OFFSET or LENGTH parameter is invalid !")
552 raise Exception ("Copy command needs 3 parameters !")
555 raise Exception ("Copy failed from offset 0x%08X to offset 0x%08X!" % (src
, dest
))
557 print "Copied %d bytes from offset 0x%08X ~ offset 0x%08X # %s" % (clen
, src
, dest
, comment
)
559 raise Exception ("Unknown command %s!" % command
)
562 except Exception as (ex
):
563 print "ERROR: %s" % ex
566 if __name__
== '__main__':