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