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