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