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