blob: 1cdbcb2339e5d9bde2f3b7d5927391344327caf8 [file] [log] [blame]
Simon Glass4997a7e2019-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 Glass7c173ce2019-07-08 13:18:55 -060014Currently supported: raw and stage types with compression, padding empty areas
Simon Glasse073d4e2019-07-08 13:18:56 -060015 with empty files, fixed-offset files
Simon Glass4997a7e2019-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 Glass7c173ce2019-07-08 13:18:55 -0600106TYPE_EMPTY = 0xffffffff # Empty data
Simon Glass4997a7e2019-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 Glass7c173ce2019-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 Glass4997a7e2019-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.
188 Use the get_data() method to obtain the raw output for writing to CBFS.
189
190 Properties:
191 name: Name of file
192 offset: Offset of file data from start of file header
Simon Glasse073d4e2019-07-08 13:18:56 -0600193 cbfs_offset: Offset of file data in bytes from start of CBFS, or None to
194 place this file anyway
Simon Glass4997a7e2019-07-08 13:18:52 -0600195 data: Contents of file, uncompressed
196 data_len: Length of (possibly compressed) data in bytes
197 ftype: File type (TYPE_...)
198 compression: Compression type (COMPRESS_...)
199 memlen: Length of data in memory (typically the uncompressed length)
200 load: Load address in memory if known, else None
201 entry: Entry address in memory if known, else None. This is where
202 execution starts after the file is loaded
203 base_address: Base address to use for 'stage' files
Simon Glass7c173ce2019-07-08 13:18:55 -0600204 erase_byte: Erase byte to use for padding between the file header and
205 contents (used for empty files)
206 size: Size of the file in bytes (used for empty files)
Simon Glass4997a7e2019-07-08 13:18:52 -0600207 """
Simon Glasse073d4e2019-07-08 13:18:56 -0600208 def __init__(self, name, ftype, data, cbfs_offset, compress=COMPRESS_NONE):
Simon Glass4997a7e2019-07-08 13:18:52 -0600209 self.name = name
210 self.offset = None
Simon Glasse073d4e2019-07-08 13:18:56 -0600211 self.cbfs_offset = cbfs_offset
Simon Glass4997a7e2019-07-08 13:18:52 -0600212 self.data = data
213 self.ftype = ftype
214 self.compress = compress
215 self.memlen = len(data)
216 self.load = None
217 self.entry = None
218 self.base_address = None
219 self.data_len = 0
Simon Glass7c173ce2019-07-08 13:18:55 -0600220 self.erase_byte = None
221 self.size = None
Simon Glass4997a7e2019-07-08 13:18:52 -0600222
223 def decompress(self):
224 """Handle decompressing data if necessary"""
225 indata = self.data
226 if self.compress == COMPRESS_LZ4:
227 data = tools.Decompress(indata, 'lz4')
228 elif self.compress == COMPRESS_LZMA:
229 data = tools.Decompress(indata, 'lzma')
230 else:
231 data = indata
232 self.memlen = len(data)
233 self.data = data
234 self.data_len = len(indata)
235
236 @classmethod
Simon Glasse073d4e2019-07-08 13:18:56 -0600237 def stage(cls, base_address, name, data, cbfs_offset):
Simon Glass4997a7e2019-07-08 13:18:52 -0600238 """Create a new stage file
239
240 Args:
241 base_address: Int base address for memory-mapping of ELF file
242 name: String file name to put in CBFS (does not need to correspond
243 to the name that the file originally came from)
244 data: Contents of file
Simon Glasse073d4e2019-07-08 13:18:56 -0600245 cbfs_offset: Offset of file data in bytes from start of CBFS, or
246 None to place this file anyway
Simon Glass4997a7e2019-07-08 13:18:52 -0600247
248 Returns:
249 CbfsFile object containing the file information
250 """
Simon Glasse073d4e2019-07-08 13:18:56 -0600251 cfile = CbfsFile(name, TYPE_STAGE, data, cbfs_offset)
Simon Glass4997a7e2019-07-08 13:18:52 -0600252 cfile.base_address = base_address
253 return cfile
254
255 @classmethod
Simon Glasse073d4e2019-07-08 13:18:56 -0600256 def raw(cls, name, data, cbfs_offset, compress):
Simon Glass4997a7e2019-07-08 13:18:52 -0600257 """Create a new raw file
258
259 Args:
260 name: String file name to put in CBFS (does not need to correspond
261 to the name that the file originally came from)
262 data: Contents of file
Simon Glasse073d4e2019-07-08 13:18:56 -0600263 cbfs_offset: Offset of file data in bytes from start of CBFS, or
264 None to place this file anyway
Simon Glass4997a7e2019-07-08 13:18:52 -0600265 compress: Compression algorithm to use (COMPRESS_...)
266
267 Returns:
268 CbfsFile object containing the file information
269 """
Simon Glasse073d4e2019-07-08 13:18:56 -0600270 return CbfsFile(name, TYPE_RAW, data, cbfs_offset, compress)
Simon Glass4997a7e2019-07-08 13:18:52 -0600271
Simon Glass7c173ce2019-07-08 13:18:55 -0600272 @classmethod
273 def empty(cls, space_to_use, erase_byte):
274 """Create a new empty file of a given size
275
276 Args:
277 space_to_use:: Size of available space, which must be at least as
278 large as the alignment size for this CBFS
279 erase_byte: Byte to use for contents of file (repeated through the
280 whole file)
281
282 Returns:
283 CbfsFile object containing the file information
284 """
Simon Glasse073d4e2019-07-08 13:18:56 -0600285 cfile = CbfsFile('', TYPE_EMPTY, b'', None)
Simon Glass7c173ce2019-07-08 13:18:55 -0600286 cfile.size = space_to_use - FILE_HEADER_LEN - FILENAME_ALIGN
287 cfile.erase_byte = erase_byte
288 return cfile
289
Simon Glasse073d4e2019-07-08 13:18:56 -0600290 def calc_start_offset(self):
291 """Check if this file needs to start at a particular offset in CBFS
292
293 Returns:
294 None if the file can be placed anywhere, or
295 the largest offset where the file could start (integer)
296 """
297 if self.cbfs_offset is None:
298 return None
299 return self.cbfs_offset - self.get_header_len()
300
301 def get_header_len(self):
302 """Get the length of headers required for a file
303
304 This is the minimum length required before the actual data for this file
305 could start. It might start later if there is padding.
306
307 Returns:
308 Total length of all non-data fields, in bytes
309 """
310 name = _pack_string(self.name)
311 hdr_len = len(name) + FILE_HEADER_LEN
312 if self.ftype == TYPE_STAGE:
313 pass
314 elif self.ftype == TYPE_RAW:
315 hdr_len += ATTR_COMPRESSION_LEN
316 elif self.ftype == TYPE_EMPTY:
317 pass
318 else:
319 raise ValueError('Unknown file type %#x\n' % self.ftype)
320 return hdr_len
321
322 def get_data(self, offset=None, pad_byte=None):
Simon Glass4997a7e2019-07-08 13:18:52 -0600323 """Obtain the contents of the file, in CBFS format
324
325 Returns:
326 bytes representing the contents of this file, packed and aligned
327 for directly inserting into the final CBFS output
328 """
329 name = _pack_string(self.name)
330 hdr_len = len(name) + FILE_HEADER_LEN
331 attr_pos = 0
332 content = b''
333 attr = b''
Simon Glasse073d4e2019-07-08 13:18:56 -0600334 pad = b''
Simon Glass4997a7e2019-07-08 13:18:52 -0600335 data = self.data
336 if self.ftype == TYPE_STAGE:
337 elf_data = elf.DecodeElf(data, self.base_address)
338 content = struct.pack(STAGE_FORMAT, self.compress,
339 elf_data.entry, elf_data.load,
340 len(elf_data.data), elf_data.memsize)
341 data = elf_data.data
342 elif self.ftype == TYPE_RAW:
343 orig_data = data
344 if self.compress == COMPRESS_LZ4:
345 data = tools.Compress(orig_data, 'lz4')
346 elif self.compress == COMPRESS_LZMA:
347 data = tools.Compress(orig_data, 'lzma')
348 attr = struct.pack(ATTR_COMPRESSION_FORMAT,
349 FILE_ATTR_TAG_COMPRESSION, ATTR_COMPRESSION_LEN,
350 self.compress, len(orig_data))
Simon Glass7c173ce2019-07-08 13:18:55 -0600351 elif self.ftype == TYPE_EMPTY:
352 data = tools.GetBytes(self.erase_byte, self.size)
Simon Glass4997a7e2019-07-08 13:18:52 -0600353 else:
354 raise ValueError('Unknown type %#x when writing\n' % self.ftype)
355 if attr:
356 attr_pos = hdr_len
357 hdr_len += len(attr)
Simon Glasse073d4e2019-07-08 13:18:56 -0600358 if self.cbfs_offset is not None:
359 pad_len = self.cbfs_offset - offset - hdr_len
360 if pad_len < 0: # pragma: no cover
361 # Test coverage of this is not available since this should never
362 # happen. It indicates that get_header_len() provided an
363 # incorrect value (too small) so that we decided that we could
364 # put this file at the requested place, but in fact a previous
365 # file extends far enough into the CBFS that this is not
366 # possible.
367 raise ValueError("Internal error: CBFS file '%s': Requested offset %#x but current output position is %#x" %
368 (self.name, self.cbfs_offset, offset))
369 pad = tools.GetBytes(pad_byte, pad_len)
370 hdr_len += pad_len
371 self.offset = len(content) + len(data)
372 hdr = struct.pack(FILE_HEADER_FORMAT, FILE_MAGIC, self.offset,
Simon Glass4997a7e2019-07-08 13:18:52 -0600373 self.ftype, attr_pos, hdr_len)
Simon Glasse073d4e2019-07-08 13:18:56 -0600374
375 # Do a sanity check of the get_header_len() function, to ensure that it
376 # stays in lockstep with this function
377 expected_len = self.get_header_len()
378 actual_len = len(hdr + name + attr)
379 if expected_len != actual_len: # pragma: no cover
380 # Test coverage of this is not available since this should never
381 # happen. It probably indicates that get_header_len() is broken.
382 raise ValueError("Internal error: CBFS file '%s': Expected headers of %#x bytes, got %#d" %
383 (self.name, expected_len, actual_len))
384 return hdr + name + attr + pad + content + data
Simon Glass4997a7e2019-07-08 13:18:52 -0600385
386
387class CbfsWriter(object):
388 """Class to handle writing a Coreboot File System (CBFS)
389
390 Usage is something like:
391
392 cbw = CbfsWriter(size)
393 cbw.add_file_raw('u-boot', tools.ReadFile('u-boot.bin'))
394 ...
395 data = cbw.get_data()
396
397 Attributes:
398 _master_name: Name of the file containing the master header
399 _size: Size of the filesystem, in bytes
400 _files: Ordered list of files in the CBFS, each a CbfsFile
401 _arch: Architecture of the CBFS (ARCHITECTURE_...)
402 _bootblock_size: Size of the bootblock, typically at the end of the CBFS
403 _erase_byte: Byte to use for empty space in the CBFS
404 _align: Alignment to use for files, typically ENTRY_ALIGN
405 _base_address: Boot block offset in bytes from the start of CBFS.
406 Typically this is located at top of the CBFS. It is 0 when there is
407 no boot block
408 _header_offset: Offset of master header in bytes from start of CBFS
409 _contents_offset: Offset of first file header
410 _hdr_at_start: True if the master header is at the start of the CBFS,
411 instead of the end as normal for x86
412 _add_fileheader: True to add a fileheader around the master header
413 """
414 def __init__(self, size, arch=ARCHITECTURE_X86):
415 """Set up a new CBFS
416
417 This sets up all properties to default values. Files can be added using
418 add_file_raw(), etc.
419
420 Args:
421 size: Size of CBFS in bytes
422 arch: Architecture to declare for CBFS
423 """
424 self._master_name = 'cbfs master header'
425 self._size = size
426 self._files = OrderedDict()
427 self._arch = arch
428 self._bootblock_size = 0
429 self._erase_byte = 0xff
430 self._align = ENTRY_ALIGN
431 self._add_fileheader = False
432 if self._arch == ARCHITECTURE_X86:
433 # Allow 4 bytes for the header pointer. That holds the
434 # twos-compliment negative offset of the master header in bytes
435 # measured from one byte past the end of the CBFS
436 self._base_address = self._size - max(self._bootblock_size,
437 MIN_BOOTBLOCK_SIZE)
438 self._header_offset = self._base_address - HEADER_LEN
439 self._contents_offset = 0
440 self._hdr_at_start = False
441 else:
442 # For non-x86, different rules apply
443 self._base_address = 0
444 self._header_offset = align_int(self._base_address +
445 self._bootblock_size, 4)
446 self._contents_offset = align_int(self._header_offset +
447 FILE_HEADER_LEN +
448 self._bootblock_size, self._align)
449 self._hdr_at_start = True
450
451 def _skip_to(self, fd, offset):
452 """Write out pad bytes until a given offset
453
454 Args:
455 fd: File objext to write to
456 offset: Offset to write to
457 """
458 if fd.tell() > offset:
459 raise ValueError('No space for data before offset %#x (current offset %#x)' %
460 (offset, fd.tell()))
461 fd.write(tools.GetBytes(self._erase_byte, offset - fd.tell()))
462
Simon Glass7c173ce2019-07-08 13:18:55 -0600463 def _pad_to(self, fd, offset):
464 """Write out pad bytes and/or an empty file until a given offset
465
466 Args:
467 fd: File objext to write to
468 offset: Offset to write to
469 """
470 self._align_to(fd, self._align)
471 upto = fd.tell()
472 if upto > offset:
473 raise ValueError('No space for data before pad offset %#x (current offset %#x)' %
474 (offset, upto))
475 todo = align_int_down(offset - upto, self._align)
476 if todo:
477 cbf = CbfsFile.empty(todo, self._erase_byte)
478 fd.write(cbf.get_data())
479 self._skip_to(fd, offset)
480
Simon Glass4997a7e2019-07-08 13:18:52 -0600481 def _align_to(self, fd, align):
482 """Write out pad bytes until a given alignment is reached
483
484 This only aligns if the resulting output would not reach the end of the
485 CBFS, since we want to leave the last 4 bytes for the master-header
486 pointer.
487
488 Args:
489 fd: File objext to write to
490 align: Alignment to require (e.g. 4 means pad to next 4-byte
491 boundary)
492 """
493 offset = align_int(fd.tell(), align)
494 if offset < self._size:
495 self._skip_to(fd, offset)
496
Simon Glasse073d4e2019-07-08 13:18:56 -0600497 def add_file_stage(self, name, data, cbfs_offset=None):
Simon Glass4997a7e2019-07-08 13:18:52 -0600498 """Add a new stage file to the CBFS
499
500 Args:
501 name: String file name to put in CBFS (does not need to correspond
502 to the name that the file originally came from)
503 data: Contents of file
Simon Glasse073d4e2019-07-08 13:18:56 -0600504 cbfs_offset: Offset of this file's data within the CBFS, in bytes,
505 or None to place this file anywhere
Simon Glass4997a7e2019-07-08 13:18:52 -0600506
507 Returns:
508 CbfsFile object created
509 """
Simon Glasse073d4e2019-07-08 13:18:56 -0600510 cfile = CbfsFile.stage(self._base_address, name, data, cbfs_offset)
Simon Glass4997a7e2019-07-08 13:18:52 -0600511 self._files[name] = cfile
512 return cfile
513
Simon Glasse073d4e2019-07-08 13:18:56 -0600514 def add_file_raw(self, name, data, cbfs_offset=None,
515 compress=COMPRESS_NONE):
Simon Glass4997a7e2019-07-08 13:18:52 -0600516 """Create a new raw file
517
518 Args:
519 name: String file name to put in CBFS (does not need to correspond
520 to the name that the file originally came from)
521 data: Contents of file
Simon Glasse073d4e2019-07-08 13:18:56 -0600522 cbfs_offset: Offset of this file's data within the CBFS, in bytes,
523 or None to place this file anywhere
Simon Glass4997a7e2019-07-08 13:18:52 -0600524 compress: Compression algorithm to use (COMPRESS_...)
525
526 Returns:
527 CbfsFile object created
528 """
Simon Glasse073d4e2019-07-08 13:18:56 -0600529 cfile = CbfsFile.raw(name, data, cbfs_offset, compress)
Simon Glass4997a7e2019-07-08 13:18:52 -0600530 self._files[name] = cfile
531 return cfile
532
533 def _write_header(self, fd, add_fileheader):
534 """Write out the master header to a CBFS
535
536 Args:
537 fd: File object
538 add_fileheader: True to place the master header in a file header
539 record
540 """
541 if fd.tell() > self._header_offset:
542 raise ValueError('No space for header at offset %#x (current offset %#x)' %
543 (self._header_offset, fd.tell()))
544 if not add_fileheader:
Simon Glass7c173ce2019-07-08 13:18:55 -0600545 self._pad_to(fd, self._header_offset)
Simon Glass4997a7e2019-07-08 13:18:52 -0600546 hdr = struct.pack(HEADER_FORMAT, HEADER_MAGIC, HEADER_VERSION2,
547 self._size, self._bootblock_size, self._align,
548 self._contents_offset, self._arch, 0xffffffff)
549 if add_fileheader:
550 name = _pack_string(self._master_name)
551 fd.write(struct.pack(FILE_HEADER_FORMAT, FILE_MAGIC, len(hdr),
552 TYPE_CBFSHEADER, 0,
553 FILE_HEADER_LEN + len(name)))
554 fd.write(name)
555 self._header_offset = fd.tell()
556 fd.write(hdr)
557 self._align_to(fd, self._align)
558 else:
559 fd.write(hdr)
560
561 def get_data(self):
562 """Obtain the full contents of the CBFS
563
564 Thhis builds the CBFS with headers and all required files.
565
566 Returns:
567 'bytes' type containing the data
568 """
569 fd = io.BytesIO()
570
571 # THe header can go at the start in some cases
572 if self._hdr_at_start:
573 self._write_header(fd, add_fileheader=self._add_fileheader)
574 self._skip_to(fd, self._contents_offset)
575
576 # Write out each file
577 for cbf in self._files.values():
Simon Glasse073d4e2019-07-08 13:18:56 -0600578 # Place the file at its requested place, if any
579 offset = cbf.calc_start_offset()
580 if offset is not None:
581 self._pad_to(fd, align_int_down(offset, self._align))
582 fd.write(cbf.get_data(fd.tell(), self._erase_byte))
Simon Glass4997a7e2019-07-08 13:18:52 -0600583 self._align_to(fd, self._align)
584 if not self._hdr_at_start:
585 self._write_header(fd, add_fileheader=self._add_fileheader)
586
587 # Pad to the end and write a pointer to the CBFS master header
Simon Glass7c173ce2019-07-08 13:18:55 -0600588 self._pad_to(fd, self._base_address or self._size - 4)
Simon Glass4997a7e2019-07-08 13:18:52 -0600589 rel_offset = self._header_offset - self._size
590 fd.write(struct.pack('<I', rel_offset & 0xffffffff))
591
592 return fd.getvalue()
593
594
595class CbfsReader(object):
596 """Class to handle reading a Coreboot File System (CBFS)
597
598 Usage is something like:
599 cbfs = cbfs_util.CbfsReader(data)
600 cfile = cbfs.files['u-boot']
601 self.WriteFile('u-boot.bin', cfile.data)
602
603 Attributes:
604 files: Ordered list of CbfsFile objects
605 align: Alignment to use for files, typically ENTRT_ALIGN
606 stage_base_address: Base address to use when mapping ELF files into the
607 CBFS for TYPE_STAGE files. If this is larger than the code address
608 of the ELF file, then data at the start of the ELF file will not
609 appear in the CBFS. Currently there are no tests for behaviour as
610 documentation is sparse
611 magic: Integer magic number from master header (HEADER_MAGIC)
612 version: Version number of CBFS (HEADER_VERSION2)
613 rom_size: Size of CBFS
614 boot_block_size: Size of boot block
615 cbfs_offset: Offset of the first file in bytes from start of CBFS
616 arch: Architecture of CBFS file (ARCHITECTURE_...)
617 """
618 def __init__(self, data, read=True):
619 self.align = ENTRY_ALIGN
620 self.arch = None
621 self.boot_block_size = None
622 self.cbfs_offset = None
623 self.files = OrderedDict()
624 self.magic = None
625 self.rom_size = None
626 self.stage_base_address = 0
627 self.version = None
628 self.data = data
629 if read:
630 self.read()
631
632 def read(self):
633 """Read all the files in the CBFS and add them to self.files"""
634 with io.BytesIO(self.data) as fd:
635 # First, get the master header
636 if not self._find_and_read_header(fd, len(self.data)):
637 raise ValueError('Cannot find master header')
638 fd.seek(self.cbfs_offset)
639
640 # Now read in the files one at a time
641 while True:
642 cfile = self._read_next_file(fd)
643 if cfile:
644 self.files[cfile.name] = cfile
645 elif cfile is False:
646 break
647
648 def _find_and_read_header(self, fd, size):
649 """Find and read the master header in the CBFS
650
651 This looks at the pointer word at the very end of the CBFS. This is an
652 offset to the header relative to the size of the CBFS, which is assumed
653 to be known. Note that the offset is in *little endian* format.
654
655 Args:
656 fd: File to read from
657 size: Size of file
658
659 Returns:
660 True if header was found, False if not
661 """
662 orig_pos = fd.tell()
663 fd.seek(size - 4)
664 rel_offset, = struct.unpack('<I', fd.read(4))
665 pos = (size + rel_offset) & 0xffffffff
666 fd.seek(pos)
667 found = self._read_header(fd)
668 if not found:
669 print('Relative offset seems wrong, scanning whole image')
670 for pos in range(0, size - HEADER_LEN, 4):
671 fd.seek(pos)
672 found = self._read_header(fd)
673 if found:
674 break
675 fd.seek(orig_pos)
676 return found
677
678 def _read_next_file(self, fd):
679 """Read the next file from a CBFS
680
681 Args:
682 fd: File to read from
683
684 Returns:
685 CbfsFile object, if found
686 None if no object found, but data was parsed (e.g. TYPE_CBFSHEADER)
687 False if at end of CBFS and reading should stop
688 """
689 file_pos = fd.tell()
690 data = fd.read(FILE_HEADER_LEN)
691 if len(data) < FILE_HEADER_LEN:
692 print('File header at %x ran out of data' % file_pos)
693 return False
694 magic, size, ftype, attr, offset = struct.unpack(FILE_HEADER_FORMAT,
695 data)
696 if magic != FILE_MAGIC:
697 return False
698 pos = fd.tell()
699 name = self._read_string(fd)
700 if name is None:
701 print('String at %x ran out of data' % pos)
702 return False
703
704 if DEBUG:
705 print('name', name)
706
707 # If there are attribute headers present, read those
708 compress = self._read_attr(fd, file_pos, attr, offset)
709 if compress is None:
710 return False
711
712 # Create the correct CbfsFile object depending on the type
713 cfile = None
Simon Glasse073d4e2019-07-08 13:18:56 -0600714 cbfs_offset = file_pos + offset
715 fd.seek(cbfs_offset, io.SEEK_SET)
Simon Glass4997a7e2019-07-08 13:18:52 -0600716 if ftype == TYPE_CBFSHEADER:
717 self._read_header(fd)
718 elif ftype == TYPE_STAGE:
719 data = fd.read(STAGE_LEN)
Simon Glasse073d4e2019-07-08 13:18:56 -0600720 cfile = CbfsFile.stage(self.stage_base_address, name, b'',
721 cbfs_offset)
Simon Glass4997a7e2019-07-08 13:18:52 -0600722 (cfile.compress, cfile.entry, cfile.load, cfile.data_len,
723 cfile.memlen) = struct.unpack(STAGE_FORMAT, data)
724 cfile.data = fd.read(cfile.data_len)
725 elif ftype == TYPE_RAW:
726 data = fd.read(size)
Simon Glasse073d4e2019-07-08 13:18:56 -0600727 cfile = CbfsFile.raw(name, data, cbfs_offset, compress)
Simon Glass4997a7e2019-07-08 13:18:52 -0600728 cfile.decompress()
729 if DEBUG:
730 print('data', data)
Simon Glass7c173ce2019-07-08 13:18:55 -0600731 elif ftype == TYPE_EMPTY:
732 # Just read the data and discard it, since it is only padding
733 fd.read(size)
Simon Glasse073d4e2019-07-08 13:18:56 -0600734 cfile = CbfsFile('', TYPE_EMPTY, b'', cbfs_offset)
Simon Glass4997a7e2019-07-08 13:18:52 -0600735 else:
736 raise ValueError('Unknown type %#x when reading\n' % ftype)
737 if cfile:
738 cfile.offset = offset
739
740 # Move past the padding to the start of a possible next file. If we are
741 # already at an alignment boundary, then there is no padding.
742 pad = (self.align - fd.tell() % self.align) % self.align
743 fd.seek(pad, io.SEEK_CUR)
744 return cfile
745
746 @classmethod
747 def _read_attr(cls, fd, file_pos, attr, offset):
748 """Read attributes from the file
749
750 CBFS files can have attributes which are things that cannot fit into the
Simon Glasse073d4e2019-07-08 13:18:56 -0600751 header. The only attributes currently supported are compression and the
752 unused tag.
Simon Glass4997a7e2019-07-08 13:18:52 -0600753
754 Args:
755 fd: File to read from
756 file_pos: Position of file in fd
757 attr: Offset of attributes, 0 if none
758 offset: Offset of file data (used to indicate the end of the
759 attributes)
760
761 Returns:
762 Compression to use for the file (COMPRESS_...)
763 """
764 compress = COMPRESS_NONE
765 if not attr:
766 return compress
767 attr_size = offset - attr
768 fd.seek(file_pos + attr, io.SEEK_SET)
769 while attr_size:
770 pos = fd.tell()
771 hdr = fd.read(8)
772 if len(hdr) < 8:
773 print('Attribute tag at %x ran out of data' % pos)
774 return None
775 atag, alen = struct.unpack(">II", hdr)
776 data = hdr + fd.read(alen - 8)
777 if atag == FILE_ATTR_TAG_COMPRESSION:
778 # We don't currently use this information
779 atag, alen, compress, _decomp_size = struct.unpack(
780 ATTR_COMPRESSION_FORMAT, data)
Simon Glasse073d4e2019-07-08 13:18:56 -0600781 elif atag == FILE_ATTR_TAG_UNUSED2:
782 break
Simon Glass4997a7e2019-07-08 13:18:52 -0600783 else:
784 print('Unknown attribute tag %x' % atag)
785 attr_size -= len(data)
786 return compress
787
788 def _read_header(self, fd):
789 """Read the master header
790
791 Reads the header and stores the information obtained into the member
792 variables.
793
794 Args:
795 fd: File to read from
796
797 Returns:
798 True if header was read OK, False if it is truncated or has the
799 wrong magic or version
800 """
801 pos = fd.tell()
802 data = fd.read(HEADER_LEN)
803 if len(data) < HEADER_LEN:
804 print('Header at %x ran out of data' % pos)
805 return False
806 (self.magic, self.version, self.rom_size, self.boot_block_size,
807 self.align, self.cbfs_offset, self.arch, _) = struct.unpack(
808 HEADER_FORMAT, data)
809 return self.magic == HEADER_MAGIC and (
810 self.version == HEADER_VERSION1 or
811 self.version == HEADER_VERSION2)
812
813 @classmethod
814 def _read_string(cls, fd):
815 """Read a string from a file
816
817 This reads a string and aligns the data to the next alignment boundary
818
819 Args:
820 fd: File to read from
821
822 Returns:
823 string read ('str' type) encoded to UTF-8, or None if we ran out of
824 data
825 """
826 val = b''
827 while True:
828 data = fd.read(FILENAME_ALIGN)
829 if len(data) < FILENAME_ALIGN:
830 return None
831 pos = data.find(b'\0')
832 if pos == -1:
833 val += data
834 else:
835 val += data[:pos]
836 break
837 return val.decode('utf-8')
838
839
Simon Glasse073d4e2019-07-08 13:18:56 -0600840def cbfstool(fname, *cbfs_args, **kwargs):
Simon Glass4997a7e2019-07-08 13:18:52 -0600841 """Run cbfstool with provided arguments
842
843 If the tool fails then this function raises an exception and prints out the
844 output and stderr.
845
846 Args:
847 fname: Filename of CBFS
848 *cbfs_args: List of arguments to pass to cbfstool
849
850 Returns:
851 CommandResult object containing the results
852 """
Simon Glasse073d4e2019-07-08 13:18:56 -0600853 args = ['cbfstool', fname] + list(cbfs_args)
854 if kwargs.get('base') is not None:
855 args += ['-b', '%#x' % kwargs['base']]
Simon Glass4997a7e2019-07-08 13:18:52 -0600856 result = command.RunPipe([args], capture=not VERBOSE,
857 capture_stderr=not VERBOSE, raise_on_error=False)
858 if result.return_code:
859 print(result.stderr, file=sys.stderr)
860 raise Exception("Failed to run (error %d): '%s'" %
861 (result.return_code, ' '.join(args)))