blob: 19086305af1fb0b331e045ee726f17f6c9ef8dfc [file] [log] [blame]
Simon Glass4997a7e2019-07-08 13:18:52 -06001#!/usr/bin/env python
2# SPDX-License-Identifier: GPL-2.0+
3# Copyright 2019 Google LLC
4# Written by Simon Glass <sjg@chromium.org>
5
6"""Tests for cbfs_util
7
8These create and read various CBFSs and compare the results with expected
9values and with cbfstool
10"""
11
12from __future__ import print_function
13
14import io
15import os
16import shutil
17import struct
18import tempfile
19import unittest
20
21import cbfs_util
22from cbfs_util import CbfsWriter
23import elf
24import test_util
25import tools
26
27U_BOOT_DATA = b'1234'
28U_BOOT_DTB_DATA = b'udtb'
29COMPRESS_DATA = b'compress xxxxxxxxxxxxxxxxxxxxxx data'
30
31
32class TestCbfs(unittest.TestCase):
33 """Test of cbfs_util classes"""
34 #pylint: disable=W0212
35 @classmethod
36 def setUpClass(cls):
37 # Create a temporary directory for test files
38 cls._indir = tempfile.mkdtemp(prefix='cbfs_util.')
39 tools.SetInputDirs([cls._indir])
40
41 # Set up some useful data files
42 TestCbfs._make_input_file('u-boot.bin', U_BOOT_DATA)
43 TestCbfs._make_input_file('u-boot.dtb', U_BOOT_DTB_DATA)
44 TestCbfs._make_input_file('compress', COMPRESS_DATA)
45
46 # Set up a temporary output directory, used by the tools library when
47 # compressing files
48 tools.PrepareOutputDir(None)
49
50 cls.have_cbfstool = True
51 try:
52 tools.Run('which', 'cbfstool')
53 except:
54 cls.have_cbfstool = False
55
56 cls.have_lz4 = True
57 try:
58 tools.Run('lz4', '--no-frame-crc', '-c',
59 tools.GetInputFilename('u-boot.bin'))
60 except:
61 cls.have_lz4 = False
62
63 @classmethod
64 def tearDownClass(cls):
65 """Remove the temporary input directory and its contents"""
66 if cls._indir:
67 shutil.rmtree(cls._indir)
68 cls._indir = None
69 tools.FinaliseOutputDir()
70
71 @classmethod
72 def _make_input_file(cls, fname, contents):
73 """Create a new test input file, creating directories as needed
74
75 Args:
76 fname: Filename to create
77 contents: File contents to write in to the file
78 Returns:
79 Full pathname of file created
80 """
81 pathname = os.path.join(cls._indir, fname)
82 tools.WriteFile(pathname, contents)
83 return pathname
84
85 def _check_hdr(self, data, size, offset=0, arch=cbfs_util.ARCHITECTURE_X86):
86 """Check that the CBFS has the expected header
87
88 Args:
89 data: Data to check
90 size: Expected ROM size
91 offset: Expected offset to first CBFS file
92 arch: Expected architecture
93
94 Returns:
95 CbfsReader object containing the CBFS
96 """
97 cbfs = cbfs_util.CbfsReader(data)
98 self.assertEqual(cbfs_util.HEADER_MAGIC, cbfs.magic)
99 self.assertEqual(cbfs_util.HEADER_VERSION2, cbfs.version)
100 self.assertEqual(size, cbfs.rom_size)
101 self.assertEqual(0, cbfs.boot_block_size)
102 self.assertEqual(cbfs_util.ENTRY_ALIGN, cbfs.align)
103 self.assertEqual(offset, cbfs.cbfs_offset)
104 self.assertEqual(arch, cbfs.arch)
105 return cbfs
106
107 def _check_uboot(self, cbfs, ftype=cbfs_util.TYPE_RAW, offset=0x38,
108 data=U_BOOT_DATA):
109 """Check that the U-Boot file is as expected
110
111 Args:
112 cbfs: CbfsReader object to check
113 ftype: Expected file type
114 offset: Expected offset of file
115 data: Expected data in file
116
117 Returns:
118 CbfsFile object containing the file
119 """
120 self.assertIn('u-boot', cbfs.files)
121 cfile = cbfs.files['u-boot']
122 self.assertEqual('u-boot', cfile.name)
123 self.assertEqual(offset, cfile.offset)
124 self.assertEqual(data, cfile.data)
125 self.assertEqual(ftype, cfile.ftype)
126 self.assertEqual(cbfs_util.COMPRESS_NONE, cfile.compress)
127 self.assertEqual(len(data), cfile.memlen)
128 return cfile
129
130 def _check_dtb(self, cbfs, offset=0x38, data=U_BOOT_DTB_DATA):
131 """Check that the U-Boot dtb file is as expected
132
133 Args:
134 cbfs: CbfsReader object to check
135 offset: Expected offset of file
136 data: Expected data in file
137 """
138 self.assertIn('u-boot-dtb', cbfs.files)
139 cfile = cbfs.files['u-boot-dtb']
140 self.assertEqual('u-boot-dtb', cfile.name)
141 self.assertEqual(offset, cfile.offset)
142 self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
143 self.assertEqual(cbfs_util.TYPE_RAW, cfile.ftype)
144 self.assertEqual(cbfs_util.COMPRESS_NONE, cfile.compress)
145 self.assertEqual(len(U_BOOT_DTB_DATA), cfile.memlen)
146
147 def _check_raw(self, data, size, offset=0, arch=cbfs_util.ARCHITECTURE_X86):
148 """Check that two raw files are added as expected
149
150 Args:
151 data: Data to check
152 size: Expected ROM size
153 offset: Expected offset to first CBFS file
154 arch: Expected architecture
155 """
156 cbfs = self._check_hdr(data, size, offset=offset, arch=arch)
157 self._check_uboot(cbfs)
158 self._check_dtb(cbfs)
159
160 def _get_expected_cbfs(self, size, arch='x86', compress=None):
161 """Get the file created by cbfstool for a particular scenario
162
163 Args:
164 size: Size of the CBFS in bytes
165 arch: Architecture of the CBFS, as a string
166 compress: Compression to use, e.g. cbfs_util.COMPRESS_LZMA
167
168 Returns:
169 Resulting CBFS file, or None if cbfstool is not available
170 """
171 if not self.have_cbfstool or not self.have_lz4:
172 return None
173 cbfs_fname = os.path.join(self._indir, 'test.cbfs')
174 cbfs_util.cbfstool(cbfs_fname, 'create', '-m', arch, '-s', '%#x' % size)
175 cbfs_util.cbfstool(cbfs_fname, 'add', '-n', 'u-boot', '-t', 'raw',
176 '-c', compress and compress[0] or 'none',
177 '-f', tools.GetInputFilename(
178 compress and 'compress' or 'u-boot.bin'))
179 cbfs_util.cbfstool(cbfs_fname, 'add', '-n', 'u-boot-dtb', '-t', 'raw',
180 '-c', compress and compress[1] or 'none',
181 '-f', tools.GetInputFilename(
182 compress and 'compress' or 'u-boot.dtb'))
183 return cbfs_fname
184
185 def _compare_expected_cbfs(self, data, cbfstool_fname):
186 """Compare against what cbfstool creates
187
188 This compares what binman creates with what cbfstool creates for what
189 is proportedly the same thing.
190
191 Args:
192 data: CBFS created by binman
193 cbfstool_fname: CBFS created by cbfstool
194 """
195 if not self.have_cbfstool or not self.have_lz4:
196 return
197 expect = tools.ReadFile(cbfstool_fname)
198 if expect != data:
199 tools.WriteFile('/tmp/expect', expect)
200 tools.WriteFile('/tmp/actual', data)
201 print('diff -y <(xxd -g1 /tmp/expect) <(xxd -g1 /tmp/actual) | colordiff')
202 self.fail('cbfstool produced a different result')
203
204 def test_cbfs_functions(self):
205 """Test global functions of cbfs_util"""
206 self.assertEqual(cbfs_util.ARCHITECTURE_X86, cbfs_util.find_arch('x86'))
207 self.assertIsNone(cbfs_util.find_arch('bad-arch'))
208
209 self.assertEqual(cbfs_util.COMPRESS_LZMA, cbfs_util.find_compress('lzma'))
210 self.assertIsNone(cbfs_util.find_compress('bad-comp'))
211
212 def test_cbfstool_failure(self):
213 """Test failure to run cbfstool"""
214 if not self.have_cbfstool:
215 self.skipTest('No cbfstool available')
216 try:
217 # In verbose mode this test fails since stderr is not captured. Fix
218 # this by turning off verbosity.
219 old_verbose = cbfs_util.VERBOSE
220 cbfs_util.VERBOSE = False
221 with test_util.capture_sys_output() as (_stdout, stderr):
222 with self.assertRaises(Exception) as e:
223 cbfs_util.cbfstool('missing-file', 'bad-command')
224 finally:
225 cbfs_util.VERBOSE = old_verbose
226 self.assertIn('Unknown command', stderr.getvalue())
227 self.assertIn('Failed to run', str(e.exception))
228
229 def test_cbfs_raw(self):
230 """Test base handling of a Coreboot Filesystem (CBFS)"""
231 size = 0xb0
232 cbw = CbfsWriter(size)
233 cbw.add_file_raw('u-boot', U_BOOT_DATA)
234 cbw.add_file_raw('u-boot-dtb', U_BOOT_DTB_DATA)
235 data = cbw.get_data()
236 self._check_raw(data, size)
237 cbfs_fname = self._get_expected_cbfs(size=size)
238 self._compare_expected_cbfs(data, cbfs_fname)
239
240 def test_cbfs_invalid_file_type(self):
241 """Check handling of an invalid file type when outputiing a CBFS"""
242 size = 0xb0
243 cbw = CbfsWriter(size)
244 cfile = cbw.add_file_raw('u-boot', U_BOOT_DATA)
245
246 # Change the type manually before generating the CBFS, and make sure
247 # that the generator complains
248 cfile.ftype = 0xff
249 with self.assertRaises(ValueError) as e:
250 cbw.get_data()
251 self.assertIn('Unknown type 0xff when writing', str(e.exception))
252
253 def test_cbfs_invalid_file_type_on_read(self):
254 """Check handling of an invalid file type when reading the CBFS"""
255 size = 0xb0
256 cbw = CbfsWriter(size)
257 cbw.add_file_raw('u-boot', U_BOOT_DATA)
258
259 data = cbw.get_data()
260
261 # Read in the first file header
262 cbr = cbfs_util.CbfsReader(data, read=False)
263 with io.BytesIO(data) as fd:
264 self.assertTrue(cbr._find_and_read_header(fd, len(data)))
265 pos = fd.tell()
266 hdr_data = fd.read(cbfs_util.FILE_HEADER_LEN)
267 magic, size, ftype, attr, offset = struct.unpack(
268 cbfs_util.FILE_HEADER_FORMAT, hdr_data)
269
270 # Create a new CBFS with a change to the file type
271 ftype = 0xff
272 newdata = data[:pos]
273 newdata += struct.pack(cbfs_util.FILE_HEADER_FORMAT, magic, size, ftype,
274 attr, offset)
275 newdata += data[pos + cbfs_util.FILE_HEADER_LEN:]
276
277 # Read in this CBFS and make sure that the reader complains
278 with self.assertRaises(ValueError) as e:
279 cbfs_util.CbfsReader(newdata)
280 self.assertIn('Unknown type 0xff when reading', str(e.exception))
281
282 def test_cbfs_no_space(self):
283 """Check handling of running out of space in the CBFS"""
284 size = 0x60
285 cbw = CbfsWriter(size)
286 cbw.add_file_raw('u-boot', U_BOOT_DATA)
287 with self.assertRaises(ValueError) as e:
288 cbw.get_data()
289 self.assertIn('No space for header', str(e.exception))
290
291 def test_cbfs_no_space_skip(self):
292 """Check handling of running out of space in CBFS with file header"""
293 size = 0x70
294 cbw = CbfsWriter(size)
295 cbw._add_fileheader = True
296 cbw.add_file_raw('u-boot', U_BOOT_DATA)
297 with self.assertRaises(ValueError) as e:
298 cbw.get_data()
299 self.assertIn('No space for data before offset', str(e.exception))
300
301 def test_cbfs_bad_header_ptr(self):
302 """Check handling of a bad master-header pointer"""
303 size = 0x70
304 cbw = CbfsWriter(size)
305 cbw.add_file_raw('u-boot', U_BOOT_DATA)
306 data = cbw.get_data()
307
308 # Add one to the pointer to make it invalid
309 newdata = data[:-4] + struct.pack('<I', cbw._header_offset + 1)
310
311 # We should still be able to find the master header by searching
312 with test_util.capture_sys_output() as (stdout, _stderr):
313 cbfs = cbfs_util.CbfsReader(newdata)
314 self.assertIn('Relative offset seems wrong', stdout.getvalue())
315 self.assertIn('u-boot', cbfs.files)
316 self.assertEqual(size, cbfs.rom_size)
317
318 def test_cbfs_bad_header(self):
319 """Check handling of a bad master header"""
320 size = 0x70
321 cbw = CbfsWriter(size)
322 cbw.add_file_raw('u-boot', U_BOOT_DATA)
323 data = cbw.get_data()
324
325 # Drop most of the header and try reading the modified CBFS
326 newdata = data[:cbw._header_offset + 4]
327
328 with test_util.capture_sys_output() as (stdout, _stderr):
329 with self.assertRaises(ValueError) as e:
330 cbfs_util.CbfsReader(newdata)
331 self.assertIn('Relative offset seems wrong', stdout.getvalue())
332 self.assertIn('Cannot find master header', str(e.exception))
333
334 def test_cbfs_bad_file_header(self):
335 """Check handling of a bad file header"""
336 size = 0x70
337 cbw = CbfsWriter(size)
338 cbw.add_file_raw('u-boot', U_BOOT_DATA)
339 data = cbw.get_data()
340
341 # Read in the CBFS master header (only), then stop
342 cbr = cbfs_util.CbfsReader(data, read=False)
343 with io.BytesIO(data) as fd:
344 self.assertTrue(cbr._find_and_read_header(fd, len(data)))
345 pos = fd.tell()
346
347 # Remove all but 4 bytes of the file headerm and try to read the file
348 newdata = data[:pos + 4]
349 with test_util.capture_sys_output() as (stdout, _stderr):
350 with io.BytesIO(newdata) as fd:
351 fd.seek(pos)
352 self.assertEqual(False, cbr._read_next_file(fd))
353 self.assertIn('File header at 0 ran out of data', stdout.getvalue())
354
355 def test_cbfs_bad_file_string(self):
356 """Check handling of an incomplete filename string"""
357 size = 0x70
358 cbw = CbfsWriter(size)
359 cbw.add_file_raw('16-characters xx', U_BOOT_DATA)
360 data = cbw.get_data()
361
362 # Read in the CBFS master header (only), then stop
363 cbr = cbfs_util.CbfsReader(data, read=False)
364 with io.BytesIO(data) as fd:
365 self.assertTrue(cbr._find_and_read_header(fd, len(data)))
366 pos = fd.tell()
367
368 # Create a new CBFS with only the first 16 bytes of the file name, then
369 # try to read the file
370 newdata = data[:pos + cbfs_util.FILE_HEADER_LEN + 16]
371 with test_util.capture_sys_output() as (stdout, _stderr):
372 with io.BytesIO(newdata) as fd:
373 fd.seek(pos)
374 self.assertEqual(False, cbr._read_next_file(fd))
375 self.assertIn('String at %x ran out of data' %
376 cbfs_util.FILE_HEADER_LEN, stdout.getvalue())
377
378 def test_cbfs_debug(self):
379 """Check debug output"""
380 size = 0x70
381 cbw = CbfsWriter(size)
382 cbw.add_file_raw('u-boot', U_BOOT_DATA)
383 data = cbw.get_data()
384
385 try:
386 cbfs_util.DEBUG = True
387 with test_util.capture_sys_output() as (stdout, _stderr):
388 cbfs_util.CbfsReader(data)
389 self.assertEqual('name u-boot\ndata %s\n' % U_BOOT_DATA,
390 stdout.getvalue())
391 finally:
392 cbfs_util.DEBUG = False
393
394 def test_cbfs_bad_attribute(self):
395 """Check handling of bad attribute tag"""
396 if not self.have_lz4:
397 self.skipTest('lz4 --no-frame-crc not available')
398 size = 0x140
399 cbw = CbfsWriter(size)
400 cbw.add_file_raw('u-boot', COMPRESS_DATA,
401 compress=cbfs_util.COMPRESS_LZ4)
402 data = cbw.get_data()
403
404 # Search the CBFS for the expected compression tag
405 with io.BytesIO(data) as fd:
406 while True:
407 pos = fd.tell()
408 tag, = struct.unpack('>I', fd.read(4))
409 if tag == cbfs_util.FILE_ATTR_TAG_COMPRESSION:
410 break
411
412 # Create a new CBFS with the tag changed to something invalid
413 newdata = data[:pos] + struct.pack('>I', 0x123) + data[pos + 4:]
414 with test_util.capture_sys_output() as (stdout, _stderr):
415 cbfs_util.CbfsReader(newdata)
416 self.assertEqual('Unknown attribute tag 123\n', stdout.getvalue())
417
418 def test_cbfs_missing_attribute(self):
419 """Check handling of an incomplete attribute tag"""
420 if not self.have_lz4:
421 self.skipTest('lz4 --no-frame-crc not available')
422 size = 0x140
423 cbw = CbfsWriter(size)
424 cbw.add_file_raw('u-boot', COMPRESS_DATA,
425 compress=cbfs_util.COMPRESS_LZ4)
426 data = cbw.get_data()
427
428 # Read in the CBFS master header (only), then stop
429 cbr = cbfs_util.CbfsReader(data, read=False)
430 with io.BytesIO(data) as fd:
431 self.assertTrue(cbr._find_and_read_header(fd, len(data)))
432 pos = fd.tell()
433
434 # Create a new CBFS with only the first 4 bytes of the compression tag,
435 # then try to read the file
436 tag_pos = pos + cbfs_util.FILE_HEADER_LEN + cbfs_util.FILENAME_ALIGN
437 newdata = data[:tag_pos + 4]
438 with test_util.capture_sys_output() as (stdout, _stderr):
439 with io.BytesIO(newdata) as fd:
440 fd.seek(pos)
441 self.assertEqual(False, cbr._read_next_file(fd))
442 self.assertIn('Attribute tag at %x ran out of data' % tag_pos,
443 stdout.getvalue())
444
445 def test_cbfs_file_master_header(self):
446 """Check handling of a file containing a master header"""
447 size = 0x100
448 cbw = CbfsWriter(size)
449 cbw._add_fileheader = True
450 cbw.add_file_raw('u-boot', U_BOOT_DATA)
451 data = cbw.get_data()
452
453 cbr = cbfs_util.CbfsReader(data)
454 self.assertIn('u-boot', cbr.files)
455 self.assertEqual(size, cbr.rom_size)
456
457 def test_cbfs_arch(self):
458 """Test on non-x86 architecture"""
459 size = 0x100
460 cbw = CbfsWriter(size, arch=cbfs_util.ARCHITECTURE_PPC64)
461 cbw.add_file_raw('u-boot', U_BOOT_DATA)
462 cbw.add_file_raw('u-boot-dtb', U_BOOT_DTB_DATA)
463 data = cbw.get_data()
464 self._check_raw(data, size, offset=0x40,
465 arch=cbfs_util.ARCHITECTURE_PPC64)
466
467 # Compare against what cbfstool creates
468 cbfs_fname = self._get_expected_cbfs(size=size, arch='ppc64')
469 self._compare_expected_cbfs(data, cbfs_fname)
470
471 def test_cbfs_stage(self):
472 """Tests handling of a Coreboot Filesystem (CBFS)"""
473 if not elf.ELF_TOOLS:
474 self.skipTest('Python elftools not available')
475 elf_fname = os.path.join(self._indir, 'cbfs-stage.elf')
476 elf.MakeElf(elf_fname, U_BOOT_DATA, U_BOOT_DTB_DATA)
477
478 size = 0xb0
479 cbw = CbfsWriter(size)
480 cbw.add_file_stage('u-boot', tools.ReadFile(elf_fname))
481
482 data = cbw.get_data()
483 cbfs = self._check_hdr(data, size)
484 load = 0xfef20000
485 entry = load + 2
486
487 cfile = self._check_uboot(cbfs, cbfs_util.TYPE_STAGE, offset=0x28,
488 data=U_BOOT_DATA + U_BOOT_DTB_DATA)
489
490 self.assertEqual(entry, cfile.entry)
491 self.assertEqual(load, cfile.load)
492 self.assertEqual(len(U_BOOT_DATA) + len(U_BOOT_DTB_DATA),
493 cfile.data_len)
494
495 # Compare against what cbfstool creates
496 if self.have_cbfstool:
497 cbfs_fname = os.path.join(self._indir, 'test.cbfs')
498 cbfs_util.cbfstool(cbfs_fname, 'create', '-m', 'x86', '-s',
499 '%#x' % size)
500 cbfs_util.cbfstool(cbfs_fname, 'add-stage', '-n', 'u-boot',
501 '-f', elf_fname)
502 self._compare_expected_cbfs(data, cbfs_fname)
503
504 def test_cbfs_raw_compress(self):
505 """Test base handling of compressing raw files"""
506 if not self.have_lz4:
507 self.skipTest('lz4 --no-frame-crc not available')
508 size = 0x140
509 cbw = CbfsWriter(size)
510 cbw.add_file_raw('u-boot', COMPRESS_DATA,
511 compress=cbfs_util.COMPRESS_LZ4)
512 cbw.add_file_raw('u-boot-dtb', COMPRESS_DATA,
513 compress=cbfs_util.COMPRESS_LZMA)
514 data = cbw.get_data()
515
516 cbfs = self._check_hdr(data, size)
517 self.assertIn('u-boot', cbfs.files)
518 cfile = cbfs.files['u-boot']
519 self.assertEqual(cfile.name, 'u-boot')
520 self.assertEqual(cfile.offset, 56)
521 self.assertEqual(cfile.data, COMPRESS_DATA)
522 self.assertEqual(cfile.ftype, cbfs_util.TYPE_RAW)
523 self.assertEqual(cfile.compress, cbfs_util.COMPRESS_LZ4)
524 self.assertEqual(cfile.memlen, len(COMPRESS_DATA))
525
526 self.assertIn('u-boot-dtb', cbfs.files)
527 cfile = cbfs.files['u-boot-dtb']
528 self.assertEqual(cfile.name, 'u-boot-dtb')
529 self.assertEqual(cfile.offset, 56)
530 self.assertEqual(cfile.data, COMPRESS_DATA)
531 self.assertEqual(cfile.ftype, cbfs_util.TYPE_RAW)
532 self.assertEqual(cfile.compress, cbfs_util.COMPRESS_LZMA)
533 self.assertEqual(cfile.memlen, len(COMPRESS_DATA))
534
535 cbfs_fname = self._get_expected_cbfs(size=size, compress=['lz4', 'lzma'])
536 self._compare_expected_cbfs(data, cbfs_fname)
537
538
539if __name__ == '__main__':
540 unittest.main()