blob: 530629a5c9641bb216eda6c9276f53a0b9f1e64d [file] [log] [blame]
Simon Glass96a62962019-07-08 13:18:52 -06001# SPDX-License-Identifier: GPL-2.0+
2# Copyright 2019 Google LLC
3# Written by Simon Glass <sjg@chromium.org>
4
5"""Support for coreboot's CBFS format
6
7CBFS supports a header followed by a number of files, generally targeted at SPI
8flash.
9
10The format is somewhat defined by documentation in the coreboot tree although
11it is necessary to rely on the C structures and source code (mostly cbfstool)
12to fully understand it.
13
Simon Glassa61e6fe2019-07-08 13:18:55 -060014Currently supported: raw and stage types with compression, padding empty areas
Simon Glassc2f1aed2019-07-08 13:18:56 -060015 with empty files, fixed-offset files
Simon Glass96a62962019-07-08 13:18:52 -060016"""
17
18from __future__ import print_function
19
20from collections import OrderedDict
21import io
22import struct
23import sys
24
25import command
26import elf
27import tools
28
29# Set to True to enable printing output while working
30DEBUG = False
31
32# Set to True to enable output from running cbfstool for debugging
33VERBOSE = False
34
35# The master header, at the start of the CBFS
36HEADER_FORMAT = '>IIIIIIII'
37HEADER_LEN = 0x20
38HEADER_MAGIC = 0x4f524243
39HEADER_VERSION1 = 0x31313131
40HEADER_VERSION2 = 0x31313132
41
42# The file header, at the start of each file in the CBFS
43FILE_HEADER_FORMAT = b'>8sIIII'
44FILE_HEADER_LEN = 0x18
45FILE_MAGIC = b'LARCHIVE'
46FILENAME_ALIGN = 16 # Filename lengths are aligned to this
47
48# A stage header containing information about 'stage' files
49# Yes this is correct: this header is in litte-endian format
50STAGE_FORMAT = '<IQQII'
51STAGE_LEN = 0x1c
52
53# An attribute describring the compression used in a file
54ATTR_COMPRESSION_FORMAT = '>IIII'
55ATTR_COMPRESSION_LEN = 0x10
56
57# Attribute tags
58# Depending on how the header was initialised, it may be backed with 0x00 or
59# 0xff. Support both.
60FILE_ATTR_TAG_UNUSED = 0
61FILE_ATTR_TAG_UNUSED2 = 0xffffffff
62FILE_ATTR_TAG_COMPRESSION = 0x42435a4c
63FILE_ATTR_TAG_HASH = 0x68736148
64FILE_ATTR_TAG_POSITION = 0x42435350 # PSCB
65FILE_ATTR_TAG_ALIGNMENT = 0x42434c41 # ALCB
66FILE_ATTR_TAG_PADDING = 0x47444150 # PDNG
67
68# This is 'the size of bootblock reserved in firmware image (cbfs.txt)'
69# Not much more info is available, but we set it to 4, due to this comment in
70# cbfstool.c:
71# This causes 4 bytes to be left out at the end of the image, for two reasons:
72# 1. The cbfs master header pointer resides there
73# 2. Ssme cbfs implementations assume that an image that resides below 4GB has
74# a bootblock and get confused when the end of the image is at 4GB == 0.
75MIN_BOOTBLOCK_SIZE = 4
76
77# Files start aligned to this boundary in the CBFS
78ENTRY_ALIGN = 0x40
79
80# CBFSs must declare an architecture since much of the logic is designed with
81# x86 in mind. The effect of setting this value is not well documented, but in
82# general x86 is used and this makes use of a boot block and an image that ends
83# at the end of 32-bit address space.
84ARCHITECTURE_UNKNOWN = 0xffffffff
85ARCHITECTURE_X86 = 0x00000001
86ARCHITECTURE_ARM = 0x00000010
87ARCHITECTURE_AARCH64 = 0x0000aa64
88ARCHITECTURE_MIPS = 0x00000100
89ARCHITECTURE_RISCV = 0xc001d0de
90ARCHITECTURE_PPC64 = 0x407570ff
91
92ARCH_NAMES = {
93 ARCHITECTURE_UNKNOWN : 'unknown',
94 ARCHITECTURE_X86 : 'x86',
95 ARCHITECTURE_ARM : 'arm',
96 ARCHITECTURE_AARCH64 : 'arm64',
97 ARCHITECTURE_MIPS : 'mips',
98 ARCHITECTURE_RISCV : 'riscv',
99 ARCHITECTURE_PPC64 : 'ppc64',
100 }
101
102# File types. Only supported ones are included here
103TYPE_CBFSHEADER = 0x02 # Master header, HEADER_FORMAT
104TYPE_STAGE = 0x10 # Stage, holding an executable, see STAGE_FORMAT
105TYPE_RAW = 0x50 # Raw file, possibly compressed
Simon Glassa61e6fe2019-07-08 13:18:55 -0600106TYPE_EMPTY = 0xffffffff # Empty data
Simon Glass96a62962019-07-08 13:18:52 -0600107
108# Compression types
109COMPRESS_NONE, COMPRESS_LZMA, COMPRESS_LZ4 = range(3)
110
111COMPRESS_NAMES = {
112 COMPRESS_NONE : 'none',
113 COMPRESS_LZMA : 'lzma',
114 COMPRESS_LZ4 : 'lz4',
115 }
116
117def find_arch(find_name):
118 """Look up an architecture name
119
120 Args:
121 find_name: Architecture name to find
122
123 Returns:
124 ARCHITECTURE_... value or None if not found
125 """
126 for arch, name in ARCH_NAMES.items():
127 if name == find_name:
128 return arch
129 return None
130
131def find_compress(find_name):
132 """Look up a compression algorithm name
133
134 Args:
135 find_name: Compression algorithm name to find
136
137 Returns:
138 COMPRESS_... value or None if not found
139 """
140 for compress, name in COMPRESS_NAMES.items():
141 if name == find_name:
142 return compress
143 return None
144
145def align_int(val, align):
146 """Align a value up to the given alignment
147
148 Args:
149 val: Integer value to align
150 align: Integer alignment value (e.g. 4 to align to 4-byte boundary)
151
152 Returns:
153 integer value aligned to the required boundary, rounding up if necessary
154 """
155 return int((val + align - 1) / align) * align
156
Simon Glassa61e6fe2019-07-08 13:18:55 -0600157def align_int_down(val, align):
158 """Align a value down to the given alignment
159
160 Args:
161 val: Integer value to align
162 align: Integer alignment value (e.g. 4 to align to 4-byte boundary)
163
164 Returns:
165 integer value aligned to the required boundary, rounding down if
166 necessary
167 """
168 return int(val / align) * align
169
Simon Glass96a62962019-07-08 13:18:52 -0600170def _pack_string(instr):
171 """Pack a string to the required aligned size by adding padding
172
173 Args:
174 instr: String to process
175
176 Returns:
177 String with required padding (at least one 0x00 byte) at the end
178 """
179 val = tools.ToBytes(instr)
180 pad_len = align_int(len(val) + 1, FILENAME_ALIGN)
181 return val + tools.GetBytes(0, pad_len - len(val))
182
183
184class CbfsFile(object):
185 """Class to represent a single CBFS file
186
187 This is used to hold the information about a file, including its contents.
Simon Glass3170e542019-07-08 14:25:39 -0600188 Use the get_data_and_offset() method to obtain the raw output for writing to
189 CBFS.
Simon Glass96a62962019-07-08 13:18:52 -0600190
191 Properties:
192 name: Name of file
193 offset: Offset of file data from start of file header
Simon Glassc2f1aed2019-07-08 13:18:56 -0600194 cbfs_offset: Offset of file data in bytes from start of CBFS, or None to
195 place this file anyway
Simon Glass96a62962019-07-08 13:18:52 -0600196 data: Contents of file, uncompressed
197 data_len: Length of (possibly compressed) data in bytes
198 ftype: File type (TYPE_...)
199 compression: Compression type (COMPRESS_...)
200 memlen: Length of data in memory (typically the uncompressed length)
201 load: Load address in memory if known, else None
202 entry: Entry address in memory if known, else None. This is where
203 execution starts after the file is loaded
204 base_address: Base address to use for 'stage' files
Simon Glassa61e6fe2019-07-08 13:18:55 -0600205 erase_byte: Erase byte to use for padding between the file header and
206 contents (used for empty files)
207 size: Size of the file in bytes (used for empty files)
Simon Glass96a62962019-07-08 13:18:52 -0600208 """
Simon Glassc2f1aed2019-07-08 13:18:56 -0600209 def __init__(self, name, ftype, data, cbfs_offset, compress=COMPRESS_NONE):
Simon Glass96a62962019-07-08 13:18:52 -0600210 self.name = name
211 self.offset = None
Simon Glassc2f1aed2019-07-08 13:18:56 -0600212 self.cbfs_offset = cbfs_offset
Simon Glass96a62962019-07-08 13:18:52 -0600213 self.data = data
214 self.ftype = ftype
215 self.compress = compress
216 self.memlen = len(data)
217 self.load = None
218 self.entry = None
219 self.base_address = None
220 self.data_len = 0
Simon Glassa61e6fe2019-07-08 13:18:55 -0600221 self.erase_byte = None
222 self.size = None
Simon Glass96a62962019-07-08 13:18:52 -0600223
224 def decompress(self):
225 """Handle decompressing data if necessary"""
226 indata = self.data
227 if self.compress == COMPRESS_LZ4:
228 data = tools.Decompress(indata, 'lz4')
229 elif self.compress == COMPRESS_LZMA:
230 data = tools.Decompress(indata, 'lzma')
231 else:
232 data = indata
233 self.memlen = len(data)
234 self.data = data
235 self.data_len = len(indata)
236
237 @classmethod
Simon Glassc2f1aed2019-07-08 13:18:56 -0600238 def stage(cls, base_address, name, data, cbfs_offset):
Simon Glass96a62962019-07-08 13:18:52 -0600239 """Create a new stage file
240
241 Args:
242 base_address: Int base address for memory-mapping of ELF file
243 name: String file name to put in CBFS (does not need to correspond
244 to the name that the file originally came from)
245 data: Contents of file
Simon Glassc2f1aed2019-07-08 13:18:56 -0600246 cbfs_offset: Offset of file data in bytes from start of CBFS, or
247 None to place this file anyway
Simon Glass96a62962019-07-08 13:18:52 -0600248
249 Returns:
250 CbfsFile object containing the file information
251 """
Simon Glassc2f1aed2019-07-08 13:18:56 -0600252 cfile = CbfsFile(name, TYPE_STAGE, data, cbfs_offset)
Simon Glass96a62962019-07-08 13:18:52 -0600253 cfile.base_address = base_address
254 return cfile
255
256 @classmethod
Simon Glassc2f1aed2019-07-08 13:18:56 -0600257 def raw(cls, name, data, cbfs_offset, compress):
Simon Glass96a62962019-07-08 13:18:52 -0600258 """Create a new raw file
259
260 Args:
261 name: String file name to put in CBFS (does not need to correspond
262 to the name that the file originally came from)
263 data: Contents of file
Simon Glassc2f1aed2019-07-08 13:18:56 -0600264 cbfs_offset: Offset of file data in bytes from start of CBFS, or
265 None to place this file anyway
Simon Glass96a62962019-07-08 13:18:52 -0600266 compress: Compression algorithm to use (COMPRESS_...)
267
268 Returns:
269 CbfsFile object containing the file information
270 """
Simon Glassc2f1aed2019-07-08 13:18:56 -0600271 return CbfsFile(name, TYPE_RAW, data, cbfs_offset, compress)
Simon Glass96a62962019-07-08 13:18:52 -0600272
Simon Glassa61e6fe2019-07-08 13:18:55 -0600273 @classmethod
274 def empty(cls, space_to_use, erase_byte):
275 """Create a new empty file of a given size
276
277 Args:
278 space_to_use:: Size of available space, which must be at least as
279 large as the alignment size for this CBFS
280 erase_byte: Byte to use for contents of file (repeated through the
281 whole file)
282
283 Returns:
284 CbfsFile object containing the file information
285 """
Simon Glassc2f1aed2019-07-08 13:18:56 -0600286 cfile = CbfsFile('', TYPE_EMPTY, b'', None)
Simon Glassa61e6fe2019-07-08 13:18:55 -0600287 cfile.size = space_to_use - FILE_HEADER_LEN - FILENAME_ALIGN
288 cfile.erase_byte = erase_byte
289 return cfile
290
Simon Glassc2f1aed2019-07-08 13:18:56 -0600291 def calc_start_offset(self):
292 """Check if this file needs to start at a particular offset in CBFS
293
294 Returns:
295 None if the file can be placed anywhere, or
296 the largest offset where the file could start (integer)
297 """
298 if self.cbfs_offset is None:
299 return None
300 return self.cbfs_offset - self.get_header_len()
301
302 def get_header_len(self):
303 """Get the length of headers required for a file
304
305 This is the minimum length required before the actual data for this file
306 could start. It might start later if there is padding.
307
308 Returns:
309 Total length of all non-data fields, in bytes
310 """
311 name = _pack_string(self.name)
312 hdr_len = len(name) + FILE_HEADER_LEN
313 if self.ftype == TYPE_STAGE:
314 pass
315 elif self.ftype == TYPE_RAW:
316 hdr_len += ATTR_COMPRESSION_LEN
317 elif self.ftype == TYPE_EMPTY:
318 pass
319 else:
320 raise ValueError('Unknown file type %#x\n' % self.ftype)
321 return hdr_len
322
Simon Glass3170e542019-07-08 14:25:39 -0600323 def get_data_and_offset(self, offset=None, pad_byte=None):
324 """Obtain the contents of the file, in CBFS format and the offset of
325 the data within the file
Simon Glass96a62962019-07-08 13:18:52 -0600326
327 Returns:
Simon Glass3170e542019-07-08 14:25:39 -0600328 tuple:
329 bytes representing the contents of this file, packed and aligned
330 for directly inserting into the final CBFS output
331 offset to the file data from the start of the returned data.
Simon Glass96a62962019-07-08 13:18:52 -0600332 """
333 name = _pack_string(self.name)
334 hdr_len = len(name) + FILE_HEADER_LEN
335 attr_pos = 0
336 content = b''
337 attr = b''
Simon Glassc2f1aed2019-07-08 13:18:56 -0600338 pad = b''
Simon Glass96a62962019-07-08 13:18:52 -0600339 data = self.data
340 if self.ftype == TYPE_STAGE:
341 elf_data = elf.DecodeElf(data, self.base_address)
342 content = struct.pack(STAGE_FORMAT, self.compress,
343 elf_data.entry, elf_data.load,
344 len(elf_data.data), elf_data.memsize)
345 data = elf_data.data
346 elif self.ftype == TYPE_RAW:
347 orig_data = data
348 if self.compress == COMPRESS_LZ4:
349 data = tools.Compress(orig_data, 'lz4')
350 elif self.compress == COMPRESS_LZMA:
351 data = tools.Compress(orig_data, 'lzma')
352 attr = struct.pack(ATTR_COMPRESSION_FORMAT,
353 FILE_ATTR_TAG_COMPRESSION, ATTR_COMPRESSION_LEN,
354 self.compress, len(orig_data))
Simon Glassa61e6fe2019-07-08 13:18:55 -0600355 elif self.ftype == TYPE_EMPTY:
356 data = tools.GetBytes(self.erase_byte, self.size)
Simon Glass96a62962019-07-08 13:18:52 -0600357 else:
358 raise ValueError('Unknown type %#x when writing\n' % self.ftype)
359 if attr:
360 attr_pos = hdr_len
361 hdr_len += len(attr)
Simon Glassc2f1aed2019-07-08 13:18:56 -0600362 if self.cbfs_offset is not None:
363 pad_len = self.cbfs_offset - offset - hdr_len
364 if pad_len < 0: # pragma: no cover
365 # Test coverage of this is not available since this should never
366 # happen. It indicates that get_header_len() provided an
367 # incorrect value (too small) so that we decided that we could
368 # put this file at the requested place, but in fact a previous
369 # file extends far enough into the CBFS that this is not
370 # possible.
371 raise ValueError("Internal error: CBFS file '%s': Requested offset %#x but current output position is %#x" %
372 (self.name, self.cbfs_offset, offset))
373 pad = tools.GetBytes(pad_byte, pad_len)
374 hdr_len += pad_len
Simon Glass3170e542019-07-08 14:25:39 -0600375
376 # This is the offset of the start of the file's data,
377 size = len(content) + len(data)
378 hdr = struct.pack(FILE_HEADER_FORMAT, FILE_MAGIC, size,
Simon Glass96a62962019-07-08 13:18:52 -0600379 self.ftype, attr_pos, hdr_len)
Simon Glassc2f1aed2019-07-08 13:18:56 -0600380
381 # Do a sanity check of the get_header_len() function, to ensure that it
382 # stays in lockstep with this function
383 expected_len = self.get_header_len()
384 actual_len = len(hdr + name + attr)
385 if expected_len != actual_len: # pragma: no cover
386 # Test coverage of this is not available since this should never
387 # happen. It probably indicates that get_header_len() is broken.
388 raise ValueError("Internal error: CBFS file '%s': Expected headers of %#x bytes, got %#d" %
389 (self.name, expected_len, actual_len))
Simon Glass3170e542019-07-08 14:25:39 -0600390 return hdr + name + attr + pad + content + data, hdr_len
Simon Glass96a62962019-07-08 13:18:52 -0600391
392
393class CbfsWriter(object):
394 """Class to handle writing a Coreboot File System (CBFS)
395
396 Usage is something like:
397
398 cbw = CbfsWriter(size)
399 cbw.add_file_raw('u-boot', tools.ReadFile('u-boot.bin'))
400 ...
Simon Glass3170e542019-07-08 14:25:39 -0600401 data, cbfs_offset = cbw.get_data_and_offset()
Simon Glass96a62962019-07-08 13:18:52 -0600402
403 Attributes:
404 _master_name: Name of the file containing the master header
405 _size: Size of the filesystem, in bytes
406 _files: Ordered list of files in the CBFS, each a CbfsFile
407 _arch: Architecture of the CBFS (ARCHITECTURE_...)
408 _bootblock_size: Size of the bootblock, typically at the end of the CBFS
409 _erase_byte: Byte to use for empty space in the CBFS
410 _align: Alignment to use for files, typically ENTRY_ALIGN
411 _base_address: Boot block offset in bytes from the start of CBFS.
412 Typically this is located at top of the CBFS. It is 0 when there is
413 no boot block
414 _header_offset: Offset of master header in bytes from start of CBFS
415 _contents_offset: Offset of first file header
416 _hdr_at_start: True if the master header is at the start of the CBFS,
417 instead of the end as normal for x86
418 _add_fileheader: True to add a fileheader around the master header
419 """
420 def __init__(self, size, arch=ARCHITECTURE_X86):
421 """Set up a new CBFS
422
423 This sets up all properties to default values. Files can be added using
424 add_file_raw(), etc.
425
426 Args:
427 size: Size of CBFS in bytes
428 arch: Architecture to declare for CBFS
429 """
430 self._master_name = 'cbfs master header'
431 self._size = size
432 self._files = OrderedDict()
433 self._arch = arch
434 self._bootblock_size = 0
435 self._erase_byte = 0xff
436 self._align = ENTRY_ALIGN
437 self._add_fileheader = False
438 if self._arch == ARCHITECTURE_X86:
439 # Allow 4 bytes for the header pointer. That holds the
440 # twos-compliment negative offset of the master header in bytes
441 # measured from one byte past the end of the CBFS
442 self._base_address = self._size - max(self._bootblock_size,
443 MIN_BOOTBLOCK_SIZE)
444 self._header_offset = self._base_address - HEADER_LEN
445 self._contents_offset = 0
446 self._hdr_at_start = False
447 else:
448 # For non-x86, different rules apply
449 self._base_address = 0
450 self._header_offset = align_int(self._base_address +
451 self._bootblock_size, 4)
452 self._contents_offset = align_int(self._header_offset +
453 FILE_HEADER_LEN +
454 self._bootblock_size, self._align)
455 self._hdr_at_start = True
456
457 def _skip_to(self, fd, offset):
458 """Write out pad bytes until a given offset
459
460 Args:
461 fd: File objext to write to
462 offset: Offset to write to
463 """
464 if fd.tell() > offset:
465 raise ValueError('No space for data before offset %#x (current offset %#x)' %
466 (offset, fd.tell()))
467 fd.write(tools.GetBytes(self._erase_byte, offset - fd.tell()))
468
Simon Glassa61e6fe2019-07-08 13:18:55 -0600469 def _pad_to(self, fd, offset):
470 """Write out pad bytes and/or an empty file until a given offset
471
472 Args:
473 fd: File objext to write to
474 offset: Offset to write to
475 """
476 self._align_to(fd, self._align)
477 upto = fd.tell()
478 if upto > offset:
479 raise ValueError('No space for data before pad offset %#x (current offset %#x)' %
480 (offset, upto))
481 todo = align_int_down(offset - upto, self._align)
482 if todo:
483 cbf = CbfsFile.empty(todo, self._erase_byte)
Simon Glass3170e542019-07-08 14:25:39 -0600484 fd.write(cbf.get_data_and_offset()[0])
Simon Glassa61e6fe2019-07-08 13:18:55 -0600485 self._skip_to(fd, offset)
486
Simon Glass96a62962019-07-08 13:18:52 -0600487 def _align_to(self, fd, align):
488 """Write out pad bytes until a given alignment is reached
489
490 This only aligns if the resulting output would not reach the end of the
491 CBFS, since we want to leave the last 4 bytes for the master-header
492 pointer.
493
494 Args:
495 fd: File objext to write to
496 align: Alignment to require (e.g. 4 means pad to next 4-byte
497 boundary)
498 """
499 offset = align_int(fd.tell(), align)
500 if offset < self._size:
501 self._skip_to(fd, offset)
502
Simon Glassc2f1aed2019-07-08 13:18:56 -0600503 def add_file_stage(self, name, data, cbfs_offset=None):
Simon Glass96a62962019-07-08 13:18:52 -0600504 """Add a new stage file to the CBFS
505
506 Args:
507 name: String file name to put in CBFS (does not need to correspond
508 to the name that the file originally came from)
509 data: Contents of file
Simon Glassc2f1aed2019-07-08 13:18:56 -0600510 cbfs_offset: Offset of this file's data within the CBFS, in bytes,
511 or None to place this file anywhere
Simon Glass96a62962019-07-08 13:18:52 -0600512
513 Returns:
514 CbfsFile object created
515 """
Simon Glassc2f1aed2019-07-08 13:18:56 -0600516 cfile = CbfsFile.stage(self._base_address, name, data, cbfs_offset)
Simon Glass96a62962019-07-08 13:18:52 -0600517 self._files[name] = cfile
518 return cfile
519
Simon Glassc2f1aed2019-07-08 13:18:56 -0600520 def add_file_raw(self, name, data, cbfs_offset=None,
521 compress=COMPRESS_NONE):
Simon Glass96a62962019-07-08 13:18:52 -0600522 """Create a new raw file
523
524 Args:
525 name: String file name to put in CBFS (does not need to correspond
526 to the name that the file originally came from)
527 data: Contents of file
Simon Glassc2f1aed2019-07-08 13:18:56 -0600528 cbfs_offset: Offset of this file's data within the CBFS, in bytes,
529 or None to place this file anywhere
Simon Glass96a62962019-07-08 13:18:52 -0600530 compress: Compression algorithm to use (COMPRESS_...)
531
532 Returns:
533 CbfsFile object created
534 """
Simon Glassc2f1aed2019-07-08 13:18:56 -0600535 cfile = CbfsFile.raw(name, data, cbfs_offset, compress)
Simon Glass96a62962019-07-08 13:18:52 -0600536 self._files[name] = cfile
537 return cfile
538
539 def _write_header(self, fd, add_fileheader):
540 """Write out the master header to a CBFS
541
542 Args:
543 fd: File object
544 add_fileheader: True to place the master header in a file header
545 record
546 """
547 if fd.tell() > self._header_offset:
548 raise ValueError('No space for header at offset %#x (current offset %#x)' %
549 (self._header_offset, fd.tell()))
550 if not add_fileheader:
Simon Glassa61e6fe2019-07-08 13:18:55 -0600551 self._pad_to(fd, self._header_offset)
Simon Glass96a62962019-07-08 13:18:52 -0600552 hdr = struct.pack(HEADER_FORMAT, HEADER_MAGIC, HEADER_VERSION2,
553 self._size, self._bootblock_size, self._align,
554 self._contents_offset, self._arch, 0xffffffff)
555 if add_fileheader:
556 name = _pack_string(self._master_name)
557 fd.write(struct.pack(FILE_HEADER_FORMAT, FILE_MAGIC, len(hdr),
558 TYPE_CBFSHEADER, 0,
559 FILE_HEADER_LEN + len(name)))
560 fd.write(name)
561 self._header_offset = fd.tell()
562 fd.write(hdr)
563 self._align_to(fd, self._align)
564 else:
565 fd.write(hdr)
566
567 def get_data(self):
568 """Obtain the full contents of the CBFS
569
570 Thhis builds the CBFS with headers and all required files.
571
572 Returns:
573 'bytes' type containing the data
574 """
575 fd = io.BytesIO()
576
577 # THe header can go at the start in some cases
578 if self._hdr_at_start:
579 self._write_header(fd, add_fileheader=self._add_fileheader)
580 self._skip_to(fd, self._contents_offset)
581
582 # Write out each file
583 for cbf in self._files.values():
Simon Glassc2f1aed2019-07-08 13:18:56 -0600584 # Place the file at its requested place, if any
585 offset = cbf.calc_start_offset()
586 if offset is not None:
587 self._pad_to(fd, align_int_down(offset, self._align))
Simon Glass3170e542019-07-08 14:25:39 -0600588 pos = fd.tell()
589 data, data_offset = cbf.get_data_and_offset(pos, self._erase_byte)
590 fd.write(data)
Simon Glass96a62962019-07-08 13:18:52 -0600591 self._align_to(fd, self._align)
Simon Glass3170e542019-07-08 14:25:39 -0600592 cbf.calced_cbfs_offset = pos + data_offset
Simon Glass96a62962019-07-08 13:18:52 -0600593 if not self._hdr_at_start:
594 self._write_header(fd, add_fileheader=self._add_fileheader)
595
596 # Pad to the end and write a pointer to the CBFS master header
Simon Glassa61e6fe2019-07-08 13:18:55 -0600597 self._pad_to(fd, self._base_address or self._size - 4)
Simon Glass96a62962019-07-08 13:18:52 -0600598 rel_offset = self._header_offset - self._size
599 fd.write(struct.pack('<I', rel_offset & 0xffffffff))
600
601 return fd.getvalue()
602
603
604class CbfsReader(object):
605 """Class to handle reading a Coreboot File System (CBFS)
606
607 Usage is something like:
608 cbfs = cbfs_util.CbfsReader(data)
609 cfile = cbfs.files['u-boot']
610 self.WriteFile('u-boot.bin', cfile.data)
611
612 Attributes:
613 files: Ordered list of CbfsFile objects
614 align: Alignment to use for files, typically ENTRT_ALIGN
615 stage_base_address: Base address to use when mapping ELF files into the
616 CBFS for TYPE_STAGE files. If this is larger than the code address
617 of the ELF file, then data at the start of the ELF file will not
618 appear in the CBFS. Currently there are no tests for behaviour as
619 documentation is sparse
620 magic: Integer magic number from master header (HEADER_MAGIC)
621 version: Version number of CBFS (HEADER_VERSION2)
622 rom_size: Size of CBFS
623 boot_block_size: Size of boot block
624 cbfs_offset: Offset of the first file in bytes from start of CBFS
625 arch: Architecture of CBFS file (ARCHITECTURE_...)
626 """
627 def __init__(self, data, read=True):
628 self.align = ENTRY_ALIGN
629 self.arch = None
630 self.boot_block_size = None
631 self.cbfs_offset = None
632 self.files = OrderedDict()
633 self.magic = None
634 self.rom_size = None
635 self.stage_base_address = 0
636 self.version = None
637 self.data = data
638 if read:
639 self.read()
640
641 def read(self):
642 """Read all the files in the CBFS and add them to self.files"""
643 with io.BytesIO(self.data) as fd:
644 # First, get the master header
645 if not self._find_and_read_header(fd, len(self.data)):
646 raise ValueError('Cannot find master header')
647 fd.seek(self.cbfs_offset)
648
649 # Now read in the files one at a time
650 while True:
651 cfile = self._read_next_file(fd)
652 if cfile:
653 self.files[cfile.name] = cfile
654 elif cfile is False:
655 break
656
657 def _find_and_read_header(self, fd, size):
658 """Find and read the master header in the CBFS
659
660 This looks at the pointer word at the very end of the CBFS. This is an
661 offset to the header relative to the size of the CBFS, which is assumed
662 to be known. Note that the offset is in *little endian* format.
663
664 Args:
665 fd: File to read from
666 size: Size of file
667
668 Returns:
669 True if header was found, False if not
670 """
671 orig_pos = fd.tell()
672 fd.seek(size - 4)
673 rel_offset, = struct.unpack('<I', fd.read(4))
674 pos = (size + rel_offset) & 0xffffffff
675 fd.seek(pos)
676 found = self._read_header(fd)
677 if not found:
678 print('Relative offset seems wrong, scanning whole image')
679 for pos in range(0, size - HEADER_LEN, 4):
680 fd.seek(pos)
681 found = self._read_header(fd)
682 if found:
683 break
684 fd.seek(orig_pos)
685 return found
686
687 def _read_next_file(self, fd):
688 """Read the next file from a CBFS
689
690 Args:
691 fd: File to read from
692
693 Returns:
694 CbfsFile object, if found
695 None if no object found, but data was parsed (e.g. TYPE_CBFSHEADER)
696 False if at end of CBFS and reading should stop
697 """
698 file_pos = fd.tell()
699 data = fd.read(FILE_HEADER_LEN)
700 if len(data) < FILE_HEADER_LEN:
701 print('File header at %x ran out of data' % file_pos)
702 return False
703 magic, size, ftype, attr, offset = struct.unpack(FILE_HEADER_FORMAT,
704 data)
705 if magic != FILE_MAGIC:
706 return False
707 pos = fd.tell()
708 name = self._read_string(fd)
709 if name is None:
710 print('String at %x ran out of data' % pos)
711 return False
712
713 if DEBUG:
714 print('name', name)
715
716 # If there are attribute headers present, read those
717 compress = self._read_attr(fd, file_pos, attr, offset)
718 if compress is None:
719 return False
720
721 # Create the correct CbfsFile object depending on the type
722 cfile = None
Simon Glassc2f1aed2019-07-08 13:18:56 -0600723 cbfs_offset = file_pos + offset
724 fd.seek(cbfs_offset, io.SEEK_SET)
Simon Glass96a62962019-07-08 13:18:52 -0600725 if ftype == TYPE_CBFSHEADER:
726 self._read_header(fd)
727 elif ftype == TYPE_STAGE:
728 data = fd.read(STAGE_LEN)
Simon Glassc2f1aed2019-07-08 13:18:56 -0600729 cfile = CbfsFile.stage(self.stage_base_address, name, b'',
730 cbfs_offset)
Simon Glass96a62962019-07-08 13:18:52 -0600731 (cfile.compress, cfile.entry, cfile.load, cfile.data_len,
732 cfile.memlen) = struct.unpack(STAGE_FORMAT, data)
733 cfile.data = fd.read(cfile.data_len)
734 elif ftype == TYPE_RAW:
735 data = fd.read(size)
Simon Glassc2f1aed2019-07-08 13:18:56 -0600736 cfile = CbfsFile.raw(name, data, cbfs_offset, compress)
Simon Glass96a62962019-07-08 13:18:52 -0600737 cfile.decompress()
738 if DEBUG:
739 print('data', data)
Simon Glassa61e6fe2019-07-08 13:18:55 -0600740 elif ftype == TYPE_EMPTY:
741 # Just read the data and discard it, since it is only padding
742 fd.read(size)
Simon Glassc2f1aed2019-07-08 13:18:56 -0600743 cfile = CbfsFile('', TYPE_EMPTY, b'', cbfs_offset)
Simon Glass96a62962019-07-08 13:18:52 -0600744 else:
745 raise ValueError('Unknown type %#x when reading\n' % ftype)
746 if cfile:
747 cfile.offset = offset
748
749 # Move past the padding to the start of a possible next file. If we are
750 # already at an alignment boundary, then there is no padding.
751 pad = (self.align - fd.tell() % self.align) % self.align
752 fd.seek(pad, io.SEEK_CUR)
753 return cfile
754
755 @classmethod
756 def _read_attr(cls, fd, file_pos, attr, offset):
757 """Read attributes from the file
758
759 CBFS files can have attributes which are things that cannot fit into the
Simon Glassc2f1aed2019-07-08 13:18:56 -0600760 header. The only attributes currently supported are compression and the
761 unused tag.
Simon Glass96a62962019-07-08 13:18:52 -0600762
763 Args:
764 fd: File to read from
765 file_pos: Position of file in fd
766 attr: Offset of attributes, 0 if none
767 offset: Offset of file data (used to indicate the end of the
768 attributes)
769
770 Returns:
771 Compression to use for the file (COMPRESS_...)
772 """
773 compress = COMPRESS_NONE
774 if not attr:
775 return compress
776 attr_size = offset - attr
777 fd.seek(file_pos + attr, io.SEEK_SET)
778 while attr_size:
779 pos = fd.tell()
780 hdr = fd.read(8)
781 if len(hdr) < 8:
782 print('Attribute tag at %x ran out of data' % pos)
783 return None
784 atag, alen = struct.unpack(">II", hdr)
785 data = hdr + fd.read(alen - 8)
786 if atag == FILE_ATTR_TAG_COMPRESSION:
787 # We don't currently use this information
788 atag, alen, compress, _decomp_size = struct.unpack(
789 ATTR_COMPRESSION_FORMAT, data)
Simon Glassc2f1aed2019-07-08 13:18:56 -0600790 elif atag == FILE_ATTR_TAG_UNUSED2:
791 break
Simon Glass96a62962019-07-08 13:18:52 -0600792 else:
793 print('Unknown attribute tag %x' % atag)
794 attr_size -= len(data)
795 return compress
796
797 def _read_header(self, fd):
798 """Read the master header
799
800 Reads the header and stores the information obtained into the member
801 variables.
802
803 Args:
804 fd: File to read from
805
806 Returns:
807 True if header was read OK, False if it is truncated or has the
808 wrong magic or version
809 """
810 pos = fd.tell()
811 data = fd.read(HEADER_LEN)
812 if len(data) < HEADER_LEN:
813 print('Header at %x ran out of data' % pos)
814 return False
815 (self.magic, self.version, self.rom_size, self.boot_block_size,
816 self.align, self.cbfs_offset, self.arch, _) = struct.unpack(
817 HEADER_FORMAT, data)
818 return self.magic == HEADER_MAGIC and (
819 self.version == HEADER_VERSION1 or
820 self.version == HEADER_VERSION2)
821
822 @classmethod
823 def _read_string(cls, fd):
824 """Read a string from a file
825
826 This reads a string and aligns the data to the next alignment boundary
827
828 Args:
829 fd: File to read from
830
831 Returns:
832 string read ('str' type) encoded to UTF-8, or None if we ran out of
833 data
834 """
835 val = b''
836 while True:
837 data = fd.read(FILENAME_ALIGN)
838 if len(data) < FILENAME_ALIGN:
839 return None
840 pos = data.find(b'\0')
841 if pos == -1:
842 val += data
843 else:
844 val += data[:pos]
845 break
846 return val.decode('utf-8')
847
848
Simon Glassc2f1aed2019-07-08 13:18:56 -0600849def cbfstool(fname, *cbfs_args, **kwargs):
Simon Glass96a62962019-07-08 13:18:52 -0600850 """Run cbfstool with provided arguments
851
852 If the tool fails then this function raises an exception and prints out the
853 output and stderr.
854
855 Args:
856 fname: Filename of CBFS
857 *cbfs_args: List of arguments to pass to cbfstool
858
859 Returns:
860 CommandResult object containing the results
861 """
Simon Glassc2f1aed2019-07-08 13:18:56 -0600862 args = ['cbfstool', fname] + list(cbfs_args)
863 if kwargs.get('base') is not None:
864 args += ['-b', '%#x' % kwargs['base']]
Simon Glass96a62962019-07-08 13:18:52 -0600865 result = command.RunPipe([args], capture=not VERBOSE,
866 capture_stderr=not VERBOSE, raise_on_error=False)
867 if result.return_code:
868 print(result.stderr, file=sys.stderr)
869 raise Exception("Failed to run (error %d): '%s'" %
870 (result.return_code, ' '.join(args)))