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)
|
---|
365 | #(GUID=86D70125-BAA3-4296-A62F-602BEBBB9081 .textbaseaddress=0x00fffb4398 .databaseaddress=0x00fffb4178)
|
---|
366 | match = re.match("([_a-zA-Z0-9\-]+)\s\(.+BaseAddress=(0x[0-9a-fA-F]+),\s+EntryPoint=(0x[0-9a-fA-F]+)\)", rptLine)
|
---|
367 | if match is not None:
|
---|
368 | foundModHdr = True
|
---|
369 | modName = match.group(1)
|
---|
370 | if len(modName) == 36:
|
---|
371 | modName = self.dictGuidNameXref[modName.upper()]
|
---|
372 | self.dictModBase['%s:BASE' % modName] = int (match.group(2), 16)
|
---|
373 | self.dictModBase['%s:ENTRY' % modName] = int (match.group(3), 16)
|
---|
374 | match = re.match("\(GUID=([A-Z0-9\-]+)\s+\.textbaseaddress=(0x[0-9a-fA-F]+)\s+\.databaseaddress=(0x[0-9a-fA-F]+)\)", rptLine)
|
---|
375 | if match is not None:
|
---|
376 | if foundModHdr:
|
---|
377 | foundModHdr = False
|
---|
378 | else:
|
---|
379 | modName = match.group(1)
|
---|
380 | if len(modName) == 36:
|
---|
381 | modName = self.dictGuidNameXref[modName.upper()]
|
---|
382 | self.dictModBase['%s:TEXT' % modName] = int (match.group(2), 16)
|
---|
383 | self.dictModBase['%s:DATA' % modName] = int (match.group(3), 16)
|
---|
384 | else:
|
---|
385 | # 0x00fff8016c __ModuleEntryPoint
|
---|
386 | foundModHdr = False
|
---|
387 | match = re.match("^\s+(0x[a-z0-9]+)\s+([_a-zA-Z0-9]+)", rptLine)
|
---|
388 | if match is not None:
|
---|
389 | self.dictSymbolAddress["%s:%s"%(modName, match.group(2))] = match.group(1)
|
---|
390 | rptLine = fdIn.readline()
|
---|
391 | fdIn.close()
|
---|
392 | return 0
|
---|
393 |
|
---|
394 | #
|
---|
395 | # Parse MOD MAP file
|
---|
396 | #
|
---|
397 | # param [in] moduleName Module name
|
---|
398 | # param [in] mapFile .Fv.map file
|
---|
399 | #
|
---|
400 | # retval 0 Parsed MOD MAP file successfully
|
---|
401 | # retval 1 There is no moduleEntryPoint in modSymbols
|
---|
402 | #
|
---|
403 | def parseModMapFile(self, moduleName, mapFile):
|
---|
404 | #
|
---|
405 | # Get information from mapFile by moduleName in order to create a dictionary
|
---|
406 | # For example,
|
---|
407 | # self.dictSymbolAddress[FspSecCore:___guard_fids_count] = 0x00fffa4778
|
---|
408 | #
|
---|
409 | modSymbols = {}
|
---|
410 | fdIn = open(mapFile, "r")
|
---|
411 | reportLines = fdIn.readlines()
|
---|
412 | fdIn.close()
|
---|
413 |
|
---|
414 | moduleEntryPoint = "__ModuleEntryPoint"
|
---|
415 | reportLine = reportLines[0]
|
---|
416 | if reportLine.strip().find("Archive member included") != -1:
|
---|
417 | #GCC
|
---|
418 | # 0x0000000000001d55 IoRead8
|
---|
419 | patchMapFileMatchString = "\s+(0x[0-9a-fA-F]{16})\s+([^\s][^0x][_a-zA-Z0-9\-]+)\s"
|
---|
420 | matchKeyGroupIndex = 2
|
---|
421 | matchSymbolGroupIndex = 1
|
---|
422 | prefix = '_'
|
---|
423 | else:
|
---|
424 | #MSFT
|
---|
425 | #0003:00000190 _gComBase 00007a50 SerialPo
|
---|
426 | patchMapFileMatchString = "^\s[0-9a-fA-F]{4}:[0-9a-fA-F]{8}\s+(\w+)\s+([0-9a-fA-F]{8}\s+)"
|
---|
427 | matchKeyGroupIndex = 1
|
---|
428 | matchSymbolGroupIndex = 2
|
---|
429 | prefix = ''
|
---|
430 |
|
---|
431 | for reportLine in reportLines:
|
---|
432 | match = re.match(patchMapFileMatchString, reportLine)
|
---|
433 | if match is not None:
|
---|
434 | modSymbols[prefix + match.group(matchKeyGroupIndex)] = match.group(matchSymbolGroupIndex)
|
---|
435 |
|
---|
436 | # Handle extra module patchable PCD variable in Linux map since it might have different format
|
---|
437 | # .data._gPcd_BinaryPatch_PcdVpdBaseAddress
|
---|
438 | # 0x0000000000003714 0x4 /tmp/ccmytayk.ltrans1.ltrans.o
|
---|
439 | handleNext = False
|
---|
440 | if matchSymbolGroupIndex == 1:
|
---|
441 | for reportLine in reportLines:
|
---|
442 | if handleNext:
|
---|
443 | handleNext = False
|
---|
444 | pcdName = match.group(1)
|
---|
445 | match = re.match("\s+(0x[0-9a-fA-F]{16})\s+", reportLine)
|
---|
446 | if match is not None:
|
---|
447 | modSymbols[prefix + pcdName] = match.group(1)
|
---|
448 | else:
|
---|
449 | match = re.match("^\s\.data\.(_gPcd_BinaryPatch[_a-zA-Z0-9\-]+)", reportLine)
|
---|
450 | if match is not None:
|
---|
451 | handleNext = True
|
---|
452 | continue
|
---|
453 |
|
---|
454 | if not moduleEntryPoint in modSymbols:
|
---|
455 | return 1
|
---|
456 |
|
---|
457 | modEntry = '%s:%s' % (moduleName,moduleEntryPoint)
|
---|
458 | if not modEntry in self.dictSymbolAddress:
|
---|
459 | modKey = '%s:ENTRY' % moduleName
|
---|
460 | if modKey in self.dictModBase:
|
---|
461 | baseOffset = self.dictModBase['%s:ENTRY' % moduleName] - int(modSymbols[moduleEntryPoint], 16)
|
---|
462 | else:
|
---|
463 | return 2
|
---|
464 | else:
|
---|
465 | baseOffset = int(self.dictSymbolAddress[modEntry], 16) - int(modSymbols[moduleEntryPoint], 16)
|
---|
466 | for symbol in modSymbols:
|
---|
467 | fullSym = "%s:%s" % (moduleName, symbol)
|
---|
468 | if not fullSym in self.dictSymbolAddress:
|
---|
469 | self.dictSymbolAddress[fullSym] = "0x00%08x" % (baseOffset+ int(modSymbols[symbol], 16))
|
---|
470 | return 0
|
---|
471 |
|
---|
472 | #
|
---|
473 | # Parse Guid.xref file
|
---|
474 | #
|
---|
475 | # param [in] xrefFile the full directory of Guid.xref file
|
---|
476 | #
|
---|
477 | # retval 0 Parsed Guid.xref file successfully
|
---|
478 | #
|
---|
479 | def parseGuidXrefFile(self, xrefFile):
|
---|
480 | #
|
---|
481 | # Get information from Guid.xref in order to create a GuidNameXref dictionary
|
---|
482 | # The dictGuidNameXref, for example, will be like
|
---|
483 | # dictGuidNameXref [1BA0062E-C779-4582-8566-336AE8F78F09] = FspSecCore
|
---|
484 | #
|
---|
485 | fdIn = open(xrefFile, "r")
|
---|
486 | rptLine = fdIn.readline()
|
---|
487 | while (rptLine != "" ):
|
---|
488 | match = re.match("([0-9a-fA-F\-]+)\s([_a-zA-Z0-9]+)", rptLine)
|
---|
489 | if match is not None:
|
---|
490 | self.dictGuidNameXref[match.group(1).upper()] = match.group(2)
|
---|
491 | rptLine = fdIn.readline()
|
---|
492 | fdIn.close()
|
---|
493 | return 0
|
---|
494 |
|
---|
495 | #
|
---|
496 | # Get current character
|
---|
497 | #
|
---|
498 | # retval elf.string[self.index]
|
---|
499 | # retval '' Exception
|
---|
500 | #
|
---|
501 | def getCurr(self):
|
---|
502 | try:
|
---|
503 | return self.string[self.index]
|
---|
504 | except Exception:
|
---|
505 | return ''
|
---|
506 |
|
---|
507 | #
|
---|
508 | # Check to see if it is last index
|
---|
509 | #
|
---|
510 | # retval self.index
|
---|
511 | #
|
---|
512 | def isLast(self):
|
---|
513 | return self.index == len(self.string)
|
---|
514 |
|
---|
515 | #
|
---|
516 | # Move to next index
|
---|
517 | #
|
---|
518 | def moveNext(self):
|
---|
519 | self.index += 1
|
---|
520 |
|
---|
521 | #
|
---|
522 | # Skip space
|
---|
523 | #
|
---|
524 | def skipSpace(self):
|
---|
525 | while not self.isLast():
|
---|
526 | if self.getCurr() in ' \t':
|
---|
527 | self.moveNext()
|
---|
528 | else:
|
---|
529 | return
|
---|
530 |
|
---|
531 | #
|
---|
532 | # Parse value
|
---|
533 | #
|
---|
534 | # retval value
|
---|
535 | #
|
---|
536 | def parseValue(self):
|
---|
537 | self.skipSpace()
|
---|
538 | var = ''
|
---|
539 | while not self.isLast():
|
---|
540 | char = self.getCurr()
|
---|
541 | if char.lower() in '_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:-':
|
---|
542 | var += char
|
---|
543 | self.moveNext()
|
---|
544 | else:
|
---|
545 | break
|
---|
546 |
|
---|
547 | if ':' in var:
|
---|
548 | partList = var.split(':')
|
---|
549 | lenList = len(partList)
|
---|
550 | if lenList != 2 and lenList != 3:
|
---|
551 | raise Exception("Unrecognized expression %s" % var)
|
---|
552 | modName = partList[lenList-2]
|
---|
553 | modOff = partList[lenList-1]
|
---|
554 | if ('-' not in modName) and (modOff[0] in '0123456789'):
|
---|
555 | # MOD: OFFSET
|
---|
556 | var = self.getModGuid(modName) + ":" + modOff
|
---|
557 | if '-' in var: # GUID:OFFSET
|
---|
558 | value = self.getGuidOff(var)
|
---|
559 | else:
|
---|
560 | value = self.getSymbols(var)
|
---|
561 | self.synUsed = True
|
---|
562 | else:
|
---|
563 | if var[0] in '0123456789':
|
---|
564 | value = self.getNumber(var)
|
---|
565 | else:
|
---|
566 | value = self.getVariable(var)
|
---|
567 | return int(value)
|
---|
568 |
|
---|
569 | #
|
---|
570 | # Parse single operation
|
---|
571 | #
|
---|
572 | # retval ~self.parseBrace() or self.parseValue()
|
---|
573 | #
|
---|
574 | def parseSingleOp(self):
|
---|
575 | self.skipSpace()
|
---|
576 | char = self.getCurr()
|
---|
577 | if char == '~':
|
---|
578 | self.moveNext()
|
---|
579 | return ~self.parseBrace()
|
---|
580 | else:
|
---|
581 | return self.parseValue()
|
---|
582 |
|
---|
583 | #
|
---|
584 | # Parse symbol of Brace([, {, <)
|
---|
585 | #
|
---|
586 | # retval value or self.parseSingleOp()
|
---|
587 | #
|
---|
588 | def parseBrace(self):
|
---|
589 | self.skipSpace()
|
---|
590 | char = self.getCurr()
|
---|
591 | parenthesisType = self.parenthesisOpenSet.find(char)
|
---|
592 | if parenthesisType >= 0:
|
---|
593 | self.moveNext()
|
---|
594 | value = self.parseExpr()
|
---|
595 | self.skipSpace()
|
---|
596 | if self.getCurr() != self.parenthesisCloseSet[parenthesisType]:
|
---|
597 | raise Exception("No closing brace")
|
---|
598 | self.moveNext()
|
---|
599 | if parenthesisType == 1: # [ : Get content
|
---|
600 | value = self.getContent(value)
|
---|
601 | elif parenthesisType == 2: # { : To address
|
---|
602 | value = self.toAddress(value)
|
---|
603 | elif parenthesisType == 3: # < : To offset
|
---|
604 | value = self.toOffset(value)
|
---|
605 | return value
|
---|
606 | else:
|
---|
607 | return self.parseSingleOp()
|
---|
608 |
|
---|
609 | #
|
---|
610 | # Parse symbol of Multiplier(*)
|
---|
611 | #
|
---|
612 | # retval value or self.parseSingleOp()
|
---|
613 | #
|
---|
614 | def parseMul(self):
|
---|
615 | values = [self.parseBrace()]
|
---|
616 | while True:
|
---|
617 | self.skipSpace()
|
---|
618 | char = self.getCurr()
|
---|
619 | if char == '*':
|
---|
620 | self.moveNext()
|
---|
621 | values.append(self.parseBrace())
|
---|
622 | else:
|
---|
623 | break
|
---|
624 | value = 1
|
---|
625 | for each in values:
|
---|
626 | value *= each
|
---|
627 | return value
|
---|
628 |
|
---|
629 | #
|
---|
630 | # Parse symbol of And(&) and Or(|)
|
---|
631 | #
|
---|
632 | # retval value
|
---|
633 | #
|
---|
634 | def parseAndOr(self):
|
---|
635 | value = self.parseMul()
|
---|
636 | op = None
|
---|
637 | while True:
|
---|
638 | self.skipSpace()
|
---|
639 | char = self.getCurr()
|
---|
640 | if char == '&':
|
---|
641 | self.moveNext()
|
---|
642 | value &= self.parseMul()
|
---|
643 | elif char == '|':
|
---|
644 | div_index = self.index
|
---|
645 | self.moveNext()
|
---|
646 | value |= self.parseMul()
|
---|
647 | else:
|
---|
648 | break
|
---|
649 |
|
---|
650 | return value
|
---|
651 |
|
---|
652 | #
|
---|
653 | # Parse symbol of Add(+) and Minus(-)
|
---|
654 | #
|
---|
655 | # retval sum(values)
|
---|
656 | #
|
---|
657 | def parseAddMinus(self):
|
---|
658 | values = [self.parseAndOr()]
|
---|
659 | while True:
|
---|
660 | self.skipSpace()
|
---|
661 | char = self.getCurr()
|
---|
662 | if char == '+':
|
---|
663 | self.moveNext()
|
---|
664 | values.append(self.parseAndOr())
|
---|
665 | elif char == '-':
|
---|
666 | self.moveNext()
|
---|
667 | values.append(-1 * self.parseAndOr())
|
---|
668 | else:
|
---|
669 | break
|
---|
670 | return sum(values)
|
---|
671 |
|
---|
672 | #
|
---|
673 | # Parse expression
|
---|
674 | #
|
---|
675 | # retval self.parseAddMinus()
|
---|
676 | #
|
---|
677 | def parseExpr(self):
|
---|
678 | return self.parseAddMinus()
|
---|
679 |
|
---|
680 | #
|
---|
681 | # Get result
|
---|
682 | #
|
---|
683 | # retval value
|
---|
684 | #
|
---|
685 | def getResult(self):
|
---|
686 | value = self.parseExpr()
|
---|
687 | self.skipSpace()
|
---|
688 | if not self.isLast():
|
---|
689 | raise Exception("Unexpected character found '%s'" % self.getCurr())
|
---|
690 | return value
|
---|
691 |
|
---|
692 | #
|
---|
693 | # Get module GUID
|
---|
694 | #
|
---|
695 | # retval value
|
---|
696 | #
|
---|
697 | def getModGuid(self, var):
|
---|
698 | guid = (guid for guid,name in self.dictGuidNameXref.items() if name==var)
|
---|
699 | try:
|
---|
700 | value = guid.next()
|
---|
701 | except Exception:
|
---|
702 | raise Exception("Unknown module name %s !" % var)
|
---|
703 | return value
|
---|
704 |
|
---|
705 | #
|
---|
706 | # Get variable
|
---|
707 | #
|
---|
708 | # retval value
|
---|
709 | #
|
---|
710 | def getVariable(self, var):
|
---|
711 | value = self.dictVariable.get(var, None)
|
---|
712 | if value == None:
|
---|
713 | raise Exception("Unrecognized variable '%s'" % var)
|
---|
714 | return value
|
---|
715 |
|
---|
716 | #
|
---|
717 | # Get number
|
---|
718 | #
|
---|
719 | # retval value
|
---|
720 | #
|
---|
721 | def getNumber(self, var):
|
---|
722 | var = var.strip()
|
---|
723 | if var.startswith('0x'): # HEX
|
---|
724 | value = int(var, 16)
|
---|
725 | else:
|
---|
726 | value = int(var, 10)
|
---|
727 | return value
|
---|
728 |
|
---|
729 | #
|
---|
730 | # Get content
|
---|
731 | #
|
---|
732 | # param [in] value
|
---|
733 | #
|
---|
734 | # retval value
|
---|
735 | #
|
---|
736 | def getContent(self, value):
|
---|
737 | return readDataFromFile (self.fdFile, self.toOffset(value), 4)
|
---|
738 |
|
---|
739 | #
|
---|
740 | # Change value to address
|
---|
741 | #
|
---|
742 | # param [in] value
|
---|
743 | #
|
---|
744 | # retval value
|
---|
745 | #
|
---|
746 | def toAddress(self, value):
|
---|
747 | if value < self.fdSize:
|
---|
748 | value = value + self.fdBase
|
---|
749 | return value
|
---|
750 |
|
---|
751 | #
|
---|
752 | # Change value to offset
|
---|
753 | #
|
---|
754 | # param [in] value
|
---|
755 | #
|
---|
756 | # retval value
|
---|
757 | #
|
---|
758 | def toOffset(self, value):
|
---|
759 | offset = None
|
---|
760 | for fvInfo in self.fvList:
|
---|
761 | if (value >= fvInfo['Base']) and (value < fvInfo['Base'] + fvInfo['Size']):
|
---|
762 | offset = value - fvInfo['Base'] + fvInfo['Offset']
|
---|
763 | if not offset:
|
---|
764 | if (value >= self.fdBase) and (value < self.fdBase + self.fdSize):
|
---|
765 | offset = value - self.fdBase
|
---|
766 | else:
|
---|
767 | offset = value
|
---|
768 | if offset >= self.fdSize:
|
---|
769 | raise Exception("Invalid file offset 0x%08x !" % value)
|
---|
770 | return offset
|
---|
771 |
|
---|
772 | #
|
---|
773 | # Get GUID offset
|
---|
774 | #
|
---|
775 | # param [in] value
|
---|
776 | #
|
---|
777 | # retval value
|
---|
778 | #
|
---|
779 | def getGuidOff(self, value):
|
---|
780 | # GUID:Offset
|
---|
781 | symbolName = value.split(':')
|
---|
782 | if len(symbolName) == 3:
|
---|
783 | fvName = symbolName[0].upper()
|
---|
784 | keyName = '%s:%s' % (fvName, symbolName[1])
|
---|
785 | offStr = symbolName[2]
|
---|
786 | elif len(symbolName) == 2:
|
---|
787 | keyName = symbolName[0]
|
---|
788 | offStr = symbolName[1]
|
---|
789 | if keyName in self.dictFfsOffset:
|
---|
790 | value = (int(self.dictFfsOffset[keyName], 16) + int(offStr, 16)) & 0xFFFFFFFF
|
---|
791 | else:
|
---|
792 | raise Exception("Unknown GUID %s !" % value)
|
---|
793 | return value
|
---|
794 |
|
---|
795 | #
|
---|
796 | # Get symbols
|
---|
797 | #
|
---|
798 | # param [in] value
|
---|
799 | #
|
---|
800 | # retval ret
|
---|
801 | #
|
---|
802 | def getSymbols(self, value):
|
---|
803 | if value in self.dictSymbolAddress:
|
---|
804 | # Module:Function
|
---|
805 | ret = int (self.dictSymbolAddress[value], 16)
|
---|
806 | else:
|
---|
807 | raise Exception("Unknown symbol %s !" % value)
|
---|
808 | return ret
|
---|
809 |
|
---|
810 | #
|
---|
811 | # Evaluate symbols
|
---|
812 | #
|
---|
813 | # param [in] expression
|
---|
814 | # param [in] isOffset
|
---|
815 | #
|
---|
816 | # retval value & 0xFFFFFFFF
|
---|
817 | #
|
---|
818 | def evaluate(self, expression, isOffset):
|
---|
819 | self.index = 0
|
---|
820 | self.synUsed = False
|
---|
821 | self.string = expression
|
---|
822 | value = self.getResult()
|
---|
823 | if isOffset:
|
---|
824 | if self.synUsed:
|
---|
825 | # Consider it as an address first
|
---|
826 | value = self.toOffset(value)
|
---|
827 | if value & 0x80000000:
|
---|
828 | # Consider it as a negative offset next
|
---|
829 | offset = (~value & 0xFFFFFFFF) + 1
|
---|
830 | if offset < self.fdSize:
|
---|
831 | value = self.fdSize - offset
|
---|
832 | if value >= self.fdSize:
|
---|
833 | raise Exception("Invalid offset expression !")
|
---|
834 | return value & 0xFFFFFFFF
|
---|
835 |
|
---|
836 | #
|
---|
837 | # Print out the usage
|
---|
838 | #
|
---|
839 | def Usage():
|
---|
840 | print ("PatchFv Version 0.50")
|
---|
841 | print ("Usage: \n\tPatchFv FvBuildDir [FvFileBaseNames:]FdFileBaseNameToPatch \"Offset, Value\"")
|
---|
842 |
|
---|
843 | def main():
|
---|
844 | #
|
---|
845 | # Parse the options and args
|
---|
846 | #
|
---|
847 | symTables = Symbols()
|
---|
848 |
|
---|
849 | #
|
---|
850 | # If the arguments are less than 4, then return an error.
|
---|
851 | #
|
---|
852 | if len(sys.argv) < 4:
|
---|
853 | Usage()
|
---|
854 | return 1
|
---|
855 |
|
---|
856 | #
|
---|
857 | # If it fails to create dictionaries, then return an error.
|
---|
858 | #
|
---|
859 | if symTables.createDicts(sys.argv[1], sys.argv[2]) != 0:
|
---|
860 | print ("ERROR: Failed to create symbol dictionary!!")
|
---|
861 | return 2
|
---|
862 |
|
---|
863 | #
|
---|
864 | # Get FD file and size
|
---|
865 | #
|
---|
866 | fdFile = symTables.getFdFile()
|
---|
867 | fdSize = symTables.getFdSize()
|
---|
868 |
|
---|
869 | try:
|
---|
870 | #
|
---|
871 | # Check to see if FSP header is valid
|
---|
872 | #
|
---|
873 | ret = IsFspHeaderValid(fdFile)
|
---|
874 | if ret == False:
|
---|
875 | raise Exception ("The FSP header is not valid. Stop patching FD.")
|
---|
876 | comment = ""
|
---|
877 | for fvFile in sys.argv[3:]:
|
---|
878 | #
|
---|
879 | # Check to see if it has enough arguments
|
---|
880 | #
|
---|
881 | items = fvFile.split(",")
|
---|
882 | if len (items) < 2:
|
---|
883 | raise Exception("Expect more arguments for '%s'!" % fvFile)
|
---|
884 |
|
---|
885 | comment = ""
|
---|
886 | command = ""
|
---|
887 | params = []
|
---|
888 | for item in items:
|
---|
889 | item = item.strip()
|
---|
890 | if item.startswith("@"):
|
---|
891 | comment = item[1:]
|
---|
892 | elif item.startswith("$"):
|
---|
893 | command = item[1:]
|
---|
894 | else:
|
---|
895 | if len(params) == 0:
|
---|
896 | isOffset = True
|
---|
897 | else :
|
---|
898 | isOffset = False
|
---|
899 | #
|
---|
900 | # Parse symbols then append it to params
|
---|
901 | #
|
---|
902 | params.append (symTables.evaluate(item, isOffset))
|
---|
903 |
|
---|
904 | #
|
---|
905 | # Patch a new value into FD file if it is not a command
|
---|
906 | #
|
---|
907 | if command == "":
|
---|
908 | # Patch a DWORD
|
---|
909 | if len (params) == 2:
|
---|
910 | offset = params[0]
|
---|
911 | value = params[1]
|
---|
912 | oldvalue = readDataFromFile(fdFile, offset, 4)
|
---|
913 | ret = patchDataInFile (fdFile, offset, value, 4) - 4
|
---|
914 | else:
|
---|
915 | raise Exception ("Patch command needs 2 parameters !")
|
---|
916 |
|
---|
917 | if ret:
|
---|
918 | raise Exception ("Patch failed for offset 0x%08X" % offset)
|
---|
919 | else:
|
---|
920 | print ("Patched offset 0x%08X:[%08X] with value 0x%08X # %s" % (offset, oldvalue, value, comment))
|
---|
921 |
|
---|
922 | elif command == "COPY":
|
---|
923 | #
|
---|
924 | # Copy binary block from source to destination
|
---|
925 | #
|
---|
926 | if len (params) == 3:
|
---|
927 | src = symTables.toOffset(params[0])
|
---|
928 | dest = symTables.toOffset(params[1])
|
---|
929 | clen = symTables.toOffset(params[2])
|
---|
930 | if (dest + clen <= fdSize) and (src + clen <= fdSize):
|
---|
931 | oldvalue = readDataFromFile(fdFile, src, clen)
|
---|
932 | ret = patchDataInFile (fdFile, dest, oldvalue, clen) - clen
|
---|
933 | else:
|
---|
934 | raise Exception ("Copy command OFFSET or LENGTH parameter is invalid !")
|
---|
935 | else:
|
---|
936 | raise Exception ("Copy command needs 3 parameters !")
|
---|
937 |
|
---|
938 | if ret:
|
---|
939 | raise Exception ("Copy failed from offset 0x%08X to offset 0x%08X!" % (src, dest))
|
---|
940 | else :
|
---|
941 | print ("Copied %d bytes from offset 0x%08X ~ offset 0x%08X # %s" % (clen, src, dest, comment))
|
---|
942 | else:
|
---|
943 | raise Exception ("Unknown command %s!" % command)
|
---|
944 | return 0
|
---|
945 |
|
---|
946 | except Exception as ex:
|
---|
947 | print ("ERROR: %s" % ex)
|
---|
948 | return 1
|
---|
949 |
|
---|
950 | if __name__ == '__main__':
|
---|
951 | sys.exit(main())
|
---|