]> git.proxmox.com Git - mirror_edk2.git/blob - IntelFsp2Pkg/Tools/SplitFspBin.py
IntelFsp2Pkg SplitFspBin.py: Correct file name in file header
[mirror_edk2.git] / IntelFsp2Pkg / Tools / SplitFspBin.py
1 ## @ SplitFspBin.py
2 #
3 # Copyright (c) 2015 - 2021, Intel Corporation. All rights reserved.<BR>
4 # SPDX-License-Identifier: BSD-2-Clause-Patent
5 #
6 ##
7
8 import os
9 import sys
10 import uuid
11 import copy
12 import struct
13 import argparse
14 from ctypes import *
15 from functools import reduce
16
17 """
18 This utility supports some operations for Intel FSP 1.x/2.x image.
19 It supports:
20 - Display FSP 1.x/2.x information header
21 - Split FSP 2.x image into individual FSP-T/M/S/O component
22 - Rebase FSP 1.x/2.x components to a different base address
23 - Generate FSP 1.x/2.x mapping C header file
24 """
25
26 CopyRightHeaderFile = """/*
27 *
28 * Automatically generated file; DO NOT EDIT.
29 * FSP mapping file
30 *
31 */
32 """
33
34 class c_uint24(Structure):
35 """Little-Endian 24-bit Unsigned Integer"""
36 _pack_ = 1
37 _fields_ = [('Data', (c_uint8 * 3))]
38
39 def __init__(self, val=0):
40 self.set_value(val)
41
42 def __str__(self, indent=0):
43 return '0x%.6x' % self.value
44
45 def __int__(self):
46 return self.get_value()
47
48 def set_value(self, val):
49 self.Data[0:3] = Val2Bytes(val, 3)
50
51 def get_value(self):
52 return Bytes2Val(self.Data[0:3])
53
54 value = property(get_value, set_value)
55
56 class EFI_FIRMWARE_VOLUME_HEADER(Structure):
57 _fields_ = [
58 ('ZeroVector', ARRAY(c_uint8, 16)),
59 ('FileSystemGuid', ARRAY(c_uint8, 16)),
60 ('FvLength', c_uint64),
61 ('Signature', ARRAY(c_char, 4)),
62 ('Attributes', c_uint32),
63 ('HeaderLength', c_uint16),
64 ('Checksum', c_uint16),
65 ('ExtHeaderOffset', c_uint16),
66 ('Reserved', c_uint8),
67 ('Revision', c_uint8)
68 ]
69
70 class EFI_FIRMWARE_VOLUME_EXT_HEADER(Structure):
71 _fields_ = [
72 ('FvName', ARRAY(c_uint8, 16)),
73 ('ExtHeaderSize', c_uint32)
74 ]
75
76 class EFI_FFS_INTEGRITY_CHECK(Structure):
77 _fields_ = [
78 ('Header', c_uint8),
79 ('File', c_uint8)
80 ]
81
82 class EFI_FFS_FILE_HEADER(Structure):
83 _fields_ = [
84 ('Name', ARRAY(c_uint8, 16)),
85 ('IntegrityCheck', EFI_FFS_INTEGRITY_CHECK),
86 ('Type', c_uint8),
87 ('Attributes', c_uint8),
88 ('Size', c_uint24),
89 ('State', c_uint8)
90 ]
91
92 class EFI_COMMON_SECTION_HEADER(Structure):
93 _fields_ = [
94 ('Size', c_uint24),
95 ('Type', c_uint8)
96 ]
97
98 class FSP_COMMON_HEADER(Structure):
99 _fields_ = [
100 ('Signature', ARRAY(c_char, 4)),
101 ('HeaderLength', c_uint32)
102 ]
103
104 class FSP_INFORMATION_HEADER(Structure):
105 _fields_ = [
106 ('Signature', ARRAY(c_char, 4)),
107 ('HeaderLength', c_uint32),
108 ('Reserved1', c_uint16),
109 ('SpecVersion', c_uint8),
110 ('HeaderRevision', c_uint8),
111 ('ImageRevision', c_uint32),
112 ('ImageId', ARRAY(c_char, 8)),
113 ('ImageSize', c_uint32),
114 ('ImageBase', c_uint32),
115 ('ImageAttribute', c_uint16),
116 ('ComponentAttribute', c_uint16),
117 ('CfgRegionOffset', c_uint32),
118 ('CfgRegionSize', c_uint32),
119 ('Reserved2', c_uint32),
120 ('TempRamInitEntryOffset', c_uint32),
121 ('Reserved3', c_uint32),
122 ('NotifyPhaseEntryOffset', c_uint32),
123 ('FspMemoryInitEntryOffset', c_uint32),
124 ('TempRamExitEntryOffset', c_uint32),
125 ('FspSiliconInitEntryOffset', c_uint32),
126 ('FspMultiPhaseSiInitEntryOffset', c_uint32),
127 ('ExtendedImageRevision', c_uint16),
128 ('Reserved4', c_uint16)
129 ]
130
131 class FSP_PATCH_TABLE(Structure):
132 _fields_ = [
133 ('Signature', ARRAY(c_char, 4)),
134 ('HeaderLength', c_uint16),
135 ('HeaderRevision', c_uint8),
136 ('Reserved', c_uint8),
137 ('PatchEntryNum', c_uint32)
138 ]
139
140 class EFI_IMAGE_DATA_DIRECTORY(Structure):
141 _fields_ = [
142 ('VirtualAddress', c_uint32),
143 ('Size', c_uint32)
144 ]
145
146 class EFI_TE_IMAGE_HEADER(Structure):
147 _fields_ = [
148 ('Signature', ARRAY(c_char, 2)),
149 ('Machine', c_uint16),
150 ('NumberOfSections', c_uint8),
151 ('Subsystem', c_uint8),
152 ('StrippedSize', c_uint16),
153 ('AddressOfEntryPoint', c_uint32),
154 ('BaseOfCode', c_uint32),
155 ('ImageBase', c_uint64),
156 ('DataDirectoryBaseReloc', EFI_IMAGE_DATA_DIRECTORY),
157 ('DataDirectoryDebug', EFI_IMAGE_DATA_DIRECTORY)
158 ]
159
160 class EFI_IMAGE_DOS_HEADER(Structure):
161 _fields_ = [
162 ('e_magic', c_uint16),
163 ('e_cblp', c_uint16),
164 ('e_cp', c_uint16),
165 ('e_crlc', c_uint16),
166 ('e_cparhdr', c_uint16),
167 ('e_minalloc', c_uint16),
168 ('e_maxalloc', c_uint16),
169 ('e_ss', c_uint16),
170 ('e_sp', c_uint16),
171 ('e_csum', c_uint16),
172 ('e_ip', c_uint16),
173 ('e_cs', c_uint16),
174 ('e_lfarlc', c_uint16),
175 ('e_ovno', c_uint16),
176 ('e_res', ARRAY(c_uint16, 4)),
177 ('e_oemid', c_uint16),
178 ('e_oeminfo', c_uint16),
179 ('e_res2', ARRAY(c_uint16, 10)),
180 ('e_lfanew', c_uint16)
181 ]
182
183 class EFI_IMAGE_FILE_HEADER(Structure):
184 _fields_ = [
185 ('Machine', c_uint16),
186 ('NumberOfSections', c_uint16),
187 ('TimeDateStamp', c_uint32),
188 ('PointerToSymbolTable', c_uint32),
189 ('NumberOfSymbols', c_uint32),
190 ('SizeOfOptionalHeader', c_uint16),
191 ('Characteristics', c_uint16)
192 ]
193
194 class PE_RELOC_BLOCK_HEADER(Structure):
195 _fields_ = [
196 ('PageRVA', c_uint32),
197 ('BlockSize', c_uint32)
198 ]
199
200 class EFI_IMAGE_OPTIONAL_HEADER32(Structure):
201 _fields_ = [
202 ('Magic', c_uint16),
203 ('MajorLinkerVersion', c_uint8),
204 ('MinorLinkerVersion', c_uint8),
205 ('SizeOfCode', c_uint32),
206 ('SizeOfInitializedData', c_uint32),
207 ('SizeOfUninitializedData', c_uint32),
208 ('AddressOfEntryPoint', c_uint32),
209 ('BaseOfCode', c_uint32),
210 ('BaseOfData', c_uint32),
211 ('ImageBase', c_uint32),
212 ('SectionAlignment', c_uint32),
213 ('FileAlignment', c_uint32),
214 ('MajorOperatingSystemVersion', c_uint16),
215 ('MinorOperatingSystemVersion', c_uint16),
216 ('MajorImageVersion', c_uint16),
217 ('MinorImageVersion', c_uint16),
218 ('MajorSubsystemVersion', c_uint16),
219 ('MinorSubsystemVersion', c_uint16),
220 ('Win32VersionValue', c_uint32),
221 ('SizeOfImage', c_uint32),
222 ('SizeOfHeaders', c_uint32),
223 ('CheckSum' , c_uint32),
224 ('Subsystem', c_uint16),
225 ('DllCharacteristics', c_uint16),
226 ('SizeOfStackReserve', c_uint32),
227 ('SizeOfStackCommit' , c_uint32),
228 ('SizeOfHeapReserve', c_uint32),
229 ('SizeOfHeapCommit' , c_uint32),
230 ('LoaderFlags' , c_uint32),
231 ('NumberOfRvaAndSizes', c_uint32),
232 ('DataDirectory', ARRAY(EFI_IMAGE_DATA_DIRECTORY, 16))
233 ]
234
235 class EFI_IMAGE_OPTIONAL_HEADER32_PLUS(Structure):
236 _fields_ = [
237 ('Magic', c_uint16),
238 ('MajorLinkerVersion', c_uint8),
239 ('MinorLinkerVersion', c_uint8),
240 ('SizeOfCode', c_uint32),
241 ('SizeOfInitializedData', c_uint32),
242 ('SizeOfUninitializedData', c_uint32),
243 ('AddressOfEntryPoint', c_uint32),
244 ('BaseOfCode', c_uint32),
245 ('ImageBase', c_uint64),
246 ('SectionAlignment', c_uint32),
247 ('FileAlignment', c_uint32),
248 ('MajorOperatingSystemVersion', c_uint16),
249 ('MinorOperatingSystemVersion', c_uint16),
250 ('MajorImageVersion', c_uint16),
251 ('MinorImageVersion', c_uint16),
252 ('MajorSubsystemVersion', c_uint16),
253 ('MinorSubsystemVersion', c_uint16),
254 ('Win32VersionValue', c_uint32),
255 ('SizeOfImage', c_uint32),
256 ('SizeOfHeaders', c_uint32),
257 ('CheckSum' , c_uint32),
258 ('Subsystem', c_uint16),
259 ('DllCharacteristics', c_uint16),
260 ('SizeOfStackReserve', c_uint64),
261 ('SizeOfStackCommit' , c_uint64),
262 ('SizeOfHeapReserve', c_uint64),
263 ('SizeOfHeapCommit' , c_uint64),
264 ('LoaderFlags' , c_uint32),
265 ('NumberOfRvaAndSizes', c_uint32),
266 ('DataDirectory', ARRAY(EFI_IMAGE_DATA_DIRECTORY, 16))
267 ]
268
269 class EFI_IMAGE_OPTIONAL_HEADER(Union):
270 _fields_ = [
271 ('PeOptHdr', EFI_IMAGE_OPTIONAL_HEADER32),
272 ('PePlusOptHdr', EFI_IMAGE_OPTIONAL_HEADER32_PLUS)
273 ]
274
275 class EFI_IMAGE_NT_HEADERS32(Structure):
276 _fields_ = [
277 ('Signature', c_uint32),
278 ('FileHeader', EFI_IMAGE_FILE_HEADER),
279 ('OptionalHeader', EFI_IMAGE_OPTIONAL_HEADER)
280 ]
281
282
283 class EFI_IMAGE_DIRECTORY_ENTRY:
284 EXPORT = 0
285 IMPORT = 1
286 RESOURCE = 2
287 EXCEPTION = 3
288 SECURITY = 4
289 BASERELOC = 5
290 DEBUG = 6
291 COPYRIGHT = 7
292 GLOBALPTR = 8
293 TLS = 9
294 LOAD_CONFIG = 10
295
296 class EFI_FV_FILETYPE:
297 ALL = 0x00
298 RAW = 0x01
299 FREEFORM = 0x02
300 SECURITY_CORE = 0x03
301 PEI_CORE = 0x04
302 DXE_CORE = 0x05
303 PEIM = 0x06
304 DRIVER = 0x07
305 COMBINED_PEIM_DRIVER = 0x08
306 APPLICATION = 0x09
307 SMM = 0x0a
308 FIRMWARE_VOLUME_IMAGE = 0x0b
309 COMBINED_SMM_DXE = 0x0c
310 SMM_CORE = 0x0d
311 OEM_MIN = 0xc0
312 OEM_MAX = 0xdf
313 DEBUG_MIN = 0xe0
314 DEBUG_MAX = 0xef
315 FFS_MIN = 0xf0
316 FFS_MAX = 0xff
317 FFS_PAD = 0xf0
318
319 class EFI_SECTION_TYPE:
320 """Enumeration of all valid firmware file section types."""
321 ALL = 0x00
322 COMPRESSION = 0x01
323 GUID_DEFINED = 0x02
324 DISPOSABLE = 0x03
325 PE32 = 0x10
326 PIC = 0x11
327 TE = 0x12
328 DXE_DEPEX = 0x13
329 VERSION = 0x14
330 USER_INTERFACE = 0x15
331 COMPATIBILITY16 = 0x16
332 FIRMWARE_VOLUME_IMAGE = 0x17
333 FREEFORM_SUBTYPE_GUID = 0x18
334 RAW = 0x19
335 PEI_DEPEX = 0x1b
336 SMM_DEPEX = 0x1c
337
338 def AlignPtr (offset, alignment = 8):
339 return (offset + alignment - 1) & ~(alignment - 1)
340
341 def Bytes2Val (bytes):
342 return reduce(lambda x,y: (x<<8)|y, bytes[::-1] )
343
344 def Val2Bytes (value, blen):
345 return [(value>>(i*8) & 0xff) for i in range(blen)]
346
347 def IsIntegerType (val):
348 if sys.version_info[0] < 3:
349 if type(val) in (int, long):
350 return True
351 else:
352 if type(val) is int:
353 return True
354 return False
355
356 def IsStrType (val):
357 if sys.version_info[0] < 3:
358 if type(val) is str:
359 return True
360 else:
361 if type(val) is bytes:
362 return True
363 return False
364
365 def HandleNameStr (val):
366 if sys.version_info[0] < 3:
367 rep = "0x%X ('%s')" % (Bytes2Val (bytearray (val)), val)
368 else:
369 rep = "0x%X ('%s')" % (Bytes2Val (bytearray (val)), str (val, 'utf-8'))
370 return rep
371
372 def OutputStruct (obj, indent = 0, plen = 0):
373 if indent:
374 body = ''
375 else:
376 body = (' ' * indent + '<%s>:\n') % obj.__class__.__name__
377
378 if plen == 0:
379 plen = sizeof(obj)
380
381 max_key_len = 26
382 pstr = (' ' * (indent + 1) + '{0:<%d} = {1}\n') % max_key_len
383
384 for field in obj._fields_:
385 key = field[0]
386 val = getattr(obj, key)
387 rep = ''
388 if not isinstance(val, c_uint24) and isinstance(val, Structure):
389 body += pstr.format(key, val.__class__.__name__)
390 body += OutputStruct (val, indent + 1)
391 plen -= sizeof(val)
392 else:
393 if IsStrType (val):
394 rep = HandleNameStr (val)
395 elif IsIntegerType (val):
396 if (key == 'ImageRevision'):
397 FspImageRevisionMajor = ((val >> 24) & 0xFF)
398 FspImageRevisionMinor = ((val >> 16) & 0xFF)
399 FspImageRevisionRevision = ((val >> 8) & 0xFF)
400 FspImageRevisionBuildNumber = (val & 0xFF)
401 rep = '0x%08X' % val
402 elif (key == 'ExtendedImageRevision'):
403 FspImageRevisionRevision |= (val & 0xFF00)
404 FspImageRevisionBuildNumber |= ((val << 8) & 0xFF00)
405 rep = "0x%04X ('%02X.%02X.%04X.%04X')" % (val, FspImageRevisionMajor, FspImageRevisionMinor, FspImageRevisionRevision, FspImageRevisionBuildNumber)
406 elif field[1] == c_uint64:
407 rep = '0x%016X' % val
408 elif field[1] == c_uint32:
409 rep = '0x%08X' % val
410 elif field[1] == c_uint16:
411 rep = '0x%04X' % val
412 elif field[1] == c_uint8:
413 rep = '0x%02X' % val
414 else:
415 rep = '0x%X' % val
416 elif isinstance(val, c_uint24):
417 rep = '0x%X' % val.get_value()
418 elif 'c_ubyte_Array' in str(type(val)):
419 if sizeof(val) == 16:
420 if sys.version_info[0] < 3:
421 rep = str(bytearray(val))
422 else:
423 rep = bytes(val)
424 rep = str(uuid.UUID(bytes_le = rep)).upper()
425 else:
426 res = ['0x%02X'%i for i in bytearray(val)]
427 rep = '[%s]' % (','.join(res))
428 else:
429 rep = str(val)
430 plen -= sizeof(field[1])
431 body += pstr.format(key, rep)
432 if plen <= 0:
433 break
434 return body
435
436 class Section:
437 def __init__(self, offset, secdata):
438 self.SecHdr = EFI_COMMON_SECTION_HEADER.from_buffer (secdata, 0)
439 self.SecData = secdata[0:int(self.SecHdr.Size)]
440 self.Offset = offset
441
442 class FirmwareFile:
443 def __init__(self, offset, filedata):
444 self.FfsHdr = EFI_FFS_FILE_HEADER.from_buffer (filedata, 0)
445 self.FfsData = filedata[0:int(self.FfsHdr.Size)]
446 self.Offset = offset
447 self.SecList = []
448
449 def ParseFfs(self):
450 ffssize = len(self.FfsData)
451 offset = sizeof(self.FfsHdr)
452 if self.FfsHdr.Name != '\xff' * 16:
453 while offset < (ffssize - sizeof (EFI_COMMON_SECTION_HEADER)):
454 sechdr = EFI_COMMON_SECTION_HEADER.from_buffer (self.FfsData, offset)
455 sec = Section (offset, self.FfsData[offset:offset + int(sechdr.Size)])
456 self.SecList.append(sec)
457 offset += int(sechdr.Size)
458 offset = AlignPtr(offset, 4)
459
460 class FirmwareVolume:
461 def __init__(self, offset, fvdata):
462 self.FvHdr = EFI_FIRMWARE_VOLUME_HEADER.from_buffer (fvdata, 0)
463 self.FvData = fvdata[0 : self.FvHdr.FvLength]
464 self.Offset = offset
465 if self.FvHdr.ExtHeaderOffset > 0:
466 self.FvExtHdr = EFI_FIRMWARE_VOLUME_EXT_HEADER.from_buffer (self.FvData, self.FvHdr.ExtHeaderOffset)
467 else:
468 self.FvExtHdr = None
469 self.FfsList = []
470
471 def ParseFv(self):
472 fvsize = len(self.FvData)
473 if self.FvExtHdr:
474 offset = self.FvHdr.ExtHeaderOffset + self.FvExtHdr.ExtHeaderSize
475 else:
476 offset = self.FvHdr.HeaderLength
477 offset = AlignPtr(offset)
478 while offset < (fvsize - sizeof (EFI_FFS_FILE_HEADER)):
479 ffshdr = EFI_FFS_FILE_HEADER.from_buffer (self.FvData, offset)
480 if (ffshdr.Name == '\xff' * 16) and (int(ffshdr.Size) == 0xFFFFFF):
481 offset = fvsize
482 else:
483 ffs = FirmwareFile (offset, self.FvData[offset:offset + int(ffshdr.Size)])
484 ffs.ParseFfs()
485 self.FfsList.append(ffs)
486 offset += int(ffshdr.Size)
487 offset = AlignPtr(offset)
488
489 class FspImage:
490 def __init__(self, offset, fih, fihoff, patch):
491 self.Fih = fih
492 self.FihOffset = fihoff
493 self.Offset = offset
494 self.FvIdxList = []
495 self.Type = "XTMSXXXXOXXXXXXX"[(fih.ComponentAttribute >> 12) & 0x0F]
496 self.PatchList = patch
497 self.PatchList.append(fihoff + 0x1C)
498
499 def AppendFv(self, FvIdx):
500 self.FvIdxList.append(FvIdx)
501
502 def Patch(self, delta, fdbin):
503 count = 0
504 applied = 0
505 for idx, patch in enumerate(self.PatchList):
506 ptype = (patch>>24) & 0x0F
507 if ptype not in [0x00, 0x0F]:
508 raise Exception('ERROR: Invalid patch type %d !' % ptype)
509 if patch & 0x80000000:
510 patch = self.Fih.ImageSize - (0x1000000 - (patch & 0xFFFFFF))
511 else:
512 patch = patch & 0xFFFFFF
513 if (patch < self.Fih.ImageSize) and (patch + sizeof(c_uint32) <= self.Fih.ImageSize):
514 offset = patch + self.Offset
515 value = Bytes2Val(fdbin[offset:offset+sizeof(c_uint32)])
516 value += delta
517 fdbin[offset:offset+sizeof(c_uint32)] = Val2Bytes(value, sizeof(c_uint32))
518 applied += 1
519 count += 1
520 # Don't count the FSP base address patch entry appended at the end
521 if count != 0:
522 count -= 1
523 applied -= 1
524 return (count, applied)
525
526 class FirmwareDevice:
527 def __init__(self, offset, fdfile):
528 self.FvList = []
529 self.FspList = []
530 self.FdFile = fdfile
531 self.Offset = 0
532 hfsp = open (self.FdFile, 'rb')
533 self.FdData = bytearray(hfsp.read())
534 hfsp.close()
535
536 def ParseFd(self):
537 offset = 0
538 fdsize = len(self.FdData)
539 self.FvList = []
540 while offset < (fdsize - sizeof (EFI_FIRMWARE_VOLUME_HEADER)):
541 fvh = EFI_FIRMWARE_VOLUME_HEADER.from_buffer (self.FdData, offset)
542 if b'_FVH' != fvh.Signature:
543 raise Exception("ERROR: Invalid FV header !")
544 fv = FirmwareVolume (offset, self.FdData[offset:offset + fvh.FvLength])
545 fv.ParseFv ()
546 self.FvList.append(fv)
547 offset += fv.FvHdr.FvLength
548
549 def CheckFsp (self):
550 if len(self.FspList) == 0:
551 return
552
553 fih = None
554 for fsp in self.FspList:
555 if not fih:
556 fih = fsp.Fih
557 else:
558 newfih = fsp.Fih
559 if (newfih.ImageId != fih.ImageId) or (newfih.ImageRevision != fih.ImageRevision):
560 raise Exception("ERROR: Inconsistent FSP ImageId or ImageRevision detected !")
561
562 def ParseFsp(self):
563 flen = 0
564 for idx, fv in enumerate(self.FvList):
565 # Check if this FV contains FSP header
566 if flen == 0:
567 if len(fv.FfsList) == 0:
568 continue
569 ffs = fv.FfsList[0]
570 if len(ffs.SecList) == 0:
571 continue
572 sec = ffs.SecList[0]
573 if sec.SecHdr.Type != EFI_SECTION_TYPE.RAW:
574 continue
575 fihoffset = ffs.Offset + sec.Offset + sizeof(sec.SecHdr)
576 fspoffset = fv.Offset
577 offset = fspoffset + fihoffset
578 fih = FSP_INFORMATION_HEADER.from_buffer (self.FdData, offset)
579 if b'FSPH' != fih.Signature:
580 continue
581
582 offset += fih.HeaderLength
583 offset = AlignPtr(offset, 4)
584 plist = []
585 while True:
586 fch = FSP_COMMON_HEADER.from_buffer (self.FdData, offset)
587 if b'FSPP' != fch.Signature:
588 offset += fch.HeaderLength
589 offset = AlignPtr(offset, 4)
590 else:
591 fspp = FSP_PATCH_TABLE.from_buffer (self.FdData, offset)
592 offset += sizeof(fspp)
593 pdata = (c_uint32 * fspp.PatchEntryNum).from_buffer(self.FdData, offset)
594 plist = list(pdata)
595 break
596
597 fsp = FspImage (fspoffset, fih, fihoffset, plist)
598 fsp.AppendFv (idx)
599 self.FspList.append(fsp)
600 flen = fsp.Fih.ImageSize - fv.FvHdr.FvLength
601 else:
602 fsp.AppendFv (idx)
603 flen -= fv.FvHdr.FvLength
604 if flen < 0:
605 raise Exception("ERROR: Incorrect FV size in image !")
606 self.CheckFsp ()
607
608 class PeTeImage:
609 def __init__(self, offset, data):
610 self.Offset = offset
611 tehdr = EFI_TE_IMAGE_HEADER.from_buffer (data, 0)
612 if tehdr.Signature == b'VZ': # TE image
613 self.TeHdr = tehdr
614 elif tehdr.Signature == b'MZ': # PE image
615 self.TeHdr = None
616 self.DosHdr = EFI_IMAGE_DOS_HEADER.from_buffer (data, 0)
617 self.PeHdr = EFI_IMAGE_NT_HEADERS32.from_buffer (data, self.DosHdr.e_lfanew)
618 if self.PeHdr.Signature != 0x4550:
619 raise Exception("ERROR: Invalid PE32 header !")
620 if self.PeHdr.OptionalHeader.PeOptHdr.Magic == 0x10b: # PE32 image
621 if self.PeHdr.FileHeader.SizeOfOptionalHeader < EFI_IMAGE_OPTIONAL_HEADER32.DataDirectory.offset:
622 raise Exception("ERROR: Unsupported PE32 image !")
623 if self.PeHdr.OptionalHeader.PeOptHdr.NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY.BASERELOC:
624 raise Exception("ERROR: No relocation information available !")
625 elif self.PeHdr.OptionalHeader.PeOptHdr.Magic == 0x20b: # PE32+ image
626 if self.PeHdr.FileHeader.SizeOfOptionalHeader < EFI_IMAGE_OPTIONAL_HEADER32_PLUS.DataDirectory.offset:
627 raise Exception("ERROR: Unsupported PE32+ image !")
628 if self.PeHdr.OptionalHeader.PePlusOptHdr.NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY.BASERELOC:
629 raise Exception("ERROR: No relocation information available !")
630 else:
631 raise Exception("ERROR: Invalid PE32 optional header !")
632 self.Offset = offset
633 self.Data = data
634 self.RelocList = []
635
636 def IsTeImage(self):
637 return self.TeHdr is not None
638
639 def ParseReloc(self):
640 if self.IsTeImage():
641 rsize = self.TeHdr.DataDirectoryBaseReloc.Size
642 roffset = sizeof(self.TeHdr) - self.TeHdr.StrippedSize + self.TeHdr.DataDirectoryBaseReloc.VirtualAddress
643 else:
644 # Assuming PE32 image type (self.PeHdr.OptionalHeader.PeOptHdr.Magic == 0x10b)
645 rsize = self.PeHdr.OptionalHeader.PeOptHdr.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY.BASERELOC].Size
646 roffset = self.PeHdr.OptionalHeader.PeOptHdr.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY.BASERELOC].VirtualAddress
647 if self.PeHdr.OptionalHeader.PePlusOptHdr.Magic == 0x20b: # PE32+ image
648 rsize = self.PeHdr.OptionalHeader.PePlusOptHdr.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY.BASERELOC].Size
649 roffset = self.PeHdr.OptionalHeader.PePlusOptHdr.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY.BASERELOC].VirtualAddress
650
651 alignment = 4
652 offset = roffset
653 while offset < roffset + rsize:
654 offset = AlignPtr(offset, 4)
655 blkhdr = PE_RELOC_BLOCK_HEADER.from_buffer(self.Data, offset)
656 offset += sizeof(blkhdr)
657 # Read relocation type,offset pairs
658 rlen = blkhdr.BlockSize - sizeof(PE_RELOC_BLOCK_HEADER)
659 rnum = int (rlen/sizeof(c_uint16))
660 rdata = (c_uint16 * rnum).from_buffer(self.Data, offset)
661 for each in rdata:
662 roff = each & 0xfff
663 rtype = each >> 12
664 if rtype == 0: # IMAGE_REL_BASED_ABSOLUTE:
665 continue
666 if ((rtype != 3) and (rtype != 10)): # IMAGE_REL_BASED_HIGHLOW and IMAGE_REL_BASED_DIR64
667 raise Exception("ERROR: Unsupported relocation type %d!" % rtype)
668 # Calculate the offset of the relocation
669 aoff = blkhdr.PageRVA + roff
670 if self.IsTeImage():
671 aoff += sizeof(self.TeHdr) - self.TeHdr.StrippedSize
672 self.RelocList.append((rtype, aoff))
673 offset += sizeof(rdata)
674
675 def Rebase(self, delta, fdbin):
676 count = 0
677 if delta == 0:
678 return count
679
680 for (rtype, roff) in self.RelocList:
681 if rtype == 3: # IMAGE_REL_BASED_HIGHLOW
682 offset = roff + self.Offset
683 value = Bytes2Val(fdbin[offset:offset+sizeof(c_uint32)])
684 value += delta
685 fdbin[offset:offset+sizeof(c_uint32)] = Val2Bytes(value, sizeof(c_uint32))
686 count += 1
687 elif rtype == 10: # IMAGE_REL_BASED_DIR64
688 offset = roff + self.Offset
689 value = Bytes2Val(fdbin[offset:offset+sizeof(c_uint64)])
690 value += delta
691 fdbin[offset:offset+sizeof(c_uint64)] = Val2Bytes(value, sizeof(c_uint64))
692 count += 1
693 else:
694 raise Exception('ERROR: Unknown relocation type %d !' % rtype)
695
696 if self.IsTeImage():
697 offset = self.Offset + EFI_TE_IMAGE_HEADER.ImageBase.offset
698 size = EFI_TE_IMAGE_HEADER.ImageBase.size
699 else:
700 offset = self.Offset + self.DosHdr.e_lfanew
701 offset += EFI_IMAGE_NT_HEADERS32.OptionalHeader.offset
702 if self.PeHdr.OptionalHeader.PePlusOptHdr.Magic == 0x20b: # PE32+ image
703 offset += EFI_IMAGE_OPTIONAL_HEADER32_PLUS.ImageBase.offset
704 size = EFI_IMAGE_OPTIONAL_HEADER32_PLUS.ImageBase.size
705 else:
706 offset += EFI_IMAGE_OPTIONAL_HEADER32.ImageBase.offset
707 size = EFI_IMAGE_OPTIONAL_HEADER32.ImageBase.size
708
709 value = Bytes2Val(fdbin[offset:offset+size]) + delta
710 fdbin[offset:offset+size] = Val2Bytes(value, size)
711
712 return count
713
714 def ShowFspInfo (fspfile):
715 fd = FirmwareDevice(0, fspfile)
716 fd.ParseFd ()
717 fd.ParseFsp ()
718
719 print ("\nFound the following %d Firmware Volumes in FSP binary:" % (len(fd.FvList)))
720 for idx, fv in enumerate(fd.FvList):
721 name = fv.FvExtHdr.FvName
722 if not name:
723 name = '\xff' * 16
724 else:
725 if sys.version_info[0] < 3:
726 name = str(bytearray(name))
727 else:
728 name = bytes(name)
729 guid = uuid.UUID(bytes_le = name)
730 print ("FV%d:" % idx)
731 print (" GUID : %s" % str(guid).upper())
732 print (" Offset : 0x%08X" % fv.Offset)
733 print (" Length : 0x%08X" % fv.FvHdr.FvLength)
734 print ("\n")
735
736 for fsp in fd.FspList:
737 fvlist = map(lambda x : 'FV%d' % x, fsp.FvIdxList)
738 print ("FSP_%s contains %s" % (fsp.Type, ','.join(fvlist)))
739 print ("%s" % (OutputStruct(fsp.Fih, 0, fsp.Fih.HeaderLength)))
740
741 def GenFspHdr (fspfile, outdir, hfile):
742 fd = FirmwareDevice(0, fspfile)
743 fd.ParseFd ()
744 fd.ParseFsp ()
745
746 if not hfile:
747 hfile = os.path.splitext(os.path.basename(fspfile))[0] + '.h'
748 fspname, ext = os.path.splitext(os.path.basename(hfile))
749 filename = os.path.join(outdir, fspname + ext)
750 hfsp = open(filename, 'w')
751 hfsp.write ('%s\n\n' % CopyRightHeaderFile)
752
753 firstfv = True
754 for fsp in fd.FspList:
755 fih = fsp.Fih
756 if firstfv:
757 if sys.version_info[0] < 3:
758 hfsp.write("#define FSP_IMAGE_ID 0x%016X /* '%s' */\n" % (Bytes2Val(bytearray(fih.ImageId)), fih.ImageId))
759 else:
760 hfsp.write("#define FSP_IMAGE_ID 0x%016X /* '%s' */\n" % (Bytes2Val(bytearray(fih.ImageId)), str (fih.ImageId, 'utf-8')))
761 hfsp.write("#define FSP_IMAGE_REV 0x%08X \n\n" % fih.ImageRevision)
762 firstfv = False
763 fv = fd.FvList[fsp.FvIdxList[0]]
764 hfsp.write ('#define FSP%s_BASE 0x%08X\n' % (fsp.Type, fih.ImageBase))
765 hfsp.write ('#define FSP%s_OFFSET 0x%08X\n' % (fsp.Type, fv.Offset))
766 hfsp.write ('#define FSP%s_LENGTH 0x%08X\n\n' % (fsp.Type, fih.ImageSize))
767
768 hfsp.close()
769
770 def SplitFspBin (fspfile, outdir, nametemplate):
771 fd = FirmwareDevice(0, fspfile)
772 fd.ParseFd ()
773 fd.ParseFsp ()
774
775 for fsp in fd.FspList:
776 if fsp.Fih.HeaderRevision < 3:
777 raise Exception("ERROR: FSP 1.x is not supported by the split command !")
778 ftype = fsp.Type
779 if not nametemplate:
780 nametemplate = fspfile
781 fspname, ext = os.path.splitext(os.path.basename(nametemplate))
782 filename = os.path.join(outdir, fspname + '_' + fsp.Type + ext)
783 hfsp = open(filename, 'wb')
784 print ("Create FSP component file '%s'" % filename)
785 for fvidx in fsp.FvIdxList:
786 fv = fd.FvList[fvidx]
787 hfsp.write(fv.FvData)
788 hfsp.close()
789
790 def RebaseFspBin (FspBinary, FspComponent, FspBase, OutputDir, OutputFile):
791 fd = FirmwareDevice(0, FspBinary)
792 fd.ParseFd ()
793 fd.ParseFsp ()
794
795 numcomp = len(FspComponent)
796 baselist = FspBase
797 if numcomp != len(baselist):
798 print ("ERROR: Required number of base does not match number of FSP component !")
799 return
800
801 newfspbin = fd.FdData[:]
802
803 for idx, fspcomp in enumerate(FspComponent):
804
805 found = False
806 for fsp in fd.FspList:
807 # Is this FSP 1.x single binary?
808 if fsp.Fih.HeaderRevision < 3:
809 found = True
810 ftype = 'X'
811 break
812 ftype = fsp.Type.lower()
813 if ftype == fspcomp:
814 found = True
815 break
816
817 if not found:
818 print ("ERROR: Could not find FSP_%c component to rebase !" % fspcomp.upper())
819 return
820
821 fspbase = baselist[idx]
822 if fspbase.startswith('0x'):
823 newbase = int(fspbase, 16)
824 else:
825 newbase = int(fspbase)
826 oldbase = fsp.Fih.ImageBase
827 delta = newbase - oldbase
828 print ("Rebase FSP-%c from 0x%08X to 0x%08X:" % (ftype.upper(),oldbase,newbase))
829
830 imglist = []
831 for fvidx in fsp.FvIdxList:
832 fv = fd.FvList[fvidx]
833 for ffs in fv.FfsList:
834 for sec in ffs.SecList:
835 if sec.SecHdr.Type in [EFI_SECTION_TYPE.TE, EFI_SECTION_TYPE.PE32]: # TE or PE32
836 offset = fd.Offset + fv.Offset + ffs.Offset + sec.Offset + sizeof(sec.SecHdr)
837 imglist.append ((offset, len(sec.SecData) - sizeof(sec.SecHdr)))
838
839 fcount = 0
840 pcount = 0
841 for (offset, length) in imglist:
842 img = PeTeImage(offset, fd.FdData[offset:offset + length])
843 img.ParseReloc()
844 pcount += img.Rebase(delta, newfspbin)
845 fcount += 1
846
847 print (" Patched %d entries in %d TE/PE32 images." % (pcount, fcount))
848
849 (count, applied) = fsp.Patch(delta, newfspbin)
850 print (" Patched %d entries using FSP patch table." % applied)
851 if count != applied:
852 print (" %d invalid entries are ignored !" % (count - applied))
853
854 if OutputFile == '':
855 filename = os.path.basename(FspBinary)
856 base, ext = os.path.splitext(filename)
857 OutputFile = base + "_%08X" % newbase + ext
858
859 fspname, ext = os.path.splitext(os.path.basename(OutputFile))
860 filename = os.path.join(OutputDir, fspname + ext)
861 fd = open(filename, "wb")
862 fd.write(newfspbin)
863 fd.close()
864
865 def main ():
866 parser = argparse.ArgumentParser()
867 subparsers = parser.add_subparsers(title='commands', dest="which")
868
869 parser_rebase = subparsers.add_parser('rebase', help='rebase a FSP into a new base address')
870 parser_rebase.set_defaults(which='rebase')
871 parser_rebase.add_argument('-f', '--fspbin' , dest='FspBinary', type=str, help='FSP binary file path', required = True)
872 parser_rebase.add_argument('-c', '--fspcomp', choices=['t','m','s','o'], nargs='+', dest='FspComponent', type=str, help='FSP component to rebase', default = "['t']", required = True)
873 parser_rebase.add_argument('-b', '--newbase', dest='FspBase', nargs='+', type=str, help='Rebased FSP binary file name', default = '', required = True)
874 parser_rebase.add_argument('-o', '--outdir' , dest='OutputDir', type=str, help='Output directory path', default = '.')
875 parser_rebase.add_argument('-n', '--outfile', dest='OutputFile', type=str, help='Rebased FSP binary file name', default = '')
876
877 parser_split = subparsers.add_parser('split', help='split a FSP into multiple components')
878 parser_split.set_defaults(which='split')
879 parser_split.add_argument('-f', '--fspbin' , dest='FspBinary', type=str, help='FSP binary file path', required = True)
880 parser_split.add_argument('-o', '--outdir' , dest='OutputDir', type=str, help='Output directory path', default = '.')
881 parser_split.add_argument('-n', '--nametpl', dest='NameTemplate', type=str, help='Output name template', default = '')
882
883 parser_genhdr = subparsers.add_parser('genhdr', help='generate a header file for FSP binary')
884 parser_genhdr.set_defaults(which='genhdr')
885 parser_genhdr.add_argument('-f', '--fspbin' , dest='FspBinary', type=str, help='FSP binary file path', required = True)
886 parser_genhdr.add_argument('-o', '--outdir' , dest='OutputDir', type=str, help='Output directory path', default = '.')
887 parser_genhdr.add_argument('-n', '--hfile', dest='HFileName', type=str, help='Output header file name', default = '')
888
889 parser_info = subparsers.add_parser('info', help='display FSP information')
890 parser_info.set_defaults(which='info')
891 parser_info.add_argument('-f', '--fspbin' , dest='FspBinary', type=str, help='FSP binary file path', required = True)
892
893 args = parser.parse_args()
894 if args.which in ['rebase', 'split', 'genhdr', 'info']:
895 if not os.path.exists(args.FspBinary):
896 raise Exception ("ERROR: Could not locate FSP binary file '%s' !" % args.FspBinary)
897 if hasattr(args, 'OutputDir') and not os.path.exists(args.OutputDir):
898 raise Exception ("ERROR: Invalid output directory '%s' !" % args.OutputDir)
899
900 if args.which == 'rebase':
901 RebaseFspBin (args.FspBinary, args.FspComponent, args.FspBase, args.OutputDir, args.OutputFile)
902 elif args.which == 'split':
903 SplitFspBin (args.FspBinary, args.OutputDir, args.NameTemplate)
904 elif args.which == 'genhdr':
905 GenFspHdr (args.FspBinary, args.OutputDir, args.HFileName)
906 elif args.which == 'info':
907 ShowFspInfo (args.FspBinary)
908 else:
909 parser.print_help()
910
911 return 0
912
913 if __name__ == '__main__':
914 sys.exit(main())