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