blob: 2b3690e88e08386420fe9bfe35f541bfb5fb02c8 [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass4f443042016-11-25 20:15:52 -07002# Copyright (c) 2016 Google, Inc
3# Written by Simon Glass <sjg@chromium.org>
4#
Simon Glass4f443042016-11-25 20:15:52 -07005# To run a single test, change to this directory, and:
6#
7# python -m unittest func_test.TestFunctional.testHelp
8
Simon Glassfdc34362020-07-09 18:39:45 -06009import collections
Simon Glass16287932020-04-17 18:09:03 -060010import gzip
Simon Glasse0e5df92018-09-14 04:57:31 -060011import hashlib
Simon Glass4f443042016-11-25 20:15:52 -070012from optparse import OptionParser
13import os
Simon Glassfdc34362020-07-09 18:39:45 -060014import re
Simon Glass4f443042016-11-25 20:15:52 -070015import shutil
16import struct
17import sys
18import tempfile
19import unittest
20
Simon Glass16287932020-04-17 18:09:03 -060021from binman import cbfs_util
22from binman import cmdline
23from binman import control
24from binman import elf
25from binman import elf_test
26from binman import fmap_util
Simon Glass16287932020-04-17 18:09:03 -060027from binman import state
28from dtoc import fdt
29from dtoc import fdt_util
30from binman.etype import fdtmap
31from binman.etype import image_header
Simon Glass07237982020-08-05 13:27:47 -060032from binman.image import Image
Simon Glassbf776672020-04-17 18:09:04 -060033from patman import command
34from patman import test_util
35from patman import tools
36from patman import tout
Simon Glass4f443042016-11-25 20:15:52 -070037
38# Contents of test files, corresponding to different entry types
Simon Glassc6c10e72019-05-17 22:00:46 -060039U_BOOT_DATA = b'1234'
40U_BOOT_IMG_DATA = b'img'
Simon Glasseb0086f2019-08-24 07:23:04 -060041U_BOOT_SPL_DATA = b'56780123456789abcdefghi'
42U_BOOT_TPL_DATA = b'tpl9876543210fedcbazyw'
Simon Glassc6c10e72019-05-17 22:00:46 -060043BLOB_DATA = b'89'
44ME_DATA = b'0abcd'
45VGA_DATA = b'vga'
46U_BOOT_DTB_DATA = b'udtb'
47U_BOOT_SPL_DTB_DATA = b'spldtb'
48U_BOOT_TPL_DTB_DATA = b'tpldtb'
49X86_START16_DATA = b'start16'
50X86_START16_SPL_DATA = b'start16spl'
51X86_START16_TPL_DATA = b'start16tpl'
Simon Glass2250ee62019-08-24 07:22:48 -060052X86_RESET16_DATA = b'reset16'
53X86_RESET16_SPL_DATA = b'reset16spl'
54X86_RESET16_TPL_DATA = b'reset16tpl'
Simon Glassc6c10e72019-05-17 22:00:46 -060055PPC_MPC85XX_BR_DATA = b'ppcmpc85xxbr'
56U_BOOT_NODTB_DATA = b'nodtb with microcode pointer somewhere in here'
57U_BOOT_SPL_NODTB_DATA = b'splnodtb with microcode pointer somewhere in here'
58U_BOOT_TPL_NODTB_DATA = b'tplnodtb with microcode pointer somewhere in here'
59FSP_DATA = b'fsp'
60CMC_DATA = b'cmc'
61VBT_DATA = b'vbt'
62MRC_DATA = b'mrc'
Simon Glassbb748372018-07-17 13:25:33 -060063TEXT_DATA = 'text'
64TEXT_DATA2 = 'text2'
65TEXT_DATA3 = 'text3'
Simon Glassc6c10e72019-05-17 22:00:46 -060066CROS_EC_RW_DATA = b'ecrw'
67GBB_DATA = b'gbbd'
68BMPBLK_DATA = b'bmp'
69VBLOCK_DATA = b'vblk'
70FILES_DATA = (b"sorry I'm late\nOh, don't bother apologising, I'm " +
71 b"sorry you're alive\n")
Simon Glassff5c7e32019-07-08 13:18:42 -060072COMPRESS_DATA = b'compress xxxxxxxxxxxxxxxxxxxxxx data'
Simon Glassc6c10e72019-05-17 22:00:46 -060073REFCODE_DATA = b'refcode'
Simon Glassea0fff92019-08-24 07:23:07 -060074FSP_M_DATA = b'fsp_m'
Simon Glassbc6a88f2019-10-20 21:31:35 -060075FSP_S_DATA = b'fsp_s'
Simon Glass998d1482019-10-20 21:31:36 -060076FSP_T_DATA = b'fsp_t'
Simon Glassdc2f81a2020-09-01 05:13:58 -060077ATF_BL31_DATA = b'bl31'
Simon Glassec127af2018-07-17 13:25:39 -060078
Simon Glass6ccbfcd2019-07-20 12:23:47 -060079# The expected size for the device tree in some tests
Simon Glassf667e452019-07-08 14:25:50 -060080EXTRACT_DTB_SIZE = 0x3c9
81
Simon Glass6ccbfcd2019-07-20 12:23:47 -060082# Properties expected to be in the device tree when update_dtb is used
83BASE_DTB_PROPS = ['offset', 'size', 'image-pos']
84
Simon Glass12bb1a92019-07-20 12:23:51 -060085# Extra properties expected to be in the device tree when allow-repack is used
86REPACK_DTB_PROPS = ['orig-offset', 'orig-size']
87
Simon Glass4f443042016-11-25 20:15:52 -070088
89class TestFunctional(unittest.TestCase):
90 """Functional tests for binman
91
92 Most of these use a sample .dts file to build an image and then check
93 that it looks correct. The sample files are in the test/ subdirectory
94 and are numbered.
95
96 For each entry type a very small test file is created using fixed
97 string contents. This makes it easy to test that things look right, and
98 debug problems.
99
100 In some cases a 'real' file must be used - these are also supplied in
101 the test/ diurectory.
102 """
103 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600104 def setUpClass(cls):
Simon Glass4d5994f2017-11-12 21:52:20 -0700105 global entry
Simon Glass16287932020-04-17 18:09:03 -0600106 from binman import entry
Simon Glass4d5994f2017-11-12 21:52:20 -0700107
Simon Glass4f443042016-11-25 20:15:52 -0700108 # Handle the case where argv[0] is 'python'
Simon Glassb986b3b2019-08-24 07:22:43 -0600109 cls._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
110 cls._binman_pathname = os.path.join(cls._binman_dir, 'binman')
Simon Glass4f443042016-11-25 20:15:52 -0700111
112 # Create a temporary directory for input files
Simon Glassb986b3b2019-08-24 07:22:43 -0600113 cls._indir = tempfile.mkdtemp(prefix='binmant.')
Simon Glass4f443042016-11-25 20:15:52 -0700114
115 # Create some test files
116 TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
117 TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
118 TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
Simon Glassb8ef5b62018-07-17 13:25:48 -0600119 TestFunctional._MakeInputFile('tpl/u-boot-tpl.bin', U_BOOT_TPL_DATA)
Simon Glass4f443042016-11-25 20:15:52 -0700120 TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -0700121 TestFunctional._MakeInputFile('me.bin', ME_DATA)
122 TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
Simon Glassb986b3b2019-08-24 07:22:43 -0600123 cls._ResetDtbs()
Simon Glass2250ee62019-08-24 07:22:48 -0600124
Jagdish Gediya9d368f32018-09-03 21:35:08 +0530125 TestFunctional._MakeInputFile('u-boot-br.bin', PPC_MPC85XX_BR_DATA)
Simon Glass2250ee62019-08-24 07:22:48 -0600126
Simon Glass5e239182019-08-24 07:22:49 -0600127 TestFunctional._MakeInputFile('u-boot-x86-start16.bin', X86_START16_DATA)
128 TestFunctional._MakeInputFile('spl/u-boot-x86-start16-spl.bin',
Simon Glass87722132017-11-12 21:52:26 -0700129 X86_START16_SPL_DATA)
Simon Glass5e239182019-08-24 07:22:49 -0600130 TestFunctional._MakeInputFile('tpl/u-boot-x86-start16-tpl.bin',
Simon Glass35b384c2018-09-14 04:57:10 -0600131 X86_START16_TPL_DATA)
Simon Glass2250ee62019-08-24 07:22:48 -0600132
133 TestFunctional._MakeInputFile('u-boot-x86-reset16.bin',
134 X86_RESET16_DATA)
135 TestFunctional._MakeInputFile('spl/u-boot-x86-reset16-spl.bin',
136 X86_RESET16_SPL_DATA)
137 TestFunctional._MakeInputFile('tpl/u-boot-x86-reset16-tpl.bin',
138 X86_RESET16_TPL_DATA)
139
Simon Glass4f443042016-11-25 20:15:52 -0700140 TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
Simon Glass6b187df2017-11-12 21:52:27 -0700141 TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
142 U_BOOT_SPL_NODTB_DATA)
Simon Glassf0253632018-09-14 04:57:32 -0600143 TestFunctional._MakeInputFile('tpl/u-boot-tpl-nodtb.bin',
144 U_BOOT_TPL_NODTB_DATA)
Simon Glassda229092016-11-25 20:15:56 -0700145 TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
146 TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
Bin Meng59ea8c22017-08-15 22:41:54 -0700147 TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
Simon Glassca4f4ff2017-11-12 21:52:28 -0700148 TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
Simon Glassec127af2018-07-17 13:25:39 -0600149 TestFunctional._MakeInputFile('ecrw.bin', CROS_EC_RW_DATA)
Simon Glass0ef87aa2018-07-17 13:25:44 -0600150 TestFunctional._MakeInputDir('devkeys')
151 TestFunctional._MakeInputFile('bmpblk.bin', BMPBLK_DATA)
Simon Glass3ae192c2018-10-01 12:22:31 -0600152 TestFunctional._MakeInputFile('refcode.bin', REFCODE_DATA)
Simon Glassea0fff92019-08-24 07:23:07 -0600153 TestFunctional._MakeInputFile('fsp_m.bin', FSP_M_DATA)
Simon Glassbc6a88f2019-10-20 21:31:35 -0600154 TestFunctional._MakeInputFile('fsp_s.bin', FSP_S_DATA)
Simon Glass998d1482019-10-20 21:31:36 -0600155 TestFunctional._MakeInputFile('fsp_t.bin', FSP_T_DATA)
Simon Glass4f443042016-11-25 20:15:52 -0700156
Simon Glass53e22bf2019-08-24 07:22:53 -0600157 cls._elf_testdir = os.path.join(cls._indir, 'elftest')
158 elf_test.BuildElfTestFiles(cls._elf_testdir)
159
Simon Glasse0ff8552016-11-25 20:15:53 -0700160 # ELF file with a '_dt_ucode_base_size' symbol
Simon Glassf514d8f2019-08-24 07:22:54 -0600161 TestFunctional._MakeInputFile('u-boot',
162 tools.ReadFile(cls.ElfTestFile('u_boot_ucode_ptr')))
Simon Glasse0ff8552016-11-25 20:15:53 -0700163
164 # Intel flash descriptor file
Simon Glass0ba4b3d2020-07-09 18:39:41 -0600165 cls._SetupDescriptor()
Simon Glasse0ff8552016-11-25 20:15:53 -0700166
Simon Glassb986b3b2019-08-24 07:22:43 -0600167 shutil.copytree(cls.TestFile('files'),
168 os.path.join(cls._indir, 'files'))
Simon Glass0a98b282018-09-14 04:57:28 -0600169
Simon Glass83d73c22018-09-14 04:57:26 -0600170 TestFunctional._MakeInputFile('compress', COMPRESS_DATA)
Simon Glassdc2f81a2020-09-01 05:13:58 -0600171 TestFunctional._MakeInputFile('bl31.bin', ATF_BL31_DATA)
Simon Glass83d73c22018-09-14 04:57:26 -0600172
Simon Glassac62fba2019-07-08 13:18:53 -0600173 # Travis-CI may have an old lz4
Simon Glassb986b3b2019-08-24 07:22:43 -0600174 cls.have_lz4 = True
Simon Glassac62fba2019-07-08 13:18:53 -0600175 try:
176 tools.Run('lz4', '--no-frame-crc', '-c',
Simon Glass3b3e3c02019-10-31 07:42:50 -0600177 os.path.join(cls._indir, 'u-boot.bin'), binary=True)
Simon Glassac62fba2019-07-08 13:18:53 -0600178 except:
Simon Glassb986b3b2019-08-24 07:22:43 -0600179 cls.have_lz4 = False
Simon Glassac62fba2019-07-08 13:18:53 -0600180
Simon Glass4f443042016-11-25 20:15:52 -0700181 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600182 def tearDownClass(cls):
Simon Glass4f443042016-11-25 20:15:52 -0700183 """Remove the temporary input directory and its contents"""
Simon Glassb986b3b2019-08-24 07:22:43 -0600184 if cls.preserve_indir:
185 print('Preserving input dir: %s' % cls._indir)
Simon Glassd5164a72019-07-08 13:18:49 -0600186 else:
Simon Glassb986b3b2019-08-24 07:22:43 -0600187 if cls._indir:
188 shutil.rmtree(cls._indir)
189 cls._indir = None
Simon Glass4f443042016-11-25 20:15:52 -0700190
Simon Glassd5164a72019-07-08 13:18:49 -0600191 @classmethod
Simon Glass8acce602019-07-08 13:18:50 -0600192 def setup_test_args(cls, preserve_indir=False, preserve_outdirs=False,
Simon Glass53cd5d92019-07-08 14:25:29 -0600193 toolpath=None, verbosity=None):
Simon Glassd5164a72019-07-08 13:18:49 -0600194 """Accept arguments controlling test execution
195
196 Args:
197 preserve_indir: Preserve the shared input directory used by all
198 tests in this class.
199 preserve_outdir: Preserve the output directories used by tests. Each
200 test has its own, so this is normally only useful when running a
201 single test.
Simon Glass8acce602019-07-08 13:18:50 -0600202 toolpath: ist of paths to use for tools
Simon Glassd5164a72019-07-08 13:18:49 -0600203 """
204 cls.preserve_indir = preserve_indir
205 cls.preserve_outdirs = preserve_outdirs
Simon Glass8acce602019-07-08 13:18:50 -0600206 cls.toolpath = toolpath
Simon Glass53cd5d92019-07-08 14:25:29 -0600207 cls.verbosity = verbosity
Simon Glassd5164a72019-07-08 13:18:49 -0600208
Simon Glassac62fba2019-07-08 13:18:53 -0600209 def _CheckLz4(self):
210 if not self.have_lz4:
211 self.skipTest('lz4 --no-frame-crc not available')
212
Simon Glassbf574f12019-07-20 12:24:09 -0600213 def _CleanupOutputDir(self):
214 """Remove the temporary output directory"""
215 if self.preserve_outdirs:
216 print('Preserving output dir: %s' % tools.outdir)
217 else:
218 tools._FinaliseForTest()
219
Simon Glass4f443042016-11-25 20:15:52 -0700220 def setUp(self):
221 # Enable this to turn on debugging output
222 # tout.Init(tout.DEBUG)
223 command.test_result = None
224
225 def tearDown(self):
226 """Remove the temporary output directory"""
Simon Glassbf574f12019-07-20 12:24:09 -0600227 self._CleanupOutputDir()
Simon Glass4f443042016-11-25 20:15:52 -0700228
Simon Glassf86a7362019-07-20 12:24:10 -0600229 def _SetupImageInTmpdir(self):
230 """Set up the output image in a new temporary directory
231
232 This is used when an image has been generated in the output directory,
233 but we want to run binman again. This will create a new output
234 directory and fail to delete the original one.
235
236 This creates a new temporary directory, copies the image to it (with a
237 new name) and removes the old output directory.
238
239 Returns:
240 Tuple:
241 Temporary directory to use
242 New image filename
243 """
244 image_fname = tools.GetOutputFilename('image.bin')
245 tmpdir = tempfile.mkdtemp(prefix='binman.')
246 updated_fname = os.path.join(tmpdir, 'image-updated.bin')
247 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
248 self._CleanupOutputDir()
249 return tmpdir, updated_fname
250
Simon Glassb8ef5b62018-07-17 13:25:48 -0600251 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600252 def _ResetDtbs(cls):
Simon Glassb8ef5b62018-07-17 13:25:48 -0600253 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
254 TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
255 TestFunctional._MakeInputFile('tpl/u-boot-tpl.dtb', U_BOOT_TPL_DTB_DATA)
256
Simon Glass4f443042016-11-25 20:15:52 -0700257 def _RunBinman(self, *args, **kwargs):
258 """Run binman using the command line
259
260 Args:
261 Arguments to pass, as a list of strings
262 kwargs: Arguments to pass to Command.RunPipe()
263 """
264 result = command.RunPipe([[self._binman_pathname] + list(args)],
265 capture=True, capture_stderr=True, raise_on_error=False)
266 if result.return_code and kwargs.get('raise_on_error', True):
267 raise Exception("Error running '%s': %s" % (' '.join(args),
268 result.stdout + result.stderr))
269 return result
270
Simon Glass53cd5d92019-07-08 14:25:29 -0600271 def _DoBinman(self, *argv):
Simon Glass4f443042016-11-25 20:15:52 -0700272 """Run binman using directly (in the same process)
273
274 Args:
275 Arguments to pass, as a list of strings
276 Returns:
277 Return value (0 for success)
278 """
Simon Glass53cd5d92019-07-08 14:25:29 -0600279 argv = list(argv)
280 args = cmdline.ParseArgs(argv)
281 args.pager = 'binman-invalid-pager'
282 args.build_dir = self._indir
Simon Glass4f443042016-11-25 20:15:52 -0700283
284 # For testing, you can force an increase in verbosity here
Simon Glass53cd5d92019-07-08 14:25:29 -0600285 # args.verbosity = tout.DEBUG
286 return control.Binman(args)
Simon Glass4f443042016-11-25 20:15:52 -0700287
Simon Glass53af22a2018-07-17 13:25:32 -0600288 def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
Simon Glasseb833d82019-04-25 21:58:34 -0600289 entry_args=None, images=None, use_real_dtb=False,
Simon Glass4f9f1052020-07-09 18:39:38 -0600290 verbosity=None, allow_missing=False):
Simon Glass4f443042016-11-25 20:15:52 -0700291 """Run binman with a given test file
292
293 Args:
Simon Glass741f2d62018-10-01 12:22:30 -0600294 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass7ae5f312018-06-01 09:38:19 -0600295 debug: True to enable debugging output
Simon Glass3b0c3822018-06-01 09:38:20 -0600296 map: True to output map files for the images
Simon Glass3ab95982018-08-01 15:22:37 -0600297 update_dtb: Update the offset and size of each entry in the device
Simon Glass16b8d6b2018-07-06 10:27:42 -0600298 tree before packing it into the image
Simon Glass0bfa7b02018-09-14 04:57:12 -0600299 entry_args: Dict of entry args to supply to binman
300 key: arg name
301 value: value of that arg
302 images: List of image names to build
Simon Glasse9d336d2020-09-01 05:13:55 -0600303 use_real_dtb: True to use the test file as the contents of
304 the u-boot-dtb entry. Normally this is not needed and the
305 test contents (the U_BOOT_DTB_DATA string) can be used.
306 But in some test we need the real contents.
307 verbosity: Verbosity level to use (0-3, None=don't set it)
308 allow_missing: Set the '--allow-missing' flag so that missing
309 external binaries just produce a warning instead of an error
Simon Glass4f443042016-11-25 20:15:52 -0700310 """
Simon Glass53cd5d92019-07-08 14:25:29 -0600311 args = []
Simon Glass7fe91732017-11-13 18:55:00 -0700312 if debug:
313 args.append('-D')
Simon Glass53cd5d92019-07-08 14:25:29 -0600314 if verbosity is not None:
315 args.append('-v%d' % verbosity)
316 elif self.verbosity:
317 args.append('-v%d' % self.verbosity)
318 if self.toolpath:
319 for path in self.toolpath:
320 args += ['--toolpath', path]
321 args += ['build', '-p', '-I', self._indir, '-d', self.TestFile(fname)]
Simon Glass3b0c3822018-06-01 09:38:20 -0600322 if map:
323 args.append('-m')
Simon Glass16b8d6b2018-07-06 10:27:42 -0600324 if update_dtb:
Simon Glass2569e102019-07-08 13:18:47 -0600325 args.append('-u')
Simon Glass93d17412018-09-14 04:57:23 -0600326 if not use_real_dtb:
327 args.append('--fake-dtb')
Simon Glass53af22a2018-07-17 13:25:32 -0600328 if entry_args:
Simon Glass50979152019-05-14 15:53:41 -0600329 for arg, value in entry_args.items():
Simon Glass53af22a2018-07-17 13:25:32 -0600330 args.append('-a%s=%s' % (arg, value))
Simon Glass4f9f1052020-07-09 18:39:38 -0600331 if allow_missing:
332 args.append('-M')
Simon Glass0bfa7b02018-09-14 04:57:12 -0600333 if images:
334 for image in images:
335 args += ['-i', image]
Simon Glass7fe91732017-11-13 18:55:00 -0700336 return self._DoBinman(*args)
Simon Glass4f443042016-11-25 20:15:52 -0700337
338 def _SetupDtb(self, fname, outfile='u-boot.dtb'):
Simon Glasse0ff8552016-11-25 20:15:53 -0700339 """Set up a new test device-tree file
340
341 The given file is compiled and set up as the device tree to be used
342 for ths test.
343
344 Args:
345 fname: Filename of .dts file to read
Simon Glass7ae5f312018-06-01 09:38:19 -0600346 outfile: Output filename for compiled device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700347
348 Returns:
Simon Glass7ae5f312018-06-01 09:38:19 -0600349 Contents of device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700350 """
Simon Glassa004f292019-07-20 12:23:49 -0600351 tmpdir = tempfile.mkdtemp(prefix='binmant.')
352 dtb = fdt_util.EnsureCompiled(self.TestFile(fname), tmpdir)
Simon Glass1d0ebf72019-05-14 15:53:42 -0600353 with open(dtb, 'rb') as fd:
Simon Glass4f443042016-11-25 20:15:52 -0700354 data = fd.read()
355 TestFunctional._MakeInputFile(outfile, data)
Simon Glassa004f292019-07-20 12:23:49 -0600356 shutil.rmtree(tmpdir)
Simon Glasse0e62752018-10-01 21:12:41 -0600357 return data
Simon Glass4f443042016-11-25 20:15:52 -0700358
Simon Glass6ed45ba2018-09-14 04:57:24 -0600359 def _GetDtbContentsForSplTpl(self, dtb_data, name):
360 """Create a version of the main DTB for SPL or SPL
361
362 For testing we don't actually have different versions of the DTB. With
363 U-Boot we normally run fdtgrep to remove unwanted nodes, but for tests
364 we don't normally have any unwanted nodes.
365
366 We still want the DTBs for SPL and TPL to be different though, since
367 otherwise it is confusing to know which one we are looking at. So add
368 an 'spl' or 'tpl' property to the top-level node.
Simon Glasse9d336d2020-09-01 05:13:55 -0600369
370 Args:
371 dtb_data: dtb data to modify (this should be a value devicetree)
372 name: Name of a new property to add
373
374 Returns:
375 New dtb data with the property added
Simon Glass6ed45ba2018-09-14 04:57:24 -0600376 """
377 dtb = fdt.Fdt.FromData(dtb_data)
378 dtb.Scan()
379 dtb.GetNode('/binman').AddZeroProp(name)
380 dtb.Sync(auto_resize=True)
381 dtb.Pack()
382 return dtb.GetContents()
383
Simon Glass16b8d6b2018-07-06 10:27:42 -0600384 def _DoReadFileDtb(self, fname, use_real_dtb=False, map=False,
Simon Glass6ed45ba2018-09-14 04:57:24 -0600385 update_dtb=False, entry_args=None, reset_dtbs=True):
Simon Glass4f443042016-11-25 20:15:52 -0700386 """Run binman and return the resulting image
387
388 This runs binman with a given test file and then reads the resulting
389 output file. It is a shortcut function since most tests need to do
390 these steps.
391
392 Raises an assertion failure if binman returns a non-zero exit code.
393
394 Args:
Simon Glass741f2d62018-10-01 12:22:30 -0600395 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass4f443042016-11-25 20:15:52 -0700396 use_real_dtb: True to use the test file as the contents of
397 the u-boot-dtb entry. Normally this is not needed and the
398 test contents (the U_BOOT_DTB_DATA string) can be used.
399 But in some test we need the real contents.
Simon Glass3b0c3822018-06-01 09:38:20 -0600400 map: True to output map files for the images
Simon Glass3ab95982018-08-01 15:22:37 -0600401 update_dtb: Update the offset and size of each entry in the device
Simon Glass16b8d6b2018-07-06 10:27:42 -0600402 tree before packing it into the image
Simon Glasse9d336d2020-09-01 05:13:55 -0600403 entry_args: Dict of entry args to supply to binman
404 key: arg name
405 value: value of that arg
406 reset_dtbs: With use_real_dtb the test dtb is overwritten by this
407 function. If reset_dtbs is True, then the original test dtb
408 is written back before this function finishes
Simon Glasse0ff8552016-11-25 20:15:53 -0700409
410 Returns:
411 Tuple:
412 Resulting image contents
413 Device tree contents
Simon Glass3b0c3822018-06-01 09:38:20 -0600414 Map data showing contents of image (or None if none)
Simon Glassea6922e2018-07-17 13:25:27 -0600415 Output device tree binary filename ('u-boot.dtb' path)
Simon Glass4f443042016-11-25 20:15:52 -0700416 """
Simon Glasse0ff8552016-11-25 20:15:53 -0700417 dtb_data = None
Simon Glass4f443042016-11-25 20:15:52 -0700418 # Use the compiled test file as the u-boot-dtb input
419 if use_real_dtb:
Simon Glasse0ff8552016-11-25 20:15:53 -0700420 dtb_data = self._SetupDtb(fname)
Simon Glass6ed45ba2018-09-14 04:57:24 -0600421
422 # For testing purposes, make a copy of the DT for SPL and TPL. Add
423 # a node indicating which it is, so aid verification.
424 for name in ['spl', 'tpl']:
425 dtb_fname = '%s/u-boot-%s.dtb' % (name, name)
426 outfile = os.path.join(self._indir, dtb_fname)
427 TestFunctional._MakeInputFile(dtb_fname,
428 self._GetDtbContentsForSplTpl(dtb_data, name))
Simon Glass4f443042016-11-25 20:15:52 -0700429
430 try:
Simon Glass53af22a2018-07-17 13:25:32 -0600431 retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
Simon Glass6ed45ba2018-09-14 04:57:24 -0600432 entry_args=entry_args, use_real_dtb=use_real_dtb)
Simon Glass4f443042016-11-25 20:15:52 -0700433 self.assertEqual(0, retcode)
Simon Glass6ed45ba2018-09-14 04:57:24 -0600434 out_dtb_fname = tools.GetOutputFilename('u-boot.dtb.out')
Simon Glass4f443042016-11-25 20:15:52 -0700435
436 # Find the (only) image, read it and return its contents
437 image = control.images['image']
Simon Glass16b8d6b2018-07-06 10:27:42 -0600438 image_fname = tools.GetOutputFilename('image.bin')
439 self.assertTrue(os.path.exists(image_fname))
Simon Glass3b0c3822018-06-01 09:38:20 -0600440 if map:
441 map_fname = tools.GetOutputFilename('image.map')
442 with open(map_fname) as fd:
443 map_data = fd.read()
444 else:
445 map_data = None
Simon Glass1d0ebf72019-05-14 15:53:42 -0600446 with open(image_fname, 'rb') as fd:
Simon Glass16b8d6b2018-07-06 10:27:42 -0600447 return fd.read(), dtb_data, map_data, out_dtb_fname
Simon Glass4f443042016-11-25 20:15:52 -0700448 finally:
449 # Put the test file back
Simon Glass6ed45ba2018-09-14 04:57:24 -0600450 if reset_dtbs and use_real_dtb:
Simon Glassb8ef5b62018-07-17 13:25:48 -0600451 self._ResetDtbs()
Simon Glass4f443042016-11-25 20:15:52 -0700452
Simon Glass3c081312019-07-08 14:25:26 -0600453 def _DoReadFileRealDtb(self, fname):
454 """Run binman with a real .dtb file and return the resulting data
455
456 Args:
457 fname: DT source filename to use (e.g. 082_fdt_update_all.dts)
458
459 Returns:
460 Resulting image contents
461 """
462 return self._DoReadFileDtb(fname, use_real_dtb=True, update_dtb=True)[0]
463
Simon Glasse0ff8552016-11-25 20:15:53 -0700464 def _DoReadFile(self, fname, use_real_dtb=False):
Simon Glass7ae5f312018-06-01 09:38:19 -0600465 """Helper function which discards the device-tree binary
466
467 Args:
Simon Glass741f2d62018-10-01 12:22:30 -0600468 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass7ae5f312018-06-01 09:38:19 -0600469 use_real_dtb: True to use the test file as the contents of
470 the u-boot-dtb entry. Normally this is not needed and the
471 test contents (the U_BOOT_DTB_DATA string) can be used.
472 But in some test we need the real contents.
Simon Glassea6922e2018-07-17 13:25:27 -0600473
474 Returns:
475 Resulting image contents
Simon Glass7ae5f312018-06-01 09:38:19 -0600476 """
Simon Glasse0ff8552016-11-25 20:15:53 -0700477 return self._DoReadFileDtb(fname, use_real_dtb)[0]
478
Simon Glass4f443042016-11-25 20:15:52 -0700479 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600480 def _MakeInputFile(cls, fname, contents):
Simon Glass4f443042016-11-25 20:15:52 -0700481 """Create a new test input file, creating directories as needed
482
483 Args:
Simon Glass3ab95982018-08-01 15:22:37 -0600484 fname: Filename to create
Simon Glass4f443042016-11-25 20:15:52 -0700485 contents: File contents to write in to the file
486 Returns:
487 Full pathname of file created
488 """
Simon Glassb986b3b2019-08-24 07:22:43 -0600489 pathname = os.path.join(cls._indir, fname)
Simon Glass4f443042016-11-25 20:15:52 -0700490 dirname = os.path.dirname(pathname)
491 if dirname and not os.path.exists(dirname):
492 os.makedirs(dirname)
493 with open(pathname, 'wb') as fd:
494 fd.write(contents)
495 return pathname
496
497 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600498 def _MakeInputDir(cls, dirname):
Simon Glass0ef87aa2018-07-17 13:25:44 -0600499 """Create a new test input directory, creating directories as needed
500
501 Args:
502 dirname: Directory name to create
503
504 Returns:
505 Full pathname of directory created
506 """
Simon Glassb986b3b2019-08-24 07:22:43 -0600507 pathname = os.path.join(cls._indir, dirname)
Simon Glass0ef87aa2018-07-17 13:25:44 -0600508 if not os.path.exists(pathname):
509 os.makedirs(pathname)
510 return pathname
511
512 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600513 def _SetupSplElf(cls, src_fname='bss_data'):
Simon Glass11ae93e2018-10-01 21:12:47 -0600514 """Set up an ELF file with a '_dt_ucode_base_size' symbol
515
516 Args:
517 Filename of ELF file to use as SPL
518 """
Simon Glassc9a0b272019-08-24 07:22:59 -0600519 TestFunctional._MakeInputFile('spl/u-boot-spl',
520 tools.ReadFile(cls.ElfTestFile(src_fname)))
Simon Glass11ae93e2018-10-01 21:12:47 -0600521
522 @classmethod
Simon Glass2090f1e2019-08-24 07:23:00 -0600523 def _SetupTplElf(cls, src_fname='bss_data'):
524 """Set up an ELF file with a '_dt_ucode_base_size' symbol
525
526 Args:
527 Filename of ELF file to use as TPL
528 """
529 TestFunctional._MakeInputFile('tpl/u-boot-tpl',
530 tools.ReadFile(cls.ElfTestFile(src_fname)))
531
532 @classmethod
Simon Glass0ba4b3d2020-07-09 18:39:41 -0600533 def _SetupDescriptor(cls):
534 with open(cls.TestFile('descriptor.bin'), 'rb') as fd:
535 TestFunctional._MakeInputFile('descriptor.bin', fd.read())
536
537 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600538 def TestFile(cls, fname):
539 return os.path.join(cls._binman_dir, 'test', fname)
Simon Glass4f443042016-11-25 20:15:52 -0700540
Simon Glass53e22bf2019-08-24 07:22:53 -0600541 @classmethod
542 def ElfTestFile(cls, fname):
543 return os.path.join(cls._elf_testdir, fname)
544
Simon Glass4f443042016-11-25 20:15:52 -0700545 def AssertInList(self, grep_list, target):
546 """Assert that at least one of a list of things is in a target
547
548 Args:
549 grep_list: List of strings to check
550 target: Target string
551 """
552 for grep in grep_list:
553 if grep in target:
554 return
Simon Glass1fc62de2019-05-17 22:00:50 -0600555 self.fail("Error: '%s' not found in '%s'" % (grep_list, target))
Simon Glass4f443042016-11-25 20:15:52 -0700556
557 def CheckNoGaps(self, entries):
558 """Check that all entries fit together without gaps
559
560 Args:
561 entries: List of entries to check
562 """
Simon Glass3ab95982018-08-01 15:22:37 -0600563 offset = 0
Simon Glass4f443042016-11-25 20:15:52 -0700564 for entry in entries.values():
Simon Glass3ab95982018-08-01 15:22:37 -0600565 self.assertEqual(offset, entry.offset)
566 offset += entry.size
Simon Glass4f443042016-11-25 20:15:52 -0700567
Simon Glasse0ff8552016-11-25 20:15:53 -0700568 def GetFdtLen(self, dtb):
Simon Glass7ae5f312018-06-01 09:38:19 -0600569 """Get the totalsize field from a device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700570
571 Args:
Simon Glass7ae5f312018-06-01 09:38:19 -0600572 dtb: Device-tree binary contents
Simon Glasse0ff8552016-11-25 20:15:53 -0700573
574 Returns:
Simon Glass7ae5f312018-06-01 09:38:19 -0600575 Total size of device-tree binary, from the header
Simon Glasse0ff8552016-11-25 20:15:53 -0700576 """
577 return struct.unpack('>L', dtb[4:8])[0]
578
Simon Glass086cec92019-07-08 14:25:27 -0600579 def _GetPropTree(self, dtb, prop_names, prefix='/binman/'):
Simon Glass16b8d6b2018-07-06 10:27:42 -0600580 def AddNode(node, path):
581 if node.name != '/':
582 path += '/' + node.name
Simon Glass086cec92019-07-08 14:25:27 -0600583 for prop in node.props.values():
584 if prop.name in prop_names:
585 prop_path = path + ':' + prop.name
586 tree[prop_path[len(prefix):]] = fdt_util.fdt32_to_cpu(
587 prop.value)
Simon Glass16b8d6b2018-07-06 10:27:42 -0600588 for subnode in node.subnodes:
Simon Glass16b8d6b2018-07-06 10:27:42 -0600589 AddNode(subnode, path)
590
591 tree = {}
Simon Glass16b8d6b2018-07-06 10:27:42 -0600592 AddNode(dtb.GetRoot(), '')
593 return tree
594
Simon Glass4f443042016-11-25 20:15:52 -0700595 def testRun(self):
596 """Test a basic run with valid args"""
597 result = self._RunBinman('-h')
598
599 def testFullHelp(self):
600 """Test that the full help is displayed with -H"""
601 result = self._RunBinman('-H')
602 help_file = os.path.join(self._binman_dir, 'README')
Tom Rini3759df02018-01-16 15:29:50 -0500603 # Remove possible extraneous strings
604 extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
605 gothelp = result.stdout.replace(extra, '')
606 self.assertEqual(len(gothelp), os.path.getsize(help_file))
Simon Glass4f443042016-11-25 20:15:52 -0700607 self.assertEqual(0, len(result.stderr))
608 self.assertEqual(0, result.return_code)
609
610 def testFullHelpInternal(self):
611 """Test that the full help is displayed with -H"""
612 try:
613 command.test_result = command.CommandResult()
614 result = self._DoBinman('-H')
615 help_file = os.path.join(self._binman_dir, 'README')
616 finally:
617 command.test_result = None
618
619 def testHelp(self):
620 """Test that the basic help is displayed with -h"""
621 result = self._RunBinman('-h')
622 self.assertTrue(len(result.stdout) > 200)
623 self.assertEqual(0, len(result.stderr))
624 self.assertEqual(0, result.return_code)
625
Simon Glass4f443042016-11-25 20:15:52 -0700626 def testBoard(self):
627 """Test that we can run it with a specific board"""
Simon Glass741f2d62018-10-01 12:22:30 -0600628 self._SetupDtb('005_simple.dts', 'sandbox/u-boot.dtb')
Simon Glass4f443042016-11-25 20:15:52 -0700629 TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
Simon Glass53cd5d92019-07-08 14:25:29 -0600630 result = self._DoBinman('build', '-b', 'sandbox')
Simon Glass4f443042016-11-25 20:15:52 -0700631 self.assertEqual(0, result)
632
633 def testNeedBoard(self):
634 """Test that we get an error when no board ius supplied"""
635 with self.assertRaises(ValueError) as e:
Simon Glass53cd5d92019-07-08 14:25:29 -0600636 result = self._DoBinman('build')
Simon Glass4f443042016-11-25 20:15:52 -0700637 self.assertIn("Must provide a board to process (use -b <board>)",
638 str(e.exception))
639
640 def testMissingDt(self):
Simon Glass7ae5f312018-06-01 09:38:19 -0600641 """Test that an invalid device-tree file generates an error"""
Simon Glass4f443042016-11-25 20:15:52 -0700642 with self.assertRaises(Exception) as e:
Simon Glass53cd5d92019-07-08 14:25:29 -0600643 self._RunBinman('build', '-d', 'missing_file')
Simon Glass4f443042016-11-25 20:15:52 -0700644 # We get one error from libfdt, and a different one from fdtget.
645 self.AssertInList(["Couldn't open blob from 'missing_file'",
646 'No such file or directory'], str(e.exception))
647
648 def testBrokenDt(self):
Simon Glass7ae5f312018-06-01 09:38:19 -0600649 """Test that an invalid device-tree source file generates an error
Simon Glass4f443042016-11-25 20:15:52 -0700650
651 Since this is a source file it should be compiled and the error
652 will come from the device-tree compiler (dtc).
653 """
654 with self.assertRaises(Exception) as e:
Simon Glass53cd5d92019-07-08 14:25:29 -0600655 self._RunBinman('build', '-d', self.TestFile('001_invalid.dts'))
Simon Glass4f443042016-11-25 20:15:52 -0700656 self.assertIn("FATAL ERROR: Unable to parse input tree",
657 str(e.exception))
658
659 def testMissingNode(self):
660 """Test that a device tree without a 'binman' node generates an error"""
661 with self.assertRaises(Exception) as e:
Simon Glass53cd5d92019-07-08 14:25:29 -0600662 self._DoBinman('build', '-d', self.TestFile('002_missing_node.dts'))
Simon Glass4f443042016-11-25 20:15:52 -0700663 self.assertIn("does not have a 'binman' node", str(e.exception))
664
665 def testEmpty(self):
666 """Test that an empty binman node works OK (i.e. does nothing)"""
Simon Glass53cd5d92019-07-08 14:25:29 -0600667 result = self._RunBinman('build', '-d', self.TestFile('003_empty.dts'))
Simon Glass4f443042016-11-25 20:15:52 -0700668 self.assertEqual(0, len(result.stderr))
669 self.assertEqual(0, result.return_code)
670
671 def testInvalidEntry(self):
672 """Test that an invalid entry is flagged"""
673 with self.assertRaises(Exception) as e:
Simon Glass53cd5d92019-07-08 14:25:29 -0600674 result = self._RunBinman('build', '-d',
Simon Glass741f2d62018-10-01 12:22:30 -0600675 self.TestFile('004_invalid_entry.dts'))
Simon Glass4f443042016-11-25 20:15:52 -0700676 self.assertIn("Unknown entry type 'not-a-valid-type' in node "
677 "'/binman/not-a-valid-type'", str(e.exception))
678
679 def testSimple(self):
680 """Test a simple binman with a single file"""
Simon Glass741f2d62018-10-01 12:22:30 -0600681 data = self._DoReadFile('005_simple.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700682 self.assertEqual(U_BOOT_DATA, data)
683
Simon Glass7fe91732017-11-13 18:55:00 -0700684 def testSimpleDebug(self):
685 """Test a simple binman run with debugging enabled"""
Simon Glasse2705fa2019-07-08 14:25:53 -0600686 self._DoTestFile('005_simple.dts', debug=True)
Simon Glass7fe91732017-11-13 18:55:00 -0700687
Simon Glass4f443042016-11-25 20:15:52 -0700688 def testDual(self):
689 """Test that we can handle creating two images
690
691 This also tests image padding.
692 """
Simon Glass741f2d62018-10-01 12:22:30 -0600693 retcode = self._DoTestFile('006_dual_image.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700694 self.assertEqual(0, retcode)
695
696 image = control.images['image1']
Simon Glass8beb11e2019-07-08 14:25:47 -0600697 self.assertEqual(len(U_BOOT_DATA), image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700698 fname = tools.GetOutputFilename('image1.bin')
699 self.assertTrue(os.path.exists(fname))
Simon Glass1d0ebf72019-05-14 15:53:42 -0600700 with open(fname, 'rb') as fd:
Simon Glass4f443042016-11-25 20:15:52 -0700701 data = fd.read()
702 self.assertEqual(U_BOOT_DATA, data)
703
704 image = control.images['image2']
Simon Glass8beb11e2019-07-08 14:25:47 -0600705 self.assertEqual(3 + len(U_BOOT_DATA) + 5, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700706 fname = tools.GetOutputFilename('image2.bin')
707 self.assertTrue(os.path.exists(fname))
Simon Glass1d0ebf72019-05-14 15:53:42 -0600708 with open(fname, 'rb') as fd:
Simon Glass4f443042016-11-25 20:15:52 -0700709 data = fd.read()
710 self.assertEqual(U_BOOT_DATA, data[3:7])
Simon Glasse6d85ff2019-05-14 15:53:47 -0600711 self.assertEqual(tools.GetBytes(0, 3), data[:3])
712 self.assertEqual(tools.GetBytes(0, 5), data[7:])
Simon Glass4f443042016-11-25 20:15:52 -0700713
714 def testBadAlign(self):
715 """Test that an invalid alignment value is detected"""
716 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600717 self._DoTestFile('007_bad_align.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700718 self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
719 "of two", str(e.exception))
720
721 def testPackSimple(self):
722 """Test that packing works as expected"""
Simon Glass741f2d62018-10-01 12:22:30 -0600723 retcode = self._DoTestFile('008_pack.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700724 self.assertEqual(0, retcode)
725 self.assertIn('image', control.images)
726 image = control.images['image']
Simon Glass8f1da502018-06-01 09:38:12 -0600727 entries = image.GetEntries()
Simon Glass4f443042016-11-25 20:15:52 -0700728 self.assertEqual(5, len(entries))
729
730 # First u-boot
731 self.assertIn('u-boot', entries)
732 entry = entries['u-boot']
Simon Glass3ab95982018-08-01 15:22:37 -0600733 self.assertEqual(0, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700734 self.assertEqual(len(U_BOOT_DATA), entry.size)
735
736 # Second u-boot, aligned to 16-byte boundary
737 self.assertIn('u-boot-align', entries)
738 entry = entries['u-boot-align']
Simon Glass3ab95982018-08-01 15:22:37 -0600739 self.assertEqual(16, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700740 self.assertEqual(len(U_BOOT_DATA), entry.size)
741
742 # Third u-boot, size 23 bytes
743 self.assertIn('u-boot-size', entries)
744 entry = entries['u-boot-size']
Simon Glass3ab95982018-08-01 15:22:37 -0600745 self.assertEqual(20, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700746 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
747 self.assertEqual(23, entry.size)
748
749 # Fourth u-boot, placed immediate after the above
750 self.assertIn('u-boot-next', entries)
751 entry = entries['u-boot-next']
Simon Glass3ab95982018-08-01 15:22:37 -0600752 self.assertEqual(43, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700753 self.assertEqual(len(U_BOOT_DATA), entry.size)
754
Simon Glass3ab95982018-08-01 15:22:37 -0600755 # Fifth u-boot, placed at a fixed offset
Simon Glass4f443042016-11-25 20:15:52 -0700756 self.assertIn('u-boot-fixed', entries)
757 entry = entries['u-boot-fixed']
Simon Glass3ab95982018-08-01 15:22:37 -0600758 self.assertEqual(61, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700759 self.assertEqual(len(U_BOOT_DATA), entry.size)
760
Simon Glass8beb11e2019-07-08 14:25:47 -0600761 self.assertEqual(65, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700762
763 def testPackExtra(self):
764 """Test that extra packing feature works as expected"""
Simon Glass741f2d62018-10-01 12:22:30 -0600765 retcode = self._DoTestFile('009_pack_extra.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700766
767 self.assertEqual(0, retcode)
768 self.assertIn('image', control.images)
769 image = control.images['image']
Simon Glass8f1da502018-06-01 09:38:12 -0600770 entries = image.GetEntries()
Simon Glass4f443042016-11-25 20:15:52 -0700771 self.assertEqual(5, len(entries))
772
773 # First u-boot with padding before and after
774 self.assertIn('u-boot', entries)
775 entry = entries['u-boot']
Simon Glass3ab95982018-08-01 15:22:37 -0600776 self.assertEqual(0, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700777 self.assertEqual(3, entry.pad_before)
778 self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
779
780 # Second u-boot has an aligned size, but it has no effect
781 self.assertIn('u-boot-align-size-nop', entries)
782 entry = entries['u-boot-align-size-nop']
Simon Glass3ab95982018-08-01 15:22:37 -0600783 self.assertEqual(12, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700784 self.assertEqual(4, entry.size)
785
786 # Third u-boot has an aligned size too
787 self.assertIn('u-boot-align-size', entries)
788 entry = entries['u-boot-align-size']
Simon Glass3ab95982018-08-01 15:22:37 -0600789 self.assertEqual(16, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700790 self.assertEqual(32, entry.size)
791
792 # Fourth u-boot has an aligned end
793 self.assertIn('u-boot-align-end', entries)
794 entry = entries['u-boot-align-end']
Simon Glass3ab95982018-08-01 15:22:37 -0600795 self.assertEqual(48, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700796 self.assertEqual(16, entry.size)
797
798 # Fifth u-boot immediately afterwards
799 self.assertIn('u-boot-align-both', entries)
800 entry = entries['u-boot-align-both']
Simon Glass3ab95982018-08-01 15:22:37 -0600801 self.assertEqual(64, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700802 self.assertEqual(64, entry.size)
803
804 self.CheckNoGaps(entries)
Simon Glass8beb11e2019-07-08 14:25:47 -0600805 self.assertEqual(128, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700806
807 def testPackAlignPowerOf2(self):
808 """Test that invalid entry alignment is detected"""
809 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600810 self._DoTestFile('010_pack_align_power2.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700811 self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
812 "of two", str(e.exception))
813
814 def testPackAlignSizePowerOf2(self):
815 """Test that invalid entry size alignment is detected"""
816 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600817 self._DoTestFile('011_pack_align_size_power2.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700818 self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
819 "power of two", str(e.exception))
820
821 def testPackInvalidAlign(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600822 """Test detection of an offset that does not match its alignment"""
Simon Glass4f443042016-11-25 20:15:52 -0700823 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600824 self._DoTestFile('012_pack_inv_align.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600825 self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
Simon Glass4f443042016-11-25 20:15:52 -0700826 "align 0x4 (4)", str(e.exception))
827
828 def testPackInvalidSizeAlign(self):
829 """Test that invalid entry size alignment is detected"""
830 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600831 self._DoTestFile('013_pack_inv_size_align.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700832 self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
833 "align-size 0x4 (4)", str(e.exception))
834
835 def testPackOverlap(self):
836 """Test that overlapping regions are detected"""
837 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600838 self._DoTestFile('014_pack_overlap.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600839 self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
Simon Glass4f443042016-11-25 20:15:52 -0700840 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
841 str(e.exception))
842
843 def testPackEntryOverflow(self):
844 """Test that entries that overflow their size are detected"""
845 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600846 self._DoTestFile('015_pack_overflow.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700847 self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
848 "but entry size is 0x3 (3)", str(e.exception))
849
850 def testPackImageOverflow(self):
851 """Test that entries which overflow the image size are detected"""
852 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600853 self._DoTestFile('016_pack_image_overflow.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600854 self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
Simon Glass4f443042016-11-25 20:15:52 -0700855 "size 0x3 (3)", str(e.exception))
856
857 def testPackImageSize(self):
858 """Test that the image size can be set"""
Simon Glass741f2d62018-10-01 12:22:30 -0600859 retcode = self._DoTestFile('017_pack_image_size.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700860 self.assertEqual(0, retcode)
861 self.assertIn('image', control.images)
862 image = control.images['image']
Simon Glass8beb11e2019-07-08 14:25:47 -0600863 self.assertEqual(7, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700864
865 def testPackImageSizeAlign(self):
866 """Test that image size alignemnt works as expected"""
Simon Glass741f2d62018-10-01 12:22:30 -0600867 retcode = self._DoTestFile('018_pack_image_align.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700868 self.assertEqual(0, retcode)
869 self.assertIn('image', control.images)
870 image = control.images['image']
Simon Glass8beb11e2019-07-08 14:25:47 -0600871 self.assertEqual(16, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700872
873 def testPackInvalidImageAlign(self):
874 """Test that invalid image alignment is detected"""
875 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600876 self._DoTestFile('019_pack_inv_image_align.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600877 self.assertIn("Section '/binman': Size 0x7 (7) does not match "
Simon Glass4f443042016-11-25 20:15:52 -0700878 "align-size 0x8 (8)", str(e.exception))
879
880 def testPackAlignPowerOf2(self):
881 """Test that invalid image alignment is detected"""
882 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600883 self._DoTestFile('020_pack_inv_image_align_power2.dts')
Simon Glass8beb11e2019-07-08 14:25:47 -0600884 self.assertIn("Image '/binman': Alignment size 131 must be a power of "
Simon Glass4f443042016-11-25 20:15:52 -0700885 "two", str(e.exception))
886
887 def testImagePadByte(self):
888 """Test that the image pad byte can be specified"""
Simon Glass11ae93e2018-10-01 21:12:47 -0600889 self._SetupSplElf()
Simon Glass741f2d62018-10-01 12:22:30 -0600890 data = self._DoReadFile('021_image_pad.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -0600891 self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0xff, 1) +
892 U_BOOT_DATA, data)
Simon Glass4f443042016-11-25 20:15:52 -0700893
894 def testImageName(self):
895 """Test that image files can be named"""
Simon Glass741f2d62018-10-01 12:22:30 -0600896 retcode = self._DoTestFile('022_image_name.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700897 self.assertEqual(0, retcode)
898 image = control.images['image1']
899 fname = tools.GetOutputFilename('test-name')
900 self.assertTrue(os.path.exists(fname))
901
902 image = control.images['image2']
903 fname = tools.GetOutputFilename('test-name.xx')
904 self.assertTrue(os.path.exists(fname))
905
906 def testBlobFilename(self):
907 """Test that generic blobs can be provided by filename"""
Simon Glass741f2d62018-10-01 12:22:30 -0600908 data = self._DoReadFile('023_blob.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700909 self.assertEqual(BLOB_DATA, data)
910
911 def testPackSorted(self):
912 """Test that entries can be sorted"""
Simon Glass11ae93e2018-10-01 21:12:47 -0600913 self._SetupSplElf()
Simon Glass741f2d62018-10-01 12:22:30 -0600914 data = self._DoReadFile('024_sorted.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -0600915 self.assertEqual(tools.GetBytes(0, 1) + U_BOOT_SPL_DATA +
916 tools.GetBytes(0, 2) + U_BOOT_DATA, data)
Simon Glass4f443042016-11-25 20:15:52 -0700917
Simon Glass3ab95982018-08-01 15:22:37 -0600918 def testPackZeroOffset(self):
919 """Test that an entry at offset 0 is not given a new offset"""
Simon Glass4f443042016-11-25 20:15:52 -0700920 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600921 self._DoTestFile('025_pack_zero_size.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600922 self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
Simon Glass4f443042016-11-25 20:15:52 -0700923 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
924 str(e.exception))
925
926 def testPackUbootDtb(self):
927 """Test that a device tree can be added to U-Boot"""
Simon Glass741f2d62018-10-01 12:22:30 -0600928 data = self._DoReadFile('026_pack_u_boot_dtb.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700929 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
Simon Glasse0ff8552016-11-25 20:15:53 -0700930
931 def testPackX86RomNoSize(self):
932 """Test that the end-at-4gb property requires a size property"""
933 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600934 self._DoTestFile('027_pack_4gb_no_size.dts')
Simon Glass8beb11e2019-07-08 14:25:47 -0600935 self.assertIn("Image '/binman': Section size must be provided when "
Simon Glasse0ff8552016-11-25 20:15:53 -0700936 "using end-at-4gb", str(e.exception))
937
Jagdish Gediya94b57db2018-09-03 21:35:07 +0530938 def test4gbAndSkipAtStartTogether(self):
939 """Test that the end-at-4gb and skip-at-size property can't be used
940 together"""
941 with self.assertRaises(ValueError) as e:
Simon Glassdfdd2b62019-08-24 07:23:02 -0600942 self._DoTestFile('098_4gb_and_skip_at_start_together.dts')
Simon Glass8beb11e2019-07-08 14:25:47 -0600943 self.assertIn("Image '/binman': Provide either 'end-at-4gb' or "
Jagdish Gediya94b57db2018-09-03 21:35:07 +0530944 "'skip-at-start'", str(e.exception))
945
Simon Glasse0ff8552016-11-25 20:15:53 -0700946 def testPackX86RomOutside(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600947 """Test that the end-at-4gb property checks for offset boundaries"""
Simon Glasse0ff8552016-11-25 20:15:53 -0700948 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600949 self._DoTestFile('028_pack_4gb_outside.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600950 self.assertIn("Node '/binman/u-boot': Offset 0x0 (0) is outside "
Simon Glass8f1da502018-06-01 09:38:12 -0600951 "the section starting at 0xffffffe0 (4294967264)",
Simon Glasse0ff8552016-11-25 20:15:53 -0700952 str(e.exception))
953
954 def testPackX86Rom(self):
955 """Test that a basic x86 ROM can be created"""
Simon Glass11ae93e2018-10-01 21:12:47 -0600956 self._SetupSplElf()
Simon Glass9255f3c2019-08-24 07:23:01 -0600957 data = self._DoReadFile('029_x86_rom.dts')
Simon Glasseb0086f2019-08-24 07:23:04 -0600958 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 3) + U_BOOT_SPL_DATA +
Simon Glasse6d85ff2019-05-14 15:53:47 -0600959 tools.GetBytes(0, 2), data)
Simon Glasse0ff8552016-11-25 20:15:53 -0700960
961 def testPackX86RomMeNoDesc(self):
962 """Test that an invalid Intel descriptor entry is detected"""
Simon Glass0ba4b3d2020-07-09 18:39:41 -0600963 try:
Simon Glass52b10dd2020-07-25 15:11:19 -0600964 TestFunctional._MakeInputFile('descriptor-empty.bin', b'')
Simon Glass0ba4b3d2020-07-09 18:39:41 -0600965 with self.assertRaises(ValueError) as e:
Simon Glass52b10dd2020-07-25 15:11:19 -0600966 self._DoTestFile('163_x86_rom_me_empty.dts')
Simon Glass0ba4b3d2020-07-09 18:39:41 -0600967 self.assertIn("Node '/binman/intel-descriptor': Cannot find Intel Flash Descriptor (FD) signature",
968 str(e.exception))
969 finally:
970 self._SetupDescriptor()
Simon Glasse0ff8552016-11-25 20:15:53 -0700971
972 def testPackX86RomBadDesc(self):
973 """Test that the Intel requires a descriptor entry"""
974 with self.assertRaises(ValueError) as e:
Simon Glass9255f3c2019-08-24 07:23:01 -0600975 self._DoTestFile('030_x86_rom_me_no_desc.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600976 self.assertIn("Node '/binman/intel-me': No offset set with "
977 "offset-unset: should another entry provide this correct "
978 "offset?", str(e.exception))
Simon Glasse0ff8552016-11-25 20:15:53 -0700979
980 def testPackX86RomMe(self):
981 """Test that an x86 ROM with an ME region can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -0600982 data = self._DoReadFile('031_x86_rom_me.dts')
Simon Glassc5ac1382019-07-08 13:18:54 -0600983 expected_desc = tools.ReadFile(self.TestFile('descriptor.bin'))
984 if data[:0x1000] != expected_desc:
985 self.fail('Expected descriptor binary at start of image')
Simon Glasse0ff8552016-11-25 20:15:53 -0700986 self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
987
988 def testPackVga(self):
989 """Test that an image with a VGA binary can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -0600990 data = self._DoReadFile('032_intel_vga.dts')
Simon Glasse0ff8552016-11-25 20:15:53 -0700991 self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
992
993 def testPackStart16(self):
994 """Test that an image with an x86 start16 region can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -0600995 data = self._DoReadFile('033_x86_start16.dts')
Simon Glasse0ff8552016-11-25 20:15:53 -0700996 self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
997
Jagdish Gediya9d368f32018-09-03 21:35:08 +0530998 def testPackPowerpcMpc85xxBootpgResetvec(self):
999 """Test that an image with powerpc-mpc85xx-bootpg-resetvec can be
1000 created"""
Simon Glassdfdd2b62019-08-24 07:23:02 -06001001 data = self._DoReadFile('150_powerpc_mpc85xx_bootpg_resetvec.dts')
Jagdish Gediya9d368f32018-09-03 21:35:08 +05301002 self.assertEqual(PPC_MPC85XX_BR_DATA, data[:len(PPC_MPC85XX_BR_DATA)])
1003
Simon Glass736bb0a2018-07-06 10:27:17 -06001004 def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
Simon Glassadc57012018-07-06 10:27:16 -06001005 """Handle running a test for insertion of microcode
1006
1007 Args:
1008 dts_fname: Name of test .dts file
1009 nodtb_data: Data that we expect in the first section
Simon Glass736bb0a2018-07-06 10:27:17 -06001010 ucode_second: True if the microsecond entry is second instead of
1011 third
Simon Glassadc57012018-07-06 10:27:16 -06001012
1013 Returns:
1014 Tuple:
1015 Contents of first region (U-Boot or SPL)
Simon Glass3ab95982018-08-01 15:22:37 -06001016 Offset and size components of microcode pointer, as inserted
Simon Glassadc57012018-07-06 10:27:16 -06001017 in the above (two 4-byte words)
1018 """
Simon Glass6b187df2017-11-12 21:52:27 -07001019 data = self._DoReadFile(dts_fname, True)
Simon Glasse0ff8552016-11-25 20:15:53 -07001020
1021 # Now check the device tree has no microcode
Simon Glass736bb0a2018-07-06 10:27:17 -06001022 if ucode_second:
1023 ucode_content = data[len(nodtb_data):]
1024 ucode_pos = len(nodtb_data)
1025 dtb_with_ucode = ucode_content[16:]
1026 fdt_len = self.GetFdtLen(dtb_with_ucode)
1027 else:
1028 dtb_with_ucode = data[len(nodtb_data):]
1029 fdt_len = self.GetFdtLen(dtb_with_ucode)
1030 ucode_content = dtb_with_ucode[fdt_len:]
1031 ucode_pos = len(nodtb_data) + fdt_len
Simon Glasse0ff8552016-11-25 20:15:53 -07001032 fname = tools.GetOutputFilename('test.dtb')
1033 with open(fname, 'wb') as fd:
Simon Glassadc57012018-07-06 10:27:16 -06001034 fd.write(dtb_with_ucode)
Simon Glassec3f3782017-05-27 07:38:29 -06001035 dtb = fdt.FdtScan(fname)
1036 ucode = dtb.GetNode('/microcode')
Simon Glasse0ff8552016-11-25 20:15:53 -07001037 self.assertTrue(ucode)
1038 for node in ucode.subnodes:
1039 self.assertFalse(node.props.get('data'))
1040
Simon Glasse0ff8552016-11-25 20:15:53 -07001041 # Check that the microcode appears immediately after the Fdt
1042 # This matches the concatenation of the data properties in
Simon Glass87722132017-11-12 21:52:26 -07001043 # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
Simon Glasse0ff8552016-11-25 20:15:53 -07001044 ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
1045 0x78235609)
Simon Glassadc57012018-07-06 10:27:16 -06001046 self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
Simon Glasse0ff8552016-11-25 20:15:53 -07001047
1048 # Check that the microcode pointer was inserted. It should match the
Simon Glass3ab95982018-08-01 15:22:37 -06001049 # expected offset and size
Simon Glasse0ff8552016-11-25 20:15:53 -07001050 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
1051 len(ucode_data))
Simon Glass736bb0a2018-07-06 10:27:17 -06001052 u_boot = data[:len(nodtb_data)]
1053 return u_boot, pos_and_size
Simon Glass6b187df2017-11-12 21:52:27 -07001054
1055 def testPackUbootMicrocode(self):
1056 """Test that x86 microcode can be handled correctly
1057
1058 We expect to see the following in the image, in order:
1059 u-boot-nodtb.bin with a microcode pointer inserted at the correct
1060 place
1061 u-boot.dtb with the microcode removed
1062 the microcode
1063 """
Simon Glass741f2d62018-10-01 12:22:30 -06001064 first, pos_and_size = self._RunMicrocodeTest('034_x86_ucode.dts',
Simon Glass6b187df2017-11-12 21:52:27 -07001065 U_BOOT_NODTB_DATA)
Simon Glassc6c10e72019-05-17 22:00:46 -06001066 self.assertEqual(b'nodtb with microcode' + pos_and_size +
1067 b' somewhere in here', first)
Simon Glasse0ff8552016-11-25 20:15:53 -07001068
Simon Glass160a7662017-05-27 07:38:26 -06001069 def _RunPackUbootSingleMicrocode(self):
Simon Glasse0ff8552016-11-25 20:15:53 -07001070 """Test that x86 microcode can be handled correctly
1071
1072 We expect to see the following in the image, in order:
1073 u-boot-nodtb.bin with a microcode pointer inserted at the correct
1074 place
1075 u-boot.dtb with the microcode
1076 an empty microcode region
1077 """
1078 # We need the libfdt library to run this test since only that allows
1079 # finding the offset of a property. This is required by
1080 # Entry_u_boot_dtb_with_ucode.ObtainContents().
Simon Glass741f2d62018-10-01 12:22:30 -06001081 data = self._DoReadFile('035_x86_single_ucode.dts', True)
Simon Glasse0ff8552016-11-25 20:15:53 -07001082
1083 second = data[len(U_BOOT_NODTB_DATA):]
1084
1085 fdt_len = self.GetFdtLen(second)
1086 third = second[fdt_len:]
1087 second = second[:fdt_len]
1088
Simon Glass160a7662017-05-27 07:38:26 -06001089 ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
1090 self.assertIn(ucode_data, second)
1091 ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -07001092
Simon Glass160a7662017-05-27 07:38:26 -06001093 # Check that the microcode pointer was inserted. It should match the
Simon Glass3ab95982018-08-01 15:22:37 -06001094 # expected offset and size
Simon Glass160a7662017-05-27 07:38:26 -06001095 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
1096 len(ucode_data))
1097 first = data[:len(U_BOOT_NODTB_DATA)]
Simon Glassc6c10e72019-05-17 22:00:46 -06001098 self.assertEqual(b'nodtb with microcode' + pos_and_size +
1099 b' somewhere in here', first)
Simon Glassc49deb82016-11-25 20:15:54 -07001100
Simon Glass75db0862016-11-25 20:15:55 -07001101 def testPackUbootSingleMicrocode(self):
1102 """Test that x86 microcode can be handled correctly with fdt_normal.
1103 """
Simon Glass160a7662017-05-27 07:38:26 -06001104 self._RunPackUbootSingleMicrocode()
Simon Glass75db0862016-11-25 20:15:55 -07001105
Simon Glassc49deb82016-11-25 20:15:54 -07001106 def testUBootImg(self):
1107 """Test that u-boot.img can be put in a file"""
Simon Glass741f2d62018-10-01 12:22:30 -06001108 data = self._DoReadFile('036_u_boot_img.dts')
Simon Glassc49deb82016-11-25 20:15:54 -07001109 self.assertEqual(U_BOOT_IMG_DATA, data)
Simon Glass75db0862016-11-25 20:15:55 -07001110
1111 def testNoMicrocode(self):
1112 """Test that a missing microcode region is detected"""
1113 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001114 self._DoReadFile('037_x86_no_ucode.dts', True)
Simon Glass75db0862016-11-25 20:15:55 -07001115 self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
1116 "node found in ", str(e.exception))
1117
1118 def testMicrocodeWithoutNode(self):
1119 """Test that a missing u-boot-dtb-with-ucode node is detected"""
1120 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001121 self._DoReadFile('038_x86_ucode_missing_node.dts', True)
Simon Glass75db0862016-11-25 20:15:55 -07001122 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
1123 "microcode region u-boot-dtb-with-ucode", str(e.exception))
1124
1125 def testMicrocodeWithoutNode2(self):
1126 """Test that a missing u-boot-ucode node is detected"""
1127 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001128 self._DoReadFile('039_x86_ucode_missing_node2.dts', True)
Simon Glass75db0862016-11-25 20:15:55 -07001129 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
1130 "microcode region u-boot-ucode", str(e.exception))
1131
1132 def testMicrocodeWithoutPtrInElf(self):
1133 """Test that a U-Boot binary without the microcode symbol is detected"""
1134 # ELF file without a '_dt_ucode_base_size' symbol
Simon Glass75db0862016-11-25 20:15:55 -07001135 try:
Simon Glassbccd91d2019-08-24 07:22:55 -06001136 TestFunctional._MakeInputFile('u-boot',
1137 tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
Simon Glass75db0862016-11-25 20:15:55 -07001138
1139 with self.assertRaises(ValueError) as e:
Simon Glass160a7662017-05-27 07:38:26 -06001140 self._RunPackUbootSingleMicrocode()
Simon Glass75db0862016-11-25 20:15:55 -07001141 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
1142 "_dt_ucode_base_size symbol in u-boot", str(e.exception))
1143
1144 finally:
1145 # Put the original file back
Simon Glassf514d8f2019-08-24 07:22:54 -06001146 TestFunctional._MakeInputFile('u-boot',
1147 tools.ReadFile(self.ElfTestFile('u_boot_ucode_ptr')))
Simon Glass75db0862016-11-25 20:15:55 -07001148
1149 def testMicrocodeNotInImage(self):
1150 """Test that microcode must be placed within the image"""
1151 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001152 self._DoReadFile('040_x86_ucode_not_in_image.dts', True)
Simon Glass75db0862016-11-25 20:15:55 -07001153 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
1154 "pointer _dt_ucode_base_size at fffffe14 is outside the "
Simon Glass25ac0e62018-06-01 09:38:14 -06001155 "section ranging from 00000000 to 0000002e", str(e.exception))
Simon Glass75db0862016-11-25 20:15:55 -07001156
1157 def testWithoutMicrocode(self):
1158 """Test that we can cope with an image without microcode (e.g. qemu)"""
Simon Glassbccd91d2019-08-24 07:22:55 -06001159 TestFunctional._MakeInputFile('u-boot',
1160 tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
Simon Glass741f2d62018-10-01 12:22:30 -06001161 data, dtb, _, _ = self._DoReadFileDtb('044_x86_optional_ucode.dts', True)
Simon Glass75db0862016-11-25 20:15:55 -07001162
1163 # Now check the device tree has no microcode
1164 self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
1165 second = data[len(U_BOOT_NODTB_DATA):]
1166
1167 fdt_len = self.GetFdtLen(second)
1168 self.assertEqual(dtb, second[:fdt_len])
1169
1170 used_len = len(U_BOOT_NODTB_DATA) + fdt_len
1171 third = data[used_len:]
Simon Glasse6d85ff2019-05-14 15:53:47 -06001172 self.assertEqual(tools.GetBytes(0, 0x200 - used_len), third)
Simon Glass75db0862016-11-25 20:15:55 -07001173
1174 def testUnknownPosSize(self):
1175 """Test that microcode must be placed within the image"""
1176 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001177 self._DoReadFile('041_unknown_pos_size.dts', True)
Simon Glass3ab95982018-08-01 15:22:37 -06001178 self.assertIn("Section '/binman': Unable to set offset/size for unknown "
Simon Glass75db0862016-11-25 20:15:55 -07001179 "entry 'invalid-entry'", str(e.exception))
Simon Glassda229092016-11-25 20:15:56 -07001180
1181 def testPackFsp(self):
1182 """Test that an image with a FSP binary can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001183 data = self._DoReadFile('042_intel_fsp.dts')
Simon Glassda229092016-11-25 20:15:56 -07001184 self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
1185
1186 def testPackCmc(self):
Bin Meng59ea8c22017-08-15 22:41:54 -07001187 """Test that an image with a CMC binary can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001188 data = self._DoReadFile('043_intel_cmc.dts')
Simon Glassda229092016-11-25 20:15:56 -07001189 self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
Bin Meng59ea8c22017-08-15 22:41:54 -07001190
1191 def testPackVbt(self):
1192 """Test that an image with a VBT binary can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001193 data = self._DoReadFile('046_intel_vbt.dts')
Bin Meng59ea8c22017-08-15 22:41:54 -07001194 self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
Simon Glass9fc60b42017-11-12 21:52:22 -07001195
Simon Glass56509842017-11-12 21:52:25 -07001196 def testSplBssPad(self):
1197 """Test that we can pad SPL's BSS with zeros"""
Simon Glass6b187df2017-11-12 21:52:27 -07001198 # ELF file with a '__bss_size' symbol
Simon Glass11ae93e2018-10-01 21:12:47 -06001199 self._SetupSplElf()
Simon Glass741f2d62018-10-01 12:22:30 -06001200 data = self._DoReadFile('047_spl_bss_pad.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -06001201 self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0, 10) + U_BOOT_DATA,
1202 data)
Simon Glass56509842017-11-12 21:52:25 -07001203
Simon Glass86af5112018-10-01 21:12:42 -06001204 def testSplBssPadMissing(self):
1205 """Test that a missing symbol is detected"""
Simon Glass11ae93e2018-10-01 21:12:47 -06001206 self._SetupSplElf('u_boot_ucode_ptr')
Simon Glassb50e5612017-11-13 18:54:54 -07001207 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001208 self._DoReadFile('047_spl_bss_pad.dts')
Simon Glassb50e5612017-11-13 18:54:54 -07001209 self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
1210 str(e.exception))
1211
Simon Glass87722132017-11-12 21:52:26 -07001212 def testPackStart16Spl(self):
Simon Glass35b384c2018-09-14 04:57:10 -06001213 """Test that an image with an x86 start16 SPL region can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001214 data = self._DoReadFile('048_x86_start16_spl.dts')
Simon Glass87722132017-11-12 21:52:26 -07001215 self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
1216
Simon Glass736bb0a2018-07-06 10:27:17 -06001217 def _PackUbootSplMicrocode(self, dts, ucode_second=False):
1218 """Helper function for microcode tests
Simon Glass6b187df2017-11-12 21:52:27 -07001219
1220 We expect to see the following in the image, in order:
1221 u-boot-spl-nodtb.bin with a microcode pointer inserted at the
1222 correct place
1223 u-boot.dtb with the microcode removed
1224 the microcode
Simon Glass736bb0a2018-07-06 10:27:17 -06001225
1226 Args:
1227 dts: Device tree file to use for test
1228 ucode_second: True if the microsecond entry is second instead of
1229 third
Simon Glass6b187df2017-11-12 21:52:27 -07001230 """
Simon Glass11ae93e2018-10-01 21:12:47 -06001231 self._SetupSplElf('u_boot_ucode_ptr')
Simon Glass736bb0a2018-07-06 10:27:17 -06001232 first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
1233 ucode_second=ucode_second)
Simon Glassc6c10e72019-05-17 22:00:46 -06001234 self.assertEqual(b'splnodtb with microc' + pos_and_size +
1235 b'ter somewhere in here', first)
Simon Glass6b187df2017-11-12 21:52:27 -07001236
Simon Glass736bb0a2018-07-06 10:27:17 -06001237 def testPackUbootSplMicrocode(self):
1238 """Test that x86 microcode can be handled correctly in SPL"""
Simon Glass741f2d62018-10-01 12:22:30 -06001239 self._PackUbootSplMicrocode('049_x86_ucode_spl.dts')
Simon Glass736bb0a2018-07-06 10:27:17 -06001240
1241 def testPackUbootSplMicrocodeReorder(self):
1242 """Test that order doesn't matter for microcode entries
1243
1244 This is the same as testPackUbootSplMicrocode but when we process the
1245 u-boot-ucode entry we have not yet seen the u-boot-dtb-with-ucode
1246 entry, so we reply on binman to try later.
1247 """
Simon Glass741f2d62018-10-01 12:22:30 -06001248 self._PackUbootSplMicrocode('058_x86_ucode_spl_needs_retry.dts',
Simon Glass736bb0a2018-07-06 10:27:17 -06001249 ucode_second=True)
1250
Simon Glassca4f4ff2017-11-12 21:52:28 -07001251 def testPackMrc(self):
1252 """Test that an image with an MRC binary can be created"""
Simon Glass741f2d62018-10-01 12:22:30 -06001253 data = self._DoReadFile('050_intel_mrc.dts')
Simon Glassca4f4ff2017-11-12 21:52:28 -07001254 self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
1255
Simon Glass47419ea2017-11-13 18:54:55 -07001256 def testSplDtb(self):
1257 """Test that an image with spl/u-boot-spl.dtb can be created"""
Simon Glass741f2d62018-10-01 12:22:30 -06001258 data = self._DoReadFile('051_u_boot_spl_dtb.dts')
Simon Glass47419ea2017-11-13 18:54:55 -07001259 self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
1260
Simon Glass4e6fdbe2017-11-13 18:54:56 -07001261 def testSplNoDtb(self):
1262 """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
Simon Glass741f2d62018-10-01 12:22:30 -06001263 data = self._DoReadFile('052_u_boot_spl_nodtb.dts')
Simon Glass4e6fdbe2017-11-13 18:54:56 -07001264 self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
1265
Simon Glass19790632017-11-13 18:55:01 -07001266 def testSymbols(self):
1267 """Test binman can assign symbols embedded in U-Boot"""
Simon Glass1542c8b2019-08-24 07:22:56 -06001268 elf_fname = self.ElfTestFile('u_boot_binman_syms')
Simon Glass19790632017-11-13 18:55:01 -07001269 syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
1270 addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
Simon Glass3ab95982018-08-01 15:22:37 -06001271 self.assertEqual(syms['_binman_u_boot_spl_prop_offset'].address, addr)
Simon Glass19790632017-11-13 18:55:01 -07001272
Simon Glass11ae93e2018-10-01 21:12:47 -06001273 self._SetupSplElf('u_boot_binman_syms')
Simon Glass741f2d62018-10-01 12:22:30 -06001274 data = self._DoReadFile('053_symbols.dts')
Simon Glass7c150132019-11-06 17:22:44 -07001275 sym_values = struct.pack('<LQLL', 0x00, 0x1c, 0x28, 0x04)
Simon Glassb87064c2019-08-24 07:23:05 -06001276 expected = (sym_values + U_BOOT_SPL_DATA[20:] +
Simon Glasse6d85ff2019-05-14 15:53:47 -06001277 tools.GetBytes(0xff, 1) + U_BOOT_DATA + sym_values +
Simon Glassb87064c2019-08-24 07:23:05 -06001278 U_BOOT_SPL_DATA[20:])
Simon Glass19790632017-11-13 18:55:01 -07001279 self.assertEqual(expected, data)
1280
Simon Glassdd57c132018-06-01 09:38:11 -06001281 def testPackUnitAddress(self):
1282 """Test that we support multiple binaries with the same name"""
Simon Glass741f2d62018-10-01 12:22:30 -06001283 data = self._DoReadFile('054_unit_address.dts')
Simon Glassdd57c132018-06-01 09:38:11 -06001284 self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
1285
Simon Glass18546952018-06-01 09:38:16 -06001286 def testSections(self):
1287 """Basic test of sections"""
Simon Glass741f2d62018-10-01 12:22:30 -06001288 data = self._DoReadFile('055_sections.dts')
Simon Glassc6c10e72019-05-17 22:00:46 -06001289 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
1290 U_BOOT_DATA + tools.GetBytes(ord('a'), 12) +
1291 U_BOOT_DATA + tools.GetBytes(ord('&'), 4))
Simon Glass18546952018-06-01 09:38:16 -06001292 self.assertEqual(expected, data)
Simon Glass9fc60b42017-11-12 21:52:22 -07001293
Simon Glass3b0c3822018-06-01 09:38:20 -06001294 def testMap(self):
1295 """Tests outputting a map of the images"""
Simon Glass741f2d62018-10-01 12:22:30 -06001296 _, _, map_data, _ = self._DoReadFileDtb('055_sections.dts', map=True)
Simon Glass1be70d22018-07-17 13:25:49 -06001297 self.assertEqual('''ImagePos Offset Size Name
129800000000 00000000 00000028 main-section
129900000000 00000000 00000010 section@0
130000000000 00000000 00000004 u-boot
130100000010 00000010 00000010 section@1
130200000010 00000000 00000004 u-boot
130300000020 00000020 00000004 section@2
130400000020 00000000 00000004 u-boot
Simon Glass3b0c3822018-06-01 09:38:20 -06001305''', map_data)
1306
Simon Glassc8d48ef2018-06-01 09:38:21 -06001307 def testNamePrefix(self):
1308 """Tests that name prefixes are used"""
Simon Glass741f2d62018-10-01 12:22:30 -06001309 _, _, map_data, _ = self._DoReadFileDtb('056_name_prefix.dts', map=True)
Simon Glass1be70d22018-07-17 13:25:49 -06001310 self.assertEqual('''ImagePos Offset Size Name
131100000000 00000000 00000028 main-section
131200000000 00000000 00000010 section@0
131300000000 00000000 00000004 ro-u-boot
131400000010 00000010 00000010 section@1
131500000010 00000000 00000004 rw-u-boot
Simon Glassc8d48ef2018-06-01 09:38:21 -06001316''', map_data)
1317
Simon Glass736bb0a2018-07-06 10:27:17 -06001318 def testUnknownContents(self):
1319 """Test that obtaining the contents works as expected"""
1320 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001321 self._DoReadFile('057_unknown_contents.dts', True)
Simon Glass8beb11e2019-07-08 14:25:47 -06001322 self.assertIn("Image '/binman': Internal error: Could not complete "
Simon Glass16287932020-04-17 18:09:03 -06001323 "processing of contents: remaining ["
1324 "<binman.etype._testing.Entry__testing ", str(e.exception))
Simon Glass736bb0a2018-07-06 10:27:17 -06001325
Simon Glass5c890232018-07-06 10:27:19 -06001326 def testBadChangeSize(self):
1327 """Test that trying to change the size of an entry fails"""
Simon Glassc52c9e72019-07-08 14:25:37 -06001328 try:
1329 state.SetAllowEntryExpansion(False)
1330 with self.assertRaises(ValueError) as e:
1331 self._DoReadFile('059_change_size.dts', True)
Simon Glass79d3c582019-07-20 12:23:57 -06001332 self.assertIn("Node '/binman/_testing': Cannot update entry size from 2 to 3",
Simon Glassc52c9e72019-07-08 14:25:37 -06001333 str(e.exception))
1334 finally:
1335 state.SetAllowEntryExpansion(True)
Simon Glass5c890232018-07-06 10:27:19 -06001336
Simon Glass16b8d6b2018-07-06 10:27:42 -06001337 def testUpdateFdt(self):
Simon Glass3ab95982018-08-01 15:22:37 -06001338 """Test that we can update the device tree with offset/size info"""
Simon Glass741f2d62018-10-01 12:22:30 -06001339 _, _, _, out_dtb_fname = self._DoReadFileDtb('060_fdt_update.dts',
Simon Glass16b8d6b2018-07-06 10:27:42 -06001340 update_dtb=True)
Simon Glasscee02e62018-07-17 13:25:52 -06001341 dtb = fdt.Fdt(out_dtb_fname)
1342 dtb.Scan()
Simon Glass12bb1a92019-07-20 12:23:51 -06001343 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS)
Simon Glass16b8d6b2018-07-06 10:27:42 -06001344 self.assertEqual({
Simon Glassdbf6be92018-08-01 15:22:42 -06001345 'image-pos': 0,
Simon Glass8122f392018-07-17 13:25:28 -06001346 'offset': 0,
Simon Glass3ab95982018-08-01 15:22:37 -06001347 '_testing:offset': 32,
Simon Glass79d3c582019-07-20 12:23:57 -06001348 '_testing:size': 2,
Simon Glassdbf6be92018-08-01 15:22:42 -06001349 '_testing:image-pos': 32,
Simon Glass3ab95982018-08-01 15:22:37 -06001350 'section@0/u-boot:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001351 'section@0/u-boot:size': len(U_BOOT_DATA),
Simon Glassdbf6be92018-08-01 15:22:42 -06001352 'section@0/u-boot:image-pos': 0,
Simon Glass3ab95982018-08-01 15:22:37 -06001353 'section@0:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001354 'section@0:size': 16,
Simon Glassdbf6be92018-08-01 15:22:42 -06001355 'section@0:image-pos': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001356
Simon Glass3ab95982018-08-01 15:22:37 -06001357 'section@1/u-boot:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001358 'section@1/u-boot:size': len(U_BOOT_DATA),
Simon Glassdbf6be92018-08-01 15:22:42 -06001359 'section@1/u-boot:image-pos': 16,
Simon Glass3ab95982018-08-01 15:22:37 -06001360 'section@1:offset': 16,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001361 'section@1:size': 16,
Simon Glassdbf6be92018-08-01 15:22:42 -06001362 'section@1:image-pos': 16,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001363 'size': 40
1364 }, props)
1365
1366 def testUpdateFdtBad(self):
1367 """Test that we detect when ProcessFdt never completes"""
1368 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001369 self._DoReadFileDtb('061_fdt_update_bad.dts', update_dtb=True)
Simon Glass16b8d6b2018-07-06 10:27:42 -06001370 self.assertIn('Could not complete processing of Fdt: remaining '
Simon Glass16287932020-04-17 18:09:03 -06001371 '[<binman.etype._testing.Entry__testing',
1372 str(e.exception))
Simon Glass5c890232018-07-06 10:27:19 -06001373
Simon Glass53af22a2018-07-17 13:25:32 -06001374 def testEntryArgs(self):
1375 """Test passing arguments to entries from the command line"""
1376 entry_args = {
1377 'test-str-arg': 'test1',
1378 'test-int-arg': '456',
1379 }
Simon Glass741f2d62018-10-01 12:22:30 -06001380 self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
Simon Glass53af22a2018-07-17 13:25:32 -06001381 self.assertIn('image', control.images)
1382 entry = control.images['image'].GetEntries()['_testing']
1383 self.assertEqual('test0', entry.test_str_fdt)
1384 self.assertEqual('test1', entry.test_str_arg)
1385 self.assertEqual(123, entry.test_int_fdt)
1386 self.assertEqual(456, entry.test_int_arg)
1387
1388 def testEntryArgsMissing(self):
1389 """Test missing arguments and properties"""
1390 entry_args = {
1391 'test-int-arg': '456',
1392 }
Simon Glass741f2d62018-10-01 12:22:30 -06001393 self._DoReadFileDtb('063_entry_args_missing.dts', entry_args=entry_args)
Simon Glass53af22a2018-07-17 13:25:32 -06001394 entry = control.images['image'].GetEntries()['_testing']
1395 self.assertEqual('test0', entry.test_str_fdt)
1396 self.assertEqual(None, entry.test_str_arg)
1397 self.assertEqual(None, entry.test_int_fdt)
1398 self.assertEqual(456, entry.test_int_arg)
1399
1400 def testEntryArgsRequired(self):
1401 """Test missing arguments and properties"""
1402 entry_args = {
1403 'test-int-arg': '456',
1404 }
1405 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001406 self._DoReadFileDtb('064_entry_args_required.dts')
Simon Glass3decfa32020-09-01 05:13:54 -06001407 self.assertIn("Node '/binman/_testing': "
1408 'Missing required properties/entry args: test-str-arg, '
1409 'test-int-fdt, test-int-arg',
Simon Glass53af22a2018-07-17 13:25:32 -06001410 str(e.exception))
1411
1412 def testEntryArgsInvalidFormat(self):
1413 """Test that an invalid entry-argument format is detected"""
Simon Glass53cd5d92019-07-08 14:25:29 -06001414 args = ['build', '-d', self.TestFile('064_entry_args_required.dts'),
1415 '-ano-value']
Simon Glass53af22a2018-07-17 13:25:32 -06001416 with self.assertRaises(ValueError) as e:
1417 self._DoBinman(*args)
1418 self.assertIn("Invalid entry arguemnt 'no-value'", str(e.exception))
1419
1420 def testEntryArgsInvalidInteger(self):
1421 """Test that an invalid entry-argument integer is detected"""
1422 entry_args = {
1423 'test-int-arg': 'abc',
1424 }
1425 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001426 self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
Simon Glass53af22a2018-07-17 13:25:32 -06001427 self.assertIn("Node '/binman/_testing': Cannot convert entry arg "
1428 "'test-int-arg' (value 'abc') to integer",
1429 str(e.exception))
1430
1431 def testEntryArgsInvalidDatatype(self):
1432 """Test that an invalid entry-argument datatype is detected
1433
1434 This test could be written in entry_test.py except that it needs
1435 access to control.entry_args, which seems more than that module should
1436 be able to see.
1437 """
1438 entry_args = {
1439 'test-bad-datatype-arg': '12',
1440 }
1441 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001442 self._DoReadFileDtb('065_entry_args_unknown_datatype.dts',
Simon Glass53af22a2018-07-17 13:25:32 -06001443 entry_args=entry_args)
1444 self.assertIn('GetArg() internal error: Unknown data type ',
1445 str(e.exception))
1446
Simon Glassbb748372018-07-17 13:25:33 -06001447 def testText(self):
1448 """Test for a text entry type"""
1449 entry_args = {
1450 'test-id': TEXT_DATA,
1451 'test-id2': TEXT_DATA2,
1452 'test-id3': TEXT_DATA3,
1453 }
Simon Glass741f2d62018-10-01 12:22:30 -06001454 data, _, _, _ = self._DoReadFileDtb('066_text.dts',
Simon Glassbb748372018-07-17 13:25:33 -06001455 entry_args=entry_args)
Simon Glassc6c10e72019-05-17 22:00:46 -06001456 expected = (tools.ToBytes(TEXT_DATA) +
1457 tools.GetBytes(0, 8 - len(TEXT_DATA)) +
1458 tools.ToBytes(TEXT_DATA2) + tools.ToBytes(TEXT_DATA3) +
Simon Glassaa88b502019-07-08 13:18:40 -06001459 b'some text' + b'more text')
Simon Glassbb748372018-07-17 13:25:33 -06001460 self.assertEqual(expected, data)
1461
Simon Glassfd8d1f72018-07-17 13:25:36 -06001462 def testEntryDocs(self):
1463 """Test for creation of entry documentation"""
1464 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass87d43322020-08-05 13:27:46 -06001465 control.WriteEntryDocs(control.GetEntryModules())
Simon Glassfd8d1f72018-07-17 13:25:36 -06001466 self.assertTrue(len(stdout.getvalue()) > 0)
1467
1468 def testEntryDocsMissing(self):
1469 """Test handling of missing entry documentation"""
1470 with self.assertRaises(ValueError) as e:
1471 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass87d43322020-08-05 13:27:46 -06001472 control.WriteEntryDocs(control.GetEntryModules(), 'u_boot')
Simon Glassfd8d1f72018-07-17 13:25:36 -06001473 self.assertIn('Documentation is missing for modules: u_boot',
1474 str(e.exception))
1475
Simon Glass11e36cc2018-07-17 13:25:38 -06001476 def testFmap(self):
1477 """Basic test of generation of a flashrom fmap"""
Simon Glass741f2d62018-10-01 12:22:30 -06001478 data = self._DoReadFile('067_fmap.dts')
Simon Glass11e36cc2018-07-17 13:25:38 -06001479 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
Simon Glassc6c10e72019-05-17 22:00:46 -06001480 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
1481 U_BOOT_DATA + tools.GetBytes(ord('a'), 12))
Simon Glass11e36cc2018-07-17 13:25:38 -06001482 self.assertEqual(expected, data[:32])
Simon Glassc6c10e72019-05-17 22:00:46 -06001483 self.assertEqual(b'__FMAP__', fhdr.signature)
Simon Glass11e36cc2018-07-17 13:25:38 -06001484 self.assertEqual(1, fhdr.ver_major)
1485 self.assertEqual(0, fhdr.ver_minor)
1486 self.assertEqual(0, fhdr.base)
1487 self.assertEqual(16 + 16 +
1488 fmap_util.FMAP_HEADER_LEN +
1489 fmap_util.FMAP_AREA_LEN * 3, fhdr.image_size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001490 self.assertEqual(b'FMAP', fhdr.name)
Simon Glass11e36cc2018-07-17 13:25:38 -06001491 self.assertEqual(3, fhdr.nareas)
1492 for fentry in fentries:
1493 self.assertEqual(0, fentry.flags)
1494
1495 self.assertEqual(0, fentries[0].offset)
1496 self.assertEqual(4, fentries[0].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001497 self.assertEqual(b'RO_U_BOOT', fentries[0].name)
Simon Glass11e36cc2018-07-17 13:25:38 -06001498
1499 self.assertEqual(16, fentries[1].offset)
1500 self.assertEqual(4, fentries[1].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001501 self.assertEqual(b'RW_U_BOOT', fentries[1].name)
Simon Glass11e36cc2018-07-17 13:25:38 -06001502
1503 self.assertEqual(32, fentries[2].offset)
1504 self.assertEqual(fmap_util.FMAP_HEADER_LEN +
1505 fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001506 self.assertEqual(b'FMAP', fentries[2].name)
Simon Glass11e36cc2018-07-17 13:25:38 -06001507
Simon Glassec127af2018-07-17 13:25:39 -06001508 def testBlobNamedByArg(self):
1509 """Test we can add a blob with the filename coming from an entry arg"""
1510 entry_args = {
1511 'cros-ec-rw-path': 'ecrw.bin',
1512 }
Simon Glass3decfa32020-09-01 05:13:54 -06001513 self._DoReadFileDtb('068_blob_named_by_arg.dts', entry_args=entry_args)
Simon Glassec127af2018-07-17 13:25:39 -06001514
Simon Glass3af8e492018-07-17 13:25:40 -06001515 def testFill(self):
1516 """Test for an fill entry type"""
Simon Glass741f2d62018-10-01 12:22:30 -06001517 data = self._DoReadFile('069_fill.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -06001518 expected = tools.GetBytes(0xff, 8) + tools.GetBytes(0, 8)
Simon Glass3af8e492018-07-17 13:25:40 -06001519 self.assertEqual(expected, data)
1520
1521 def testFillNoSize(self):
1522 """Test for an fill entry type with no size"""
1523 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001524 self._DoReadFile('070_fill_no_size.dts')
Simon Glass3af8e492018-07-17 13:25:40 -06001525 self.assertIn("'fill' entry must have a size property",
1526 str(e.exception))
1527
Simon Glass0ef87aa2018-07-17 13:25:44 -06001528 def _HandleGbbCommand(self, pipe_list):
1529 """Fake calls to the futility utility"""
1530 if pipe_list[0][0] == 'futility':
1531 fname = pipe_list[0][-1]
1532 # Append our GBB data to the file, which will happen every time the
1533 # futility command is called.
Simon Glass1d0ebf72019-05-14 15:53:42 -06001534 with open(fname, 'ab') as fd:
Simon Glass0ef87aa2018-07-17 13:25:44 -06001535 fd.write(GBB_DATA)
1536 return command.CommandResult()
1537
1538 def testGbb(self):
1539 """Test for the Chromium OS Google Binary Block"""
1540 command.test_result = self._HandleGbbCommand
1541 entry_args = {
1542 'keydir': 'devkeys',
1543 'bmpblk': 'bmpblk.bin',
1544 }
Simon Glass741f2d62018-10-01 12:22:30 -06001545 data, _, _, _ = self._DoReadFileDtb('071_gbb.dts', entry_args=entry_args)
Simon Glass0ef87aa2018-07-17 13:25:44 -06001546
1547 # Since futility
Simon Glasse6d85ff2019-05-14 15:53:47 -06001548 expected = (GBB_DATA + GBB_DATA + tools.GetBytes(0, 8) +
1549 tools.GetBytes(0, 0x2180 - 16))
Simon Glass0ef87aa2018-07-17 13:25:44 -06001550 self.assertEqual(expected, data)
1551
1552 def testGbbTooSmall(self):
1553 """Test for the Chromium OS Google Binary Block being large enough"""
1554 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001555 self._DoReadFileDtb('072_gbb_too_small.dts')
Simon Glass0ef87aa2018-07-17 13:25:44 -06001556 self.assertIn("Node '/binman/gbb': GBB is too small",
1557 str(e.exception))
1558
1559 def testGbbNoSize(self):
1560 """Test for the Chromium OS Google Binary Block having a size"""
1561 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001562 self._DoReadFileDtb('073_gbb_no_size.dts')
Simon Glass0ef87aa2018-07-17 13:25:44 -06001563 self.assertIn("Node '/binman/gbb': GBB must have a fixed size",
1564 str(e.exception))
1565
Simon Glass24d0d3c2018-07-17 13:25:47 -06001566 def _HandleVblockCommand(self, pipe_list):
1567 """Fake calls to the futility utility"""
1568 if pipe_list[0][0] == 'futility':
1569 fname = pipe_list[0][3]
Simon Glassa326b492018-09-14 04:57:11 -06001570 with open(fname, 'wb') as fd:
Simon Glass24d0d3c2018-07-17 13:25:47 -06001571 fd.write(VBLOCK_DATA)
1572 return command.CommandResult()
1573
1574 def testVblock(self):
1575 """Test for the Chromium OS Verified Boot Block"""
1576 command.test_result = self._HandleVblockCommand
1577 entry_args = {
1578 'keydir': 'devkeys',
1579 }
Simon Glass741f2d62018-10-01 12:22:30 -06001580 data, _, _, _ = self._DoReadFileDtb('074_vblock.dts',
Simon Glass24d0d3c2018-07-17 13:25:47 -06001581 entry_args=entry_args)
1582 expected = U_BOOT_DATA + VBLOCK_DATA + U_BOOT_DTB_DATA
1583 self.assertEqual(expected, data)
1584
1585 def testVblockNoContent(self):
1586 """Test we detect a vblock which has no content to sign"""
1587 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001588 self._DoReadFile('075_vblock_no_content.dts')
Simon Glass24d0d3c2018-07-17 13:25:47 -06001589 self.assertIn("Node '/binman/vblock': Vblock must have a 'content' "
1590 'property', str(e.exception))
1591
1592 def testVblockBadPhandle(self):
1593 """Test that we detect a vblock with an invalid phandle in contents"""
1594 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001595 self._DoReadFile('076_vblock_bad_phandle.dts')
Simon Glass24d0d3c2018-07-17 13:25:47 -06001596 self.assertIn("Node '/binman/vblock': Cannot find node for phandle "
1597 '1000', str(e.exception))
1598
1599 def testVblockBadEntry(self):
1600 """Test that we detect an entry that points to a non-entry"""
1601 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001602 self._DoReadFile('077_vblock_bad_entry.dts')
Simon Glass24d0d3c2018-07-17 13:25:47 -06001603 self.assertIn("Node '/binman/vblock': Cannot find entry for node "
1604 "'other'", str(e.exception))
1605
Simon Glassb8ef5b62018-07-17 13:25:48 -06001606 def testTpl(self):
Simon Glass2090f1e2019-08-24 07:23:00 -06001607 """Test that an image with TPL and its device tree can be created"""
Simon Glassb8ef5b62018-07-17 13:25:48 -06001608 # ELF file with a '__bss_size' symbol
Simon Glass2090f1e2019-08-24 07:23:00 -06001609 self._SetupTplElf()
Simon Glass741f2d62018-10-01 12:22:30 -06001610 data = self._DoReadFile('078_u_boot_tpl.dts')
Simon Glassb8ef5b62018-07-17 13:25:48 -06001611 self.assertEqual(U_BOOT_TPL_DATA + U_BOOT_TPL_DTB_DATA, data)
1612
Simon Glass15a587c2018-07-17 13:25:51 -06001613 def testUsesPos(self):
1614 """Test that the 'pos' property cannot be used anymore"""
1615 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001616 data = self._DoReadFile('079_uses_pos.dts')
Simon Glass15a587c2018-07-17 13:25:51 -06001617 self.assertIn("Node '/binman/u-boot': Please use 'offset' instead of "
1618 "'pos'", str(e.exception))
1619
Simon Glassd178eab2018-09-14 04:57:08 -06001620 def testFillZero(self):
1621 """Test for an fill entry type with a size of 0"""
Simon Glass741f2d62018-10-01 12:22:30 -06001622 data = self._DoReadFile('080_fill_empty.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -06001623 self.assertEqual(tools.GetBytes(0, 16), data)
Simon Glassd178eab2018-09-14 04:57:08 -06001624
Simon Glass0b489362018-09-14 04:57:09 -06001625 def testTextMissing(self):
1626 """Test for a text entry type where there is no text"""
1627 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001628 self._DoReadFileDtb('066_text.dts',)
Simon Glass0b489362018-09-14 04:57:09 -06001629 self.assertIn("Node '/binman/text': No value provided for text label "
1630 "'test-id'", str(e.exception))
1631
Simon Glass35b384c2018-09-14 04:57:10 -06001632 def testPackStart16Tpl(self):
1633 """Test that an image with an x86 start16 TPL region can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001634 data = self._DoReadFile('081_x86_start16_tpl.dts')
Simon Glass35b384c2018-09-14 04:57:10 -06001635 self.assertEqual(X86_START16_TPL_DATA, data[:len(X86_START16_TPL_DATA)])
1636
Simon Glass0bfa7b02018-09-14 04:57:12 -06001637 def testSelectImage(self):
1638 """Test that we can select which images to build"""
Simon Glasseb833d82019-04-25 21:58:34 -06001639 expected = 'Skipping images: image1'
Simon Glass0bfa7b02018-09-14 04:57:12 -06001640
Simon Glasseb833d82019-04-25 21:58:34 -06001641 # We should only get the expected message in verbose mode
Simon Glassee0c9a72019-07-08 13:18:48 -06001642 for verbosity in (0, 2):
Simon Glasseb833d82019-04-25 21:58:34 -06001643 with test_util.capture_sys_output() as (stdout, stderr):
1644 retcode = self._DoTestFile('006_dual_image.dts',
1645 verbosity=verbosity,
1646 images=['image2'])
1647 self.assertEqual(0, retcode)
1648 if verbosity:
1649 self.assertIn(expected, stdout.getvalue())
1650 else:
1651 self.assertNotIn(expected, stdout.getvalue())
1652
1653 self.assertFalse(os.path.exists(tools.GetOutputFilename('image1.bin')))
1654 self.assertTrue(os.path.exists(tools.GetOutputFilename('image2.bin')))
Simon Glassf86a7362019-07-20 12:24:10 -06001655 self._CleanupOutputDir()
Simon Glass0bfa7b02018-09-14 04:57:12 -06001656
Simon Glass6ed45ba2018-09-14 04:57:24 -06001657 def testUpdateFdtAll(self):
1658 """Test that all device trees are updated with offset/size info"""
Simon Glass3c081312019-07-08 14:25:26 -06001659 data = self._DoReadFileRealDtb('082_fdt_update_all.dts')
Simon Glass6ed45ba2018-09-14 04:57:24 -06001660
1661 base_expected = {
1662 'section:image-pos': 0,
1663 'u-boot-tpl-dtb:size': 513,
1664 'u-boot-spl-dtb:size': 513,
1665 'u-boot-spl-dtb:offset': 493,
1666 'image-pos': 0,
1667 'section/u-boot-dtb:image-pos': 0,
1668 'u-boot-spl-dtb:image-pos': 493,
1669 'section/u-boot-dtb:size': 493,
1670 'u-boot-tpl-dtb:image-pos': 1006,
1671 'section/u-boot-dtb:offset': 0,
1672 'section:size': 493,
1673 'offset': 0,
1674 'section:offset': 0,
1675 'u-boot-tpl-dtb:offset': 1006,
1676 'size': 1519
1677 }
1678
1679 # We expect three device-tree files in the output, one after the other.
1680 # Read them in sequence. We look for an 'spl' property in the SPL tree,
1681 # and 'tpl' in the TPL tree, to make sure they are distinct from the
1682 # main U-Boot tree. All three should have the same postions and offset.
1683 start = 0
1684 for item in ['', 'spl', 'tpl']:
1685 dtb = fdt.Fdt.FromData(data[start:])
1686 dtb.Scan()
Simon Glass12bb1a92019-07-20 12:23:51 -06001687 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS +
1688 ['spl', 'tpl'])
Simon Glass6ed45ba2018-09-14 04:57:24 -06001689 expected = dict(base_expected)
1690 if item:
1691 expected[item] = 0
1692 self.assertEqual(expected, props)
1693 start += dtb._fdt_obj.totalsize()
1694
1695 def testUpdateFdtOutput(self):
1696 """Test that output DTB files are updated"""
1697 try:
Simon Glass741f2d62018-10-01 12:22:30 -06001698 data, dtb_data, _, _ = self._DoReadFileDtb('082_fdt_update_all.dts',
Simon Glass6ed45ba2018-09-14 04:57:24 -06001699 use_real_dtb=True, update_dtb=True, reset_dtbs=False)
1700
1701 # Unfortunately, compiling a source file always results in a file
1702 # called source.dtb (see fdt_util.EnsureCompiled()). The test
Simon Glass741f2d62018-10-01 12:22:30 -06001703 # source file (e.g. test/075_fdt_update_all.dts) thus does not enter
Simon Glass6ed45ba2018-09-14 04:57:24 -06001704 # binman as a file called u-boot.dtb. To fix this, copy the file
1705 # over to the expected place.
Simon Glass6ed45ba2018-09-14 04:57:24 -06001706 start = 0
1707 for fname in ['u-boot.dtb.out', 'spl/u-boot-spl.dtb.out',
1708 'tpl/u-boot-tpl.dtb.out']:
1709 dtb = fdt.Fdt.FromData(data[start:])
1710 size = dtb._fdt_obj.totalsize()
1711 pathname = tools.GetOutputFilename(os.path.split(fname)[1])
1712 outdata = tools.ReadFile(pathname)
1713 name = os.path.split(fname)[0]
1714
1715 if name:
1716 orig_indata = self._GetDtbContentsForSplTpl(dtb_data, name)
1717 else:
1718 orig_indata = dtb_data
1719 self.assertNotEqual(outdata, orig_indata,
1720 "Expected output file '%s' be updated" % pathname)
1721 self.assertEqual(outdata, data[start:start + size],
1722 "Expected output file '%s' to match output image" %
1723 pathname)
1724 start += size
1725 finally:
1726 self._ResetDtbs()
1727
Simon Glass83d73c22018-09-14 04:57:26 -06001728 def _decompress(self, data):
Simon Glassff5c7e32019-07-08 13:18:42 -06001729 return tools.Decompress(data, 'lz4')
Simon Glass83d73c22018-09-14 04:57:26 -06001730
1731 def testCompress(self):
1732 """Test compression of blobs"""
Simon Glassac62fba2019-07-08 13:18:53 -06001733 self._CheckLz4()
Simon Glass741f2d62018-10-01 12:22:30 -06001734 data, _, _, out_dtb_fname = self._DoReadFileDtb('083_compress.dts',
Simon Glass83d73c22018-09-14 04:57:26 -06001735 use_real_dtb=True, update_dtb=True)
1736 dtb = fdt.Fdt(out_dtb_fname)
1737 dtb.Scan()
1738 props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
1739 orig = self._decompress(data)
1740 self.assertEquals(COMPRESS_DATA, orig)
1741 expected = {
1742 'blob:uncomp-size': len(COMPRESS_DATA),
1743 'blob:size': len(data),
1744 'size': len(data),
1745 }
1746 self.assertEqual(expected, props)
1747
Simon Glass0a98b282018-09-14 04:57:28 -06001748 def testFiles(self):
1749 """Test bringing in multiple files"""
Simon Glass741f2d62018-10-01 12:22:30 -06001750 data = self._DoReadFile('084_files.dts')
Simon Glass0a98b282018-09-14 04:57:28 -06001751 self.assertEqual(FILES_DATA, data)
1752
1753 def testFilesCompress(self):
1754 """Test bringing in multiple files and compressing them"""
Simon Glassac62fba2019-07-08 13:18:53 -06001755 self._CheckLz4()
Simon Glass741f2d62018-10-01 12:22:30 -06001756 data = self._DoReadFile('085_files_compress.dts')
Simon Glass0a98b282018-09-14 04:57:28 -06001757
1758 image = control.images['image']
1759 entries = image.GetEntries()
1760 files = entries['files']
Simon Glass8beb11e2019-07-08 14:25:47 -06001761 entries = files._entries
Simon Glass0a98b282018-09-14 04:57:28 -06001762
Simon Glassc6c10e72019-05-17 22:00:46 -06001763 orig = b''
Simon Glass0a98b282018-09-14 04:57:28 -06001764 for i in range(1, 3):
1765 key = '%d.dat' % i
1766 start = entries[key].image_pos
1767 len = entries[key].size
1768 chunk = data[start:start + len]
1769 orig += self._decompress(chunk)
1770
1771 self.assertEqual(FILES_DATA, orig)
1772
1773 def testFilesMissing(self):
1774 """Test missing files"""
1775 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001776 data = self._DoReadFile('086_files_none.dts')
Simon Glass0a98b282018-09-14 04:57:28 -06001777 self.assertIn("Node '/binman/files': Pattern \'files/*.none\' matched "
1778 'no files', str(e.exception))
1779
1780 def testFilesNoPattern(self):
1781 """Test missing files"""
1782 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001783 data = self._DoReadFile('087_files_no_pattern.dts')
Simon Glass0a98b282018-09-14 04:57:28 -06001784 self.assertIn("Node '/binman/files': Missing 'pattern' property",
1785 str(e.exception))
1786
Simon Glassba64a0b2018-09-14 04:57:29 -06001787 def testExpandSize(self):
1788 """Test an expanding entry"""
Simon Glass741f2d62018-10-01 12:22:30 -06001789 data, _, map_data, _ = self._DoReadFileDtb('088_expand_size.dts',
Simon Glassba64a0b2018-09-14 04:57:29 -06001790 map=True)
Simon Glassc6c10e72019-05-17 22:00:46 -06001791 expect = (tools.GetBytes(ord('a'), 8) + U_BOOT_DATA +
1792 MRC_DATA + tools.GetBytes(ord('b'), 1) + U_BOOT_DATA +
1793 tools.GetBytes(ord('c'), 8) + U_BOOT_DATA +
1794 tools.GetBytes(ord('d'), 8))
Simon Glassba64a0b2018-09-14 04:57:29 -06001795 self.assertEqual(expect, data)
1796 self.assertEqual('''ImagePos Offset Size Name
179700000000 00000000 00000028 main-section
179800000000 00000000 00000008 fill
179900000008 00000008 00000004 u-boot
18000000000c 0000000c 00000004 section
18010000000c 00000000 00000003 intel-mrc
180200000010 00000010 00000004 u-boot2
180300000014 00000014 0000000c section2
180400000014 00000000 00000008 fill
18050000001c 00000008 00000004 u-boot
180600000020 00000020 00000008 fill2
1807''', map_data)
1808
1809 def testExpandSizeBad(self):
1810 """Test an expanding entry which fails to provide contents"""
Simon Glass163ed6c2018-09-14 04:57:36 -06001811 with test_util.capture_sys_output() as (stdout, stderr):
1812 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001813 self._DoReadFileDtb('089_expand_size_bad.dts', map=True)
Simon Glassba64a0b2018-09-14 04:57:29 -06001814 self.assertIn("Node '/binman/_testing': Cannot obtain contents when "
1815 'expanding entry', str(e.exception))
1816
Simon Glasse0e5df92018-09-14 04:57:31 -06001817 def testHash(self):
1818 """Test hashing of the contents of an entry"""
Simon Glass741f2d62018-10-01 12:22:30 -06001819 _, _, _, out_dtb_fname = self._DoReadFileDtb('090_hash.dts',
Simon Glasse0e5df92018-09-14 04:57:31 -06001820 use_real_dtb=True, update_dtb=True)
1821 dtb = fdt.Fdt(out_dtb_fname)
1822 dtb.Scan()
1823 hash_node = dtb.GetNode('/binman/u-boot/hash').props['value']
1824 m = hashlib.sha256()
1825 m.update(U_BOOT_DATA)
Simon Glassc6c10e72019-05-17 22:00:46 -06001826 self.assertEqual(m.digest(), b''.join(hash_node.value))
Simon Glasse0e5df92018-09-14 04:57:31 -06001827
1828 def testHashNoAlgo(self):
1829 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001830 self._DoReadFileDtb('091_hash_no_algo.dts', update_dtb=True)
Simon Glasse0e5df92018-09-14 04:57:31 -06001831 self.assertIn("Node \'/binman/u-boot\': Missing \'algo\' property for "
1832 'hash node', str(e.exception))
1833
1834 def testHashBadAlgo(self):
1835 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001836 self._DoReadFileDtb('092_hash_bad_algo.dts', update_dtb=True)
Simon Glasse0e5df92018-09-14 04:57:31 -06001837 self.assertIn("Node '/binman/u-boot': Unknown hash algorithm",
1838 str(e.exception))
1839
1840 def testHashSection(self):
1841 """Test hashing of the contents of an entry"""
Simon Glass741f2d62018-10-01 12:22:30 -06001842 _, _, _, out_dtb_fname = self._DoReadFileDtb('099_hash_section.dts',
Simon Glasse0e5df92018-09-14 04:57:31 -06001843 use_real_dtb=True, update_dtb=True)
1844 dtb = fdt.Fdt(out_dtb_fname)
1845 dtb.Scan()
1846 hash_node = dtb.GetNode('/binman/section/hash').props['value']
1847 m = hashlib.sha256()
1848 m.update(U_BOOT_DATA)
Simon Glassc6c10e72019-05-17 22:00:46 -06001849 m.update(tools.GetBytes(ord('a'), 16))
1850 self.assertEqual(m.digest(), b''.join(hash_node.value))
Simon Glasse0e5df92018-09-14 04:57:31 -06001851
Simon Glassf0253632018-09-14 04:57:32 -06001852 def testPackUBootTplMicrocode(self):
1853 """Test that x86 microcode can be handled correctly in TPL
1854
1855 We expect to see the following in the image, in order:
1856 u-boot-tpl-nodtb.bin with a microcode pointer inserted at the correct
1857 place
1858 u-boot-tpl.dtb with the microcode removed
1859 the microcode
1860 """
Simon Glass2090f1e2019-08-24 07:23:00 -06001861 self._SetupTplElf('u_boot_ucode_ptr')
Simon Glass741f2d62018-10-01 12:22:30 -06001862 first, pos_and_size = self._RunMicrocodeTest('093_x86_tpl_ucode.dts',
Simon Glassf0253632018-09-14 04:57:32 -06001863 U_BOOT_TPL_NODTB_DATA)
Simon Glassc6c10e72019-05-17 22:00:46 -06001864 self.assertEqual(b'tplnodtb with microc' + pos_and_size +
1865 b'ter somewhere in here', first)
Simon Glassf0253632018-09-14 04:57:32 -06001866
Simon Glassf8f8df62018-09-14 04:57:34 -06001867 def testFmapX86(self):
1868 """Basic test of generation of a flashrom fmap"""
Simon Glass741f2d62018-10-01 12:22:30 -06001869 data = self._DoReadFile('094_fmap_x86.dts')
Simon Glassf8f8df62018-09-14 04:57:34 -06001870 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
Simon Glassc6c10e72019-05-17 22:00:46 -06001871 expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('a'), 32 - 7)
Simon Glassf8f8df62018-09-14 04:57:34 -06001872 self.assertEqual(expected, data[:32])
1873 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
1874
1875 self.assertEqual(0x100, fhdr.image_size)
1876
1877 self.assertEqual(0, fentries[0].offset)
1878 self.assertEqual(4, fentries[0].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001879 self.assertEqual(b'U_BOOT', fentries[0].name)
Simon Glassf8f8df62018-09-14 04:57:34 -06001880
1881 self.assertEqual(4, fentries[1].offset)
1882 self.assertEqual(3, fentries[1].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001883 self.assertEqual(b'INTEL_MRC', fentries[1].name)
Simon Glassf8f8df62018-09-14 04:57:34 -06001884
1885 self.assertEqual(32, fentries[2].offset)
1886 self.assertEqual(fmap_util.FMAP_HEADER_LEN +
1887 fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001888 self.assertEqual(b'FMAP', fentries[2].name)
Simon Glassf8f8df62018-09-14 04:57:34 -06001889
1890 def testFmapX86Section(self):
1891 """Basic test of generation of a flashrom fmap"""
Simon Glass741f2d62018-10-01 12:22:30 -06001892 data = self._DoReadFile('095_fmap_x86_section.dts')
Simon Glassc6c10e72019-05-17 22:00:46 -06001893 expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('b'), 32 - 7)
Simon Glassf8f8df62018-09-14 04:57:34 -06001894 self.assertEqual(expected, data[:32])
1895 fhdr, fentries = fmap_util.DecodeFmap(data[36:])
1896
1897 self.assertEqual(0x100, fhdr.image_size)
1898
1899 self.assertEqual(0, fentries[0].offset)
1900 self.assertEqual(4, fentries[0].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001901 self.assertEqual(b'U_BOOT', fentries[0].name)
Simon Glassf8f8df62018-09-14 04:57:34 -06001902
1903 self.assertEqual(4, fentries[1].offset)
1904 self.assertEqual(3, fentries[1].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001905 self.assertEqual(b'INTEL_MRC', fentries[1].name)
Simon Glassf8f8df62018-09-14 04:57:34 -06001906
1907 self.assertEqual(36, fentries[2].offset)
1908 self.assertEqual(fmap_util.FMAP_HEADER_LEN +
1909 fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001910 self.assertEqual(b'FMAP', fentries[2].name)
Simon Glassf8f8df62018-09-14 04:57:34 -06001911
Simon Glassfe1ae3e2018-09-14 04:57:35 -06001912 def testElf(self):
1913 """Basic test of ELF entries"""
Simon Glass11ae93e2018-10-01 21:12:47 -06001914 self._SetupSplElf()
Simon Glass2090f1e2019-08-24 07:23:00 -06001915 self._SetupTplElf()
Simon Glass53e22bf2019-08-24 07:22:53 -06001916 with open(self.ElfTestFile('bss_data'), 'rb') as fd:
Simon Glassfe1ae3e2018-09-14 04:57:35 -06001917 TestFunctional._MakeInputFile('-boot', fd.read())
Simon Glass741f2d62018-10-01 12:22:30 -06001918 data = self._DoReadFile('096_elf.dts')
Simon Glassfe1ae3e2018-09-14 04:57:35 -06001919
Simon Glass093d1682019-07-08 13:18:25 -06001920 def testElfStrip(self):
Simon Glassfe1ae3e2018-09-14 04:57:35 -06001921 """Basic test of ELF entries"""
Simon Glass11ae93e2018-10-01 21:12:47 -06001922 self._SetupSplElf()
Simon Glass53e22bf2019-08-24 07:22:53 -06001923 with open(self.ElfTestFile('bss_data'), 'rb') as fd:
Simon Glassfe1ae3e2018-09-14 04:57:35 -06001924 TestFunctional._MakeInputFile('-boot', fd.read())
Simon Glass741f2d62018-10-01 12:22:30 -06001925 data = self._DoReadFile('097_elf_strip.dts')
Simon Glassfe1ae3e2018-09-14 04:57:35 -06001926
Simon Glass163ed6c2018-09-14 04:57:36 -06001927 def testPackOverlapMap(self):
1928 """Test that overlapping regions are detected"""
1929 with test_util.capture_sys_output() as (stdout, stderr):
1930 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001931 self._DoTestFile('014_pack_overlap.dts', map=True)
Simon Glass163ed6c2018-09-14 04:57:36 -06001932 map_fname = tools.GetOutputFilename('image.map')
1933 self.assertEqual("Wrote map file '%s' to show errors\n" % map_fname,
1934 stdout.getvalue())
1935
1936 # We should not get an inmage, but there should be a map file
1937 self.assertFalse(os.path.exists(tools.GetOutputFilename('image.bin')))
1938 self.assertTrue(os.path.exists(map_fname))
Simon Glasseb546ac2019-05-17 22:00:51 -06001939 map_data = tools.ReadFile(map_fname, binary=False)
Simon Glass163ed6c2018-09-14 04:57:36 -06001940 self.assertEqual('''ImagePos Offset Size Name
1941<none> 00000000 00000007 main-section
1942<none> 00000000 00000004 u-boot
1943<none> 00000003 00000004 u-boot-align
1944''', map_data)
1945
Simon Glass093d1682019-07-08 13:18:25 -06001946 def testPackRefCode(self):
Simon Glass3ae192c2018-10-01 12:22:31 -06001947 """Test that an image with an Intel Reference code binary works"""
1948 data = self._DoReadFile('100_intel_refcode.dts')
1949 self.assertEqual(REFCODE_DATA, data[:len(REFCODE_DATA)])
1950
Simon Glass9481c802019-04-25 21:58:39 -06001951 def testSectionOffset(self):
1952 """Tests use of a section with an offset"""
1953 data, _, map_data, _ = self._DoReadFileDtb('101_sections_offset.dts',
1954 map=True)
1955 self.assertEqual('''ImagePos Offset Size Name
195600000000 00000000 00000038 main-section
195700000004 00000004 00000010 section@0
195800000004 00000000 00000004 u-boot
195900000018 00000018 00000010 section@1
196000000018 00000000 00000004 u-boot
19610000002c 0000002c 00000004 section@2
19620000002c 00000000 00000004 u-boot
1963''', map_data)
1964 self.assertEqual(data,
Simon Glasse6d85ff2019-05-14 15:53:47 -06001965 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
1966 tools.GetBytes(0x21, 12) +
1967 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
1968 tools.GetBytes(0x61, 12) +
1969 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
1970 tools.GetBytes(0x26, 8))
Simon Glass9481c802019-04-25 21:58:39 -06001971
Simon Glassac62fba2019-07-08 13:18:53 -06001972 def testCbfsRaw(self):
1973 """Test base handling of a Coreboot Filesystem (CBFS)
1974
1975 The exact contents of the CBFS is verified by similar tests in
1976 cbfs_util_test.py. The tests here merely check that the files added to
1977 the CBFS can be found in the final image.
1978 """
1979 data = self._DoReadFile('102_cbfs_raw.dts')
1980 size = 0xb0
1981
1982 cbfs = cbfs_util.CbfsReader(data)
1983 self.assertEqual(size, cbfs.rom_size)
1984
1985 self.assertIn('u-boot-dtb', cbfs.files)
1986 cfile = cbfs.files['u-boot-dtb']
1987 self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
1988
1989 def testCbfsArch(self):
1990 """Test on non-x86 architecture"""
1991 data = self._DoReadFile('103_cbfs_raw_ppc.dts')
1992 size = 0x100
1993
1994 cbfs = cbfs_util.CbfsReader(data)
1995 self.assertEqual(size, cbfs.rom_size)
1996
1997 self.assertIn('u-boot-dtb', cbfs.files)
1998 cfile = cbfs.files['u-boot-dtb']
1999 self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
2000
2001 def testCbfsStage(self):
2002 """Tests handling of a Coreboot Filesystem (CBFS)"""
2003 if not elf.ELF_TOOLS:
2004 self.skipTest('Python elftools not available')
2005 elf_fname = os.path.join(self._indir, 'cbfs-stage.elf')
2006 elf.MakeElf(elf_fname, U_BOOT_DATA, U_BOOT_DTB_DATA)
2007 size = 0xb0
2008
2009 data = self._DoReadFile('104_cbfs_stage.dts')
2010 cbfs = cbfs_util.CbfsReader(data)
2011 self.assertEqual(size, cbfs.rom_size)
2012
2013 self.assertIn('u-boot', cbfs.files)
2014 cfile = cbfs.files['u-boot']
2015 self.assertEqual(U_BOOT_DATA + U_BOOT_DTB_DATA, cfile.data)
2016
2017 def testCbfsRawCompress(self):
2018 """Test handling of compressing raw files"""
2019 self._CheckLz4()
2020 data = self._DoReadFile('105_cbfs_raw_compress.dts')
2021 size = 0x140
2022
2023 cbfs = cbfs_util.CbfsReader(data)
2024 self.assertIn('u-boot', cbfs.files)
2025 cfile = cbfs.files['u-boot']
2026 self.assertEqual(COMPRESS_DATA, cfile.data)
2027
2028 def testCbfsBadArch(self):
2029 """Test handling of a bad architecture"""
2030 with self.assertRaises(ValueError) as e:
2031 self._DoReadFile('106_cbfs_bad_arch.dts')
2032 self.assertIn("Invalid architecture 'bad-arch'", str(e.exception))
2033
2034 def testCbfsNoSize(self):
2035 """Test handling of a missing size property"""
2036 with self.assertRaises(ValueError) as e:
2037 self._DoReadFile('107_cbfs_no_size.dts')
2038 self.assertIn('entry must have a size property', str(e.exception))
2039
2040 def testCbfsNoCOntents(self):
2041 """Test handling of a CBFS entry which does not provide contentsy"""
2042 with self.assertRaises(ValueError) as e:
2043 self._DoReadFile('108_cbfs_no_contents.dts')
2044 self.assertIn('Could not complete processing of contents',
2045 str(e.exception))
2046
2047 def testCbfsBadCompress(self):
2048 """Test handling of a bad architecture"""
2049 with self.assertRaises(ValueError) as e:
2050 self._DoReadFile('109_cbfs_bad_compress.dts')
2051 self.assertIn("Invalid compression in 'u-boot': 'invalid-algo'",
2052 str(e.exception))
2053
2054 def testCbfsNamedEntries(self):
2055 """Test handling of named entries"""
2056 data = self._DoReadFile('110_cbfs_name.dts')
2057
2058 cbfs = cbfs_util.CbfsReader(data)
2059 self.assertIn('FRED', cbfs.files)
2060 cfile1 = cbfs.files['FRED']
2061 self.assertEqual(U_BOOT_DATA, cfile1.data)
2062
2063 self.assertIn('hello', cbfs.files)
2064 cfile2 = cbfs.files['hello']
2065 self.assertEqual(U_BOOT_DTB_DATA, cfile2.data)
2066
Simon Glassc5ac1382019-07-08 13:18:54 -06002067 def _SetupIfwi(self, fname):
2068 """Set up to run an IFWI test
2069
2070 Args:
2071 fname: Filename of input file to provide (fitimage.bin or ifwi.bin)
2072 """
2073 self._SetupSplElf()
Simon Glass2090f1e2019-08-24 07:23:00 -06002074 self._SetupTplElf()
Simon Glassc5ac1382019-07-08 13:18:54 -06002075
2076 # Intel Integrated Firmware Image (IFWI) file
2077 with gzip.open(self.TestFile('%s.gz' % fname), 'rb') as fd:
2078 data = fd.read()
2079 TestFunctional._MakeInputFile(fname,data)
2080
2081 def _CheckIfwi(self, data):
2082 """Check that an image with an IFWI contains the correct output
2083
2084 Args:
2085 data: Conents of output file
2086 """
2087 expected_desc = tools.ReadFile(self.TestFile('descriptor.bin'))
2088 if data[:0x1000] != expected_desc:
2089 self.fail('Expected descriptor binary at start of image')
2090
2091 # We expect to find the TPL wil in subpart IBBP entry IBBL
2092 image_fname = tools.GetOutputFilename('image.bin')
2093 tpl_fname = tools.GetOutputFilename('tpl.out')
2094 tools.RunIfwiTool(image_fname, tools.CMD_EXTRACT, fname=tpl_fname,
2095 subpart='IBBP', entry_name='IBBL')
2096
2097 tpl_data = tools.ReadFile(tpl_fname)
Simon Glasse95be632019-08-24 07:22:51 -06002098 self.assertEqual(U_BOOT_TPL_DATA, tpl_data[:len(U_BOOT_TPL_DATA)])
Simon Glassc5ac1382019-07-08 13:18:54 -06002099
2100 def testPackX86RomIfwi(self):
2101 """Test that an x86 ROM with Integrated Firmware Image can be created"""
2102 self._SetupIfwi('fitimage.bin')
Simon Glass9255f3c2019-08-24 07:23:01 -06002103 data = self._DoReadFile('111_x86_rom_ifwi.dts')
Simon Glassc5ac1382019-07-08 13:18:54 -06002104 self._CheckIfwi(data)
2105
2106 def testPackX86RomIfwiNoDesc(self):
2107 """Test that an x86 ROM with IFWI can be created from an ifwi.bin file"""
2108 self._SetupIfwi('ifwi.bin')
Simon Glass9255f3c2019-08-24 07:23:01 -06002109 data = self._DoReadFile('112_x86_rom_ifwi_nodesc.dts')
Simon Glassc5ac1382019-07-08 13:18:54 -06002110 self._CheckIfwi(data)
2111
2112 def testPackX86RomIfwiNoData(self):
2113 """Test that an x86 ROM with IFWI handles missing data"""
2114 self._SetupIfwi('ifwi.bin')
2115 with self.assertRaises(ValueError) as e:
Simon Glass9255f3c2019-08-24 07:23:01 -06002116 data = self._DoReadFile('113_x86_rom_ifwi_nodata.dts')
Simon Glassc5ac1382019-07-08 13:18:54 -06002117 self.assertIn('Could not complete processing of contents',
2118 str(e.exception))
Simon Glass53af22a2018-07-17 13:25:32 -06002119
Simon Glasse073d4e2019-07-08 13:18:56 -06002120 def testCbfsOffset(self):
2121 """Test a CBFS with files at particular offsets
2122
2123 Like all CFBS tests, this is just checking the logic that calls
2124 cbfs_util. See cbfs_util_test for fully tests (e.g. test_cbfs_offset()).
2125 """
2126 data = self._DoReadFile('114_cbfs_offset.dts')
2127 size = 0x200
2128
2129 cbfs = cbfs_util.CbfsReader(data)
2130 self.assertEqual(size, cbfs.rom_size)
2131
2132 self.assertIn('u-boot', cbfs.files)
2133 cfile = cbfs.files['u-boot']
2134 self.assertEqual(U_BOOT_DATA, cfile.data)
2135 self.assertEqual(0x40, cfile.cbfs_offset)
2136
2137 self.assertIn('u-boot-dtb', cbfs.files)
2138 cfile2 = cbfs.files['u-boot-dtb']
2139 self.assertEqual(U_BOOT_DTB_DATA, cfile2.data)
2140 self.assertEqual(0x140, cfile2.cbfs_offset)
2141
Simon Glass086cec92019-07-08 14:25:27 -06002142 def testFdtmap(self):
2143 """Test an FDT map can be inserted in the image"""
2144 data = self.data = self._DoReadFileRealDtb('115_fdtmap.dts')
2145 fdtmap_data = data[len(U_BOOT_DATA):]
2146 magic = fdtmap_data[:8]
Simon Glassb6ee0cf2019-10-31 07:43:03 -06002147 self.assertEqual(b'_FDTMAP_', magic)
Simon Glass086cec92019-07-08 14:25:27 -06002148 self.assertEqual(tools.GetBytes(0, 8), fdtmap_data[8:16])
2149
2150 fdt_data = fdtmap_data[16:]
2151 dtb = fdt.Fdt.FromData(fdt_data)
2152 dtb.Scan()
Simon Glass6ccbfcd2019-07-20 12:23:47 -06002153 props = self._GetPropTree(dtb, BASE_DTB_PROPS, prefix='/')
Simon Glass086cec92019-07-08 14:25:27 -06002154 self.assertEqual({
2155 'image-pos': 0,
2156 'offset': 0,
2157 'u-boot:offset': 0,
2158 'u-boot:size': len(U_BOOT_DATA),
2159 'u-boot:image-pos': 0,
2160 'fdtmap:image-pos': 4,
2161 'fdtmap:offset': 4,
2162 'fdtmap:size': len(fdtmap_data),
2163 'size': len(data),
2164 }, props)
2165
2166 def testFdtmapNoMatch(self):
2167 """Check handling of an FDT map when the section cannot be found"""
2168 self.data = self._DoReadFileRealDtb('115_fdtmap.dts')
2169
2170 # Mangle the section name, which should cause a mismatch between the
2171 # correct FDT path and the one expected by the section
2172 image = control.images['image']
Simon Glasscf228942019-07-08 14:25:28 -06002173 image._node.path += '-suffix'
Simon Glass086cec92019-07-08 14:25:27 -06002174 entries = image.GetEntries()
2175 fdtmap = entries['fdtmap']
2176 with self.assertRaises(ValueError) as e:
2177 fdtmap._GetFdtmap()
2178 self.assertIn("Cannot locate node for path '/binman-suffix'",
2179 str(e.exception))
2180
Simon Glasscf228942019-07-08 14:25:28 -06002181 def testFdtmapHeader(self):
2182 """Test an FDT map and image header can be inserted in the image"""
2183 data = self.data = self._DoReadFileRealDtb('116_fdtmap_hdr.dts')
2184 fdtmap_pos = len(U_BOOT_DATA)
2185 fdtmap_data = data[fdtmap_pos:]
2186 fdt_data = fdtmap_data[16:]
2187 dtb = fdt.Fdt.FromData(fdt_data)
2188 fdt_size = dtb.GetFdtObj().totalsize()
2189 hdr_data = data[-8:]
Simon Glassb6ee0cf2019-10-31 07:43:03 -06002190 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscf228942019-07-08 14:25:28 -06002191 offset = struct.unpack('<I', hdr_data[4:])[0] & 0xffffffff
2192 self.assertEqual(fdtmap_pos - 0x400, offset - (1 << 32))
2193
2194 def testFdtmapHeaderStart(self):
2195 """Test an image header can be inserted at the image start"""
2196 data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
2197 fdtmap_pos = 0x100 + len(U_BOOT_DATA)
2198 hdr_data = data[:8]
Simon Glassb6ee0cf2019-10-31 07:43:03 -06002199 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscf228942019-07-08 14:25:28 -06002200 offset = struct.unpack('<I', hdr_data[4:])[0]
2201 self.assertEqual(fdtmap_pos, offset)
2202
2203 def testFdtmapHeaderPos(self):
2204 """Test an image header can be inserted at a chosen position"""
2205 data = self.data = self._DoReadFileRealDtb('118_fdtmap_hdr_pos.dts')
2206 fdtmap_pos = 0x100 + len(U_BOOT_DATA)
2207 hdr_data = data[0x80:0x88]
Simon Glassb6ee0cf2019-10-31 07:43:03 -06002208 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscf228942019-07-08 14:25:28 -06002209 offset = struct.unpack('<I', hdr_data[4:])[0]
2210 self.assertEqual(fdtmap_pos, offset)
2211
2212 def testHeaderMissingFdtmap(self):
2213 """Test an image header requires an fdtmap"""
2214 with self.assertRaises(ValueError) as e:
2215 self.data = self._DoReadFileRealDtb('119_fdtmap_hdr_missing.dts')
2216 self.assertIn("'image_header' section must have an 'fdtmap' sibling",
2217 str(e.exception))
2218
2219 def testHeaderNoLocation(self):
2220 """Test an image header with a no specified location is detected"""
2221 with self.assertRaises(ValueError) as e:
2222 self.data = self._DoReadFileRealDtb('120_hdr_no_location.dts')
2223 self.assertIn("Invalid location 'None', expected 'start' or 'end'",
2224 str(e.exception))
2225
Simon Glassc52c9e72019-07-08 14:25:37 -06002226 def testEntryExpand(self):
2227 """Test expanding an entry after it is packed"""
2228 data = self._DoReadFile('121_entry_expand.dts')
Simon Glass79d3c582019-07-20 12:23:57 -06002229 self.assertEqual(b'aaa', data[:3])
2230 self.assertEqual(U_BOOT_DATA, data[3:3 + len(U_BOOT_DATA)])
2231 self.assertEqual(b'aaa', data[-3:])
Simon Glassc52c9e72019-07-08 14:25:37 -06002232
2233 def testEntryExpandBad(self):
2234 """Test expanding an entry after it is packed, twice"""
2235 with self.assertRaises(ValueError) as e:
2236 self._DoReadFile('122_entry_expand_twice.dts')
Simon Glass61ec04f2019-07-20 12:23:58 -06002237 self.assertIn("Image '/binman': Entries changed size after packing",
Simon Glassc52c9e72019-07-08 14:25:37 -06002238 str(e.exception))
2239
2240 def testEntryExpandSection(self):
2241 """Test expanding an entry within a section after it is packed"""
2242 data = self._DoReadFile('123_entry_expand_section.dts')
Simon Glass79d3c582019-07-20 12:23:57 -06002243 self.assertEqual(b'aaa', data[:3])
2244 self.assertEqual(U_BOOT_DATA, data[3:3 + len(U_BOOT_DATA)])
2245 self.assertEqual(b'aaa', data[-3:])
Simon Glassc52c9e72019-07-08 14:25:37 -06002246
Simon Glass6c223fd2019-07-08 14:25:38 -06002247 def testCompressDtb(self):
2248 """Test that compress of device-tree files is supported"""
2249 self._CheckLz4()
2250 data = self.data = self._DoReadFileRealDtb('124_compress_dtb.dts')
2251 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
2252 comp_data = data[len(U_BOOT_DATA):]
2253 orig = self._decompress(comp_data)
2254 dtb = fdt.Fdt.FromData(orig)
2255 dtb.Scan()
2256 props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
2257 expected = {
2258 'u-boot:size': len(U_BOOT_DATA),
2259 'u-boot-dtb:uncomp-size': len(orig),
2260 'u-boot-dtb:size': len(comp_data),
2261 'size': len(data),
2262 }
2263 self.assertEqual(expected, props)
2264
Simon Glass69f7cb32019-07-08 14:25:41 -06002265 def testCbfsUpdateFdt(self):
2266 """Test that we can update the device tree with CBFS offset/size info"""
2267 self._CheckLz4()
2268 data, _, _, out_dtb_fname = self._DoReadFileDtb('125_cbfs_update.dts',
2269 update_dtb=True)
2270 dtb = fdt.Fdt(out_dtb_fname)
2271 dtb.Scan()
Simon Glass6ccbfcd2019-07-20 12:23:47 -06002272 props = self._GetPropTree(dtb, BASE_DTB_PROPS + ['uncomp-size'])
Simon Glass69f7cb32019-07-08 14:25:41 -06002273 del props['cbfs/u-boot:size']
2274 self.assertEqual({
2275 'offset': 0,
2276 'size': len(data),
2277 'image-pos': 0,
2278 'cbfs:offset': 0,
2279 'cbfs:size': len(data),
2280 'cbfs:image-pos': 0,
2281 'cbfs/u-boot:offset': 0x38,
2282 'cbfs/u-boot:uncomp-size': len(U_BOOT_DATA),
2283 'cbfs/u-boot:image-pos': 0x38,
2284 'cbfs/u-boot-dtb:offset': 0xb8,
2285 'cbfs/u-boot-dtb:size': len(U_BOOT_DATA),
2286 'cbfs/u-boot-dtb:image-pos': 0xb8,
2287 }, props)
2288
Simon Glass8a1ad062019-07-08 14:25:42 -06002289 def testCbfsBadType(self):
2290 """Test an image header with a no specified location is detected"""
2291 with self.assertRaises(ValueError) as e:
2292 self._DoReadFile('126_cbfs_bad_type.dts')
2293 self.assertIn("Unknown cbfs-type 'badtype'", str(e.exception))
2294
Simon Glass41b8ba02019-07-08 14:25:43 -06002295 def testList(self):
2296 """Test listing the files in an image"""
2297 self._CheckLz4()
2298 data = self._DoReadFile('127_list.dts')
2299 image = control.images['image']
2300 entries = image.BuildEntryList()
2301 self.assertEqual(7, len(entries))
2302
2303 ent = entries[0]
2304 self.assertEqual(0, ent.indent)
2305 self.assertEqual('main-section', ent.name)
2306 self.assertEqual('section', ent.etype)
2307 self.assertEqual(len(data), ent.size)
2308 self.assertEqual(0, ent.image_pos)
2309 self.assertEqual(None, ent.uncomp_size)
Simon Glass8beb11e2019-07-08 14:25:47 -06002310 self.assertEqual(0, ent.offset)
Simon Glass41b8ba02019-07-08 14:25:43 -06002311
2312 ent = entries[1]
2313 self.assertEqual(1, ent.indent)
2314 self.assertEqual('u-boot', ent.name)
2315 self.assertEqual('u-boot', ent.etype)
2316 self.assertEqual(len(U_BOOT_DATA), ent.size)
2317 self.assertEqual(0, ent.image_pos)
2318 self.assertEqual(None, ent.uncomp_size)
2319 self.assertEqual(0, ent.offset)
2320
2321 ent = entries[2]
2322 self.assertEqual(1, ent.indent)
2323 self.assertEqual('section', ent.name)
2324 self.assertEqual('section', ent.etype)
2325 section_size = ent.size
2326 self.assertEqual(0x100, ent.image_pos)
2327 self.assertEqual(None, ent.uncomp_size)
Simon Glass8beb11e2019-07-08 14:25:47 -06002328 self.assertEqual(0x100, ent.offset)
Simon Glass41b8ba02019-07-08 14:25:43 -06002329
2330 ent = entries[3]
2331 self.assertEqual(2, ent.indent)
2332 self.assertEqual('cbfs', ent.name)
2333 self.assertEqual('cbfs', ent.etype)
2334 self.assertEqual(0x400, ent.size)
2335 self.assertEqual(0x100, ent.image_pos)
2336 self.assertEqual(None, ent.uncomp_size)
2337 self.assertEqual(0, ent.offset)
2338
2339 ent = entries[4]
2340 self.assertEqual(3, ent.indent)
2341 self.assertEqual('u-boot', ent.name)
2342 self.assertEqual('u-boot', ent.etype)
2343 self.assertEqual(len(U_BOOT_DATA), ent.size)
2344 self.assertEqual(0x138, ent.image_pos)
2345 self.assertEqual(None, ent.uncomp_size)
2346 self.assertEqual(0x38, ent.offset)
2347
2348 ent = entries[5]
2349 self.assertEqual(3, ent.indent)
2350 self.assertEqual('u-boot-dtb', ent.name)
2351 self.assertEqual('text', ent.etype)
2352 self.assertGreater(len(COMPRESS_DATA), ent.size)
2353 self.assertEqual(0x178, ent.image_pos)
2354 self.assertEqual(len(COMPRESS_DATA), ent.uncomp_size)
2355 self.assertEqual(0x78, ent.offset)
2356
2357 ent = entries[6]
2358 self.assertEqual(2, ent.indent)
2359 self.assertEqual('u-boot-dtb', ent.name)
2360 self.assertEqual('u-boot-dtb', ent.etype)
2361 self.assertEqual(0x500, ent.image_pos)
2362 self.assertEqual(len(U_BOOT_DTB_DATA), ent.uncomp_size)
2363 dtb_size = ent.size
2364 # Compressing this data expands it since headers are added
2365 self.assertGreater(dtb_size, len(U_BOOT_DTB_DATA))
2366 self.assertEqual(0x400, ent.offset)
2367
2368 self.assertEqual(len(data), 0x100 + section_size)
2369 self.assertEqual(section_size, 0x400 + dtb_size)
2370
Simon Glasse1925fa2019-07-08 14:25:44 -06002371 def testFindFdtmap(self):
2372 """Test locating an FDT map in an image"""
2373 self._CheckLz4()
2374 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
2375 image = control.images['image']
2376 entries = image.GetEntries()
2377 entry = entries['fdtmap']
2378 self.assertEqual(entry.image_pos, fdtmap.LocateFdtmap(data))
2379
2380 def testFindFdtmapMissing(self):
2381 """Test failing to locate an FDP map"""
2382 data = self._DoReadFile('005_simple.dts')
2383 self.assertEqual(None, fdtmap.LocateFdtmap(data))
2384
Simon Glass2d260032019-07-08 14:25:45 -06002385 def testFindImageHeader(self):
2386 """Test locating a image header"""
2387 self._CheckLz4()
Simon Glassffded752019-07-08 14:25:46 -06002388 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
Simon Glass2d260032019-07-08 14:25:45 -06002389 image = control.images['image']
2390 entries = image.GetEntries()
2391 entry = entries['fdtmap']
2392 # The header should point to the FDT map
2393 self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data))
2394
2395 def testFindImageHeaderStart(self):
2396 """Test locating a image header located at the start of an image"""
Simon Glassffded752019-07-08 14:25:46 -06002397 data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
Simon Glass2d260032019-07-08 14:25:45 -06002398 image = control.images['image']
2399 entries = image.GetEntries()
2400 entry = entries['fdtmap']
2401 # The header should point to the FDT map
2402 self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data))
2403
2404 def testFindImageHeaderMissing(self):
2405 """Test failing to locate an image header"""
2406 data = self._DoReadFile('005_simple.dts')
2407 self.assertEqual(None, image_header.LocateHeaderOffset(data))
2408
Simon Glassffded752019-07-08 14:25:46 -06002409 def testReadImage(self):
2410 """Test reading an image and accessing its FDT map"""
2411 self._CheckLz4()
2412 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
2413 image_fname = tools.GetOutputFilename('image.bin')
2414 orig_image = control.images['image']
2415 image = Image.FromFile(image_fname)
2416 self.assertEqual(orig_image.GetEntries().keys(),
2417 image.GetEntries().keys())
2418
2419 orig_entry = orig_image.GetEntries()['fdtmap']
2420 entry = image.GetEntries()['fdtmap']
2421 self.assertEquals(orig_entry.offset, entry.offset)
2422 self.assertEquals(orig_entry.size, entry.size)
2423 self.assertEquals(orig_entry.image_pos, entry.image_pos)
2424
2425 def testReadImageNoHeader(self):
2426 """Test accessing an image's FDT map without an image header"""
2427 self._CheckLz4()
2428 data = self._DoReadFileRealDtb('129_decode_image_nohdr.dts')
2429 image_fname = tools.GetOutputFilename('image.bin')
2430 image = Image.FromFile(image_fname)
2431 self.assertTrue(isinstance(image, Image))
Simon Glass10f9d002019-07-20 12:23:50 -06002432 self.assertEqual('image', image.image_name[-5:])
Simon Glassffded752019-07-08 14:25:46 -06002433
2434 def testReadImageFail(self):
2435 """Test failing to read an image image's FDT map"""
2436 self._DoReadFile('005_simple.dts')
2437 image_fname = tools.GetOutputFilename('image.bin')
2438 with self.assertRaises(ValueError) as e:
2439 image = Image.FromFile(image_fname)
2440 self.assertIn("Cannot find FDT map in image", str(e.exception))
Simon Glasse073d4e2019-07-08 13:18:56 -06002441
Simon Glass61f564d2019-07-08 14:25:48 -06002442 def testListCmd(self):
2443 """Test listing the files in an image using an Fdtmap"""
2444 self._CheckLz4()
2445 data = self._DoReadFileRealDtb('130_list_fdtmap.dts')
2446
2447 # lz4 compression size differs depending on the version
2448 image = control.images['image']
2449 entries = image.GetEntries()
2450 section_size = entries['section'].size
2451 fdt_size = entries['section'].GetEntries()['u-boot-dtb'].size
2452 fdtmap_offset = entries['fdtmap'].offset
2453
Simon Glassf86a7362019-07-20 12:24:10 -06002454 try:
2455 tmpdir, updated_fname = self._SetupImageInTmpdir()
2456 with test_util.capture_sys_output() as (stdout, stderr):
2457 self._DoBinman('ls', '-i', updated_fname)
2458 finally:
2459 shutil.rmtree(tmpdir)
Simon Glass61f564d2019-07-08 14:25:48 -06002460 lines = stdout.getvalue().splitlines()
2461 expected = [
2462'Name Image-pos Size Entry-type Offset Uncomp-size',
2463'----------------------------------------------------------------------',
2464'main-section 0 c00 section 0',
2465' u-boot 0 4 u-boot 0',
2466' section 100 %x section 100' % section_size,
2467' cbfs 100 400 cbfs 0',
2468' u-boot 138 4 u-boot 38',
Simon Glassb6ee0cf2019-10-31 07:43:03 -06002469' u-boot-dtb 180 105 u-boot-dtb 80 3c9',
Simon Glass61f564d2019-07-08 14:25:48 -06002470' u-boot-dtb 500 %x u-boot-dtb 400 3c9' % fdt_size,
Simon Glassb6ee0cf2019-10-31 07:43:03 -06002471' fdtmap %x 3bd fdtmap %x' %
Simon Glass61f564d2019-07-08 14:25:48 -06002472 (fdtmap_offset, fdtmap_offset),
2473' image-header bf8 8 image-header bf8',
2474 ]
2475 self.assertEqual(expected, lines)
2476
2477 def testListCmdFail(self):
2478 """Test failing to list an image"""
2479 self._DoReadFile('005_simple.dts')
Simon Glassf86a7362019-07-20 12:24:10 -06002480 try:
2481 tmpdir, updated_fname = self._SetupImageInTmpdir()
2482 with self.assertRaises(ValueError) as e:
2483 self._DoBinman('ls', '-i', updated_fname)
2484 finally:
2485 shutil.rmtree(tmpdir)
Simon Glass61f564d2019-07-08 14:25:48 -06002486 self.assertIn("Cannot find FDT map in image", str(e.exception))
2487
2488 def _RunListCmd(self, paths, expected):
2489 """List out entries and check the result
2490
2491 Args:
2492 paths: List of paths to pass to the list command
2493 expected: Expected list of filenames to be returned, in order
2494 """
2495 self._CheckLz4()
2496 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2497 image_fname = tools.GetOutputFilename('image.bin')
2498 image = Image.FromFile(image_fname)
2499 lines = image.GetListEntries(paths)[1]
2500 files = [line[0].strip() for line in lines[1:]]
2501 self.assertEqual(expected, files)
2502
2503 def testListCmdSection(self):
2504 """Test listing the files in a section"""
2505 self._RunListCmd(['section'],
2506 ['section', 'cbfs', 'u-boot', 'u-boot-dtb', 'u-boot-dtb'])
2507
2508 def testListCmdFile(self):
2509 """Test listing a particular file"""
2510 self._RunListCmd(['*u-boot-dtb'], ['u-boot-dtb', 'u-boot-dtb'])
2511
2512 def testListCmdWildcard(self):
2513 """Test listing a wildcarded file"""
2514 self._RunListCmd(['*boot*'],
2515 ['u-boot', 'u-boot', 'u-boot-dtb', 'u-boot-dtb'])
2516
2517 def testListCmdWildcardMulti(self):
2518 """Test listing a wildcarded file"""
2519 self._RunListCmd(['*cb*', '*head*'],
2520 ['cbfs', 'u-boot', 'u-boot-dtb', 'image-header'])
2521
2522 def testListCmdEmpty(self):
2523 """Test listing a wildcarded file"""
2524 self._RunListCmd(['nothing'], [])
2525
2526 def testListCmdPath(self):
2527 """Test listing the files in a sub-entry of a section"""
2528 self._RunListCmd(['section/cbfs'], ['cbfs', 'u-boot', 'u-boot-dtb'])
2529
Simon Glassf667e452019-07-08 14:25:50 -06002530 def _RunExtractCmd(self, entry_name, decomp=True):
2531 """Extract an entry from an image
2532
2533 Args:
2534 entry_name: Entry name to extract
2535 decomp: True to decompress the data if compressed, False to leave
2536 it in its raw uncompressed format
2537
2538 Returns:
2539 data from entry
2540 """
2541 self._CheckLz4()
2542 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2543 image_fname = tools.GetOutputFilename('image.bin')
2544 return control.ReadEntry(image_fname, entry_name, decomp)
2545
2546 def testExtractSimple(self):
2547 """Test extracting a single file"""
2548 data = self._RunExtractCmd('u-boot')
2549 self.assertEqual(U_BOOT_DATA, data)
2550
Simon Glass71ce0ba2019-07-08 14:25:52 -06002551 def testExtractSection(self):
2552 """Test extracting the files in a section"""
2553 data = self._RunExtractCmd('section')
2554 cbfs_data = data[:0x400]
2555 cbfs = cbfs_util.CbfsReader(cbfs_data)
Simon Glassb6ee0cf2019-10-31 07:43:03 -06002556 self.assertEqual(['u-boot', 'u-boot-dtb', ''], list(cbfs.files.keys()))
Simon Glass71ce0ba2019-07-08 14:25:52 -06002557 dtb_data = data[0x400:]
2558 dtb = self._decompress(dtb_data)
2559 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2560
2561 def testExtractCompressed(self):
2562 """Test extracting compressed data"""
2563 data = self._RunExtractCmd('section/u-boot-dtb')
2564 self.assertEqual(EXTRACT_DTB_SIZE, len(data))
2565
2566 def testExtractRaw(self):
2567 """Test extracting compressed data without decompressing it"""
2568 data = self._RunExtractCmd('section/u-boot-dtb', decomp=False)
2569 dtb = self._decompress(data)
2570 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2571
2572 def testExtractCbfs(self):
2573 """Test extracting CBFS data"""
2574 data = self._RunExtractCmd('section/cbfs/u-boot')
2575 self.assertEqual(U_BOOT_DATA, data)
2576
2577 def testExtractCbfsCompressed(self):
2578 """Test extracting CBFS compressed data"""
2579 data = self._RunExtractCmd('section/cbfs/u-boot-dtb')
2580 self.assertEqual(EXTRACT_DTB_SIZE, len(data))
2581
2582 def testExtractCbfsRaw(self):
2583 """Test extracting CBFS compressed data without decompressing it"""
2584 data = self._RunExtractCmd('section/cbfs/u-boot-dtb', decomp=False)
Simon Glasseb0f4a42019-07-20 12:24:06 -06002585 dtb = tools.Decompress(data, 'lzma', with_header=False)
Simon Glass71ce0ba2019-07-08 14:25:52 -06002586 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2587
Simon Glassf667e452019-07-08 14:25:50 -06002588 def testExtractBadEntry(self):
2589 """Test extracting a bad section path"""
2590 with self.assertRaises(ValueError) as e:
2591 self._RunExtractCmd('section/does-not-exist')
2592 self.assertIn("Entry 'does-not-exist' not found in '/section'",
2593 str(e.exception))
2594
2595 def testExtractMissingFile(self):
2596 """Test extracting file that does not exist"""
2597 with self.assertRaises(IOError) as e:
2598 control.ReadEntry('missing-file', 'name')
2599
2600 def testExtractBadFile(self):
2601 """Test extracting an invalid file"""
2602 fname = os.path.join(self._indir, 'badfile')
2603 tools.WriteFile(fname, b'')
2604 with self.assertRaises(ValueError) as e:
2605 control.ReadEntry(fname, 'name')
2606
Simon Glass71ce0ba2019-07-08 14:25:52 -06002607 def testExtractCmd(self):
2608 """Test extracting a file fron an image on the command line"""
2609 self._CheckLz4()
2610 self._DoReadFileRealDtb('130_list_fdtmap.dts')
Simon Glass71ce0ba2019-07-08 14:25:52 -06002611 fname = os.path.join(self._indir, 'output.extact')
Simon Glassf86a7362019-07-20 12:24:10 -06002612 try:
2613 tmpdir, updated_fname = self._SetupImageInTmpdir()
2614 with test_util.capture_sys_output() as (stdout, stderr):
2615 self._DoBinman('extract', '-i', updated_fname, 'u-boot',
2616 '-f', fname)
2617 finally:
2618 shutil.rmtree(tmpdir)
Simon Glass71ce0ba2019-07-08 14:25:52 -06002619 data = tools.ReadFile(fname)
2620 self.assertEqual(U_BOOT_DATA, data)
2621
2622 def testExtractOneEntry(self):
2623 """Test extracting a single entry fron an image """
2624 self._CheckLz4()
2625 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2626 image_fname = tools.GetOutputFilename('image.bin')
2627 fname = os.path.join(self._indir, 'output.extact')
2628 control.ExtractEntries(image_fname, fname, None, ['u-boot'])
2629 data = tools.ReadFile(fname)
2630 self.assertEqual(U_BOOT_DATA, data)
2631
2632 def _CheckExtractOutput(self, decomp):
2633 """Helper to test file output with and without decompression
2634
2635 Args:
2636 decomp: True to decompress entry data, False to output it raw
2637 """
2638 def _CheckPresent(entry_path, expect_data, expect_size=None):
2639 """Check and remove expected file
2640
2641 This checks the data/size of a file and removes the file both from
2642 the outfiles set and from the output directory. Once all files are
2643 processed, both the set and directory should be empty.
2644
2645 Args:
2646 entry_path: Entry path
2647 expect_data: Data to expect in file, or None to skip check
2648 expect_size: Size of data to expect in file, or None to skip
2649 """
2650 path = os.path.join(outdir, entry_path)
2651 data = tools.ReadFile(path)
2652 os.remove(path)
2653 if expect_data:
2654 self.assertEqual(expect_data, data)
2655 elif expect_size:
2656 self.assertEqual(expect_size, len(data))
2657 outfiles.remove(path)
2658
2659 def _CheckDirPresent(name):
2660 """Remove expected directory
2661
2662 This gives an error if the directory does not exist as expected
2663
2664 Args:
2665 name: Name of directory to remove
2666 """
2667 path = os.path.join(outdir, name)
2668 os.rmdir(path)
2669
2670 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2671 image_fname = tools.GetOutputFilename('image.bin')
2672 outdir = os.path.join(self._indir, 'extract')
2673 einfos = control.ExtractEntries(image_fname, None, outdir, [], decomp)
2674
2675 # Create a set of all file that were output (should be 9)
2676 outfiles = set()
2677 for root, dirs, files in os.walk(outdir):
2678 outfiles |= set([os.path.join(root, fname) for fname in files])
2679 self.assertEqual(9, len(outfiles))
2680 self.assertEqual(9, len(einfos))
2681
2682 image = control.images['image']
2683 entries = image.GetEntries()
2684
2685 # Check the 9 files in various ways
2686 section = entries['section']
2687 section_entries = section.GetEntries()
2688 cbfs_entries = section_entries['cbfs'].GetEntries()
2689 _CheckPresent('u-boot', U_BOOT_DATA)
2690 _CheckPresent('section/cbfs/u-boot', U_BOOT_DATA)
2691 dtb_len = EXTRACT_DTB_SIZE
2692 if not decomp:
2693 dtb_len = cbfs_entries['u-boot-dtb'].size
2694 _CheckPresent('section/cbfs/u-boot-dtb', None, dtb_len)
2695 if not decomp:
2696 dtb_len = section_entries['u-boot-dtb'].size
2697 _CheckPresent('section/u-boot-dtb', None, dtb_len)
2698
2699 fdtmap = entries['fdtmap']
2700 _CheckPresent('fdtmap', fdtmap.data)
2701 hdr = entries['image-header']
2702 _CheckPresent('image-header', hdr.data)
2703
2704 _CheckPresent('section/root', section.data)
2705 cbfs = section_entries['cbfs']
2706 _CheckPresent('section/cbfs/root', cbfs.data)
2707 data = tools.ReadFile(image_fname)
2708 _CheckPresent('root', data)
2709
2710 # There should be no files left. Remove all the directories to check.
2711 # If there are any files/dirs remaining, one of these checks will fail.
2712 self.assertEqual(0, len(outfiles))
2713 _CheckDirPresent('section/cbfs')
2714 _CheckDirPresent('section')
2715 _CheckDirPresent('')
2716 self.assertFalse(os.path.exists(outdir))
2717
2718 def testExtractAllEntries(self):
2719 """Test extracting all entries"""
2720 self._CheckLz4()
2721 self._CheckExtractOutput(decomp=True)
2722
2723 def testExtractAllEntriesRaw(self):
2724 """Test extracting all entries without decompressing them"""
2725 self._CheckLz4()
2726 self._CheckExtractOutput(decomp=False)
2727
2728 def testExtractSelectedEntries(self):
2729 """Test extracting some entries"""
2730 self._CheckLz4()
2731 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2732 image_fname = tools.GetOutputFilename('image.bin')
2733 outdir = os.path.join(self._indir, 'extract')
2734 einfos = control.ExtractEntries(image_fname, None, outdir,
2735 ['*cb*', '*head*'])
2736
2737 # File output is tested by testExtractAllEntries(), so just check that
2738 # the expected entries are selected
2739 names = [einfo.name for einfo in einfos]
2740 self.assertEqual(names,
2741 ['cbfs', 'u-boot', 'u-boot-dtb', 'image-header'])
2742
2743 def testExtractNoEntryPaths(self):
2744 """Test extracting some entries"""
2745 self._CheckLz4()
2746 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2747 image_fname = tools.GetOutputFilename('image.bin')
2748 with self.assertRaises(ValueError) as e:
2749 control.ExtractEntries(image_fname, 'fname', None, [])
Simon Glassbb5edc12019-07-20 12:24:14 -06002750 self.assertIn('Must specify an entry path to write with -f',
Simon Glass71ce0ba2019-07-08 14:25:52 -06002751 str(e.exception))
2752
2753 def testExtractTooManyEntryPaths(self):
2754 """Test extracting some entries"""
2755 self._CheckLz4()
2756 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2757 image_fname = tools.GetOutputFilename('image.bin')
2758 with self.assertRaises(ValueError) as e:
2759 control.ExtractEntries(image_fname, 'fname', None, ['a', 'b'])
Simon Glassbb5edc12019-07-20 12:24:14 -06002760 self.assertIn('Must specify exactly one entry path to write with -f',
Simon Glass71ce0ba2019-07-08 14:25:52 -06002761 str(e.exception))
2762
Simon Glasse2705fa2019-07-08 14:25:53 -06002763 def testPackAlignSection(self):
2764 """Test that sections can have alignment"""
2765 self._DoReadFile('131_pack_align_section.dts')
2766
2767 self.assertIn('image', control.images)
2768 image = control.images['image']
2769 entries = image.GetEntries()
2770 self.assertEqual(3, len(entries))
2771
2772 # First u-boot
2773 self.assertIn('u-boot', entries)
2774 entry = entries['u-boot']
2775 self.assertEqual(0, entry.offset)
2776 self.assertEqual(0, entry.image_pos)
2777 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2778 self.assertEqual(len(U_BOOT_DATA), entry.size)
2779
2780 # Section0
2781 self.assertIn('section0', entries)
2782 section0 = entries['section0']
2783 self.assertEqual(0x10, section0.offset)
2784 self.assertEqual(0x10, section0.image_pos)
2785 self.assertEqual(len(U_BOOT_DATA), section0.size)
2786
2787 # Second u-boot
2788 section_entries = section0.GetEntries()
2789 self.assertIn('u-boot', section_entries)
2790 entry = section_entries['u-boot']
2791 self.assertEqual(0, entry.offset)
2792 self.assertEqual(0x10, entry.image_pos)
2793 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2794 self.assertEqual(len(U_BOOT_DATA), entry.size)
2795
2796 # Section1
2797 self.assertIn('section1', entries)
2798 section1 = entries['section1']
2799 self.assertEqual(0x14, section1.offset)
2800 self.assertEqual(0x14, section1.image_pos)
2801 self.assertEqual(0x20, section1.size)
2802
2803 # Second u-boot
2804 section_entries = section1.GetEntries()
2805 self.assertIn('u-boot', section_entries)
2806 entry = section_entries['u-boot']
2807 self.assertEqual(0, entry.offset)
2808 self.assertEqual(0x14, entry.image_pos)
2809 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2810 self.assertEqual(len(U_BOOT_DATA), entry.size)
2811
2812 # Section2
2813 self.assertIn('section2', section_entries)
2814 section2 = section_entries['section2']
2815 self.assertEqual(0x4, section2.offset)
2816 self.assertEqual(0x18, section2.image_pos)
2817 self.assertEqual(4, section2.size)
2818
2819 # Third u-boot
2820 section_entries = section2.GetEntries()
2821 self.assertIn('u-boot', section_entries)
2822 entry = section_entries['u-boot']
2823 self.assertEqual(0, entry.offset)
2824 self.assertEqual(0x18, entry.image_pos)
2825 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2826 self.assertEqual(len(U_BOOT_DATA), entry.size)
2827
Simon Glass51014aa2019-07-20 12:23:56 -06002828 def _RunReplaceCmd(self, entry_name, data, decomp=True, allow_resize=True,
2829 dts='132_replace.dts'):
Simon Glass10f9d002019-07-20 12:23:50 -06002830 """Replace an entry in an image
2831
2832 This writes the entry data to update it, then opens the updated file and
2833 returns the value that it now finds there.
2834
2835 Args:
2836 entry_name: Entry name to replace
2837 data: Data to replace it with
2838 decomp: True to compress the data if needed, False if data is
2839 already compressed so should be used as is
Simon Glass51014aa2019-07-20 12:23:56 -06002840 allow_resize: True to allow entries to change size, False to raise
2841 an exception
Simon Glass10f9d002019-07-20 12:23:50 -06002842
2843 Returns:
2844 Tuple:
2845 data from entry
2846 data from fdtmap (excluding header)
Simon Glass51014aa2019-07-20 12:23:56 -06002847 Image object that was modified
Simon Glass10f9d002019-07-20 12:23:50 -06002848 """
Simon Glass51014aa2019-07-20 12:23:56 -06002849 dtb_data = self._DoReadFileDtb(dts, use_real_dtb=True,
Simon Glass10f9d002019-07-20 12:23:50 -06002850 update_dtb=True)[1]
2851
2852 self.assertIn('image', control.images)
2853 image = control.images['image']
2854 entries = image.GetEntries()
2855 orig_dtb_data = entries['u-boot-dtb'].data
2856 orig_fdtmap_data = entries['fdtmap'].data
2857
2858 image_fname = tools.GetOutputFilename('image.bin')
2859 updated_fname = tools.GetOutputFilename('image-updated.bin')
2860 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
Simon Glass51014aa2019-07-20 12:23:56 -06002861 image = control.WriteEntry(updated_fname, entry_name, data, decomp,
2862 allow_resize)
Simon Glass10f9d002019-07-20 12:23:50 -06002863 data = control.ReadEntry(updated_fname, entry_name, decomp)
2864
Simon Glass51014aa2019-07-20 12:23:56 -06002865 # The DT data should not change unless resized:
2866 if not allow_resize:
2867 new_dtb_data = entries['u-boot-dtb'].data
2868 self.assertEqual(new_dtb_data, orig_dtb_data)
2869 new_fdtmap_data = entries['fdtmap'].data
2870 self.assertEqual(new_fdtmap_data, orig_fdtmap_data)
Simon Glass10f9d002019-07-20 12:23:50 -06002871
Simon Glass51014aa2019-07-20 12:23:56 -06002872 return data, orig_fdtmap_data[fdtmap.FDTMAP_HDR_LEN:], image
Simon Glass10f9d002019-07-20 12:23:50 -06002873
2874 def testReplaceSimple(self):
2875 """Test replacing a single file"""
2876 expected = b'x' * len(U_BOOT_DATA)
Simon Glass51014aa2019-07-20 12:23:56 -06002877 data, expected_fdtmap, _ = self._RunReplaceCmd('u-boot', expected,
2878 allow_resize=False)
Simon Glass10f9d002019-07-20 12:23:50 -06002879 self.assertEqual(expected, data)
2880
2881 # Test that the state looks right. There should be an FDT for the fdtmap
2882 # that we jsut read back in, and it should match what we find in the
2883 # 'control' tables. Checking for an FDT that does not exist should
2884 # return None.
2885 path, fdtmap = state.GetFdtContents('fdtmap')
Simon Glass51014aa2019-07-20 12:23:56 -06002886 self.assertIsNotNone(path)
Simon Glass10f9d002019-07-20 12:23:50 -06002887 self.assertEqual(expected_fdtmap, fdtmap)
2888
2889 dtb = state.GetFdtForEtype('fdtmap')
2890 self.assertEqual(dtb.GetContents(), fdtmap)
2891
2892 missing_path, missing_fdtmap = state.GetFdtContents('missing')
2893 self.assertIsNone(missing_path)
2894 self.assertIsNone(missing_fdtmap)
2895
2896 missing_dtb = state.GetFdtForEtype('missing')
2897 self.assertIsNone(missing_dtb)
2898
2899 self.assertEqual('/binman', state.fdt_path_prefix)
2900
2901 def testReplaceResizeFail(self):
2902 """Test replacing a file by something larger"""
2903 expected = U_BOOT_DATA + b'x'
2904 with self.assertRaises(ValueError) as e:
Simon Glass51014aa2019-07-20 12:23:56 -06002905 self._RunReplaceCmd('u-boot', expected, allow_resize=False,
2906 dts='139_replace_repack.dts')
Simon Glass10f9d002019-07-20 12:23:50 -06002907 self.assertIn("Node '/u-boot': Entry data size does not match, but resize is disabled",
2908 str(e.exception))
2909
2910 def testReplaceMulti(self):
2911 """Test replacing entry data where multiple images are generated"""
2912 data = self._DoReadFileDtb('133_replace_multi.dts', use_real_dtb=True,
2913 update_dtb=True)[0]
2914 expected = b'x' * len(U_BOOT_DATA)
2915 updated_fname = tools.GetOutputFilename('image-updated.bin')
2916 tools.WriteFile(updated_fname, data)
2917 entry_name = 'u-boot'
Simon Glass51014aa2019-07-20 12:23:56 -06002918 control.WriteEntry(updated_fname, entry_name, expected,
2919 allow_resize=False)
Simon Glass10f9d002019-07-20 12:23:50 -06002920 data = control.ReadEntry(updated_fname, entry_name)
2921 self.assertEqual(expected, data)
2922
2923 # Check the state looks right.
2924 self.assertEqual('/binman/image', state.fdt_path_prefix)
2925
2926 # Now check we can write the first image
2927 image_fname = tools.GetOutputFilename('first-image.bin')
2928 updated_fname = tools.GetOutputFilename('first-updated.bin')
2929 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
2930 entry_name = 'u-boot'
Simon Glass51014aa2019-07-20 12:23:56 -06002931 control.WriteEntry(updated_fname, entry_name, expected,
2932 allow_resize=False)
Simon Glass10f9d002019-07-20 12:23:50 -06002933 data = control.ReadEntry(updated_fname, entry_name)
2934 self.assertEqual(expected, data)
2935
2936 # Check the state looks right.
2937 self.assertEqual('/binman/first-image', state.fdt_path_prefix)
Simon Glass8beb11e2019-07-08 14:25:47 -06002938
Simon Glass12bb1a92019-07-20 12:23:51 -06002939 def testUpdateFdtAllRepack(self):
2940 """Test that all device trees are updated with offset/size info"""
2941 data = self._DoReadFileRealDtb('134_fdt_update_all_repack.dts')
2942 SECTION_SIZE = 0x300
2943 DTB_SIZE = 602
2944 FDTMAP_SIZE = 608
2945 base_expected = {
2946 'offset': 0,
2947 'size': SECTION_SIZE + DTB_SIZE * 2 + FDTMAP_SIZE,
2948 'image-pos': 0,
2949 'section:offset': 0,
2950 'section:size': SECTION_SIZE,
2951 'section:image-pos': 0,
2952 'section/u-boot-dtb:offset': 4,
2953 'section/u-boot-dtb:size': 636,
2954 'section/u-boot-dtb:image-pos': 4,
2955 'u-boot-spl-dtb:offset': SECTION_SIZE,
2956 'u-boot-spl-dtb:size': DTB_SIZE,
2957 'u-boot-spl-dtb:image-pos': SECTION_SIZE,
2958 'u-boot-tpl-dtb:offset': SECTION_SIZE + DTB_SIZE,
2959 'u-boot-tpl-dtb:image-pos': SECTION_SIZE + DTB_SIZE,
2960 'u-boot-tpl-dtb:size': DTB_SIZE,
2961 'fdtmap:offset': SECTION_SIZE + DTB_SIZE * 2,
2962 'fdtmap:size': FDTMAP_SIZE,
2963 'fdtmap:image-pos': SECTION_SIZE + DTB_SIZE * 2,
2964 }
2965 main_expected = {
2966 'section:orig-size': SECTION_SIZE,
2967 'section/u-boot-dtb:orig-offset': 4,
2968 }
2969
2970 # We expect three device-tree files in the output, with the first one
2971 # within a fixed-size section.
2972 # Read them in sequence. We look for an 'spl' property in the SPL tree,
2973 # and 'tpl' in the TPL tree, to make sure they are distinct from the
2974 # main U-Boot tree. All three should have the same positions and offset
2975 # except that the main tree should include the main_expected properties
2976 start = 4
2977 for item in ['', 'spl', 'tpl', None]:
2978 if item is None:
2979 start += 16 # Move past fdtmap header
2980 dtb = fdt.Fdt.FromData(data[start:])
2981 dtb.Scan()
2982 props = self._GetPropTree(dtb,
2983 BASE_DTB_PROPS + REPACK_DTB_PROPS + ['spl', 'tpl'],
2984 prefix='/' if item is None else '/binman/')
2985 expected = dict(base_expected)
2986 if item:
2987 expected[item] = 0
2988 else:
2989 # Main DTB and fdtdec should include the 'orig-' properties
2990 expected.update(main_expected)
2991 # Helpful for debugging:
2992 #for prop in sorted(props):
2993 #print('prop %s %s %s' % (prop, props[prop], expected[prop]))
2994 self.assertEqual(expected, props)
2995 if item == '':
2996 start = SECTION_SIZE
2997 else:
2998 start += dtb._fdt_obj.totalsize()
2999
Simon Glasseba1f0c2019-07-20 12:23:55 -06003000 def testFdtmapHeaderMiddle(self):
3001 """Test an FDT map in the middle of an image when it should be at end"""
3002 with self.assertRaises(ValueError) as e:
3003 self._DoReadFileRealDtb('135_fdtmap_hdr_middle.dts')
3004 self.assertIn("Invalid sibling order 'middle' for image-header: Must be at 'end' to match location",
3005 str(e.exception))
3006
3007 def testFdtmapHeaderStartBad(self):
3008 """Test an FDT map in middle of an image when it should be at start"""
3009 with self.assertRaises(ValueError) as e:
3010 self._DoReadFileRealDtb('136_fdtmap_hdr_startbad.dts')
3011 self.assertIn("Invalid sibling order 'end' for image-header: Must be at 'start' to match location",
3012 str(e.exception))
3013
3014 def testFdtmapHeaderEndBad(self):
3015 """Test an FDT map at the start of an image when it should be at end"""
3016 with self.assertRaises(ValueError) as e:
3017 self._DoReadFileRealDtb('137_fdtmap_hdr_endbad.dts')
3018 self.assertIn("Invalid sibling order 'start' for image-header: Must be at 'end' to match location",
3019 str(e.exception))
3020
3021 def testFdtmapHeaderNoSize(self):
3022 """Test an image header at the end of an image with undefined size"""
3023 self._DoReadFileRealDtb('138_fdtmap_hdr_nosize.dts')
3024
Simon Glass51014aa2019-07-20 12:23:56 -06003025 def testReplaceResize(self):
3026 """Test replacing a single file in an entry with a larger file"""
3027 expected = U_BOOT_DATA + b'x'
3028 data, _, image = self._RunReplaceCmd('u-boot', expected,
3029 dts='139_replace_repack.dts')
3030 self.assertEqual(expected, data)
3031
3032 entries = image.GetEntries()
3033 dtb_data = entries['u-boot-dtb'].data
3034 dtb = fdt.Fdt.FromData(dtb_data)
3035 dtb.Scan()
3036
3037 # The u-boot section should now be larger in the dtb
3038 node = dtb.GetNode('/binman/u-boot')
3039 self.assertEqual(len(expected), fdt_util.GetInt(node, 'size'))
3040
3041 # Same for the fdtmap
3042 fdata = entries['fdtmap'].data
3043 fdtb = fdt.Fdt.FromData(fdata[fdtmap.FDTMAP_HDR_LEN:])
3044 fdtb.Scan()
3045 fnode = fdtb.GetNode('/u-boot')
3046 self.assertEqual(len(expected), fdt_util.GetInt(fnode, 'size'))
3047
3048 def testReplaceResizeNoRepack(self):
3049 """Test replacing an entry with a larger file when not allowed"""
3050 expected = U_BOOT_DATA + b'x'
3051 with self.assertRaises(ValueError) as e:
3052 self._RunReplaceCmd('u-boot', expected)
3053 self.assertIn('Entry data size does not match, but allow-repack is not present for this image',
3054 str(e.exception))
3055
Simon Glass61ec04f2019-07-20 12:23:58 -06003056 def testEntryShrink(self):
3057 """Test contracting an entry after it is packed"""
3058 try:
3059 state.SetAllowEntryContraction(True)
3060 data = self._DoReadFileDtb('140_entry_shrink.dts',
3061 update_dtb=True)[0]
3062 finally:
3063 state.SetAllowEntryContraction(False)
3064 self.assertEqual(b'a', data[:1])
3065 self.assertEqual(U_BOOT_DATA, data[1:1 + len(U_BOOT_DATA)])
3066 self.assertEqual(b'a', data[-1:])
3067
3068 def testEntryShrinkFail(self):
3069 """Test not being allowed to contract an entry after it is packed"""
3070 data = self._DoReadFileDtb('140_entry_shrink.dts', update_dtb=True)[0]
3071
3072 # In this case there is a spare byte at the end of the data. The size of
3073 # the contents is only 1 byte but we still have the size before it
3074 # shrunk.
3075 self.assertEqual(b'a\0', data[:2])
3076 self.assertEqual(U_BOOT_DATA, data[2:2 + len(U_BOOT_DATA)])
3077 self.assertEqual(b'a\0', data[-2:])
3078
Simon Glass27145fd2019-07-20 12:24:01 -06003079 def testDescriptorOffset(self):
3080 """Test that the Intel descriptor is always placed at at the start"""
3081 data = self._DoReadFileDtb('141_descriptor_offset.dts')
3082 image = control.images['image']
3083 entries = image.GetEntries()
3084 desc = entries['intel-descriptor']
3085 self.assertEqual(0xff800000, desc.offset);
3086 self.assertEqual(0xff800000, desc.image_pos);
3087
Simon Glasseb0f4a42019-07-20 12:24:06 -06003088 def testReplaceCbfs(self):
3089 """Test replacing a single file in CBFS without changing the size"""
3090 self._CheckLz4()
3091 expected = b'x' * len(U_BOOT_DATA)
3092 data = self._DoReadFileRealDtb('142_replace_cbfs.dts')
3093 updated_fname = tools.GetOutputFilename('image-updated.bin')
3094 tools.WriteFile(updated_fname, data)
3095 entry_name = 'section/cbfs/u-boot'
3096 control.WriteEntry(updated_fname, entry_name, expected,
3097 allow_resize=True)
3098 data = control.ReadEntry(updated_fname, entry_name)
3099 self.assertEqual(expected, data)
3100
3101 def testReplaceResizeCbfs(self):
3102 """Test replacing a single file in CBFS with one of a different size"""
3103 self._CheckLz4()
3104 expected = U_BOOT_DATA + b'x'
3105 data = self._DoReadFileRealDtb('142_replace_cbfs.dts')
3106 updated_fname = tools.GetOutputFilename('image-updated.bin')
3107 tools.WriteFile(updated_fname, data)
3108 entry_name = 'section/cbfs/u-boot'
3109 control.WriteEntry(updated_fname, entry_name, expected,
3110 allow_resize=True)
3111 data = control.ReadEntry(updated_fname, entry_name)
3112 self.assertEqual(expected, data)
3113
Simon Glassa6cb9952019-07-20 12:24:15 -06003114 def _SetupForReplace(self):
3115 """Set up some files to use to replace entries
3116
3117 This generates an image, copies it to a new file, extracts all the files
3118 in it and updates some of them
3119
3120 Returns:
3121 List
3122 Image filename
3123 Output directory
3124 Expected values for updated entries, each a string
3125 """
3126 data = self._DoReadFileRealDtb('143_replace_all.dts')
3127
3128 updated_fname = tools.GetOutputFilename('image-updated.bin')
3129 tools.WriteFile(updated_fname, data)
3130
3131 outdir = os.path.join(self._indir, 'extract')
3132 einfos = control.ExtractEntries(updated_fname, None, outdir, [])
3133
3134 expected1 = b'x' + U_BOOT_DATA + b'y'
3135 u_boot_fname1 = os.path.join(outdir, 'u-boot')
3136 tools.WriteFile(u_boot_fname1, expected1)
3137
3138 expected2 = b'a' + U_BOOT_DATA + b'b'
3139 u_boot_fname2 = os.path.join(outdir, 'u-boot2')
3140 tools.WriteFile(u_boot_fname2, expected2)
3141
3142 expected_text = b'not the same text'
3143 text_fname = os.path.join(outdir, 'text')
3144 tools.WriteFile(text_fname, expected_text)
3145
3146 dtb_fname = os.path.join(outdir, 'u-boot-dtb')
3147 dtb = fdt.FdtScan(dtb_fname)
3148 node = dtb.GetNode('/binman/text')
3149 node.AddString('my-property', 'the value')
3150 dtb.Sync(auto_resize=True)
3151 dtb.Flush()
3152
3153 return updated_fname, outdir, expected1, expected2, expected_text
3154
3155 def _CheckReplaceMultiple(self, entry_paths):
3156 """Handle replacing the contents of multiple entries
3157
3158 Args:
3159 entry_paths: List of entry paths to replace
3160
3161 Returns:
3162 List
3163 Dict of entries in the image:
3164 key: Entry name
3165 Value: Entry object
3166 Expected values for updated entries, each a string
3167 """
3168 updated_fname, outdir, expected1, expected2, expected_text = (
3169 self._SetupForReplace())
3170 control.ReplaceEntries(updated_fname, None, outdir, entry_paths)
3171
3172 image = Image.FromFile(updated_fname)
3173 image.LoadData()
3174 return image.GetEntries(), expected1, expected2, expected_text
3175
3176 def testReplaceAll(self):
3177 """Test replacing the contents of all entries"""
3178 entries, expected1, expected2, expected_text = (
3179 self._CheckReplaceMultiple([]))
3180 data = entries['u-boot'].data
3181 self.assertEqual(expected1, data)
3182
3183 data = entries['u-boot2'].data
3184 self.assertEqual(expected2, data)
3185
3186 data = entries['text'].data
3187 self.assertEqual(expected_text, data)
3188
3189 # Check that the device tree is updated
3190 data = entries['u-boot-dtb'].data
3191 dtb = fdt.Fdt.FromData(data)
3192 dtb.Scan()
3193 node = dtb.GetNode('/binman/text')
3194 self.assertEqual('the value', node.props['my-property'].value)
3195
3196 def testReplaceSome(self):
3197 """Test replacing the contents of a few entries"""
3198 entries, expected1, expected2, expected_text = (
3199 self._CheckReplaceMultiple(['u-boot2', 'text']))
3200
3201 # This one should not change
3202 data = entries['u-boot'].data
3203 self.assertEqual(U_BOOT_DATA, data)
3204
3205 data = entries['u-boot2'].data
3206 self.assertEqual(expected2, data)
3207
3208 data = entries['text'].data
3209 self.assertEqual(expected_text, data)
3210
3211 def testReplaceCmd(self):
3212 """Test replacing a file fron an image on the command line"""
3213 self._DoReadFileRealDtb('143_replace_all.dts')
3214
3215 try:
3216 tmpdir, updated_fname = self._SetupImageInTmpdir()
3217
3218 fname = os.path.join(tmpdir, 'update-u-boot.bin')
3219 expected = b'x' * len(U_BOOT_DATA)
3220 tools.WriteFile(fname, expected)
3221
3222 self._DoBinman('replace', '-i', updated_fname, 'u-boot', '-f', fname)
3223 data = tools.ReadFile(updated_fname)
3224 self.assertEqual(expected, data[:len(expected)])
3225 map_fname = os.path.join(tmpdir, 'image-updated.map')
3226 self.assertFalse(os.path.exists(map_fname))
3227 finally:
3228 shutil.rmtree(tmpdir)
3229
3230 def testReplaceCmdSome(self):
3231 """Test replacing some files fron an image on the command line"""
3232 updated_fname, outdir, expected1, expected2, expected_text = (
3233 self._SetupForReplace())
3234
3235 self._DoBinman('replace', '-i', updated_fname, '-I', outdir,
3236 'u-boot2', 'text')
3237
3238 tools.PrepareOutputDir(None)
3239 image = Image.FromFile(updated_fname)
3240 image.LoadData()
3241 entries = image.GetEntries()
3242
3243 # This one should not change
3244 data = entries['u-boot'].data
3245 self.assertEqual(U_BOOT_DATA, data)
3246
3247 data = entries['u-boot2'].data
3248 self.assertEqual(expected2, data)
3249
3250 data = entries['text'].data
3251 self.assertEqual(expected_text, data)
3252
3253 def testReplaceMissing(self):
3254 """Test replacing entries where the file is missing"""
3255 updated_fname, outdir, expected1, expected2, expected_text = (
3256 self._SetupForReplace())
3257
3258 # Remove one of the files, to generate a warning
3259 u_boot_fname1 = os.path.join(outdir, 'u-boot')
3260 os.remove(u_boot_fname1)
3261
3262 with test_util.capture_sys_output() as (stdout, stderr):
3263 control.ReplaceEntries(updated_fname, None, outdir, [])
3264 self.assertIn("Skipping entry '/u-boot' from missing file",
Simon Glass38fdb4c2020-07-09 18:39:39 -06003265 stderr.getvalue())
Simon Glassa6cb9952019-07-20 12:24:15 -06003266
3267 def testReplaceCmdMap(self):
3268 """Test replacing a file fron an image on the command line"""
3269 self._DoReadFileRealDtb('143_replace_all.dts')
3270
3271 try:
3272 tmpdir, updated_fname = self._SetupImageInTmpdir()
3273
3274 fname = os.path.join(self._indir, 'update-u-boot.bin')
3275 expected = b'x' * len(U_BOOT_DATA)
3276 tools.WriteFile(fname, expected)
3277
3278 self._DoBinman('replace', '-i', updated_fname, 'u-boot',
3279 '-f', fname, '-m')
3280 map_fname = os.path.join(tmpdir, 'image-updated.map')
3281 self.assertTrue(os.path.exists(map_fname))
3282 finally:
3283 shutil.rmtree(tmpdir)
3284
3285 def testReplaceNoEntryPaths(self):
3286 """Test replacing an entry without an entry path"""
3287 self._DoReadFileRealDtb('143_replace_all.dts')
3288 image_fname = tools.GetOutputFilename('image.bin')
3289 with self.assertRaises(ValueError) as e:
3290 control.ReplaceEntries(image_fname, 'fname', None, [])
3291 self.assertIn('Must specify an entry path to read with -f',
3292 str(e.exception))
3293
3294 def testReplaceTooManyEntryPaths(self):
3295 """Test extracting some entries"""
3296 self._DoReadFileRealDtb('143_replace_all.dts')
3297 image_fname = tools.GetOutputFilename('image.bin')
3298 with self.assertRaises(ValueError) as e:
3299 control.ReplaceEntries(image_fname, 'fname', None, ['a', 'b'])
3300 self.assertIn('Must specify exactly one entry path to write with -f',
3301 str(e.exception))
3302
Simon Glass2250ee62019-08-24 07:22:48 -06003303 def testPackReset16(self):
3304 """Test that an image with an x86 reset16 region can be created"""
3305 data = self._DoReadFile('144_x86_reset16.dts')
3306 self.assertEqual(X86_RESET16_DATA, data[:len(X86_RESET16_DATA)])
3307
3308 def testPackReset16Spl(self):
3309 """Test that an image with an x86 reset16-spl region can be created"""
3310 data = self._DoReadFile('145_x86_reset16_spl.dts')
3311 self.assertEqual(X86_RESET16_SPL_DATA, data[:len(X86_RESET16_SPL_DATA)])
3312
3313 def testPackReset16Tpl(self):
3314 """Test that an image with an x86 reset16-tpl region can be created"""
3315 data = self._DoReadFile('146_x86_reset16_tpl.dts')
3316 self.assertEqual(X86_RESET16_TPL_DATA, data[:len(X86_RESET16_TPL_DATA)])
3317
Simon Glass5af12072019-08-24 07:22:50 -06003318 def testPackIntelFit(self):
3319 """Test that an image with an Intel FIT and pointer can be created"""
3320 data = self._DoReadFile('147_intel_fit.dts')
3321 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3322 fit = data[16:32];
3323 self.assertEqual(b'_FIT_ \x01\x00\x00\x00\x00\x01\x80}' , fit)
3324 ptr = struct.unpack('<i', data[0x40:0x44])[0]
3325
3326 image = control.images['image']
3327 entries = image.GetEntries()
3328 expected_ptr = entries['intel-fit'].image_pos - (1 << 32)
3329 self.assertEqual(expected_ptr, ptr)
3330
3331 def testPackIntelFitMissing(self):
3332 """Test detection of a FIT pointer with not FIT region"""
3333 with self.assertRaises(ValueError) as e:
3334 self._DoReadFile('148_intel_fit_missing.dts')
3335 self.assertIn("'intel-fit-ptr' section must have an 'intel-fit' sibling",
3336 str(e.exception))
3337
Simon Glass7c150132019-11-06 17:22:44 -07003338 def _CheckSymbolsTplSection(self, dts, expected_vals):
3339 data = self._DoReadFile(dts)
3340 sym_values = struct.pack('<LQLL', *expected_vals)
Simon Glass2090f1e2019-08-24 07:23:00 -06003341 upto1 = 4 + len(U_BOOT_SPL_DATA)
Simon Glassb87064c2019-08-24 07:23:05 -06003342 expected1 = tools.GetBytes(0xff, 4) + sym_values + U_BOOT_SPL_DATA[20:]
Simon Glass2090f1e2019-08-24 07:23:00 -06003343 self.assertEqual(expected1, data[:upto1])
3344
3345 upto2 = upto1 + 1 + len(U_BOOT_SPL_DATA)
Simon Glassb87064c2019-08-24 07:23:05 -06003346 expected2 = tools.GetBytes(0xff, 1) + sym_values + U_BOOT_SPL_DATA[20:]
Simon Glass2090f1e2019-08-24 07:23:00 -06003347 self.assertEqual(expected2, data[upto1:upto2])
3348
Simon Glasseb0086f2019-08-24 07:23:04 -06003349 upto3 = 0x34 + len(U_BOOT_DATA)
3350 expected3 = tools.GetBytes(0xff, 1) + U_BOOT_DATA
Simon Glass2090f1e2019-08-24 07:23:00 -06003351 self.assertEqual(expected3, data[upto2:upto3])
3352
Simon Glassb87064c2019-08-24 07:23:05 -06003353 expected4 = sym_values + U_BOOT_TPL_DATA[20:]
Simon Glass7c150132019-11-06 17:22:44 -07003354 self.assertEqual(expected4, data[upto3:upto3 + len(U_BOOT_TPL_DATA)])
3355
3356 def testSymbolsTplSection(self):
3357 """Test binman can assign symbols embedded in U-Boot TPL in a section"""
3358 self._SetupSplElf('u_boot_binman_syms')
3359 self._SetupTplElf('u_boot_binman_syms')
3360 self._CheckSymbolsTplSection('149_symbols_tpl.dts',
3361 [0x04, 0x1c, 0x10 + 0x34, 0x04])
3362
3363 def testSymbolsTplSectionX86(self):
3364 """Test binman can assign symbols in a section with end-at-4gb"""
3365 self._SetupSplElf('u_boot_binman_syms_x86')
3366 self._SetupTplElf('u_boot_binman_syms_x86')
3367 self._CheckSymbolsTplSection('155_symbols_tpl_x86.dts',
3368 [0xffffff04, 0xffffff1c, 0xffffff34,
3369 0x04])
Simon Glass2090f1e2019-08-24 07:23:00 -06003370
Simon Glassbf4d0e22019-08-24 07:23:03 -06003371 def testPackX86RomIfwiSectiom(self):
3372 """Test that a section can be placed in an IFWI region"""
3373 self._SetupIfwi('fitimage.bin')
3374 data = self._DoReadFile('151_x86_rom_ifwi_section.dts')
3375 self._CheckIfwi(data)
3376
Simon Glassea0fff92019-08-24 07:23:07 -06003377 def testPackFspM(self):
3378 """Test that an image with a FSP memory-init binary can be created"""
3379 data = self._DoReadFile('152_intel_fsp_m.dts')
3380 self.assertEqual(FSP_M_DATA, data[:len(FSP_M_DATA)])
3381
Simon Glassbc6a88f2019-10-20 21:31:35 -06003382 def testPackFspS(self):
3383 """Test that an image with a FSP silicon-init binary can be created"""
3384 data = self._DoReadFile('153_intel_fsp_s.dts')
3385 self.assertEqual(FSP_S_DATA, data[:len(FSP_S_DATA)])
Simon Glassea0fff92019-08-24 07:23:07 -06003386
Simon Glass998d1482019-10-20 21:31:36 -06003387 def testPackFspT(self):
3388 """Test that an image with a FSP temp-ram-init binary can be created"""
3389 data = self._DoReadFile('154_intel_fsp_t.dts')
3390 self.assertEqual(FSP_T_DATA, data[:len(FSP_T_DATA)])
3391
Simon Glass0dc706f2020-07-09 18:39:31 -06003392 def testMkimage(self):
3393 """Test using mkimage to build an image"""
3394 data = self._DoReadFile('156_mkimage.dts')
3395
3396 # Just check that the data appears in the file somewhere
3397 self.assertIn(U_BOOT_SPL_DATA, data)
3398
Simon Glassce867ad2020-07-09 18:39:36 -06003399 def testExtblob(self):
3400 """Test an image with an external blob"""
3401 data = self._DoReadFile('157_blob_ext.dts')
3402 self.assertEqual(REFCODE_DATA, data)
3403
3404 def testExtblobMissing(self):
3405 """Test an image with a missing external blob"""
3406 with self.assertRaises(ValueError) as e:
3407 self._DoReadFile('158_blob_ext_missing.dts')
3408 self.assertIn("Filename 'missing-file' not found in input path",
3409 str(e.exception))
3410
Simon Glass4f9f1052020-07-09 18:39:38 -06003411 def testExtblobMissingOk(self):
3412 """Test an image with an missing external blob that is allowed"""
Simon Glassb1cca952020-07-09 18:39:40 -06003413 with test_util.capture_sys_output() as (stdout, stderr):
3414 self._DoTestFile('158_blob_ext_missing.dts', allow_missing=True)
3415 err = stderr.getvalue()
3416 self.assertRegex(err, "Image 'main-section'.*missing.*: blob-ext")
3417
3418 def testExtblobMissingOkSect(self):
3419 """Test an image with an missing external blob that is allowed"""
3420 with test_util.capture_sys_output() as (stdout, stderr):
3421 self._DoTestFile('159_blob_ext_missing_sect.dts',
3422 allow_missing=True)
3423 err = stderr.getvalue()
3424 self.assertRegex(err, "Image 'main-section'.*missing.*: "
3425 "blob-ext blob-ext2")
Simon Glass4f9f1052020-07-09 18:39:38 -06003426
Simon Glass0ba4b3d2020-07-09 18:39:41 -06003427 def testPackX86RomMeMissingDesc(self):
3428 """Test that an missing Intel descriptor entry is allowed"""
Simon Glass0ba4b3d2020-07-09 18:39:41 -06003429 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass52b10dd2020-07-25 15:11:19 -06003430 self._DoTestFile('164_x86_rom_me_missing.dts', allow_missing=True)
Simon Glass0ba4b3d2020-07-09 18:39:41 -06003431 err = stderr.getvalue()
3432 self.assertRegex(err,
3433 "Image 'main-section'.*missing.*: intel-descriptor")
3434
3435 def testPackX86RomMissingIfwi(self):
3436 """Test that an x86 ROM with Integrated Firmware Image can be created"""
3437 self._SetupIfwi('fitimage.bin')
3438 pathname = os.path.join(self._indir, 'fitimage.bin')
3439 os.remove(pathname)
3440 with test_util.capture_sys_output() as (stdout, stderr):
3441 self._DoTestFile('111_x86_rom_ifwi.dts', allow_missing=True)
3442 err = stderr.getvalue()
3443 self.assertRegex(err, "Image 'main-section'.*missing.*: intel-ifwi")
3444
Simon Glassb3295fd2020-07-09 18:39:42 -06003445 def testPackOverlap(self):
3446 """Test that zero-size overlapping regions are ignored"""
3447 self._DoTestFile('160_pack_overlap_zero.dts')
3448
Simon Glassfdc34362020-07-09 18:39:45 -06003449 def testSimpleFit(self):
3450 """Test an image with a FIT inside"""
3451 data = self._DoReadFile('161_fit.dts')
3452 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3453 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3454 fit_data = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3455
3456 # The data should be inside the FIT
3457 dtb = fdt.Fdt.FromData(fit_data)
3458 dtb.Scan()
3459 fnode = dtb.GetNode('/images/kernel')
3460 self.assertIn('data', fnode.props)
3461
3462 fname = os.path.join(self._indir, 'fit_data.fit')
3463 tools.WriteFile(fname, fit_data)
3464 out = tools.Run('dumpimage', '-l', fname)
3465
3466 # Check a few features to make sure the plumbing works. We don't need
3467 # to test the operation of mkimage or dumpimage here. First convert the
3468 # output into a dict where the keys are the fields printed by dumpimage
3469 # and the values are a list of values for each field
3470 lines = out.splitlines()
3471
3472 # Converts "Compression: gzip compressed" into two groups:
3473 # 'Compression' and 'gzip compressed'
3474 re_line = re.compile(r'^ *([^:]*)(?:: *(.*))?$')
3475 vals = collections.defaultdict(list)
3476 for line in lines:
3477 mat = re_line.match(line)
3478 vals[mat.group(1)].append(mat.group(2))
3479
3480 self.assertEquals('FIT description: test-desc', lines[0])
3481 self.assertIn('Created:', lines[1])
3482 self.assertIn('Image 0 (kernel)', vals)
3483 self.assertIn('Hash value', vals)
3484 data_sizes = vals.get('Data Size')
3485 self.assertIsNotNone(data_sizes)
3486 self.assertEqual(2, len(data_sizes))
3487 # Format is "4 Bytes = 0.00 KiB = 0.00 MiB" so take the first word
3488 self.assertEqual(len(U_BOOT_DATA), int(data_sizes[0].split()[0]))
3489 self.assertEqual(len(U_BOOT_SPL_DTB_DATA), int(data_sizes[1].split()[0]))
3490
3491 def testFitExternal(self):
Simon Glasse9d336d2020-09-01 05:13:55 -06003492 """Test an image with an FIT with external images"""
Simon Glassfdc34362020-07-09 18:39:45 -06003493 data = self._DoReadFile('162_fit_external.dts')
3494 fit_data = data[len(U_BOOT_DATA):-2] # _testing is 2 bytes
3495
3496 # The data should be outside the FIT
3497 dtb = fdt.Fdt.FromData(fit_data)
3498 dtb.Scan()
3499 fnode = dtb.GetNode('/images/kernel')
3500 self.assertNotIn('data', fnode.props)
Simon Glass12bb1a92019-07-20 12:23:51 -06003501
Alper Nebi Yasak8001d0b2020-08-31 12:58:18 +03003502 def testSectionIgnoreHashSignature(self):
3503 """Test that sections ignore hash, signature nodes for its data"""
3504 data = self._DoReadFile('165_section_ignore_hash_signature.dts')
3505 expected = (U_BOOT_DATA + U_BOOT_DATA)
3506 self.assertEqual(expected, data)
3507
Alper Nebi Yasak3fdeb142020-08-31 12:58:19 +03003508 def testPadInSections(self):
3509 """Test pad-before, pad-after for entries in sections"""
3510 data = self._DoReadFile('166_pad_in_sections.dts')
3511 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
3512 U_BOOT_DATA + tools.GetBytes(ord('!'), 6) +
3513 U_BOOT_DATA)
3514 self.assertEqual(expected, data)
3515
Alper Nebi Yasakfe057012020-08-31 12:58:20 +03003516 def testFitImageSubentryAlignment(self):
3517 """Test relative alignability of FIT image subentries"""
3518 entry_args = {
3519 'test-id': TEXT_DATA,
3520 }
3521 data, _, _, _ = self._DoReadFileDtb('167_fit_image_subentry_alignment.dts',
3522 entry_args=entry_args)
3523 dtb = fdt.Fdt.FromData(data)
3524 dtb.Scan()
3525
3526 node = dtb.GetNode('/images/kernel')
3527 data = dtb.GetProps(node)["data"].bytes
3528 align_pad = 0x10 - (len(U_BOOT_SPL_DATA) % 0x10)
3529 expected = (tools.GetBytes(0, 0x20) + U_BOOT_SPL_DATA +
3530 tools.GetBytes(0, align_pad) + U_BOOT_DATA)
3531 self.assertEqual(expected, data)
3532
3533 node = dtb.GetNode('/images/fdt-1')
3534 data = dtb.GetProps(node)["data"].bytes
3535 expected = (U_BOOT_SPL_DTB_DATA + tools.GetBytes(0, 20) +
3536 tools.ToBytes(TEXT_DATA) + tools.GetBytes(0, 30) +
3537 U_BOOT_DTB_DATA)
3538 self.assertEqual(expected, data)
3539
3540 def testFitExtblobMissingOk(self):
3541 """Test a FIT with a missing external blob that is allowed"""
3542 with test_util.capture_sys_output() as (stdout, stderr):
3543 self._DoTestFile('168_fit_missing_blob.dts',
3544 allow_missing=True)
3545 err = stderr.getvalue()
3546 self.assertRegex(err, "Image 'main-section'.*missing.*: blob-ext")
3547
Simon Glass3decfa32020-09-01 05:13:54 -06003548 def testBlobNamedByArgMissing(self):
3549 """Test handling of a missing entry arg"""
3550 with self.assertRaises(ValueError) as e:
3551 self._DoReadFile('068_blob_named_by_arg.dts')
3552 self.assertIn("Missing required properties/entry args: cros-ec-rw-path",
3553 str(e.exception))
3554
Simon Glassdc2f81a2020-09-01 05:13:58 -06003555 def testPackBl31(self):
3556 """Test that an image with an ATF BL31 binary can be created"""
3557 data = self._DoReadFile('169_atf_bl31.dts')
3558 self.assertEqual(ATF_BL31_DATA, data[:len(ATF_BL31_DATA)])
3559
3560ATF_BL31_DATA
3561
Simon Glass9fc60b42017-11-12 21:52:22 -07003562if __name__ == "__main__":
3563 unittest.main()