blob: d1bf64ce271a278b7a5a962af24572feef181046 [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass57454f42016-11-25 20:15:52 -07002# Copyright (c) 2016 Google, Inc
3# Written by Simon Glass <sjg@chromium.org>
4#
Simon Glass57454f42016-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 Glass45d556d2020-07-09 18:39:45 -06009import collections
Simon Glassc585dd42020-04-17 18:09:03 -060010import gzip
Simon Glassae7cf032018-09-14 04:57:31 -060011import hashlib
Simon Glass57454f42016-11-25 20:15:52 -070012from optparse import OptionParser
13import os
Simon Glass45d556d2020-07-09 18:39:45 -060014import re
Simon Glass57454f42016-11-25 20:15:52 -070015import shutil
16import struct
17import sys
18import tempfile
19import unittest
20
Simon Glassc585dd42020-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 Glassc585dd42020-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 Glass90cd6f02020-08-05 13:27:47 -060032from binman.image import Image
Simon Glassa997ea52020-04-17 18:09:04 -060033from patman import command
34from patman import test_util
35from patman import tools
36from patman import tout
Simon Glass57454f42016-11-25 20:15:52 -070037
38# Contents of test files, corresponding to different entry types
Simon Glass303f62f2019-05-17 22:00:46 -060039U_BOOT_DATA = b'1234'
40U_BOOT_IMG_DATA = b'img'
Simon Glass4e353e22019-08-24 07:23:04 -060041U_BOOT_SPL_DATA = b'56780123456789abcdefghi'
42U_BOOT_TPL_DATA = b'tpl9876543210fedcbazyw'
Simon Glass303f62f2019-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 Glass0b074d62019-08-24 07:22:48 -060052X86_RESET16_DATA = b'reset16'
53X86_RESET16_SPL_DATA = b'reset16spl'
54X86_RESET16_TPL_DATA = b'reset16tpl'
Simon Glass303f62f2019-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 Glass2ca52032018-07-17 13:25:33 -060063TEXT_DATA = 'text'
64TEXT_DATA2 = 'text2'
65TEXT_DATA3 = 'text3'
Simon Glass303f62f2019-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 Glassccec0262019-07-08 13:18:42 -060072COMPRESS_DATA = b'compress xxxxxxxxxxxxxxxxxxxxxx data'
Simon Glassd92c8362020-10-26 17:40:25 -060073COMPRESS_DATA_BIG = COMPRESS_DATA * 2
Simon Glass303f62f2019-05-17 22:00:46 -060074REFCODE_DATA = b'refcode'
Simon Glassba7985d2019-08-24 07:23:07 -060075FSP_M_DATA = b'fsp_m'
Simon Glass4d9086d2019-10-20 21:31:35 -060076FSP_S_DATA = b'fsp_s'
Simon Glass9ea87b22019-10-20 21:31:36 -060077FSP_T_DATA = b'fsp_t'
Simon Glass559c4de2020-09-01 05:13:58 -060078ATF_BL31_DATA = b'bl31'
Samuel Holland9d8cc632020-10-21 21:12:15 -050079SCP_DATA = b'scp'
Simon Glassa435cd12020-09-01 05:13:59 -060080TEST_FDT1_DATA = b'fdt1'
81TEST_FDT2_DATA = b'test-fdt2'
Simon Glassa0729502020-09-06 10:35:33 -060082ENV_DATA = b'var1=1\nvar2="2"'
Simon Glassa435cd12020-09-01 05:13:59 -060083
84# Subdirectory of the input dir to use to put test FDTs
85TEST_FDT_SUBDIR = 'fdts'
Simon Glassdb168d42018-07-17 13:25:39 -060086
Simon Glass2c6adba2019-07-20 12:23:47 -060087# The expected size for the device tree in some tests
Simon Glass4c613bf2019-07-08 14:25:50 -060088EXTRACT_DTB_SIZE = 0x3c9
89
Simon Glass2c6adba2019-07-20 12:23:47 -060090# Properties expected to be in the device tree when update_dtb is used
91BASE_DTB_PROPS = ['offset', 'size', 'image-pos']
92
Simon Glassfb30e292019-07-20 12:23:51 -060093# Extra properties expected to be in the device tree when allow-repack is used
94REPACK_DTB_PROPS = ['orig-offset', 'orig-size']
95
Simon Glass57454f42016-11-25 20:15:52 -070096
97class TestFunctional(unittest.TestCase):
98 """Functional tests for binman
99
100 Most of these use a sample .dts file to build an image and then check
101 that it looks correct. The sample files are in the test/ subdirectory
102 and are numbered.
103
104 For each entry type a very small test file is created using fixed
105 string contents. This makes it easy to test that things look right, and
106 debug problems.
107
108 In some cases a 'real' file must be used - these are also supplied in
109 the test/ diurectory.
110 """
111 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600112 def setUpClass(cls):
Simon Glassb3393262017-11-12 21:52:20 -0700113 global entry
Simon Glassc585dd42020-04-17 18:09:03 -0600114 from binman import entry
Simon Glassb3393262017-11-12 21:52:20 -0700115
Simon Glass57454f42016-11-25 20:15:52 -0700116 # Handle the case where argv[0] is 'python'
Simon Glass862f8e22019-08-24 07:22:43 -0600117 cls._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
118 cls._binman_pathname = os.path.join(cls._binman_dir, 'binman')
Simon Glass57454f42016-11-25 20:15:52 -0700119
120 # Create a temporary directory for input files
Simon Glass862f8e22019-08-24 07:22:43 -0600121 cls._indir = tempfile.mkdtemp(prefix='binmant.')
Simon Glass57454f42016-11-25 20:15:52 -0700122
123 # Create some test files
124 TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
125 TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
126 TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
Simon Glass8425a1f2018-07-17 13:25:48 -0600127 TestFunctional._MakeInputFile('tpl/u-boot-tpl.bin', U_BOOT_TPL_DATA)
Simon Glass57454f42016-11-25 20:15:52 -0700128 TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
Simon Glass72232452016-11-25 20:15:53 -0700129 TestFunctional._MakeInputFile('me.bin', ME_DATA)
130 TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
Simon Glass862f8e22019-08-24 07:22:43 -0600131 cls._ResetDtbs()
Simon Glass0b074d62019-08-24 07:22:48 -0600132
Jagdish Gediya311d4842018-09-03 21:35:08 +0530133 TestFunctional._MakeInputFile('u-boot-br.bin', PPC_MPC85XX_BR_DATA)
Simon Glass0b074d62019-08-24 07:22:48 -0600134
Simon Glassabab18c2019-08-24 07:22:49 -0600135 TestFunctional._MakeInputFile('u-boot-x86-start16.bin', X86_START16_DATA)
136 TestFunctional._MakeInputFile('spl/u-boot-x86-start16-spl.bin',
Simon Glasse83679d2017-11-12 21:52:26 -0700137 X86_START16_SPL_DATA)
Simon Glassabab18c2019-08-24 07:22:49 -0600138 TestFunctional._MakeInputFile('tpl/u-boot-x86-start16-tpl.bin',
Simon Glassed40e962018-09-14 04:57:10 -0600139 X86_START16_TPL_DATA)
Simon Glass0b074d62019-08-24 07:22:48 -0600140
141 TestFunctional._MakeInputFile('u-boot-x86-reset16.bin',
142 X86_RESET16_DATA)
143 TestFunctional._MakeInputFile('spl/u-boot-x86-reset16-spl.bin',
144 X86_RESET16_SPL_DATA)
145 TestFunctional._MakeInputFile('tpl/u-boot-x86-reset16-tpl.bin',
146 X86_RESET16_TPL_DATA)
147
Simon Glass57454f42016-11-25 20:15:52 -0700148 TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
Simon Glass3d274232017-11-12 21:52:27 -0700149 TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
150 U_BOOT_SPL_NODTB_DATA)
Simon Glass3fb4f422018-09-14 04:57:32 -0600151 TestFunctional._MakeInputFile('tpl/u-boot-tpl-nodtb.bin',
152 U_BOOT_TPL_NODTB_DATA)
Simon Glassb4176d42016-11-25 20:15:56 -0700153 TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
154 TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
Bin Mengd7bcdf52017-08-15 22:41:54 -0700155 TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
Simon Glassa409c932017-11-12 21:52:28 -0700156 TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
Simon Glassdb168d42018-07-17 13:25:39 -0600157 TestFunctional._MakeInputFile('ecrw.bin', CROS_EC_RW_DATA)
Simon Glassc1ae83c2018-07-17 13:25:44 -0600158 TestFunctional._MakeInputDir('devkeys')
159 TestFunctional._MakeInputFile('bmpblk.bin', BMPBLK_DATA)
Simon Glass41902e42018-10-01 12:22:31 -0600160 TestFunctional._MakeInputFile('refcode.bin', REFCODE_DATA)
Simon Glassba7985d2019-08-24 07:23:07 -0600161 TestFunctional._MakeInputFile('fsp_m.bin', FSP_M_DATA)
Simon Glass4d9086d2019-10-20 21:31:35 -0600162 TestFunctional._MakeInputFile('fsp_s.bin', FSP_S_DATA)
Simon Glass9ea87b22019-10-20 21:31:36 -0600163 TestFunctional._MakeInputFile('fsp_t.bin', FSP_T_DATA)
Simon Glass57454f42016-11-25 20:15:52 -0700164
Simon Glassf6290892019-08-24 07:22:53 -0600165 cls._elf_testdir = os.path.join(cls._indir, 'elftest')
166 elf_test.BuildElfTestFiles(cls._elf_testdir)
167
Simon Glass72232452016-11-25 20:15:53 -0700168 # ELF file with a '_dt_ucode_base_size' symbol
Simon Glass4affd4b2019-08-24 07:22:54 -0600169 TestFunctional._MakeInputFile('u-boot',
170 tools.ReadFile(cls.ElfTestFile('u_boot_ucode_ptr')))
Simon Glass72232452016-11-25 20:15:53 -0700171
172 # Intel flash descriptor file
Simon Glasse88cef92020-07-09 18:39:41 -0600173 cls._SetupDescriptor()
Simon Glass72232452016-11-25 20:15:53 -0700174
Simon Glass862f8e22019-08-24 07:22:43 -0600175 shutil.copytree(cls.TestFile('files'),
176 os.path.join(cls._indir, 'files'))
Simon Glassac6328c2018-09-14 04:57:28 -0600177
Simon Glass7ba33592018-09-14 04:57:26 -0600178 TestFunctional._MakeInputFile('compress', COMPRESS_DATA)
Simon Glassd92c8362020-10-26 17:40:25 -0600179 TestFunctional._MakeInputFile('compress_big', COMPRESS_DATA_BIG)
Simon Glass559c4de2020-09-01 05:13:58 -0600180 TestFunctional._MakeInputFile('bl31.bin', ATF_BL31_DATA)
Samuel Holland9d8cc632020-10-21 21:12:15 -0500181 TestFunctional._MakeInputFile('scp.bin', SCP_DATA)
Simon Glass7ba33592018-09-14 04:57:26 -0600182
Simon Glassa435cd12020-09-01 05:13:59 -0600183 # Add a few .dtb files for testing
184 TestFunctional._MakeInputFile('%s/test-fdt1.dtb' % TEST_FDT_SUBDIR,
185 TEST_FDT1_DATA)
186 TestFunctional._MakeInputFile('%s/test-fdt2.dtb' % TEST_FDT_SUBDIR,
187 TEST_FDT2_DATA)
188
Simon Glassa0729502020-09-06 10:35:33 -0600189 TestFunctional._MakeInputFile('env.txt', ENV_DATA)
190
Simon Glass1de34482019-07-08 13:18:53 -0600191 # Travis-CI may have an old lz4
Simon Glass862f8e22019-08-24 07:22:43 -0600192 cls.have_lz4 = True
Simon Glass1de34482019-07-08 13:18:53 -0600193 try:
194 tools.Run('lz4', '--no-frame-crc', '-c',
Simon Glasscc311ac2019-10-31 07:42:50 -0600195 os.path.join(cls._indir, 'u-boot.bin'), binary=True)
Simon Glass1de34482019-07-08 13:18:53 -0600196 except:
Simon Glass862f8e22019-08-24 07:22:43 -0600197 cls.have_lz4 = False
Simon Glass1de34482019-07-08 13:18:53 -0600198
Simon Glass57454f42016-11-25 20:15:52 -0700199 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600200 def tearDownClass(cls):
Simon Glass57454f42016-11-25 20:15:52 -0700201 """Remove the temporary input directory and its contents"""
Simon Glass862f8e22019-08-24 07:22:43 -0600202 if cls.preserve_indir:
203 print('Preserving input dir: %s' % cls._indir)
Simon Glass1c420c92019-07-08 13:18:49 -0600204 else:
Simon Glass862f8e22019-08-24 07:22:43 -0600205 if cls._indir:
206 shutil.rmtree(cls._indir)
207 cls._indir = None
Simon Glass57454f42016-11-25 20:15:52 -0700208
Simon Glass1c420c92019-07-08 13:18:49 -0600209 @classmethod
Simon Glasscebfab22019-07-08 13:18:50 -0600210 def setup_test_args(cls, preserve_indir=False, preserve_outdirs=False,
Simon Glassf46732a2019-07-08 14:25:29 -0600211 toolpath=None, verbosity=None):
Simon Glass1c420c92019-07-08 13:18:49 -0600212 """Accept arguments controlling test execution
213
214 Args:
215 preserve_indir: Preserve the shared input directory used by all
216 tests in this class.
217 preserve_outdir: Preserve the output directories used by tests. Each
218 test has its own, so this is normally only useful when running a
219 single test.
Simon Glasscebfab22019-07-08 13:18:50 -0600220 toolpath: ist of paths to use for tools
Simon Glass1c420c92019-07-08 13:18:49 -0600221 """
222 cls.preserve_indir = preserve_indir
223 cls.preserve_outdirs = preserve_outdirs
Simon Glasscebfab22019-07-08 13:18:50 -0600224 cls.toolpath = toolpath
Simon Glassf46732a2019-07-08 14:25:29 -0600225 cls.verbosity = verbosity
Simon Glass1c420c92019-07-08 13:18:49 -0600226
Simon Glass1de34482019-07-08 13:18:53 -0600227 def _CheckLz4(self):
228 if not self.have_lz4:
229 self.skipTest('lz4 --no-frame-crc not available')
230
Simon Glassee9d10d2019-07-20 12:24:09 -0600231 def _CleanupOutputDir(self):
232 """Remove the temporary output directory"""
233 if self.preserve_outdirs:
234 print('Preserving output dir: %s' % tools.outdir)
235 else:
236 tools._FinaliseForTest()
237
Simon Glass57454f42016-11-25 20:15:52 -0700238 def setUp(self):
239 # Enable this to turn on debugging output
240 # tout.Init(tout.DEBUG)
241 command.test_result = None
242
243 def tearDown(self):
244 """Remove the temporary output directory"""
Simon Glassee9d10d2019-07-20 12:24:09 -0600245 self._CleanupOutputDir()
Simon Glass57454f42016-11-25 20:15:52 -0700246
Simon Glassb3d6fc72019-07-20 12:24:10 -0600247 def _SetupImageInTmpdir(self):
248 """Set up the output image in a new temporary directory
249
250 This is used when an image has been generated in the output directory,
251 but we want to run binman again. This will create a new output
252 directory and fail to delete the original one.
253
254 This creates a new temporary directory, copies the image to it (with a
255 new name) and removes the old output directory.
256
257 Returns:
258 Tuple:
259 Temporary directory to use
260 New image filename
261 """
262 image_fname = tools.GetOutputFilename('image.bin')
263 tmpdir = tempfile.mkdtemp(prefix='binman.')
264 updated_fname = os.path.join(tmpdir, 'image-updated.bin')
265 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
266 self._CleanupOutputDir()
267 return tmpdir, updated_fname
268
Simon Glass8425a1f2018-07-17 13:25:48 -0600269 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600270 def _ResetDtbs(cls):
Simon Glass8425a1f2018-07-17 13:25:48 -0600271 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
272 TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
273 TestFunctional._MakeInputFile('tpl/u-boot-tpl.dtb', U_BOOT_TPL_DTB_DATA)
274
Simon Glass57454f42016-11-25 20:15:52 -0700275 def _RunBinman(self, *args, **kwargs):
276 """Run binman using the command line
277
278 Args:
279 Arguments to pass, as a list of strings
280 kwargs: Arguments to pass to Command.RunPipe()
281 """
282 result = command.RunPipe([[self._binman_pathname] + list(args)],
283 capture=True, capture_stderr=True, raise_on_error=False)
284 if result.return_code and kwargs.get('raise_on_error', True):
285 raise Exception("Error running '%s': %s" % (' '.join(args),
286 result.stdout + result.stderr))
287 return result
288
Simon Glassf46732a2019-07-08 14:25:29 -0600289 def _DoBinman(self, *argv):
Simon Glass57454f42016-11-25 20:15:52 -0700290 """Run binman using directly (in the same process)
291
292 Args:
293 Arguments to pass, as a list of strings
294 Returns:
295 Return value (0 for success)
296 """
Simon Glassf46732a2019-07-08 14:25:29 -0600297 argv = list(argv)
298 args = cmdline.ParseArgs(argv)
299 args.pager = 'binman-invalid-pager'
300 args.build_dir = self._indir
Simon Glass57454f42016-11-25 20:15:52 -0700301
302 # For testing, you can force an increase in verbosity here
Simon Glassf46732a2019-07-08 14:25:29 -0600303 # args.verbosity = tout.DEBUG
304 return control.Binman(args)
Simon Glass57454f42016-11-25 20:15:52 -0700305
Simon Glass91710b32018-07-17 13:25:32 -0600306 def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
Simon Glassb4595d82019-04-25 21:58:34 -0600307 entry_args=None, images=None, use_real_dtb=False,
Simon Glassa435cd12020-09-01 05:13:59 -0600308 verbosity=None, allow_missing=False, extra_indirs=None):
Simon Glass57454f42016-11-25 20:15:52 -0700309 """Run binman with a given test file
310
311 Args:
Simon Glass511f6582018-10-01 12:22:30 -0600312 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass1e324002018-06-01 09:38:19 -0600313 debug: True to enable debugging output
Simon Glass30732662018-06-01 09:38:20 -0600314 map: True to output map files for the images
Simon Glasse8561af2018-08-01 15:22:37 -0600315 update_dtb: Update the offset and size of each entry in the device
Simon Glassa87014e2018-07-06 10:27:42 -0600316 tree before packing it into the image
Simon Glass3b376c32018-09-14 04:57:12 -0600317 entry_args: Dict of entry args to supply to binman
318 key: arg name
319 value: value of that arg
320 images: List of image names to build
Simon Glass31ee50f2020-09-01 05:13:55 -0600321 use_real_dtb: True to use the test file as the contents of
322 the u-boot-dtb entry. Normally this is not needed and the
323 test contents (the U_BOOT_DTB_DATA string) can be used.
324 But in some test we need the real contents.
325 verbosity: Verbosity level to use (0-3, None=don't set it)
326 allow_missing: Set the '--allow-missing' flag so that missing
327 external binaries just produce a warning instead of an error
Simon Glassa435cd12020-09-01 05:13:59 -0600328 extra_indirs: Extra input directories to add using -I
Simon Glass57454f42016-11-25 20:15:52 -0700329 """
Simon Glassf46732a2019-07-08 14:25:29 -0600330 args = []
Simon Glass075a45c2017-11-13 18:55:00 -0700331 if debug:
332 args.append('-D')
Simon Glassf46732a2019-07-08 14:25:29 -0600333 if verbosity is not None:
334 args.append('-v%d' % verbosity)
335 elif self.verbosity:
336 args.append('-v%d' % self.verbosity)
337 if self.toolpath:
338 for path in self.toolpath:
339 args += ['--toolpath', path]
340 args += ['build', '-p', '-I', self._indir, '-d', self.TestFile(fname)]
Simon Glass30732662018-06-01 09:38:20 -0600341 if map:
342 args.append('-m')
Simon Glassa87014e2018-07-06 10:27:42 -0600343 if update_dtb:
Simon Glass38a411c2019-07-08 13:18:47 -0600344 args.append('-u')
Simon Glass31402012018-09-14 04:57:23 -0600345 if not use_real_dtb:
346 args.append('--fake-dtb')
Simon Glass91710b32018-07-17 13:25:32 -0600347 if entry_args:
Simon Glass5f3645b2019-05-14 15:53:41 -0600348 for arg, value in entry_args.items():
Simon Glass91710b32018-07-17 13:25:32 -0600349 args.append('-a%s=%s' % (arg, value))
Simon Glass5d94cc62020-07-09 18:39:38 -0600350 if allow_missing:
351 args.append('-M')
Simon Glass3b376c32018-09-14 04:57:12 -0600352 if images:
353 for image in images:
354 args += ['-i', image]
Simon Glassa435cd12020-09-01 05:13:59 -0600355 if extra_indirs:
356 for indir in extra_indirs:
357 args += ['-I', indir]
Simon Glass075a45c2017-11-13 18:55:00 -0700358 return self._DoBinman(*args)
Simon Glass57454f42016-11-25 20:15:52 -0700359
360 def _SetupDtb(self, fname, outfile='u-boot.dtb'):
Simon Glass72232452016-11-25 20:15:53 -0700361 """Set up a new test device-tree file
362
363 The given file is compiled and set up as the device tree to be used
364 for ths test.
365
366 Args:
367 fname: Filename of .dts file to read
Simon Glass1e324002018-06-01 09:38:19 -0600368 outfile: Output filename for compiled device-tree binary
Simon Glass72232452016-11-25 20:15:53 -0700369
370 Returns:
Simon Glass1e324002018-06-01 09:38:19 -0600371 Contents of device-tree binary
Simon Glass72232452016-11-25 20:15:53 -0700372 """
Simon Glassb8d2daa2019-07-20 12:23:49 -0600373 tmpdir = tempfile.mkdtemp(prefix='binmant.')
374 dtb = fdt_util.EnsureCompiled(self.TestFile(fname), tmpdir)
Simon Glass33486662019-05-14 15:53:42 -0600375 with open(dtb, 'rb') as fd:
Simon Glass57454f42016-11-25 20:15:52 -0700376 data = fd.read()
377 TestFunctional._MakeInputFile(outfile, data)
Simon Glassb8d2daa2019-07-20 12:23:49 -0600378 shutil.rmtree(tmpdir)
Simon Glass752e7552018-10-01 21:12:41 -0600379 return data
Simon Glass57454f42016-11-25 20:15:52 -0700380
Simon Glasse219aa42018-09-14 04:57:24 -0600381 def _GetDtbContentsForSplTpl(self, dtb_data, name):
382 """Create a version of the main DTB for SPL or SPL
383
384 For testing we don't actually have different versions of the DTB. With
385 U-Boot we normally run fdtgrep to remove unwanted nodes, but for tests
386 we don't normally have any unwanted nodes.
387
388 We still want the DTBs for SPL and TPL to be different though, since
389 otherwise it is confusing to know which one we are looking at. So add
390 an 'spl' or 'tpl' property to the top-level node.
Simon Glass31ee50f2020-09-01 05:13:55 -0600391
392 Args:
393 dtb_data: dtb data to modify (this should be a value devicetree)
394 name: Name of a new property to add
395
396 Returns:
397 New dtb data with the property added
Simon Glasse219aa42018-09-14 04:57:24 -0600398 """
399 dtb = fdt.Fdt.FromData(dtb_data)
400 dtb.Scan()
401 dtb.GetNode('/binman').AddZeroProp(name)
402 dtb.Sync(auto_resize=True)
403 dtb.Pack()
404 return dtb.GetContents()
405
Simon Glassa87014e2018-07-06 10:27:42 -0600406 def _DoReadFileDtb(self, fname, use_real_dtb=False, map=False,
Simon Glassa435cd12020-09-01 05:13:59 -0600407 update_dtb=False, entry_args=None, reset_dtbs=True,
408 extra_indirs=None):
Simon Glass57454f42016-11-25 20:15:52 -0700409 """Run binman and return the resulting image
410
411 This runs binman with a given test file and then reads the resulting
412 output file. It is a shortcut function since most tests need to do
413 these steps.
414
415 Raises an assertion failure if binman returns a non-zero exit code.
416
417 Args:
Simon Glass511f6582018-10-01 12:22:30 -0600418 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass57454f42016-11-25 20:15:52 -0700419 use_real_dtb: True to use the test file as the contents of
420 the u-boot-dtb entry. Normally this is not needed and the
421 test contents (the U_BOOT_DTB_DATA string) can be used.
422 But in some test we need the real contents.
Simon Glass30732662018-06-01 09:38:20 -0600423 map: True to output map files for the images
Simon Glasse8561af2018-08-01 15:22:37 -0600424 update_dtb: Update the offset and size of each entry in the device
Simon Glassa87014e2018-07-06 10:27:42 -0600425 tree before packing it into the image
Simon Glass31ee50f2020-09-01 05:13:55 -0600426 entry_args: Dict of entry args to supply to binman
427 key: arg name
428 value: value of that arg
429 reset_dtbs: With use_real_dtb the test dtb is overwritten by this
430 function. If reset_dtbs is True, then the original test dtb
431 is written back before this function finishes
Simon Glassa435cd12020-09-01 05:13:59 -0600432 extra_indirs: Extra input directories to add using -I
Simon Glass72232452016-11-25 20:15:53 -0700433
434 Returns:
435 Tuple:
436 Resulting image contents
437 Device tree contents
Simon Glass30732662018-06-01 09:38:20 -0600438 Map data showing contents of image (or None if none)
Simon Glassdef77b52018-07-17 13:25:27 -0600439 Output device tree binary filename ('u-boot.dtb' path)
Simon Glass57454f42016-11-25 20:15:52 -0700440 """
Simon Glass72232452016-11-25 20:15:53 -0700441 dtb_data = None
Simon Glass57454f42016-11-25 20:15:52 -0700442 # Use the compiled test file as the u-boot-dtb input
443 if use_real_dtb:
Simon Glass72232452016-11-25 20:15:53 -0700444 dtb_data = self._SetupDtb(fname)
Simon Glasse219aa42018-09-14 04:57:24 -0600445
446 # For testing purposes, make a copy of the DT for SPL and TPL. Add
447 # a node indicating which it is, so aid verification.
448 for name in ['spl', 'tpl']:
449 dtb_fname = '%s/u-boot-%s.dtb' % (name, name)
450 outfile = os.path.join(self._indir, dtb_fname)
451 TestFunctional._MakeInputFile(dtb_fname,
452 self._GetDtbContentsForSplTpl(dtb_data, name))
Simon Glass57454f42016-11-25 20:15:52 -0700453
454 try:
Simon Glass91710b32018-07-17 13:25:32 -0600455 retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
Simon Glassa435cd12020-09-01 05:13:59 -0600456 entry_args=entry_args, use_real_dtb=use_real_dtb,
457 extra_indirs=extra_indirs)
Simon Glass57454f42016-11-25 20:15:52 -0700458 self.assertEqual(0, retcode)
Simon Glasse219aa42018-09-14 04:57:24 -0600459 out_dtb_fname = tools.GetOutputFilename('u-boot.dtb.out')
Simon Glass57454f42016-11-25 20:15:52 -0700460
461 # Find the (only) image, read it and return its contents
462 image = control.images['image']
Simon Glassa87014e2018-07-06 10:27:42 -0600463 image_fname = tools.GetOutputFilename('image.bin')
464 self.assertTrue(os.path.exists(image_fname))
Simon Glass30732662018-06-01 09:38:20 -0600465 if map:
466 map_fname = tools.GetOutputFilename('image.map')
467 with open(map_fname) as fd:
468 map_data = fd.read()
469 else:
470 map_data = None
Simon Glass33486662019-05-14 15:53:42 -0600471 with open(image_fname, 'rb') as fd:
Simon Glassa87014e2018-07-06 10:27:42 -0600472 return fd.read(), dtb_data, map_data, out_dtb_fname
Simon Glass57454f42016-11-25 20:15:52 -0700473 finally:
474 # Put the test file back
Simon Glasse219aa42018-09-14 04:57:24 -0600475 if reset_dtbs and use_real_dtb:
Simon Glass8425a1f2018-07-17 13:25:48 -0600476 self._ResetDtbs()
Simon Glass57454f42016-11-25 20:15:52 -0700477
Simon Glass5b4bce32019-07-08 14:25:26 -0600478 def _DoReadFileRealDtb(self, fname):
479 """Run binman with a real .dtb file and return the resulting data
480
481 Args:
482 fname: DT source filename to use (e.g. 082_fdt_update_all.dts)
483
484 Returns:
485 Resulting image contents
486 """
487 return self._DoReadFileDtb(fname, use_real_dtb=True, update_dtb=True)[0]
488
Simon Glass72232452016-11-25 20:15:53 -0700489 def _DoReadFile(self, fname, use_real_dtb=False):
Simon Glass1e324002018-06-01 09:38:19 -0600490 """Helper function which discards the device-tree binary
491
492 Args:
Simon Glass511f6582018-10-01 12:22:30 -0600493 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass1e324002018-06-01 09:38:19 -0600494 use_real_dtb: True to use the test file as the contents of
495 the u-boot-dtb entry. Normally this is not needed and the
496 test contents (the U_BOOT_DTB_DATA string) can be used.
497 But in some test we need the real contents.
Simon Glassdef77b52018-07-17 13:25:27 -0600498
499 Returns:
500 Resulting image contents
Simon Glass1e324002018-06-01 09:38:19 -0600501 """
Simon Glass72232452016-11-25 20:15:53 -0700502 return self._DoReadFileDtb(fname, use_real_dtb)[0]
503
Simon Glass57454f42016-11-25 20:15:52 -0700504 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600505 def _MakeInputFile(cls, fname, contents):
Simon Glass57454f42016-11-25 20:15:52 -0700506 """Create a new test input file, creating directories as needed
507
508 Args:
Simon Glasse8561af2018-08-01 15:22:37 -0600509 fname: Filename to create
Simon Glass57454f42016-11-25 20:15:52 -0700510 contents: File contents to write in to the file
511 Returns:
512 Full pathname of file created
513 """
Simon Glass862f8e22019-08-24 07:22:43 -0600514 pathname = os.path.join(cls._indir, fname)
Simon Glass57454f42016-11-25 20:15:52 -0700515 dirname = os.path.dirname(pathname)
516 if dirname and not os.path.exists(dirname):
517 os.makedirs(dirname)
518 with open(pathname, 'wb') as fd:
519 fd.write(contents)
520 return pathname
521
522 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600523 def _MakeInputDir(cls, dirname):
Simon Glassc1ae83c2018-07-17 13:25:44 -0600524 """Create a new test input directory, creating directories as needed
525
526 Args:
527 dirname: Directory name to create
528
529 Returns:
530 Full pathname of directory created
531 """
Simon Glass862f8e22019-08-24 07:22:43 -0600532 pathname = os.path.join(cls._indir, dirname)
Simon Glassc1ae83c2018-07-17 13:25:44 -0600533 if not os.path.exists(pathname):
534 os.makedirs(pathname)
535 return pathname
536
537 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600538 def _SetupSplElf(cls, src_fname='bss_data'):
Simon Glass7057d022018-10-01 21:12:47 -0600539 """Set up an ELF file with a '_dt_ucode_base_size' symbol
540
541 Args:
542 Filename of ELF file to use as SPL
543 """
Simon Glass93a806f2019-08-24 07:22:59 -0600544 TestFunctional._MakeInputFile('spl/u-boot-spl',
545 tools.ReadFile(cls.ElfTestFile(src_fname)))
Simon Glass7057d022018-10-01 21:12:47 -0600546
547 @classmethod
Simon Glass3eb5b202019-08-24 07:23:00 -0600548 def _SetupTplElf(cls, src_fname='bss_data'):
549 """Set up an ELF file with a '_dt_ucode_base_size' symbol
550
551 Args:
552 Filename of ELF file to use as TPL
553 """
554 TestFunctional._MakeInputFile('tpl/u-boot-tpl',
555 tools.ReadFile(cls.ElfTestFile(src_fname)))
556
557 @classmethod
Simon Glasse88cef92020-07-09 18:39:41 -0600558 def _SetupDescriptor(cls):
559 with open(cls.TestFile('descriptor.bin'), 'rb') as fd:
560 TestFunctional._MakeInputFile('descriptor.bin', fd.read())
561
562 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600563 def TestFile(cls, fname):
564 return os.path.join(cls._binman_dir, 'test', fname)
Simon Glass57454f42016-11-25 20:15:52 -0700565
Simon Glassf6290892019-08-24 07:22:53 -0600566 @classmethod
567 def ElfTestFile(cls, fname):
568 return os.path.join(cls._elf_testdir, fname)
569
Simon Glass57454f42016-11-25 20:15:52 -0700570 def AssertInList(self, grep_list, target):
571 """Assert that at least one of a list of things is in a target
572
573 Args:
574 grep_list: List of strings to check
575 target: Target string
576 """
577 for grep in grep_list:
578 if grep in target:
579 return
Simon Glass848cdb52019-05-17 22:00:50 -0600580 self.fail("Error: '%s' not found in '%s'" % (grep_list, target))
Simon Glass57454f42016-11-25 20:15:52 -0700581
582 def CheckNoGaps(self, entries):
583 """Check that all entries fit together without gaps
584
585 Args:
586 entries: List of entries to check
587 """
Simon Glasse8561af2018-08-01 15:22:37 -0600588 offset = 0
Simon Glass57454f42016-11-25 20:15:52 -0700589 for entry in entries.values():
Simon Glasse8561af2018-08-01 15:22:37 -0600590 self.assertEqual(offset, entry.offset)
591 offset += entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700592
Simon Glass72232452016-11-25 20:15:53 -0700593 def GetFdtLen(self, dtb):
Simon Glass1e324002018-06-01 09:38:19 -0600594 """Get the totalsize field from a device-tree binary
Simon Glass72232452016-11-25 20:15:53 -0700595
596 Args:
Simon Glass1e324002018-06-01 09:38:19 -0600597 dtb: Device-tree binary contents
Simon Glass72232452016-11-25 20:15:53 -0700598
599 Returns:
Simon Glass1e324002018-06-01 09:38:19 -0600600 Total size of device-tree binary, from the header
Simon Glass72232452016-11-25 20:15:53 -0700601 """
602 return struct.unpack('>L', dtb[4:8])[0]
603
Simon Glass0f621332019-07-08 14:25:27 -0600604 def _GetPropTree(self, dtb, prop_names, prefix='/binman/'):
Simon Glassa87014e2018-07-06 10:27:42 -0600605 def AddNode(node, path):
606 if node.name != '/':
607 path += '/' + node.name
Simon Glass0f621332019-07-08 14:25:27 -0600608 for prop in node.props.values():
609 if prop.name in prop_names:
610 prop_path = path + ':' + prop.name
611 tree[prop_path[len(prefix):]] = fdt_util.fdt32_to_cpu(
612 prop.value)
Simon Glassa87014e2018-07-06 10:27:42 -0600613 for subnode in node.subnodes:
Simon Glassa87014e2018-07-06 10:27:42 -0600614 AddNode(subnode, path)
615
616 tree = {}
Simon Glassa87014e2018-07-06 10:27:42 -0600617 AddNode(dtb.GetRoot(), '')
618 return tree
619
Simon Glass57454f42016-11-25 20:15:52 -0700620 def testRun(self):
621 """Test a basic run with valid args"""
622 result = self._RunBinman('-h')
623
624 def testFullHelp(self):
625 """Test that the full help is displayed with -H"""
626 result = self._RunBinman('-H')
627 help_file = os.path.join(self._binman_dir, 'README')
Tom Rinic3c0b6d2018-01-16 15:29:50 -0500628 # Remove possible extraneous strings
629 extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
630 gothelp = result.stdout.replace(extra, '')
631 self.assertEqual(len(gothelp), os.path.getsize(help_file))
Simon Glass57454f42016-11-25 20:15:52 -0700632 self.assertEqual(0, len(result.stderr))
633 self.assertEqual(0, result.return_code)
634
635 def testFullHelpInternal(self):
636 """Test that the full help is displayed with -H"""
637 try:
638 command.test_result = command.CommandResult()
639 result = self._DoBinman('-H')
640 help_file = os.path.join(self._binman_dir, 'README')
641 finally:
642 command.test_result = None
643
644 def testHelp(self):
645 """Test that the basic help is displayed with -h"""
646 result = self._RunBinman('-h')
647 self.assertTrue(len(result.stdout) > 200)
648 self.assertEqual(0, len(result.stderr))
649 self.assertEqual(0, result.return_code)
650
Simon Glass57454f42016-11-25 20:15:52 -0700651 def testBoard(self):
652 """Test that we can run it with a specific board"""
Simon Glass511f6582018-10-01 12:22:30 -0600653 self._SetupDtb('005_simple.dts', 'sandbox/u-boot.dtb')
Simon Glass57454f42016-11-25 20:15:52 -0700654 TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
Simon Glassf46732a2019-07-08 14:25:29 -0600655 result = self._DoBinman('build', '-b', 'sandbox')
Simon Glass57454f42016-11-25 20:15:52 -0700656 self.assertEqual(0, result)
657
658 def testNeedBoard(self):
659 """Test that we get an error when no board ius supplied"""
660 with self.assertRaises(ValueError) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600661 result = self._DoBinman('build')
Simon Glass57454f42016-11-25 20:15:52 -0700662 self.assertIn("Must provide a board to process (use -b <board>)",
663 str(e.exception))
664
665 def testMissingDt(self):
Simon Glass1e324002018-06-01 09:38:19 -0600666 """Test that an invalid device-tree file generates an error"""
Simon Glass57454f42016-11-25 20:15:52 -0700667 with self.assertRaises(Exception) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600668 self._RunBinman('build', '-d', 'missing_file')
Simon Glass57454f42016-11-25 20:15:52 -0700669 # We get one error from libfdt, and a different one from fdtget.
670 self.AssertInList(["Couldn't open blob from 'missing_file'",
671 'No such file or directory'], str(e.exception))
672
673 def testBrokenDt(self):
Simon Glass1e324002018-06-01 09:38:19 -0600674 """Test that an invalid device-tree source file generates an error
Simon Glass57454f42016-11-25 20:15:52 -0700675
676 Since this is a source file it should be compiled and the error
677 will come from the device-tree compiler (dtc).
678 """
679 with self.assertRaises(Exception) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600680 self._RunBinman('build', '-d', self.TestFile('001_invalid.dts'))
Simon Glass57454f42016-11-25 20:15:52 -0700681 self.assertIn("FATAL ERROR: Unable to parse input tree",
682 str(e.exception))
683
684 def testMissingNode(self):
685 """Test that a device tree without a 'binman' node generates an error"""
686 with self.assertRaises(Exception) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600687 self._DoBinman('build', '-d', self.TestFile('002_missing_node.dts'))
Simon Glass57454f42016-11-25 20:15:52 -0700688 self.assertIn("does not have a 'binman' node", str(e.exception))
689
690 def testEmpty(self):
691 """Test that an empty binman node works OK (i.e. does nothing)"""
Simon Glassf46732a2019-07-08 14:25:29 -0600692 result = self._RunBinman('build', '-d', self.TestFile('003_empty.dts'))
Simon Glass57454f42016-11-25 20:15:52 -0700693 self.assertEqual(0, len(result.stderr))
694 self.assertEqual(0, result.return_code)
695
696 def testInvalidEntry(self):
697 """Test that an invalid entry is flagged"""
698 with self.assertRaises(Exception) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600699 result = self._RunBinman('build', '-d',
Simon Glass511f6582018-10-01 12:22:30 -0600700 self.TestFile('004_invalid_entry.dts'))
Simon Glass57454f42016-11-25 20:15:52 -0700701 self.assertIn("Unknown entry type 'not-a-valid-type' in node "
702 "'/binman/not-a-valid-type'", str(e.exception))
703
704 def testSimple(self):
705 """Test a simple binman with a single file"""
Simon Glass511f6582018-10-01 12:22:30 -0600706 data = self._DoReadFile('005_simple.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700707 self.assertEqual(U_BOOT_DATA, data)
708
Simon Glass075a45c2017-11-13 18:55:00 -0700709 def testSimpleDebug(self):
710 """Test a simple binman run with debugging enabled"""
Simon Glass52d06212019-07-08 14:25:53 -0600711 self._DoTestFile('005_simple.dts', debug=True)
Simon Glass075a45c2017-11-13 18:55:00 -0700712
Simon Glass57454f42016-11-25 20:15:52 -0700713 def testDual(self):
714 """Test that we can handle creating two images
715
716 This also tests image padding.
717 """
Simon Glass511f6582018-10-01 12:22:30 -0600718 retcode = self._DoTestFile('006_dual_image.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700719 self.assertEqual(0, retcode)
720
721 image = control.images['image1']
Simon Glass39dd2152019-07-08 14:25:47 -0600722 self.assertEqual(len(U_BOOT_DATA), image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700723 fname = tools.GetOutputFilename('image1.bin')
724 self.assertTrue(os.path.exists(fname))
Simon Glass33486662019-05-14 15:53:42 -0600725 with open(fname, 'rb') as fd:
Simon Glass57454f42016-11-25 20:15:52 -0700726 data = fd.read()
727 self.assertEqual(U_BOOT_DATA, data)
728
729 image = control.images['image2']
Simon Glass39dd2152019-07-08 14:25:47 -0600730 self.assertEqual(3 + len(U_BOOT_DATA) + 5, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700731 fname = tools.GetOutputFilename('image2.bin')
732 self.assertTrue(os.path.exists(fname))
Simon Glass33486662019-05-14 15:53:42 -0600733 with open(fname, 'rb') as fd:
Simon Glass57454f42016-11-25 20:15:52 -0700734 data = fd.read()
735 self.assertEqual(U_BOOT_DATA, data[3:7])
Simon Glassac0d4952019-05-14 15:53:47 -0600736 self.assertEqual(tools.GetBytes(0, 3), data[:3])
737 self.assertEqual(tools.GetBytes(0, 5), data[7:])
Simon Glass57454f42016-11-25 20:15:52 -0700738
739 def testBadAlign(self):
740 """Test that an invalid alignment value is detected"""
741 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600742 self._DoTestFile('007_bad_align.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700743 self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
744 "of two", str(e.exception))
745
746 def testPackSimple(self):
747 """Test that packing works as expected"""
Simon Glass511f6582018-10-01 12:22:30 -0600748 retcode = self._DoTestFile('008_pack.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700749 self.assertEqual(0, retcode)
750 self.assertIn('image', control.images)
751 image = control.images['image']
Simon Glasseca32212018-06-01 09:38:12 -0600752 entries = image.GetEntries()
Simon Glass57454f42016-11-25 20:15:52 -0700753 self.assertEqual(5, len(entries))
754
755 # First u-boot
756 self.assertIn('u-boot', entries)
757 entry = entries['u-boot']
Simon Glasse8561af2018-08-01 15:22:37 -0600758 self.assertEqual(0, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700759 self.assertEqual(len(U_BOOT_DATA), entry.size)
760
761 # Second u-boot, aligned to 16-byte boundary
762 self.assertIn('u-boot-align', entries)
763 entry = entries['u-boot-align']
Simon Glasse8561af2018-08-01 15:22:37 -0600764 self.assertEqual(16, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700765 self.assertEqual(len(U_BOOT_DATA), entry.size)
766
767 # Third u-boot, size 23 bytes
768 self.assertIn('u-boot-size', entries)
769 entry = entries['u-boot-size']
Simon Glasse8561af2018-08-01 15:22:37 -0600770 self.assertEqual(20, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700771 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
772 self.assertEqual(23, entry.size)
773
774 # Fourth u-boot, placed immediate after the above
775 self.assertIn('u-boot-next', entries)
776 entry = entries['u-boot-next']
Simon Glasse8561af2018-08-01 15:22:37 -0600777 self.assertEqual(43, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700778 self.assertEqual(len(U_BOOT_DATA), entry.size)
779
Simon Glasse8561af2018-08-01 15:22:37 -0600780 # Fifth u-boot, placed at a fixed offset
Simon Glass57454f42016-11-25 20:15:52 -0700781 self.assertIn('u-boot-fixed', entries)
782 entry = entries['u-boot-fixed']
Simon Glasse8561af2018-08-01 15:22:37 -0600783 self.assertEqual(61, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700784 self.assertEqual(len(U_BOOT_DATA), entry.size)
785
Simon Glass39dd2152019-07-08 14:25:47 -0600786 self.assertEqual(65, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700787
788 def testPackExtra(self):
789 """Test that extra packing feature works as expected"""
Simon Glassafb9caa2020-10-26 17:40:10 -0600790 data, _, _, out_dtb_fname = self._DoReadFileDtb('009_pack_extra.dts',
791 update_dtb=True)
Simon Glass57454f42016-11-25 20:15:52 -0700792
Simon Glass57454f42016-11-25 20:15:52 -0700793 self.assertIn('image', control.images)
794 image = control.images['image']
Simon Glasseca32212018-06-01 09:38:12 -0600795 entries = image.GetEntries()
Simon Glass57454f42016-11-25 20:15:52 -0700796 self.assertEqual(5, len(entries))
797
798 # First u-boot with padding before and after
799 self.assertIn('u-boot', entries)
800 entry = entries['u-boot']
Simon Glasse8561af2018-08-01 15:22:37 -0600801 self.assertEqual(0, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700802 self.assertEqual(3, entry.pad_before)
803 self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
Simon Glass187202f2020-10-26 17:40:08 -0600804 self.assertEqual(U_BOOT_DATA, entry.data)
805 self.assertEqual(tools.GetBytes(0, 3) + U_BOOT_DATA +
806 tools.GetBytes(0, 5), data[:entry.size])
807 pos = entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700808
809 # Second u-boot has an aligned size, but it has no effect
810 self.assertIn('u-boot-align-size-nop', entries)
811 entry = entries['u-boot-align-size-nop']
Simon Glass187202f2020-10-26 17:40:08 -0600812 self.assertEqual(pos, entry.offset)
813 self.assertEqual(len(U_BOOT_DATA), entry.size)
814 self.assertEqual(U_BOOT_DATA, entry.data)
815 self.assertEqual(U_BOOT_DATA, data[pos:pos + entry.size])
816 pos += entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700817
818 # Third u-boot has an aligned size too
819 self.assertIn('u-boot-align-size', entries)
820 entry = entries['u-boot-align-size']
Simon Glass187202f2020-10-26 17:40:08 -0600821 self.assertEqual(pos, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700822 self.assertEqual(32, entry.size)
Simon Glass187202f2020-10-26 17:40:08 -0600823 self.assertEqual(U_BOOT_DATA, entry.data)
824 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 32 - len(U_BOOT_DATA)),
825 data[pos:pos + entry.size])
826 pos += entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700827
828 # Fourth u-boot has an aligned end
829 self.assertIn('u-boot-align-end', entries)
830 entry = entries['u-boot-align-end']
Simon Glasse8561af2018-08-01 15:22:37 -0600831 self.assertEqual(48, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700832 self.assertEqual(16, entry.size)
Simon Glass187202f2020-10-26 17:40:08 -0600833 self.assertEqual(U_BOOT_DATA, entry.data[:len(U_BOOT_DATA)])
834 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 16 - len(U_BOOT_DATA)),
835 data[pos:pos + entry.size])
836 pos += entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700837
838 # Fifth u-boot immediately afterwards
839 self.assertIn('u-boot-align-both', entries)
840 entry = entries['u-boot-align-both']
Simon Glasse8561af2018-08-01 15:22:37 -0600841 self.assertEqual(64, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700842 self.assertEqual(64, entry.size)
Simon Glass187202f2020-10-26 17:40:08 -0600843 self.assertEqual(U_BOOT_DATA, entry.data[:len(U_BOOT_DATA)])
844 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 64 - len(U_BOOT_DATA)),
845 data[pos:pos + entry.size])
Simon Glass57454f42016-11-25 20:15:52 -0700846
847 self.CheckNoGaps(entries)
Simon Glass39dd2152019-07-08 14:25:47 -0600848 self.assertEqual(128, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700849
Simon Glassafb9caa2020-10-26 17:40:10 -0600850 dtb = fdt.Fdt(out_dtb_fname)
851 dtb.Scan()
852 props = self._GetPropTree(dtb, ['size', 'offset', 'image-pos'])
853 expected = {
854 'image-pos': 0,
855 'offset': 0,
856 'size': 128,
857
858 'u-boot:image-pos': 0,
859 'u-boot:offset': 0,
860 'u-boot:size': 3 + 5 + len(U_BOOT_DATA),
861
862 'u-boot-align-size-nop:image-pos': 12,
863 'u-boot-align-size-nop:offset': 12,
864 'u-boot-align-size-nop:size': 4,
865
866 'u-boot-align-size:image-pos': 16,
867 'u-boot-align-size:offset': 16,
868 'u-boot-align-size:size': 32,
869
870 'u-boot-align-end:image-pos': 48,
871 'u-boot-align-end:offset': 48,
872 'u-boot-align-end:size': 16,
873
874 'u-boot-align-both:image-pos': 64,
875 'u-boot-align-both:offset': 64,
876 'u-boot-align-both:size': 64,
877 }
878 self.assertEqual(expected, props)
879
Simon Glass57454f42016-11-25 20:15:52 -0700880 def testPackAlignPowerOf2(self):
881 """Test that invalid entry alignment is detected"""
882 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600883 self._DoTestFile('010_pack_align_power2.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700884 self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
885 "of two", str(e.exception))
886
887 def testPackAlignSizePowerOf2(self):
888 """Test that invalid entry size alignment is detected"""
889 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600890 self._DoTestFile('011_pack_align_size_power2.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700891 self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
892 "power of two", str(e.exception))
893
894 def testPackInvalidAlign(self):
Simon Glasse8561af2018-08-01 15:22:37 -0600895 """Test detection of an offset that does not match its alignment"""
Simon Glass57454f42016-11-25 20:15:52 -0700896 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600897 self._DoTestFile('012_pack_inv_align.dts')
Simon Glasse8561af2018-08-01 15:22:37 -0600898 self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
Simon Glass57454f42016-11-25 20:15:52 -0700899 "align 0x4 (4)", str(e.exception))
900
901 def testPackInvalidSizeAlign(self):
902 """Test that invalid entry size alignment is detected"""
903 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600904 self._DoTestFile('013_pack_inv_size_align.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700905 self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
906 "align-size 0x4 (4)", str(e.exception))
907
908 def testPackOverlap(self):
909 """Test that overlapping regions are detected"""
910 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600911 self._DoTestFile('014_pack_overlap.dts')
Simon Glasse8561af2018-08-01 15:22:37 -0600912 self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
Simon Glass57454f42016-11-25 20:15:52 -0700913 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
914 str(e.exception))
915
916 def testPackEntryOverflow(self):
917 """Test that entries that overflow their size are detected"""
918 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600919 self._DoTestFile('015_pack_overflow.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700920 self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
921 "but entry size is 0x3 (3)", str(e.exception))
922
923 def testPackImageOverflow(self):
924 """Test that entries which overflow the image size are detected"""
925 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600926 self._DoTestFile('016_pack_image_overflow.dts')
Simon Glasseca32212018-06-01 09:38:12 -0600927 self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
Simon Glass57454f42016-11-25 20:15:52 -0700928 "size 0x3 (3)", str(e.exception))
929
930 def testPackImageSize(self):
931 """Test that the image size can be set"""
Simon Glass511f6582018-10-01 12:22:30 -0600932 retcode = self._DoTestFile('017_pack_image_size.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700933 self.assertEqual(0, retcode)
934 self.assertIn('image', control.images)
935 image = control.images['image']
Simon Glass39dd2152019-07-08 14:25:47 -0600936 self.assertEqual(7, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700937
938 def testPackImageSizeAlign(self):
939 """Test that image size alignemnt works as expected"""
Simon Glass511f6582018-10-01 12:22:30 -0600940 retcode = self._DoTestFile('018_pack_image_align.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700941 self.assertEqual(0, retcode)
942 self.assertIn('image', control.images)
943 image = control.images['image']
Simon Glass39dd2152019-07-08 14:25:47 -0600944 self.assertEqual(16, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700945
946 def testPackInvalidImageAlign(self):
947 """Test that invalid image alignment is detected"""
948 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600949 self._DoTestFile('019_pack_inv_image_align.dts')
Simon Glasseca32212018-06-01 09:38:12 -0600950 self.assertIn("Section '/binman': Size 0x7 (7) does not match "
Simon Glass57454f42016-11-25 20:15:52 -0700951 "align-size 0x8 (8)", str(e.exception))
952
953 def testPackAlignPowerOf2(self):
954 """Test that invalid image alignment is detected"""
955 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600956 self._DoTestFile('020_pack_inv_image_align_power2.dts')
Simon Glass39dd2152019-07-08 14:25:47 -0600957 self.assertIn("Image '/binman': Alignment size 131 must be a power of "
Simon Glass57454f42016-11-25 20:15:52 -0700958 "two", str(e.exception))
959
960 def testImagePadByte(self):
961 """Test that the image pad byte can be specified"""
Simon Glass7057d022018-10-01 21:12:47 -0600962 self._SetupSplElf()
Simon Glass511f6582018-10-01 12:22:30 -0600963 data = self._DoReadFile('021_image_pad.dts')
Simon Glassac0d4952019-05-14 15:53:47 -0600964 self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0xff, 1) +
965 U_BOOT_DATA, data)
Simon Glass57454f42016-11-25 20:15:52 -0700966
967 def testImageName(self):
968 """Test that image files can be named"""
Simon Glass511f6582018-10-01 12:22:30 -0600969 retcode = self._DoTestFile('022_image_name.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700970 self.assertEqual(0, retcode)
971 image = control.images['image1']
972 fname = tools.GetOutputFilename('test-name')
973 self.assertTrue(os.path.exists(fname))
974
975 image = control.images['image2']
976 fname = tools.GetOutputFilename('test-name.xx')
977 self.assertTrue(os.path.exists(fname))
978
979 def testBlobFilename(self):
980 """Test that generic blobs can be provided by filename"""
Simon Glass511f6582018-10-01 12:22:30 -0600981 data = self._DoReadFile('023_blob.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700982 self.assertEqual(BLOB_DATA, data)
983
984 def testPackSorted(self):
985 """Test that entries can be sorted"""
Simon Glass7057d022018-10-01 21:12:47 -0600986 self._SetupSplElf()
Simon Glass511f6582018-10-01 12:22:30 -0600987 data = self._DoReadFile('024_sorted.dts')
Simon Glassac0d4952019-05-14 15:53:47 -0600988 self.assertEqual(tools.GetBytes(0, 1) + U_BOOT_SPL_DATA +
989 tools.GetBytes(0, 2) + U_BOOT_DATA, data)
Simon Glass57454f42016-11-25 20:15:52 -0700990
Simon Glasse8561af2018-08-01 15:22:37 -0600991 def testPackZeroOffset(self):
992 """Test that an entry at offset 0 is not given a new offset"""
Simon Glass57454f42016-11-25 20:15:52 -0700993 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600994 self._DoTestFile('025_pack_zero_size.dts')
Simon Glasse8561af2018-08-01 15:22:37 -0600995 self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
Simon Glass57454f42016-11-25 20:15:52 -0700996 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
997 str(e.exception))
998
999 def testPackUbootDtb(self):
1000 """Test that a device tree can be added to U-Boot"""
Simon Glass511f6582018-10-01 12:22:30 -06001001 data = self._DoReadFile('026_pack_u_boot_dtb.dts')
Simon Glass57454f42016-11-25 20:15:52 -07001002 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
Simon Glass72232452016-11-25 20:15:53 -07001003
1004 def testPackX86RomNoSize(self):
1005 """Test that the end-at-4gb property requires a size property"""
1006 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001007 self._DoTestFile('027_pack_4gb_no_size.dts')
Simon Glass39dd2152019-07-08 14:25:47 -06001008 self.assertIn("Image '/binman': Section size must be provided when "
Simon Glass72232452016-11-25 20:15:53 -07001009 "using end-at-4gb", str(e.exception))
1010
Jagdish Gediya0fb978c2018-09-03 21:35:07 +05301011 def test4gbAndSkipAtStartTogether(self):
1012 """Test that the end-at-4gb and skip-at-size property can't be used
1013 together"""
1014 with self.assertRaises(ValueError) as e:
Simon Glass11f2bd02019-08-24 07:23:02 -06001015 self._DoTestFile('098_4gb_and_skip_at_start_together.dts')
Simon Glass39dd2152019-07-08 14:25:47 -06001016 self.assertIn("Image '/binman': Provide either 'end-at-4gb' or "
Jagdish Gediya0fb978c2018-09-03 21:35:07 +05301017 "'skip-at-start'", str(e.exception))
1018
Simon Glass72232452016-11-25 20:15:53 -07001019 def testPackX86RomOutside(self):
Simon Glasse8561af2018-08-01 15:22:37 -06001020 """Test that the end-at-4gb property checks for offset boundaries"""
Simon Glass72232452016-11-25 20:15:53 -07001021 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001022 self._DoTestFile('028_pack_4gb_outside.dts')
Simon Glassd6179862020-10-26 17:40:05 -06001023 self.assertIn("Node '/binman/u-boot': Offset 0x0 (0) size 0x4 (4) "
1024 "is outside the section '/binman' starting at "
1025 '0xffffffe0 (4294967264) of size 0x20 (32)',
Simon Glass72232452016-11-25 20:15:53 -07001026 str(e.exception))
1027
1028 def testPackX86Rom(self):
1029 """Test that a basic x86 ROM can be created"""
Simon Glass7057d022018-10-01 21:12:47 -06001030 self._SetupSplElf()
Simon Glass1d167762019-08-24 07:23:01 -06001031 data = self._DoReadFile('029_x86_rom.dts')
Simon Glass4e353e22019-08-24 07:23:04 -06001032 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 3) + U_BOOT_SPL_DATA +
Simon Glassac0d4952019-05-14 15:53:47 -06001033 tools.GetBytes(0, 2), data)
Simon Glass72232452016-11-25 20:15:53 -07001034
1035 def testPackX86RomMeNoDesc(self):
1036 """Test that an invalid Intel descriptor entry is detected"""
Simon Glasse88cef92020-07-09 18:39:41 -06001037 try:
Simon Glass14c596c2020-07-25 15:11:19 -06001038 TestFunctional._MakeInputFile('descriptor-empty.bin', b'')
Simon Glasse88cef92020-07-09 18:39:41 -06001039 with self.assertRaises(ValueError) as e:
Simon Glass14c596c2020-07-25 15:11:19 -06001040 self._DoTestFile('163_x86_rom_me_empty.dts')
Simon Glasse88cef92020-07-09 18:39:41 -06001041 self.assertIn("Node '/binman/intel-descriptor': Cannot find Intel Flash Descriptor (FD) signature",
1042 str(e.exception))
1043 finally:
1044 self._SetupDescriptor()
Simon Glass72232452016-11-25 20:15:53 -07001045
1046 def testPackX86RomBadDesc(self):
1047 """Test that the Intel requires a descriptor entry"""
1048 with self.assertRaises(ValueError) as e:
Simon Glass1d167762019-08-24 07:23:01 -06001049 self._DoTestFile('030_x86_rom_me_no_desc.dts')
Simon Glasse8561af2018-08-01 15:22:37 -06001050 self.assertIn("Node '/binman/intel-me': No offset set with "
1051 "offset-unset: should another entry provide this correct "
1052 "offset?", str(e.exception))
Simon Glass72232452016-11-25 20:15:53 -07001053
1054 def testPackX86RomMe(self):
1055 """Test that an x86 ROM with an ME region can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001056 data = self._DoReadFile('031_x86_rom_me.dts')
Simon Glass759af872019-07-08 13:18:54 -06001057 expected_desc = tools.ReadFile(self.TestFile('descriptor.bin'))
1058 if data[:0x1000] != expected_desc:
1059 self.fail('Expected descriptor binary at start of image')
Simon Glass72232452016-11-25 20:15:53 -07001060 self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
1061
1062 def testPackVga(self):
1063 """Test that an image with a VGA binary can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001064 data = self._DoReadFile('032_intel_vga.dts')
Simon Glass72232452016-11-25 20:15:53 -07001065 self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
1066
1067 def testPackStart16(self):
1068 """Test that an image with an x86 start16 region can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001069 data = self._DoReadFile('033_x86_start16.dts')
Simon Glass72232452016-11-25 20:15:53 -07001070 self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
1071
Jagdish Gediya311d4842018-09-03 21:35:08 +05301072 def testPackPowerpcMpc85xxBootpgResetvec(self):
1073 """Test that an image with powerpc-mpc85xx-bootpg-resetvec can be
1074 created"""
Simon Glass11f2bd02019-08-24 07:23:02 -06001075 data = self._DoReadFile('150_powerpc_mpc85xx_bootpg_resetvec.dts')
Jagdish Gediya311d4842018-09-03 21:35:08 +05301076 self.assertEqual(PPC_MPC85XX_BR_DATA, data[:len(PPC_MPC85XX_BR_DATA)])
1077
Simon Glass6ba679c2018-07-06 10:27:17 -06001078 def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
Simon Glass820af1d2018-07-06 10:27:16 -06001079 """Handle running a test for insertion of microcode
1080
1081 Args:
1082 dts_fname: Name of test .dts file
1083 nodtb_data: Data that we expect in the first section
Simon Glass6ba679c2018-07-06 10:27:17 -06001084 ucode_second: True if the microsecond entry is second instead of
1085 third
Simon Glass820af1d2018-07-06 10:27:16 -06001086
1087 Returns:
1088 Tuple:
1089 Contents of first region (U-Boot or SPL)
Simon Glasse8561af2018-08-01 15:22:37 -06001090 Offset and size components of microcode pointer, as inserted
Simon Glass820af1d2018-07-06 10:27:16 -06001091 in the above (two 4-byte words)
1092 """
Simon Glass3d274232017-11-12 21:52:27 -07001093 data = self._DoReadFile(dts_fname, True)
Simon Glass72232452016-11-25 20:15:53 -07001094
1095 # Now check the device tree has no microcode
Simon Glass6ba679c2018-07-06 10:27:17 -06001096 if ucode_second:
1097 ucode_content = data[len(nodtb_data):]
1098 ucode_pos = len(nodtb_data)
1099 dtb_with_ucode = ucode_content[16:]
1100 fdt_len = self.GetFdtLen(dtb_with_ucode)
1101 else:
1102 dtb_with_ucode = data[len(nodtb_data):]
1103 fdt_len = self.GetFdtLen(dtb_with_ucode)
1104 ucode_content = dtb_with_ucode[fdt_len:]
1105 ucode_pos = len(nodtb_data) + fdt_len
Simon Glass72232452016-11-25 20:15:53 -07001106 fname = tools.GetOutputFilename('test.dtb')
1107 with open(fname, 'wb') as fd:
Simon Glass820af1d2018-07-06 10:27:16 -06001108 fd.write(dtb_with_ucode)
Simon Glass22c92ca2017-05-27 07:38:29 -06001109 dtb = fdt.FdtScan(fname)
1110 ucode = dtb.GetNode('/microcode')
Simon Glass72232452016-11-25 20:15:53 -07001111 self.assertTrue(ucode)
1112 for node in ucode.subnodes:
1113 self.assertFalse(node.props.get('data'))
1114
Simon Glass72232452016-11-25 20:15:53 -07001115 # Check that the microcode appears immediately after the Fdt
1116 # This matches the concatenation of the data properties in
Simon Glasse83679d2017-11-12 21:52:26 -07001117 # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
Simon Glass72232452016-11-25 20:15:53 -07001118 ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
1119 0x78235609)
Simon Glass820af1d2018-07-06 10:27:16 -06001120 self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
Simon Glass72232452016-11-25 20:15:53 -07001121
1122 # Check that the microcode pointer was inserted. It should match the
Simon Glasse8561af2018-08-01 15:22:37 -06001123 # expected offset and size
Simon Glass72232452016-11-25 20:15:53 -07001124 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
1125 len(ucode_data))
Simon Glass6ba679c2018-07-06 10:27:17 -06001126 u_boot = data[:len(nodtb_data)]
1127 return u_boot, pos_and_size
Simon Glass3d274232017-11-12 21:52:27 -07001128
1129 def testPackUbootMicrocode(self):
1130 """Test that x86 microcode can be handled correctly
1131
1132 We expect to see the following in the image, in order:
1133 u-boot-nodtb.bin with a microcode pointer inserted at the correct
1134 place
1135 u-boot.dtb with the microcode removed
1136 the microcode
1137 """
Simon Glass511f6582018-10-01 12:22:30 -06001138 first, pos_and_size = self._RunMicrocodeTest('034_x86_ucode.dts',
Simon Glass3d274232017-11-12 21:52:27 -07001139 U_BOOT_NODTB_DATA)
Simon Glass303f62f2019-05-17 22:00:46 -06001140 self.assertEqual(b'nodtb with microcode' + pos_and_size +
1141 b' somewhere in here', first)
Simon Glass72232452016-11-25 20:15:53 -07001142
Simon Glassbac25c82017-05-27 07:38:26 -06001143 def _RunPackUbootSingleMicrocode(self):
Simon Glass72232452016-11-25 20:15:53 -07001144 """Test that x86 microcode can be handled correctly
1145
1146 We expect to see the following in the image, in order:
1147 u-boot-nodtb.bin with a microcode pointer inserted at the correct
1148 place
1149 u-boot.dtb with the microcode
1150 an empty microcode region
1151 """
1152 # We need the libfdt library to run this test since only that allows
1153 # finding the offset of a property. This is required by
1154 # Entry_u_boot_dtb_with_ucode.ObtainContents().
Simon Glass511f6582018-10-01 12:22:30 -06001155 data = self._DoReadFile('035_x86_single_ucode.dts', True)
Simon Glass72232452016-11-25 20:15:53 -07001156
1157 second = data[len(U_BOOT_NODTB_DATA):]
1158
1159 fdt_len = self.GetFdtLen(second)
1160 third = second[fdt_len:]
1161 second = second[:fdt_len]
1162
Simon Glassbac25c82017-05-27 07:38:26 -06001163 ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
1164 self.assertIn(ucode_data, second)
1165 ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
Simon Glass72232452016-11-25 20:15:53 -07001166
Simon Glassbac25c82017-05-27 07:38:26 -06001167 # Check that the microcode pointer was inserted. It should match the
Simon Glasse8561af2018-08-01 15:22:37 -06001168 # expected offset and size
Simon Glassbac25c82017-05-27 07:38:26 -06001169 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
1170 len(ucode_data))
1171 first = data[:len(U_BOOT_NODTB_DATA)]
Simon Glass303f62f2019-05-17 22:00:46 -06001172 self.assertEqual(b'nodtb with microcode' + pos_and_size +
1173 b' somewhere in here', first)
Simon Glass996021e2016-11-25 20:15:54 -07001174
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001175 def testPackUbootSingleMicrocode(self):
1176 """Test that x86 microcode can be handled correctly with fdt_normal.
1177 """
Simon Glassbac25c82017-05-27 07:38:26 -06001178 self._RunPackUbootSingleMicrocode()
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001179
Simon Glass996021e2016-11-25 20:15:54 -07001180 def testUBootImg(self):
1181 """Test that u-boot.img can be put in a file"""
Simon Glass511f6582018-10-01 12:22:30 -06001182 data = self._DoReadFile('036_u_boot_img.dts')
Simon Glass996021e2016-11-25 20:15:54 -07001183 self.assertEqual(U_BOOT_IMG_DATA, data)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001184
1185 def testNoMicrocode(self):
1186 """Test that a missing microcode region is detected"""
1187 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001188 self._DoReadFile('037_x86_no_ucode.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001189 self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
1190 "node found in ", str(e.exception))
1191
1192 def testMicrocodeWithoutNode(self):
1193 """Test that a missing u-boot-dtb-with-ucode node is detected"""
1194 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001195 self._DoReadFile('038_x86_ucode_missing_node.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001196 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
1197 "microcode region u-boot-dtb-with-ucode", str(e.exception))
1198
1199 def testMicrocodeWithoutNode2(self):
1200 """Test that a missing u-boot-ucode node is detected"""
1201 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001202 self._DoReadFile('039_x86_ucode_missing_node2.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001203 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
1204 "microcode region u-boot-ucode", str(e.exception))
1205
1206 def testMicrocodeWithoutPtrInElf(self):
1207 """Test that a U-Boot binary without the microcode symbol is detected"""
1208 # ELF file without a '_dt_ucode_base_size' symbol
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001209 try:
Simon Glassfaaaa162019-08-24 07:22:55 -06001210 TestFunctional._MakeInputFile('u-boot',
1211 tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001212
1213 with self.assertRaises(ValueError) as e:
Simon Glassbac25c82017-05-27 07:38:26 -06001214 self._RunPackUbootSingleMicrocode()
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001215 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
1216 "_dt_ucode_base_size symbol in u-boot", str(e.exception))
1217
1218 finally:
1219 # Put the original file back
Simon Glass4affd4b2019-08-24 07:22:54 -06001220 TestFunctional._MakeInputFile('u-boot',
1221 tools.ReadFile(self.ElfTestFile('u_boot_ucode_ptr')))
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001222
1223 def testMicrocodeNotInImage(self):
1224 """Test that microcode must be placed within the image"""
1225 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001226 self._DoReadFile('040_x86_ucode_not_in_image.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001227 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
1228 "pointer _dt_ucode_base_size at fffffe14 is outside the "
Simon Glassad5a7712018-06-01 09:38:14 -06001229 "section ranging from 00000000 to 0000002e", str(e.exception))
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001230
1231 def testWithoutMicrocode(self):
1232 """Test that we can cope with an image without microcode (e.g. qemu)"""
Simon Glassfaaaa162019-08-24 07:22:55 -06001233 TestFunctional._MakeInputFile('u-boot',
1234 tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
Simon Glass511f6582018-10-01 12:22:30 -06001235 data, dtb, _, _ = self._DoReadFileDtb('044_x86_optional_ucode.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001236
1237 # Now check the device tree has no microcode
1238 self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
1239 second = data[len(U_BOOT_NODTB_DATA):]
1240
1241 fdt_len = self.GetFdtLen(second)
1242 self.assertEqual(dtb, second[:fdt_len])
1243
1244 used_len = len(U_BOOT_NODTB_DATA) + fdt_len
1245 third = data[used_len:]
Simon Glassac0d4952019-05-14 15:53:47 -06001246 self.assertEqual(tools.GetBytes(0, 0x200 - used_len), third)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001247
1248 def testUnknownPosSize(self):
1249 """Test that microcode must be placed within the image"""
1250 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001251 self._DoReadFile('041_unknown_pos_size.dts', True)
Simon Glasse8561af2018-08-01 15:22:37 -06001252 self.assertIn("Section '/binman': Unable to set offset/size for unknown "
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001253 "entry 'invalid-entry'", str(e.exception))
Simon Glassb4176d42016-11-25 20:15:56 -07001254
1255 def testPackFsp(self):
1256 """Test that an image with a FSP binary can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001257 data = self._DoReadFile('042_intel_fsp.dts')
Simon Glassb4176d42016-11-25 20:15:56 -07001258 self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
1259
1260 def testPackCmc(self):
Bin Mengd7bcdf52017-08-15 22:41:54 -07001261 """Test that an image with a CMC binary can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001262 data = self._DoReadFile('043_intel_cmc.dts')
Simon Glassb4176d42016-11-25 20:15:56 -07001263 self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
Bin Mengd7bcdf52017-08-15 22:41:54 -07001264
1265 def testPackVbt(self):
1266 """Test that an image with a VBT binary can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001267 data = self._DoReadFile('046_intel_vbt.dts')
Bin Mengd7bcdf52017-08-15 22:41:54 -07001268 self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
Simon Glassac599912017-11-12 21:52:22 -07001269
Simon Glass7f94e832017-11-12 21:52:25 -07001270 def testSplBssPad(self):
1271 """Test that we can pad SPL's BSS with zeros"""
Simon Glass3d274232017-11-12 21:52:27 -07001272 # ELF file with a '__bss_size' symbol
Simon Glass7057d022018-10-01 21:12:47 -06001273 self._SetupSplElf()
Simon Glass511f6582018-10-01 12:22:30 -06001274 data = self._DoReadFile('047_spl_bss_pad.dts')
Simon Glassac0d4952019-05-14 15:53:47 -06001275 self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0, 10) + U_BOOT_DATA,
1276 data)
Simon Glass7f94e832017-11-12 21:52:25 -07001277
Simon Glass04cda032018-10-01 21:12:42 -06001278 def testSplBssPadMissing(self):
1279 """Test that a missing symbol is detected"""
Simon Glass7057d022018-10-01 21:12:47 -06001280 self._SetupSplElf('u_boot_ucode_ptr')
Simon Glass24ad3652017-11-13 18:54:54 -07001281 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001282 self._DoReadFile('047_spl_bss_pad.dts')
Simon Glass24ad3652017-11-13 18:54:54 -07001283 self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
1284 str(e.exception))
1285
Simon Glasse83679d2017-11-12 21:52:26 -07001286 def testPackStart16Spl(self):
Simon Glassed40e962018-09-14 04:57:10 -06001287 """Test that an image with an x86 start16 SPL region can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001288 data = self._DoReadFile('048_x86_start16_spl.dts')
Simon Glasse83679d2017-11-12 21:52:26 -07001289 self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
1290
Simon Glass6ba679c2018-07-06 10:27:17 -06001291 def _PackUbootSplMicrocode(self, dts, ucode_second=False):
1292 """Helper function for microcode tests
Simon Glass3d274232017-11-12 21:52:27 -07001293
1294 We expect to see the following in the image, in order:
1295 u-boot-spl-nodtb.bin with a microcode pointer inserted at the
1296 correct place
1297 u-boot.dtb with the microcode removed
1298 the microcode
Simon Glass6ba679c2018-07-06 10:27:17 -06001299
1300 Args:
1301 dts: Device tree file to use for test
1302 ucode_second: True if the microsecond entry is second instead of
1303 third
Simon Glass3d274232017-11-12 21:52:27 -07001304 """
Simon Glass7057d022018-10-01 21:12:47 -06001305 self._SetupSplElf('u_boot_ucode_ptr')
Simon Glass6ba679c2018-07-06 10:27:17 -06001306 first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
1307 ucode_second=ucode_second)
Simon Glass303f62f2019-05-17 22:00:46 -06001308 self.assertEqual(b'splnodtb with microc' + pos_and_size +
1309 b'ter somewhere in here', first)
Simon Glass3d274232017-11-12 21:52:27 -07001310
Simon Glass6ba679c2018-07-06 10:27:17 -06001311 def testPackUbootSplMicrocode(self):
1312 """Test that x86 microcode can be handled correctly in SPL"""
Simon Glass511f6582018-10-01 12:22:30 -06001313 self._PackUbootSplMicrocode('049_x86_ucode_spl.dts')
Simon Glass6ba679c2018-07-06 10:27:17 -06001314
1315 def testPackUbootSplMicrocodeReorder(self):
1316 """Test that order doesn't matter for microcode entries
1317
1318 This is the same as testPackUbootSplMicrocode but when we process the
1319 u-boot-ucode entry we have not yet seen the u-boot-dtb-with-ucode
1320 entry, so we reply on binman to try later.
1321 """
Simon Glass511f6582018-10-01 12:22:30 -06001322 self._PackUbootSplMicrocode('058_x86_ucode_spl_needs_retry.dts',
Simon Glass6ba679c2018-07-06 10:27:17 -06001323 ucode_second=True)
1324
Simon Glassa409c932017-11-12 21:52:28 -07001325 def testPackMrc(self):
1326 """Test that an image with an MRC binary can be created"""
Simon Glass511f6582018-10-01 12:22:30 -06001327 data = self._DoReadFile('050_intel_mrc.dts')
Simon Glassa409c932017-11-12 21:52:28 -07001328 self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
1329
Simon Glass9aa6a6f2017-11-13 18:54:55 -07001330 def testSplDtb(self):
1331 """Test that an image with spl/u-boot-spl.dtb can be created"""
Simon Glass511f6582018-10-01 12:22:30 -06001332 data = self._DoReadFile('051_u_boot_spl_dtb.dts')
Simon Glass9aa6a6f2017-11-13 18:54:55 -07001333 self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
1334
Simon Glass0a6da312017-11-13 18:54:56 -07001335 def testSplNoDtb(self):
1336 """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
Simon Glass511f6582018-10-01 12:22:30 -06001337 data = self._DoReadFile('052_u_boot_spl_nodtb.dts')
Simon Glass0a6da312017-11-13 18:54:56 -07001338 self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
1339
Simon Glass31e04cb2021-03-18 20:24:56 +13001340 def checkSymbols(self, dts, base_data, u_boot_offset):
1341 """Check the image contains the expected symbol values
1342
1343 Args:
1344 dts: Device tree file to use for test
1345 base_data: Data before and after 'u-boot' section
1346 u_boot_offset: Offset of 'u-boot' section in image
1347 """
Simon Glass5d0c0262019-08-24 07:22:56 -06001348 elf_fname = self.ElfTestFile('u_boot_binman_syms')
Simon Glass4ca8e042017-11-13 18:55:01 -07001349 syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
1350 addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
Simon Glass31e04cb2021-03-18 20:24:56 +13001351 self.assertEqual(syms['_binman_u_boot_spl_any_prop_offset'].address,
1352 addr)
Simon Glass4ca8e042017-11-13 18:55:01 -07001353
Simon Glass7057d022018-10-01 21:12:47 -06001354 self._SetupSplElf('u_boot_binman_syms')
Simon Glass31e04cb2021-03-18 20:24:56 +13001355 data = self._DoReadFile(dts)
1356 # The image should contain the symbols from u_boot_binman_syms.c
1357 # Note that image_pos is adjusted by the base address of the image,
1358 # which is 0x10 in our test image
1359 sym_values = struct.pack('<LQLL', 0x00,
1360 u_boot_offset + len(U_BOOT_DATA),
1361 0x10 + u_boot_offset, 0x04)
1362 expected = (sym_values + base_data[20:] +
Simon Glassac0d4952019-05-14 15:53:47 -06001363 tools.GetBytes(0xff, 1) + U_BOOT_DATA + sym_values +
Simon Glass31e04cb2021-03-18 20:24:56 +13001364 base_data[20:])
Simon Glass4ca8e042017-11-13 18:55:01 -07001365 self.assertEqual(expected, data)
1366
Simon Glass31e04cb2021-03-18 20:24:56 +13001367 def testSymbols(self):
1368 """Test binman can assign symbols embedded in U-Boot"""
1369 self.checkSymbols('053_symbols.dts', U_BOOT_SPL_DATA, 0x18)
1370
1371 def testSymbolsNoDtb(self):
1372 """Test binman can assign symbols embedded in U-Boot SPL"""
1373 self.checkSymbols('192_symbols_nodtb.dts',
1374 U_BOOT_SPL_NODTB_DATA + U_BOOT_SPL_DTB_DATA,
1375 0x38)
1376
Simon Glasse76a3e62018-06-01 09:38:11 -06001377 def testPackUnitAddress(self):
1378 """Test that we support multiple binaries with the same name"""
Simon Glass511f6582018-10-01 12:22:30 -06001379 data = self._DoReadFile('054_unit_address.dts')
Simon Glasse76a3e62018-06-01 09:38:11 -06001380 self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
1381
Simon Glassa91e1152018-06-01 09:38:16 -06001382 def testSections(self):
1383 """Basic test of sections"""
Simon Glass511f6582018-10-01 12:22:30 -06001384 data = self._DoReadFile('055_sections.dts')
Simon Glass303f62f2019-05-17 22:00:46 -06001385 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
1386 U_BOOT_DATA + tools.GetBytes(ord('a'), 12) +
1387 U_BOOT_DATA + tools.GetBytes(ord('&'), 4))
Simon Glassa91e1152018-06-01 09:38:16 -06001388 self.assertEqual(expected, data)
Simon Glassac599912017-11-12 21:52:22 -07001389
Simon Glass30732662018-06-01 09:38:20 -06001390 def testMap(self):
1391 """Tests outputting a map of the images"""
Simon Glass511f6582018-10-01 12:22:30 -06001392 _, _, map_data, _ = self._DoReadFileDtb('055_sections.dts', map=True)
Simon Glass7eca7922018-07-17 13:25:49 -06001393 self.assertEqual('''ImagePos Offset Size Name
139400000000 00000000 00000028 main-section
139500000000 00000000 00000010 section@0
139600000000 00000000 00000004 u-boot
139700000010 00000010 00000010 section@1
139800000010 00000000 00000004 u-boot
139900000020 00000020 00000004 section@2
140000000020 00000000 00000004 u-boot
Simon Glass30732662018-06-01 09:38:20 -06001401''', map_data)
1402
Simon Glass3b78d532018-06-01 09:38:21 -06001403 def testNamePrefix(self):
1404 """Tests that name prefixes are used"""
Simon Glass511f6582018-10-01 12:22:30 -06001405 _, _, map_data, _ = self._DoReadFileDtb('056_name_prefix.dts', map=True)
Simon Glass7eca7922018-07-17 13:25:49 -06001406 self.assertEqual('''ImagePos Offset Size Name
140700000000 00000000 00000028 main-section
140800000000 00000000 00000010 section@0
140900000000 00000000 00000004 ro-u-boot
141000000010 00000010 00000010 section@1
141100000010 00000000 00000004 rw-u-boot
Simon Glass3b78d532018-06-01 09:38:21 -06001412''', map_data)
1413
Simon Glass6ba679c2018-07-06 10:27:17 -06001414 def testUnknownContents(self):
1415 """Test that obtaining the contents works as expected"""
1416 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001417 self._DoReadFile('057_unknown_contents.dts', True)
Simon Glass39dd2152019-07-08 14:25:47 -06001418 self.assertIn("Image '/binman': Internal error: Could not complete "
Simon Glassc585dd42020-04-17 18:09:03 -06001419 "processing of contents: remaining ["
1420 "<binman.etype._testing.Entry__testing ", str(e.exception))
Simon Glass6ba679c2018-07-06 10:27:17 -06001421
Simon Glass2e1169f2018-07-06 10:27:19 -06001422 def testBadChangeSize(self):
1423 """Test that trying to change the size of an entry fails"""
Simon Glasse61b6f62019-07-08 14:25:37 -06001424 try:
1425 state.SetAllowEntryExpansion(False)
1426 with self.assertRaises(ValueError) as e:
1427 self._DoReadFile('059_change_size.dts', True)
Simon Glass8c702fb2019-07-20 12:23:57 -06001428 self.assertIn("Node '/binman/_testing': Cannot update entry size from 2 to 3",
Simon Glasse61b6f62019-07-08 14:25:37 -06001429 str(e.exception))
1430 finally:
1431 state.SetAllowEntryExpansion(True)
Simon Glass2e1169f2018-07-06 10:27:19 -06001432
Simon Glassa87014e2018-07-06 10:27:42 -06001433 def testUpdateFdt(self):
Simon Glasse8561af2018-08-01 15:22:37 -06001434 """Test that we can update the device tree with offset/size info"""
Simon Glass511f6582018-10-01 12:22:30 -06001435 _, _, _, out_dtb_fname = self._DoReadFileDtb('060_fdt_update.dts',
Simon Glassa87014e2018-07-06 10:27:42 -06001436 update_dtb=True)
Simon Glass5463a6a2018-07-17 13:25:52 -06001437 dtb = fdt.Fdt(out_dtb_fname)
1438 dtb.Scan()
Simon Glassfb30e292019-07-20 12:23:51 -06001439 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS)
Simon Glassa87014e2018-07-06 10:27:42 -06001440 self.assertEqual({
Simon Glass9dcc8612018-08-01 15:22:42 -06001441 'image-pos': 0,
Simon Glass3a9a2b82018-07-17 13:25:28 -06001442 'offset': 0,
Simon Glasse8561af2018-08-01 15:22:37 -06001443 '_testing:offset': 32,
Simon Glass8c702fb2019-07-20 12:23:57 -06001444 '_testing:size': 2,
Simon Glass9dcc8612018-08-01 15:22:42 -06001445 '_testing:image-pos': 32,
Simon Glasse8561af2018-08-01 15:22:37 -06001446 'section@0/u-boot:offset': 0,
Simon Glassa87014e2018-07-06 10:27:42 -06001447 'section@0/u-boot:size': len(U_BOOT_DATA),
Simon Glass9dcc8612018-08-01 15:22:42 -06001448 'section@0/u-boot:image-pos': 0,
Simon Glasse8561af2018-08-01 15:22:37 -06001449 'section@0:offset': 0,
Simon Glassa87014e2018-07-06 10:27:42 -06001450 'section@0:size': 16,
Simon Glass9dcc8612018-08-01 15:22:42 -06001451 'section@0:image-pos': 0,
Simon Glassa87014e2018-07-06 10:27:42 -06001452
Simon Glasse8561af2018-08-01 15:22:37 -06001453 'section@1/u-boot:offset': 0,
Simon Glassa87014e2018-07-06 10:27:42 -06001454 'section@1/u-boot:size': len(U_BOOT_DATA),
Simon Glass9dcc8612018-08-01 15:22:42 -06001455 'section@1/u-boot:image-pos': 16,
Simon Glasse8561af2018-08-01 15:22:37 -06001456 'section@1:offset': 16,
Simon Glassa87014e2018-07-06 10:27:42 -06001457 'section@1:size': 16,
Simon Glass9dcc8612018-08-01 15:22:42 -06001458 'section@1:image-pos': 16,
Simon Glassa87014e2018-07-06 10:27:42 -06001459 'size': 40
1460 }, props)
1461
1462 def testUpdateFdtBad(self):
1463 """Test that we detect when ProcessFdt never completes"""
1464 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001465 self._DoReadFileDtb('061_fdt_update_bad.dts', update_dtb=True)
Simon Glassa87014e2018-07-06 10:27:42 -06001466 self.assertIn('Could not complete processing of Fdt: remaining '
Simon Glassc585dd42020-04-17 18:09:03 -06001467 '[<binman.etype._testing.Entry__testing',
1468 str(e.exception))
Simon Glass2e1169f2018-07-06 10:27:19 -06001469
Simon Glass91710b32018-07-17 13:25:32 -06001470 def testEntryArgs(self):
1471 """Test passing arguments to entries from the command line"""
1472 entry_args = {
1473 'test-str-arg': 'test1',
1474 'test-int-arg': '456',
1475 }
Simon Glass511f6582018-10-01 12:22:30 -06001476 self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
Simon Glass91710b32018-07-17 13:25:32 -06001477 self.assertIn('image', control.images)
1478 entry = control.images['image'].GetEntries()['_testing']
1479 self.assertEqual('test0', entry.test_str_fdt)
1480 self.assertEqual('test1', entry.test_str_arg)
1481 self.assertEqual(123, entry.test_int_fdt)
1482 self.assertEqual(456, entry.test_int_arg)
1483
1484 def testEntryArgsMissing(self):
1485 """Test missing arguments and properties"""
1486 entry_args = {
1487 'test-int-arg': '456',
1488 }
Simon Glass511f6582018-10-01 12:22:30 -06001489 self._DoReadFileDtb('063_entry_args_missing.dts', entry_args=entry_args)
Simon Glass91710b32018-07-17 13:25:32 -06001490 entry = control.images['image'].GetEntries()['_testing']
1491 self.assertEqual('test0', entry.test_str_fdt)
1492 self.assertEqual(None, entry.test_str_arg)
1493 self.assertEqual(None, entry.test_int_fdt)
1494 self.assertEqual(456, entry.test_int_arg)
1495
1496 def testEntryArgsRequired(self):
1497 """Test missing arguments and properties"""
1498 entry_args = {
1499 'test-int-arg': '456',
1500 }
1501 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001502 self._DoReadFileDtb('064_entry_args_required.dts')
Simon Glass21db0ff2020-09-01 05:13:54 -06001503 self.assertIn("Node '/binman/_testing': "
1504 'Missing required properties/entry args: test-str-arg, '
1505 'test-int-fdt, test-int-arg',
Simon Glass91710b32018-07-17 13:25:32 -06001506 str(e.exception))
1507
1508 def testEntryArgsInvalidFormat(self):
1509 """Test that an invalid entry-argument format is detected"""
Simon Glassf46732a2019-07-08 14:25:29 -06001510 args = ['build', '-d', self.TestFile('064_entry_args_required.dts'),
1511 '-ano-value']
Simon Glass91710b32018-07-17 13:25:32 -06001512 with self.assertRaises(ValueError) as e:
1513 self._DoBinman(*args)
1514 self.assertIn("Invalid entry arguemnt 'no-value'", str(e.exception))
1515
1516 def testEntryArgsInvalidInteger(self):
1517 """Test that an invalid entry-argument integer is detected"""
1518 entry_args = {
1519 'test-int-arg': 'abc',
1520 }
1521 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001522 self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
Simon Glass91710b32018-07-17 13:25:32 -06001523 self.assertIn("Node '/binman/_testing': Cannot convert entry arg "
1524 "'test-int-arg' (value 'abc') to integer",
1525 str(e.exception))
1526
1527 def testEntryArgsInvalidDatatype(self):
1528 """Test that an invalid entry-argument datatype is detected
1529
1530 This test could be written in entry_test.py except that it needs
1531 access to control.entry_args, which seems more than that module should
1532 be able to see.
1533 """
1534 entry_args = {
1535 'test-bad-datatype-arg': '12',
1536 }
1537 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001538 self._DoReadFileDtb('065_entry_args_unknown_datatype.dts',
Simon Glass91710b32018-07-17 13:25:32 -06001539 entry_args=entry_args)
1540 self.assertIn('GetArg() internal error: Unknown data type ',
1541 str(e.exception))
1542
Simon Glass2ca52032018-07-17 13:25:33 -06001543 def testText(self):
1544 """Test for a text entry type"""
1545 entry_args = {
1546 'test-id': TEXT_DATA,
1547 'test-id2': TEXT_DATA2,
1548 'test-id3': TEXT_DATA3,
1549 }
Simon Glass511f6582018-10-01 12:22:30 -06001550 data, _, _, _ = self._DoReadFileDtb('066_text.dts',
Simon Glass2ca52032018-07-17 13:25:33 -06001551 entry_args=entry_args)
Simon Glass303f62f2019-05-17 22:00:46 -06001552 expected = (tools.ToBytes(TEXT_DATA) +
1553 tools.GetBytes(0, 8 - len(TEXT_DATA)) +
1554 tools.ToBytes(TEXT_DATA2) + tools.ToBytes(TEXT_DATA3) +
Simon Glass47f6a622019-07-08 13:18:40 -06001555 b'some text' + b'more text')
Simon Glass2ca52032018-07-17 13:25:33 -06001556 self.assertEqual(expected, data)
1557
Simon Glass969616c2018-07-17 13:25:36 -06001558 def testEntryDocs(self):
1559 """Test for creation of entry documentation"""
1560 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass220ff5f2020-08-05 13:27:46 -06001561 control.WriteEntryDocs(control.GetEntryModules())
Simon Glass969616c2018-07-17 13:25:36 -06001562 self.assertTrue(len(stdout.getvalue()) > 0)
1563
1564 def testEntryDocsMissing(self):
1565 """Test handling of missing entry documentation"""
1566 with self.assertRaises(ValueError) as e:
1567 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass220ff5f2020-08-05 13:27:46 -06001568 control.WriteEntryDocs(control.GetEntryModules(), 'u_boot')
Simon Glass969616c2018-07-17 13:25:36 -06001569 self.assertIn('Documentation is missing for modules: u_boot',
1570 str(e.exception))
1571
Simon Glass704784b2018-07-17 13:25:38 -06001572 def testFmap(self):
1573 """Basic test of generation of a flashrom fmap"""
Simon Glass511f6582018-10-01 12:22:30 -06001574 data = self._DoReadFile('067_fmap.dts')
Simon Glass704784b2018-07-17 13:25:38 -06001575 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
Simon Glass303f62f2019-05-17 22:00:46 -06001576 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
1577 U_BOOT_DATA + tools.GetBytes(ord('a'), 12))
Simon Glass704784b2018-07-17 13:25:38 -06001578 self.assertEqual(expected, data[:32])
Simon Glass303f62f2019-05-17 22:00:46 -06001579 self.assertEqual(b'__FMAP__', fhdr.signature)
Simon Glass704784b2018-07-17 13:25:38 -06001580 self.assertEqual(1, fhdr.ver_major)
1581 self.assertEqual(0, fhdr.ver_minor)
1582 self.assertEqual(0, fhdr.base)
1583 self.assertEqual(16 + 16 +
1584 fmap_util.FMAP_HEADER_LEN +
1585 fmap_util.FMAP_AREA_LEN * 3, fhdr.image_size)
Simon Glass303f62f2019-05-17 22:00:46 -06001586 self.assertEqual(b'FMAP', fhdr.name)
Simon Glass704784b2018-07-17 13:25:38 -06001587 self.assertEqual(3, fhdr.nareas)
1588 for fentry in fentries:
1589 self.assertEqual(0, fentry.flags)
1590
1591 self.assertEqual(0, fentries[0].offset)
1592 self.assertEqual(4, fentries[0].size)
Simon Glass303f62f2019-05-17 22:00:46 -06001593 self.assertEqual(b'RO_U_BOOT', fentries[0].name)
Simon Glass704784b2018-07-17 13:25:38 -06001594
1595 self.assertEqual(16, fentries[1].offset)
1596 self.assertEqual(4, fentries[1].size)
Simon Glass303f62f2019-05-17 22:00:46 -06001597 self.assertEqual(b'RW_U_BOOT', fentries[1].name)
Simon Glass704784b2018-07-17 13:25:38 -06001598
1599 self.assertEqual(32, fentries[2].offset)
1600 self.assertEqual(fmap_util.FMAP_HEADER_LEN +
1601 fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
Simon Glass303f62f2019-05-17 22:00:46 -06001602 self.assertEqual(b'FMAP', fentries[2].name)
Simon Glass704784b2018-07-17 13:25:38 -06001603
Simon Glassdb168d42018-07-17 13:25:39 -06001604 def testBlobNamedByArg(self):
1605 """Test we can add a blob with the filename coming from an entry arg"""
1606 entry_args = {
1607 'cros-ec-rw-path': 'ecrw.bin',
1608 }
Simon Glass21db0ff2020-09-01 05:13:54 -06001609 self._DoReadFileDtb('068_blob_named_by_arg.dts', entry_args=entry_args)
Simon Glassdb168d42018-07-17 13:25:39 -06001610
Simon Glass53f53992018-07-17 13:25:40 -06001611 def testFill(self):
1612 """Test for an fill entry type"""
Simon Glass511f6582018-10-01 12:22:30 -06001613 data = self._DoReadFile('069_fill.dts')
Simon Glassac0d4952019-05-14 15:53:47 -06001614 expected = tools.GetBytes(0xff, 8) + tools.GetBytes(0, 8)
Simon Glass53f53992018-07-17 13:25:40 -06001615 self.assertEqual(expected, data)
1616
1617 def testFillNoSize(self):
1618 """Test for an fill entry type with no size"""
1619 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001620 self._DoReadFile('070_fill_no_size.dts')
Simon Glass53f53992018-07-17 13:25:40 -06001621 self.assertIn("'fill' entry must have a size property",
1622 str(e.exception))
1623
Simon Glassc1ae83c2018-07-17 13:25:44 -06001624 def _HandleGbbCommand(self, pipe_list):
1625 """Fake calls to the futility utility"""
1626 if pipe_list[0][0] == 'futility':
1627 fname = pipe_list[0][-1]
1628 # Append our GBB data to the file, which will happen every time the
1629 # futility command is called.
Simon Glass33486662019-05-14 15:53:42 -06001630 with open(fname, 'ab') as fd:
Simon Glassc1ae83c2018-07-17 13:25:44 -06001631 fd.write(GBB_DATA)
1632 return command.CommandResult()
1633
1634 def testGbb(self):
1635 """Test for the Chromium OS Google Binary Block"""
1636 command.test_result = self._HandleGbbCommand
1637 entry_args = {
1638 'keydir': 'devkeys',
1639 'bmpblk': 'bmpblk.bin',
1640 }
Simon Glass511f6582018-10-01 12:22:30 -06001641 data, _, _, _ = self._DoReadFileDtb('071_gbb.dts', entry_args=entry_args)
Simon Glassc1ae83c2018-07-17 13:25:44 -06001642
1643 # Since futility
Simon Glassac0d4952019-05-14 15:53:47 -06001644 expected = (GBB_DATA + GBB_DATA + tools.GetBytes(0, 8) +
1645 tools.GetBytes(0, 0x2180 - 16))
Simon Glassc1ae83c2018-07-17 13:25:44 -06001646 self.assertEqual(expected, data)
1647
1648 def testGbbTooSmall(self):
1649 """Test for the Chromium OS Google Binary Block being large enough"""
1650 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001651 self._DoReadFileDtb('072_gbb_too_small.dts')
Simon Glassc1ae83c2018-07-17 13:25:44 -06001652 self.assertIn("Node '/binman/gbb': GBB is too small",
1653 str(e.exception))
1654
1655 def testGbbNoSize(self):
1656 """Test for the Chromium OS Google Binary Block having a size"""
1657 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001658 self._DoReadFileDtb('073_gbb_no_size.dts')
Simon Glassc1ae83c2018-07-17 13:25:44 -06001659 self.assertIn("Node '/binman/gbb': GBB must have a fixed size",
1660 str(e.exception))
1661
Simon Glass5c350162018-07-17 13:25:47 -06001662 def _HandleVblockCommand(self, pipe_list):
Simon Glass220c6222021-01-06 21:35:17 -07001663 """Fake calls to the futility utility
1664
1665 The expected pipe is:
1666
1667 [('futility', 'vbutil_firmware', '--vblock',
1668 'vblock.vblock', '--keyblock', 'devkeys/firmware.keyblock',
1669 '--signprivate', 'devkeys/firmware_data_key.vbprivk',
1670 '--version', '1', '--fv', 'input.vblock', '--kernelkey',
1671 'devkeys/kernel_subkey.vbpubk', '--flags', '1')]
1672
1673 This writes to the output file (here, 'vblock.vblock'). If
1674 self._hash_data is False, it writes VBLOCK_DATA, else it writes a hash
1675 of the input data (here, 'input.vblock').
1676 """
Simon Glass5c350162018-07-17 13:25:47 -06001677 if pipe_list[0][0] == 'futility':
1678 fname = pipe_list[0][3]
Simon Glass639505b2018-09-14 04:57:11 -06001679 with open(fname, 'wb') as fd:
Simon Glass220c6222021-01-06 21:35:17 -07001680 if self._hash_data:
1681 infile = pipe_list[0][11]
1682 m = hashlib.sha256()
1683 data = tools.ReadFile(infile)
1684 m.update(data)
1685 fd.write(m.digest())
1686 else:
1687 fd.write(VBLOCK_DATA)
1688
Simon Glass5c350162018-07-17 13:25:47 -06001689 return command.CommandResult()
1690
1691 def testVblock(self):
1692 """Test for the Chromium OS Verified Boot Block"""
Simon Glass220c6222021-01-06 21:35:17 -07001693 self._hash_data = False
Simon Glass5c350162018-07-17 13:25:47 -06001694 command.test_result = self._HandleVblockCommand
1695 entry_args = {
1696 'keydir': 'devkeys',
1697 }
Simon Glass511f6582018-10-01 12:22:30 -06001698 data, _, _, _ = self._DoReadFileDtb('074_vblock.dts',
Simon Glass5c350162018-07-17 13:25:47 -06001699 entry_args=entry_args)
1700 expected = U_BOOT_DATA + VBLOCK_DATA + U_BOOT_DTB_DATA
1701 self.assertEqual(expected, data)
1702
1703 def testVblockNoContent(self):
1704 """Test we detect a vblock which has no content to sign"""
1705 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001706 self._DoReadFile('075_vblock_no_content.dts')
Simon Glass5c350162018-07-17 13:25:47 -06001707 self.assertIn("Node '/binman/vblock': Vblock must have a 'content' "
1708 'property', str(e.exception))
1709
1710 def testVblockBadPhandle(self):
1711 """Test that we detect a vblock with an invalid phandle in contents"""
1712 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001713 self._DoReadFile('076_vblock_bad_phandle.dts')
Simon Glass5c350162018-07-17 13:25:47 -06001714 self.assertIn("Node '/binman/vblock': Cannot find node for phandle "
1715 '1000', str(e.exception))
1716
1717 def testVblockBadEntry(self):
1718 """Test that we detect an entry that points to a non-entry"""
1719 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001720 self._DoReadFile('077_vblock_bad_entry.dts')
Simon Glass5c350162018-07-17 13:25:47 -06001721 self.assertIn("Node '/binman/vblock': Cannot find entry for node "
1722 "'other'", str(e.exception))
1723
Simon Glass220c6222021-01-06 21:35:17 -07001724 def testVblockContent(self):
1725 """Test that the vblock signs the right data"""
1726 self._hash_data = True
1727 command.test_result = self._HandleVblockCommand
1728 entry_args = {
1729 'keydir': 'devkeys',
1730 }
1731 data = self._DoReadFileDtb(
1732 '189_vblock_content.dts', use_real_dtb=True, update_dtb=True,
1733 entry_args=entry_args)[0]
1734 hashlen = 32 # SHA256 hash is 32 bytes
1735 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
1736 hashval = data[-hashlen:]
1737 dtb = data[len(U_BOOT_DATA):-hashlen]
1738
1739 expected_data = U_BOOT_DATA + dtb
1740
1741 # The hashval should be a hash of the dtb
1742 m = hashlib.sha256()
1743 m.update(expected_data)
1744 expected_hashval = m.digest()
1745 self.assertEqual(expected_hashval, hashval)
1746
Simon Glass8425a1f2018-07-17 13:25:48 -06001747 def testTpl(self):
Simon Glass3eb5b202019-08-24 07:23:00 -06001748 """Test that an image with TPL and its device tree can be created"""
Simon Glass8425a1f2018-07-17 13:25:48 -06001749 # ELF file with a '__bss_size' symbol
Simon Glass3eb5b202019-08-24 07:23:00 -06001750 self._SetupTplElf()
Simon Glass511f6582018-10-01 12:22:30 -06001751 data = self._DoReadFile('078_u_boot_tpl.dts')
Simon Glass8425a1f2018-07-17 13:25:48 -06001752 self.assertEqual(U_BOOT_TPL_DATA + U_BOOT_TPL_DTB_DATA, data)
1753
Simon Glass24b97442018-07-17 13:25:51 -06001754 def testUsesPos(self):
1755 """Test that the 'pos' property cannot be used anymore"""
1756 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001757 data = self._DoReadFile('079_uses_pos.dts')
Simon Glass24b97442018-07-17 13:25:51 -06001758 self.assertIn("Node '/binman/u-boot': Please use 'offset' instead of "
1759 "'pos'", str(e.exception))
1760
Simon Glass274bf092018-09-14 04:57:08 -06001761 def testFillZero(self):
1762 """Test for an fill entry type with a size of 0"""
Simon Glass511f6582018-10-01 12:22:30 -06001763 data = self._DoReadFile('080_fill_empty.dts')
Simon Glassac0d4952019-05-14 15:53:47 -06001764 self.assertEqual(tools.GetBytes(0, 16), data)
Simon Glass274bf092018-09-14 04:57:08 -06001765
Simon Glass267de432018-09-14 04:57:09 -06001766 def testTextMissing(self):
1767 """Test for a text entry type where there is no text"""
1768 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001769 self._DoReadFileDtb('066_text.dts',)
Simon Glass267de432018-09-14 04:57:09 -06001770 self.assertIn("Node '/binman/text': No value provided for text label "
1771 "'test-id'", str(e.exception))
1772
Simon Glassed40e962018-09-14 04:57:10 -06001773 def testPackStart16Tpl(self):
1774 """Test that an image with an x86 start16 TPL region can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001775 data = self._DoReadFile('081_x86_start16_tpl.dts')
Simon Glassed40e962018-09-14 04:57:10 -06001776 self.assertEqual(X86_START16_TPL_DATA, data[:len(X86_START16_TPL_DATA)])
1777
Simon Glass3b376c32018-09-14 04:57:12 -06001778 def testSelectImage(self):
1779 """Test that we can select which images to build"""
Simon Glassb4595d82019-04-25 21:58:34 -06001780 expected = 'Skipping images: image1'
1781
1782 # We should only get the expected message in verbose mode
Simon Glass8a50b4a2019-07-08 13:18:48 -06001783 for verbosity in (0, 2):
Simon Glassb4595d82019-04-25 21:58:34 -06001784 with test_util.capture_sys_output() as (stdout, stderr):
1785 retcode = self._DoTestFile('006_dual_image.dts',
1786 verbosity=verbosity,
1787 images=['image2'])
1788 self.assertEqual(0, retcode)
1789 if verbosity:
1790 self.assertIn(expected, stdout.getvalue())
1791 else:
1792 self.assertNotIn(expected, stdout.getvalue())
Simon Glass3b376c32018-09-14 04:57:12 -06001793
Simon Glassb4595d82019-04-25 21:58:34 -06001794 self.assertFalse(os.path.exists(tools.GetOutputFilename('image1.bin')))
1795 self.assertTrue(os.path.exists(tools.GetOutputFilename('image2.bin')))
Simon Glassb3d6fc72019-07-20 12:24:10 -06001796 self._CleanupOutputDir()
Simon Glass3b376c32018-09-14 04:57:12 -06001797
Simon Glasse219aa42018-09-14 04:57:24 -06001798 def testUpdateFdtAll(self):
1799 """Test that all device trees are updated with offset/size info"""
Simon Glass5b4bce32019-07-08 14:25:26 -06001800 data = self._DoReadFileRealDtb('082_fdt_update_all.dts')
Simon Glasse219aa42018-09-14 04:57:24 -06001801
1802 base_expected = {
1803 'section:image-pos': 0,
1804 'u-boot-tpl-dtb:size': 513,
1805 'u-boot-spl-dtb:size': 513,
1806 'u-boot-spl-dtb:offset': 493,
1807 'image-pos': 0,
1808 'section/u-boot-dtb:image-pos': 0,
1809 'u-boot-spl-dtb:image-pos': 493,
1810 'section/u-boot-dtb:size': 493,
1811 'u-boot-tpl-dtb:image-pos': 1006,
1812 'section/u-boot-dtb:offset': 0,
1813 'section:size': 493,
1814 'offset': 0,
1815 'section:offset': 0,
1816 'u-boot-tpl-dtb:offset': 1006,
1817 'size': 1519
1818 }
1819
1820 # We expect three device-tree files in the output, one after the other.
1821 # Read them in sequence. We look for an 'spl' property in the SPL tree,
1822 # and 'tpl' in the TPL tree, to make sure they are distinct from the
1823 # main U-Boot tree. All three should have the same postions and offset.
1824 start = 0
1825 for item in ['', 'spl', 'tpl']:
1826 dtb = fdt.Fdt.FromData(data[start:])
1827 dtb.Scan()
Simon Glassfb30e292019-07-20 12:23:51 -06001828 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS +
1829 ['spl', 'tpl'])
Simon Glasse219aa42018-09-14 04:57:24 -06001830 expected = dict(base_expected)
1831 if item:
1832 expected[item] = 0
1833 self.assertEqual(expected, props)
1834 start += dtb._fdt_obj.totalsize()
1835
1836 def testUpdateFdtOutput(self):
1837 """Test that output DTB files are updated"""
1838 try:
Simon Glass511f6582018-10-01 12:22:30 -06001839 data, dtb_data, _, _ = self._DoReadFileDtb('082_fdt_update_all.dts',
Simon Glasse219aa42018-09-14 04:57:24 -06001840 use_real_dtb=True, update_dtb=True, reset_dtbs=False)
1841
1842 # Unfortunately, compiling a source file always results in a file
1843 # called source.dtb (see fdt_util.EnsureCompiled()). The test
Simon Glass511f6582018-10-01 12:22:30 -06001844 # source file (e.g. test/075_fdt_update_all.dts) thus does not enter
Simon Glasse219aa42018-09-14 04:57:24 -06001845 # binman as a file called u-boot.dtb. To fix this, copy the file
1846 # over to the expected place.
Simon Glasse219aa42018-09-14 04:57:24 -06001847 start = 0
1848 for fname in ['u-boot.dtb.out', 'spl/u-boot-spl.dtb.out',
1849 'tpl/u-boot-tpl.dtb.out']:
1850 dtb = fdt.Fdt.FromData(data[start:])
1851 size = dtb._fdt_obj.totalsize()
1852 pathname = tools.GetOutputFilename(os.path.split(fname)[1])
1853 outdata = tools.ReadFile(pathname)
1854 name = os.path.split(fname)[0]
1855
1856 if name:
1857 orig_indata = self._GetDtbContentsForSplTpl(dtb_data, name)
1858 else:
1859 orig_indata = dtb_data
1860 self.assertNotEqual(outdata, orig_indata,
1861 "Expected output file '%s' be updated" % pathname)
1862 self.assertEqual(outdata, data[start:start + size],
1863 "Expected output file '%s' to match output image" %
1864 pathname)
1865 start += size
1866 finally:
1867 self._ResetDtbs()
1868
Simon Glass7ba33592018-09-14 04:57:26 -06001869 def _decompress(self, data):
Simon Glassccec0262019-07-08 13:18:42 -06001870 return tools.Decompress(data, 'lz4')
Simon Glass7ba33592018-09-14 04:57:26 -06001871
1872 def testCompress(self):
1873 """Test compression of blobs"""
Simon Glass1de34482019-07-08 13:18:53 -06001874 self._CheckLz4()
Simon Glass511f6582018-10-01 12:22:30 -06001875 data, _, _, out_dtb_fname = self._DoReadFileDtb('083_compress.dts',
Simon Glass7ba33592018-09-14 04:57:26 -06001876 use_real_dtb=True, update_dtb=True)
1877 dtb = fdt.Fdt(out_dtb_fname)
1878 dtb.Scan()
1879 props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
1880 orig = self._decompress(data)
1881 self.assertEquals(COMPRESS_DATA, orig)
Simon Glass789b34402020-10-26 17:40:15 -06001882
1883 # Do a sanity check on various fields
1884 image = control.images['image']
1885 entries = image.GetEntries()
1886 self.assertEqual(1, len(entries))
1887
1888 entry = entries['blob']
1889 self.assertEqual(COMPRESS_DATA, entry.uncomp_data)
1890 self.assertEqual(len(COMPRESS_DATA), entry.uncomp_size)
1891 orig = self._decompress(entry.data)
1892 self.assertEqual(orig, entry.uncomp_data)
1893
Simon Glass72eeff12020-10-26 17:40:16 -06001894 self.assertEqual(image.data, entry.data)
1895
Simon Glass7ba33592018-09-14 04:57:26 -06001896 expected = {
1897 'blob:uncomp-size': len(COMPRESS_DATA),
1898 'blob:size': len(data),
1899 'size': len(data),
1900 }
1901 self.assertEqual(expected, props)
1902
Simon Glassac6328c2018-09-14 04:57:28 -06001903 def testFiles(self):
1904 """Test bringing in multiple files"""
Simon Glass511f6582018-10-01 12:22:30 -06001905 data = self._DoReadFile('084_files.dts')
Simon Glassac6328c2018-09-14 04:57:28 -06001906 self.assertEqual(FILES_DATA, data)
1907
1908 def testFilesCompress(self):
1909 """Test bringing in multiple files and compressing them"""
Simon Glass1de34482019-07-08 13:18:53 -06001910 self._CheckLz4()
Simon Glass511f6582018-10-01 12:22:30 -06001911 data = self._DoReadFile('085_files_compress.dts')
Simon Glassac6328c2018-09-14 04:57:28 -06001912
1913 image = control.images['image']
1914 entries = image.GetEntries()
1915 files = entries['files']
Simon Glass39dd2152019-07-08 14:25:47 -06001916 entries = files._entries
Simon Glassac6328c2018-09-14 04:57:28 -06001917
Simon Glass303f62f2019-05-17 22:00:46 -06001918 orig = b''
Simon Glassac6328c2018-09-14 04:57:28 -06001919 for i in range(1, 3):
1920 key = '%d.dat' % i
1921 start = entries[key].image_pos
1922 len = entries[key].size
1923 chunk = data[start:start + len]
1924 orig += self._decompress(chunk)
1925
1926 self.assertEqual(FILES_DATA, orig)
1927
1928 def testFilesMissing(self):
1929 """Test missing files"""
1930 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001931 data = self._DoReadFile('086_files_none.dts')
Simon Glassac6328c2018-09-14 04:57:28 -06001932 self.assertIn("Node '/binman/files': Pattern \'files/*.none\' matched "
1933 'no files', str(e.exception))
1934
1935 def testFilesNoPattern(self):
1936 """Test missing files"""
1937 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001938 data = self._DoReadFile('087_files_no_pattern.dts')
Simon Glassac6328c2018-09-14 04:57:28 -06001939 self.assertIn("Node '/binman/files': Missing 'pattern' property",
1940 str(e.exception))
1941
Simon Glassfa79a812018-09-14 04:57:29 -06001942 def testExpandSize(self):
1943 """Test an expanding entry"""
Simon Glass511f6582018-10-01 12:22:30 -06001944 data, _, map_data, _ = self._DoReadFileDtb('088_expand_size.dts',
Simon Glassfa79a812018-09-14 04:57:29 -06001945 map=True)
Simon Glass303f62f2019-05-17 22:00:46 -06001946 expect = (tools.GetBytes(ord('a'), 8) + U_BOOT_DATA +
1947 MRC_DATA + tools.GetBytes(ord('b'), 1) + U_BOOT_DATA +
1948 tools.GetBytes(ord('c'), 8) + U_BOOT_DATA +
1949 tools.GetBytes(ord('d'), 8))
Simon Glassfa79a812018-09-14 04:57:29 -06001950 self.assertEqual(expect, data)
1951 self.assertEqual('''ImagePos Offset Size Name
195200000000 00000000 00000028 main-section
195300000000 00000000 00000008 fill
195400000008 00000008 00000004 u-boot
19550000000c 0000000c 00000004 section
19560000000c 00000000 00000003 intel-mrc
195700000010 00000010 00000004 u-boot2
195800000014 00000014 0000000c section2
195900000014 00000000 00000008 fill
19600000001c 00000008 00000004 u-boot
196100000020 00000020 00000008 fill2
1962''', map_data)
1963
1964 def testExpandSizeBad(self):
1965 """Test an expanding entry which fails to provide contents"""
Simon Glasscd817d52018-09-14 04:57:36 -06001966 with test_util.capture_sys_output() as (stdout, stderr):
1967 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001968 self._DoReadFileDtb('089_expand_size_bad.dts', map=True)
Simon Glassfa79a812018-09-14 04:57:29 -06001969 self.assertIn("Node '/binman/_testing': Cannot obtain contents when "
1970 'expanding entry', str(e.exception))
1971
Simon Glassae7cf032018-09-14 04:57:31 -06001972 def testHash(self):
1973 """Test hashing of the contents of an entry"""
Simon Glass511f6582018-10-01 12:22:30 -06001974 _, _, _, out_dtb_fname = self._DoReadFileDtb('090_hash.dts',
Simon Glassae7cf032018-09-14 04:57:31 -06001975 use_real_dtb=True, update_dtb=True)
1976 dtb = fdt.Fdt(out_dtb_fname)
1977 dtb.Scan()
1978 hash_node = dtb.GetNode('/binman/u-boot/hash').props['value']
1979 m = hashlib.sha256()
1980 m.update(U_BOOT_DATA)
Simon Glass303f62f2019-05-17 22:00:46 -06001981 self.assertEqual(m.digest(), b''.join(hash_node.value))
Simon Glassae7cf032018-09-14 04:57:31 -06001982
1983 def testHashNoAlgo(self):
1984 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001985 self._DoReadFileDtb('091_hash_no_algo.dts', update_dtb=True)
Simon Glassae7cf032018-09-14 04:57:31 -06001986 self.assertIn("Node \'/binman/u-boot\': Missing \'algo\' property for "
1987 'hash node', str(e.exception))
1988
1989 def testHashBadAlgo(self):
1990 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001991 self._DoReadFileDtb('092_hash_bad_algo.dts', update_dtb=True)
Simon Glassae7cf032018-09-14 04:57:31 -06001992 self.assertIn("Node '/binman/u-boot': Unknown hash algorithm",
1993 str(e.exception))
1994
1995 def testHashSection(self):
1996 """Test hashing of the contents of an entry"""
Simon Glass511f6582018-10-01 12:22:30 -06001997 _, _, _, out_dtb_fname = self._DoReadFileDtb('099_hash_section.dts',
Simon Glassae7cf032018-09-14 04:57:31 -06001998 use_real_dtb=True, update_dtb=True)
1999 dtb = fdt.Fdt(out_dtb_fname)
2000 dtb.Scan()
2001 hash_node = dtb.GetNode('/binman/section/hash').props['value']
2002 m = hashlib.sha256()
2003 m.update(U_BOOT_DATA)
Simon Glass303f62f2019-05-17 22:00:46 -06002004 m.update(tools.GetBytes(ord('a'), 16))
2005 self.assertEqual(m.digest(), b''.join(hash_node.value))
Simon Glassae7cf032018-09-14 04:57:31 -06002006
Simon Glass3fb4f422018-09-14 04:57:32 -06002007 def testPackUBootTplMicrocode(self):
2008 """Test that x86 microcode can be handled correctly in TPL
2009
2010 We expect to see the following in the image, in order:
2011 u-boot-tpl-nodtb.bin with a microcode pointer inserted at the correct
2012 place
2013 u-boot-tpl.dtb with the microcode removed
2014 the microcode
2015 """
Simon Glass3eb5b202019-08-24 07:23:00 -06002016 self._SetupTplElf('u_boot_ucode_ptr')
Simon Glass511f6582018-10-01 12:22:30 -06002017 first, pos_and_size = self._RunMicrocodeTest('093_x86_tpl_ucode.dts',
Simon Glass3fb4f422018-09-14 04:57:32 -06002018 U_BOOT_TPL_NODTB_DATA)
Simon Glass303f62f2019-05-17 22:00:46 -06002019 self.assertEqual(b'tplnodtb with microc' + pos_and_size +
2020 b'ter somewhere in here', first)
Simon Glass3fb4f422018-09-14 04:57:32 -06002021
Simon Glassc64aea52018-09-14 04:57:34 -06002022 def testFmapX86(self):
2023 """Basic test of generation of a flashrom fmap"""
Simon Glass511f6582018-10-01 12:22:30 -06002024 data = self._DoReadFile('094_fmap_x86.dts')
Simon Glassc64aea52018-09-14 04:57:34 -06002025 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
Simon Glass303f62f2019-05-17 22:00:46 -06002026 expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('a'), 32 - 7)
Simon Glassc64aea52018-09-14 04:57:34 -06002027 self.assertEqual(expected, data[:32])
2028 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
2029
2030 self.assertEqual(0x100, fhdr.image_size)
2031
2032 self.assertEqual(0, fentries[0].offset)
2033 self.assertEqual(4, fentries[0].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002034 self.assertEqual(b'U_BOOT', fentries[0].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002035
2036 self.assertEqual(4, fentries[1].offset)
2037 self.assertEqual(3, fentries[1].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002038 self.assertEqual(b'INTEL_MRC', fentries[1].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002039
2040 self.assertEqual(32, fentries[2].offset)
2041 self.assertEqual(fmap_util.FMAP_HEADER_LEN +
2042 fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002043 self.assertEqual(b'FMAP', fentries[2].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002044
2045 def testFmapX86Section(self):
2046 """Basic test of generation of a flashrom fmap"""
Simon Glass511f6582018-10-01 12:22:30 -06002047 data = self._DoReadFile('095_fmap_x86_section.dts')
Simon Glass303f62f2019-05-17 22:00:46 -06002048 expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('b'), 32 - 7)
Simon Glassc64aea52018-09-14 04:57:34 -06002049 self.assertEqual(expected, data[:32])
2050 fhdr, fentries = fmap_util.DecodeFmap(data[36:])
2051
2052 self.assertEqual(0x100, fhdr.image_size)
2053
2054 self.assertEqual(0, fentries[0].offset)
2055 self.assertEqual(4, fentries[0].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002056 self.assertEqual(b'U_BOOT', fentries[0].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002057
2058 self.assertEqual(4, fentries[1].offset)
2059 self.assertEqual(3, fentries[1].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002060 self.assertEqual(b'INTEL_MRC', fentries[1].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002061
2062 self.assertEqual(36, fentries[2].offset)
2063 self.assertEqual(fmap_util.FMAP_HEADER_LEN +
2064 fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002065 self.assertEqual(b'FMAP', fentries[2].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002066
Simon Glassb1714232018-09-14 04:57:35 -06002067 def testElf(self):
2068 """Basic test of ELF entries"""
Simon Glass7057d022018-10-01 21:12:47 -06002069 self._SetupSplElf()
Simon Glass3eb5b202019-08-24 07:23:00 -06002070 self._SetupTplElf()
Simon Glassf6290892019-08-24 07:22:53 -06002071 with open(self.ElfTestFile('bss_data'), 'rb') as fd:
Simon Glassb1714232018-09-14 04:57:35 -06002072 TestFunctional._MakeInputFile('-boot', fd.read())
Simon Glass511f6582018-10-01 12:22:30 -06002073 data = self._DoReadFile('096_elf.dts')
Simon Glassb1714232018-09-14 04:57:35 -06002074
Simon Glass0d673792019-07-08 13:18:25 -06002075 def testElfStrip(self):
Simon Glassb1714232018-09-14 04:57:35 -06002076 """Basic test of ELF entries"""
Simon Glass7057d022018-10-01 21:12:47 -06002077 self._SetupSplElf()
Simon Glassf6290892019-08-24 07:22:53 -06002078 with open(self.ElfTestFile('bss_data'), 'rb') as fd:
Simon Glassb1714232018-09-14 04:57:35 -06002079 TestFunctional._MakeInputFile('-boot', fd.read())
Simon Glass511f6582018-10-01 12:22:30 -06002080 data = self._DoReadFile('097_elf_strip.dts')
Simon Glassb1714232018-09-14 04:57:35 -06002081
Simon Glasscd817d52018-09-14 04:57:36 -06002082 def testPackOverlapMap(self):
2083 """Test that overlapping regions are detected"""
2084 with test_util.capture_sys_output() as (stdout, stderr):
2085 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06002086 self._DoTestFile('014_pack_overlap.dts', map=True)
Simon Glasscd817d52018-09-14 04:57:36 -06002087 map_fname = tools.GetOutputFilename('image.map')
2088 self.assertEqual("Wrote map file '%s' to show errors\n" % map_fname,
2089 stdout.getvalue())
2090
2091 # We should not get an inmage, but there should be a map file
2092 self.assertFalse(os.path.exists(tools.GetOutputFilename('image.bin')))
2093 self.assertTrue(os.path.exists(map_fname))
Simon Glassb3774752019-05-17 22:00:51 -06002094 map_data = tools.ReadFile(map_fname, binary=False)
Simon Glasscd817d52018-09-14 04:57:36 -06002095 self.assertEqual('''ImagePos Offset Size Name
Simon Glassd99850b2020-10-26 17:40:24 -06002096<none> 00000000 00000008 main-section
Simon Glasscd817d52018-09-14 04:57:36 -06002097<none> 00000000 00000004 u-boot
2098<none> 00000003 00000004 u-boot-align
2099''', map_data)
2100
Simon Glass0d673792019-07-08 13:18:25 -06002101 def testPackRefCode(self):
Simon Glass41902e42018-10-01 12:22:31 -06002102 """Test that an image with an Intel Reference code binary works"""
2103 data = self._DoReadFile('100_intel_refcode.dts')
2104 self.assertEqual(REFCODE_DATA, data[:len(REFCODE_DATA)])
2105
Simon Glasseb023b32019-04-25 21:58:39 -06002106 def testSectionOffset(self):
2107 """Tests use of a section with an offset"""
2108 data, _, map_data, _ = self._DoReadFileDtb('101_sections_offset.dts',
2109 map=True)
2110 self.assertEqual('''ImagePos Offset Size Name
211100000000 00000000 00000038 main-section
211200000004 00000004 00000010 section@0
211300000004 00000000 00000004 u-boot
211400000018 00000018 00000010 section@1
211500000018 00000000 00000004 u-boot
21160000002c 0000002c 00000004 section@2
21170000002c 00000000 00000004 u-boot
2118''', map_data)
2119 self.assertEqual(data,
Simon Glassac0d4952019-05-14 15:53:47 -06002120 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
2121 tools.GetBytes(0x21, 12) +
2122 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
2123 tools.GetBytes(0x61, 12) +
2124 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
2125 tools.GetBytes(0x26, 8))
Simon Glasseb023b32019-04-25 21:58:39 -06002126
Simon Glass1de34482019-07-08 13:18:53 -06002127 def testCbfsRaw(self):
2128 """Test base handling of a Coreboot Filesystem (CBFS)
2129
2130 The exact contents of the CBFS is verified by similar tests in
2131 cbfs_util_test.py. The tests here merely check that the files added to
2132 the CBFS can be found in the final image.
2133 """
2134 data = self._DoReadFile('102_cbfs_raw.dts')
2135 size = 0xb0
2136
2137 cbfs = cbfs_util.CbfsReader(data)
2138 self.assertEqual(size, cbfs.rom_size)
2139
2140 self.assertIn('u-boot-dtb', cbfs.files)
2141 cfile = cbfs.files['u-boot-dtb']
2142 self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
2143
2144 def testCbfsArch(self):
2145 """Test on non-x86 architecture"""
2146 data = self._DoReadFile('103_cbfs_raw_ppc.dts')
2147 size = 0x100
2148
2149 cbfs = cbfs_util.CbfsReader(data)
2150 self.assertEqual(size, cbfs.rom_size)
2151
2152 self.assertIn('u-boot-dtb', cbfs.files)
2153 cfile = cbfs.files['u-boot-dtb']
2154 self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
2155
2156 def testCbfsStage(self):
2157 """Tests handling of a Coreboot Filesystem (CBFS)"""
2158 if not elf.ELF_TOOLS:
2159 self.skipTest('Python elftools not available')
2160 elf_fname = os.path.join(self._indir, 'cbfs-stage.elf')
2161 elf.MakeElf(elf_fname, U_BOOT_DATA, U_BOOT_DTB_DATA)
2162 size = 0xb0
2163
2164 data = self._DoReadFile('104_cbfs_stage.dts')
2165 cbfs = cbfs_util.CbfsReader(data)
2166 self.assertEqual(size, cbfs.rom_size)
2167
2168 self.assertIn('u-boot', cbfs.files)
2169 cfile = cbfs.files['u-boot']
2170 self.assertEqual(U_BOOT_DATA + U_BOOT_DTB_DATA, cfile.data)
2171
2172 def testCbfsRawCompress(self):
2173 """Test handling of compressing raw files"""
2174 self._CheckLz4()
2175 data = self._DoReadFile('105_cbfs_raw_compress.dts')
2176 size = 0x140
2177
2178 cbfs = cbfs_util.CbfsReader(data)
2179 self.assertIn('u-boot', cbfs.files)
2180 cfile = cbfs.files['u-boot']
2181 self.assertEqual(COMPRESS_DATA, cfile.data)
2182
2183 def testCbfsBadArch(self):
2184 """Test handling of a bad architecture"""
2185 with self.assertRaises(ValueError) as e:
2186 self._DoReadFile('106_cbfs_bad_arch.dts')
2187 self.assertIn("Invalid architecture 'bad-arch'", str(e.exception))
2188
2189 def testCbfsNoSize(self):
2190 """Test handling of a missing size property"""
2191 with self.assertRaises(ValueError) as e:
2192 self._DoReadFile('107_cbfs_no_size.dts')
2193 self.assertIn('entry must have a size property', str(e.exception))
2194
2195 def testCbfsNoCOntents(self):
2196 """Test handling of a CBFS entry which does not provide contentsy"""
2197 with self.assertRaises(ValueError) as e:
2198 self._DoReadFile('108_cbfs_no_contents.dts')
2199 self.assertIn('Could not complete processing of contents',
2200 str(e.exception))
2201
2202 def testCbfsBadCompress(self):
2203 """Test handling of a bad architecture"""
2204 with self.assertRaises(ValueError) as e:
2205 self._DoReadFile('109_cbfs_bad_compress.dts')
2206 self.assertIn("Invalid compression in 'u-boot': 'invalid-algo'",
2207 str(e.exception))
2208
2209 def testCbfsNamedEntries(self):
2210 """Test handling of named entries"""
2211 data = self._DoReadFile('110_cbfs_name.dts')
2212
2213 cbfs = cbfs_util.CbfsReader(data)
2214 self.assertIn('FRED', cbfs.files)
2215 cfile1 = cbfs.files['FRED']
2216 self.assertEqual(U_BOOT_DATA, cfile1.data)
2217
2218 self.assertIn('hello', cbfs.files)
2219 cfile2 = cbfs.files['hello']
2220 self.assertEqual(U_BOOT_DTB_DATA, cfile2.data)
2221
Simon Glass759af872019-07-08 13:18:54 -06002222 def _SetupIfwi(self, fname):
2223 """Set up to run an IFWI test
2224
2225 Args:
2226 fname: Filename of input file to provide (fitimage.bin or ifwi.bin)
2227 """
2228 self._SetupSplElf()
Simon Glass3eb5b202019-08-24 07:23:00 -06002229 self._SetupTplElf()
Simon Glass759af872019-07-08 13:18:54 -06002230
2231 # Intel Integrated Firmware Image (IFWI) file
2232 with gzip.open(self.TestFile('%s.gz' % fname), 'rb') as fd:
2233 data = fd.read()
2234 TestFunctional._MakeInputFile(fname,data)
2235
2236 def _CheckIfwi(self, data):
2237 """Check that an image with an IFWI contains the correct output
2238
2239 Args:
2240 data: Conents of output file
2241 """
2242 expected_desc = tools.ReadFile(self.TestFile('descriptor.bin'))
2243 if data[:0x1000] != expected_desc:
2244 self.fail('Expected descriptor binary at start of image')
2245
2246 # We expect to find the TPL wil in subpart IBBP entry IBBL
2247 image_fname = tools.GetOutputFilename('image.bin')
2248 tpl_fname = tools.GetOutputFilename('tpl.out')
2249 tools.RunIfwiTool(image_fname, tools.CMD_EXTRACT, fname=tpl_fname,
2250 subpart='IBBP', entry_name='IBBL')
2251
2252 tpl_data = tools.ReadFile(tpl_fname)
Simon Glassf55bd692019-08-24 07:22:51 -06002253 self.assertEqual(U_BOOT_TPL_DATA, tpl_data[:len(U_BOOT_TPL_DATA)])
Simon Glass759af872019-07-08 13:18:54 -06002254
2255 def testPackX86RomIfwi(self):
2256 """Test that an x86 ROM with Integrated Firmware Image can be created"""
2257 self._SetupIfwi('fitimage.bin')
Simon Glass1d167762019-08-24 07:23:01 -06002258 data = self._DoReadFile('111_x86_rom_ifwi.dts')
Simon Glass759af872019-07-08 13:18:54 -06002259 self._CheckIfwi(data)
2260
2261 def testPackX86RomIfwiNoDesc(self):
2262 """Test that an x86 ROM with IFWI can be created from an ifwi.bin file"""
2263 self._SetupIfwi('ifwi.bin')
Simon Glass1d167762019-08-24 07:23:01 -06002264 data = self._DoReadFile('112_x86_rom_ifwi_nodesc.dts')
Simon Glass759af872019-07-08 13:18:54 -06002265 self._CheckIfwi(data)
2266
2267 def testPackX86RomIfwiNoData(self):
2268 """Test that an x86 ROM with IFWI handles missing data"""
2269 self._SetupIfwi('ifwi.bin')
2270 with self.assertRaises(ValueError) as e:
Simon Glass1d167762019-08-24 07:23:01 -06002271 data = self._DoReadFile('113_x86_rom_ifwi_nodata.dts')
Simon Glass759af872019-07-08 13:18:54 -06002272 self.assertIn('Could not complete processing of contents',
2273 str(e.exception))
Simon Glass91710b32018-07-17 13:25:32 -06002274
Simon Glassc2f1aed2019-07-08 13:18:56 -06002275 def testCbfsOffset(self):
2276 """Test a CBFS with files at particular offsets
2277
2278 Like all CFBS tests, this is just checking the logic that calls
2279 cbfs_util. See cbfs_util_test for fully tests (e.g. test_cbfs_offset()).
2280 """
2281 data = self._DoReadFile('114_cbfs_offset.dts')
2282 size = 0x200
2283
2284 cbfs = cbfs_util.CbfsReader(data)
2285 self.assertEqual(size, cbfs.rom_size)
2286
2287 self.assertIn('u-boot', cbfs.files)
2288 cfile = cbfs.files['u-boot']
2289 self.assertEqual(U_BOOT_DATA, cfile.data)
2290 self.assertEqual(0x40, cfile.cbfs_offset)
2291
2292 self.assertIn('u-boot-dtb', cbfs.files)
2293 cfile2 = cbfs.files['u-boot-dtb']
2294 self.assertEqual(U_BOOT_DTB_DATA, cfile2.data)
2295 self.assertEqual(0x140, cfile2.cbfs_offset)
2296
Simon Glass0f621332019-07-08 14:25:27 -06002297 def testFdtmap(self):
2298 """Test an FDT map can be inserted in the image"""
2299 data = self.data = self._DoReadFileRealDtb('115_fdtmap.dts')
2300 fdtmap_data = data[len(U_BOOT_DATA):]
2301 magic = fdtmap_data[:8]
Simon Glassc5fd10a2019-10-31 07:43:03 -06002302 self.assertEqual(b'_FDTMAP_', magic)
Simon Glass0f621332019-07-08 14:25:27 -06002303 self.assertEqual(tools.GetBytes(0, 8), fdtmap_data[8:16])
2304
2305 fdt_data = fdtmap_data[16:]
2306 dtb = fdt.Fdt.FromData(fdt_data)
2307 dtb.Scan()
Simon Glass2c6adba2019-07-20 12:23:47 -06002308 props = self._GetPropTree(dtb, BASE_DTB_PROPS, prefix='/')
Simon Glass0f621332019-07-08 14:25:27 -06002309 self.assertEqual({
2310 'image-pos': 0,
2311 'offset': 0,
2312 'u-boot:offset': 0,
2313 'u-boot:size': len(U_BOOT_DATA),
2314 'u-boot:image-pos': 0,
2315 'fdtmap:image-pos': 4,
2316 'fdtmap:offset': 4,
2317 'fdtmap:size': len(fdtmap_data),
2318 'size': len(data),
2319 }, props)
2320
2321 def testFdtmapNoMatch(self):
2322 """Check handling of an FDT map when the section cannot be found"""
2323 self.data = self._DoReadFileRealDtb('115_fdtmap.dts')
2324
2325 # Mangle the section name, which should cause a mismatch between the
2326 # correct FDT path and the one expected by the section
2327 image = control.images['image']
Simon Glasscec34ba2019-07-08 14:25:28 -06002328 image._node.path += '-suffix'
Simon Glass0f621332019-07-08 14:25:27 -06002329 entries = image.GetEntries()
2330 fdtmap = entries['fdtmap']
2331 with self.assertRaises(ValueError) as e:
2332 fdtmap._GetFdtmap()
2333 self.assertIn("Cannot locate node for path '/binman-suffix'",
2334 str(e.exception))
2335
Simon Glasscec34ba2019-07-08 14:25:28 -06002336 def testFdtmapHeader(self):
2337 """Test an FDT map and image header can be inserted in the image"""
2338 data = self.data = self._DoReadFileRealDtb('116_fdtmap_hdr.dts')
2339 fdtmap_pos = len(U_BOOT_DATA)
2340 fdtmap_data = data[fdtmap_pos:]
2341 fdt_data = fdtmap_data[16:]
2342 dtb = fdt.Fdt.FromData(fdt_data)
2343 fdt_size = dtb.GetFdtObj().totalsize()
2344 hdr_data = data[-8:]
Simon Glassc5fd10a2019-10-31 07:43:03 -06002345 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscec34ba2019-07-08 14:25:28 -06002346 offset = struct.unpack('<I', hdr_data[4:])[0] & 0xffffffff
2347 self.assertEqual(fdtmap_pos - 0x400, offset - (1 << 32))
2348
2349 def testFdtmapHeaderStart(self):
2350 """Test an image header can be inserted at the image start"""
2351 data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
2352 fdtmap_pos = 0x100 + len(U_BOOT_DATA)
2353 hdr_data = data[:8]
Simon Glassc5fd10a2019-10-31 07:43:03 -06002354 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscec34ba2019-07-08 14:25:28 -06002355 offset = struct.unpack('<I', hdr_data[4:])[0]
2356 self.assertEqual(fdtmap_pos, offset)
2357
2358 def testFdtmapHeaderPos(self):
2359 """Test an image header can be inserted at a chosen position"""
2360 data = self.data = self._DoReadFileRealDtb('118_fdtmap_hdr_pos.dts')
2361 fdtmap_pos = 0x100 + len(U_BOOT_DATA)
2362 hdr_data = data[0x80:0x88]
Simon Glassc5fd10a2019-10-31 07:43:03 -06002363 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscec34ba2019-07-08 14:25:28 -06002364 offset = struct.unpack('<I', hdr_data[4:])[0]
2365 self.assertEqual(fdtmap_pos, offset)
2366
2367 def testHeaderMissingFdtmap(self):
2368 """Test an image header requires an fdtmap"""
2369 with self.assertRaises(ValueError) as e:
2370 self.data = self._DoReadFileRealDtb('119_fdtmap_hdr_missing.dts')
2371 self.assertIn("'image_header' section must have an 'fdtmap' sibling",
2372 str(e.exception))
2373
2374 def testHeaderNoLocation(self):
2375 """Test an image header with a no specified location is detected"""
2376 with self.assertRaises(ValueError) as e:
2377 self.data = self._DoReadFileRealDtb('120_hdr_no_location.dts')
2378 self.assertIn("Invalid location 'None', expected 'start' or 'end'",
2379 str(e.exception))
2380
Simon Glasse61b6f62019-07-08 14:25:37 -06002381 def testEntryExpand(self):
2382 """Test expanding an entry after it is packed"""
2383 data = self._DoReadFile('121_entry_expand.dts')
Simon Glass8c702fb2019-07-20 12:23:57 -06002384 self.assertEqual(b'aaa', data[:3])
2385 self.assertEqual(U_BOOT_DATA, data[3:3 + len(U_BOOT_DATA)])
2386 self.assertEqual(b'aaa', data[-3:])
Simon Glasse61b6f62019-07-08 14:25:37 -06002387
2388 def testEntryExpandBad(self):
2389 """Test expanding an entry after it is packed, twice"""
2390 with self.assertRaises(ValueError) as e:
2391 self._DoReadFile('122_entry_expand_twice.dts')
Simon Glass9d8ee322019-07-20 12:23:58 -06002392 self.assertIn("Image '/binman': Entries changed size after packing",
Simon Glasse61b6f62019-07-08 14:25:37 -06002393 str(e.exception))
2394
2395 def testEntryExpandSection(self):
2396 """Test expanding an entry within a section after it is packed"""
2397 data = self._DoReadFile('123_entry_expand_section.dts')
Simon Glass8c702fb2019-07-20 12:23:57 -06002398 self.assertEqual(b'aaa', data[:3])
2399 self.assertEqual(U_BOOT_DATA, data[3:3 + len(U_BOOT_DATA)])
2400 self.assertEqual(b'aaa', data[-3:])
Simon Glasse61b6f62019-07-08 14:25:37 -06002401
Simon Glass90d29682019-07-08 14:25:38 -06002402 def testCompressDtb(self):
2403 """Test that compress of device-tree files is supported"""
2404 self._CheckLz4()
2405 data = self.data = self._DoReadFileRealDtb('124_compress_dtb.dts')
2406 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
2407 comp_data = data[len(U_BOOT_DATA):]
2408 orig = self._decompress(comp_data)
2409 dtb = fdt.Fdt.FromData(orig)
2410 dtb.Scan()
2411 props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
2412 expected = {
2413 'u-boot:size': len(U_BOOT_DATA),
2414 'u-boot-dtb:uncomp-size': len(orig),
2415 'u-boot-dtb:size': len(comp_data),
2416 'size': len(data),
2417 }
2418 self.assertEqual(expected, props)
2419
Simon Glass151bbbf2019-07-08 14:25:41 -06002420 def testCbfsUpdateFdt(self):
2421 """Test that we can update the device tree with CBFS offset/size info"""
2422 self._CheckLz4()
2423 data, _, _, out_dtb_fname = self._DoReadFileDtb('125_cbfs_update.dts',
2424 update_dtb=True)
2425 dtb = fdt.Fdt(out_dtb_fname)
2426 dtb.Scan()
Simon Glass2c6adba2019-07-20 12:23:47 -06002427 props = self._GetPropTree(dtb, BASE_DTB_PROPS + ['uncomp-size'])
Simon Glass151bbbf2019-07-08 14:25:41 -06002428 del props['cbfs/u-boot:size']
2429 self.assertEqual({
2430 'offset': 0,
2431 'size': len(data),
2432 'image-pos': 0,
2433 'cbfs:offset': 0,
2434 'cbfs:size': len(data),
2435 'cbfs:image-pos': 0,
2436 'cbfs/u-boot:offset': 0x38,
2437 'cbfs/u-boot:uncomp-size': len(U_BOOT_DATA),
2438 'cbfs/u-boot:image-pos': 0x38,
2439 'cbfs/u-boot-dtb:offset': 0xb8,
2440 'cbfs/u-boot-dtb:size': len(U_BOOT_DATA),
2441 'cbfs/u-boot-dtb:image-pos': 0xb8,
2442 }, props)
2443
Simon Glass3c9b4f22019-07-08 14:25:42 -06002444 def testCbfsBadType(self):
2445 """Test an image header with a no specified location is detected"""
2446 with self.assertRaises(ValueError) as e:
2447 self._DoReadFile('126_cbfs_bad_type.dts')
2448 self.assertIn("Unknown cbfs-type 'badtype'", str(e.exception))
2449
Simon Glass6b156f82019-07-08 14:25:43 -06002450 def testList(self):
2451 """Test listing the files in an image"""
2452 self._CheckLz4()
2453 data = self._DoReadFile('127_list.dts')
2454 image = control.images['image']
2455 entries = image.BuildEntryList()
2456 self.assertEqual(7, len(entries))
2457
2458 ent = entries[0]
2459 self.assertEqual(0, ent.indent)
2460 self.assertEqual('main-section', ent.name)
2461 self.assertEqual('section', ent.etype)
2462 self.assertEqual(len(data), ent.size)
2463 self.assertEqual(0, ent.image_pos)
2464 self.assertEqual(None, ent.uncomp_size)
Simon Glass39dd2152019-07-08 14:25:47 -06002465 self.assertEqual(0, ent.offset)
Simon Glass6b156f82019-07-08 14:25:43 -06002466
2467 ent = entries[1]
2468 self.assertEqual(1, ent.indent)
2469 self.assertEqual('u-boot', ent.name)
2470 self.assertEqual('u-boot', ent.etype)
2471 self.assertEqual(len(U_BOOT_DATA), ent.size)
2472 self.assertEqual(0, ent.image_pos)
2473 self.assertEqual(None, ent.uncomp_size)
2474 self.assertEqual(0, ent.offset)
2475
2476 ent = entries[2]
2477 self.assertEqual(1, ent.indent)
2478 self.assertEqual('section', ent.name)
2479 self.assertEqual('section', ent.etype)
2480 section_size = ent.size
2481 self.assertEqual(0x100, ent.image_pos)
2482 self.assertEqual(None, ent.uncomp_size)
Simon Glass39dd2152019-07-08 14:25:47 -06002483 self.assertEqual(0x100, ent.offset)
Simon Glass6b156f82019-07-08 14:25:43 -06002484
2485 ent = entries[3]
2486 self.assertEqual(2, ent.indent)
2487 self.assertEqual('cbfs', ent.name)
2488 self.assertEqual('cbfs', ent.etype)
2489 self.assertEqual(0x400, ent.size)
2490 self.assertEqual(0x100, ent.image_pos)
2491 self.assertEqual(None, ent.uncomp_size)
2492 self.assertEqual(0, ent.offset)
2493
2494 ent = entries[4]
2495 self.assertEqual(3, ent.indent)
2496 self.assertEqual('u-boot', ent.name)
2497 self.assertEqual('u-boot', ent.etype)
2498 self.assertEqual(len(U_BOOT_DATA), ent.size)
2499 self.assertEqual(0x138, ent.image_pos)
2500 self.assertEqual(None, ent.uncomp_size)
2501 self.assertEqual(0x38, ent.offset)
2502
2503 ent = entries[5]
2504 self.assertEqual(3, ent.indent)
2505 self.assertEqual('u-boot-dtb', ent.name)
2506 self.assertEqual('text', ent.etype)
2507 self.assertGreater(len(COMPRESS_DATA), ent.size)
2508 self.assertEqual(0x178, ent.image_pos)
2509 self.assertEqual(len(COMPRESS_DATA), ent.uncomp_size)
2510 self.assertEqual(0x78, ent.offset)
2511
2512 ent = entries[6]
2513 self.assertEqual(2, ent.indent)
2514 self.assertEqual('u-boot-dtb', ent.name)
2515 self.assertEqual('u-boot-dtb', ent.etype)
2516 self.assertEqual(0x500, ent.image_pos)
2517 self.assertEqual(len(U_BOOT_DTB_DATA), ent.uncomp_size)
2518 dtb_size = ent.size
2519 # Compressing this data expands it since headers are added
2520 self.assertGreater(dtb_size, len(U_BOOT_DTB_DATA))
2521 self.assertEqual(0x400, ent.offset)
2522
2523 self.assertEqual(len(data), 0x100 + section_size)
2524 self.assertEqual(section_size, 0x400 + dtb_size)
2525
Simon Glass8d8bf4e2019-07-08 14:25:44 -06002526 def testFindFdtmap(self):
2527 """Test locating an FDT map in an image"""
2528 self._CheckLz4()
2529 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
2530 image = control.images['image']
2531 entries = image.GetEntries()
2532 entry = entries['fdtmap']
2533 self.assertEqual(entry.image_pos, fdtmap.LocateFdtmap(data))
2534
2535 def testFindFdtmapMissing(self):
2536 """Test failing to locate an FDP map"""
2537 data = self._DoReadFile('005_simple.dts')
2538 self.assertEqual(None, fdtmap.LocateFdtmap(data))
2539
Simon Glassed39a3c2019-07-08 14:25:45 -06002540 def testFindImageHeader(self):
2541 """Test locating a image header"""
2542 self._CheckLz4()
Simon Glassb8424fa2019-07-08 14:25:46 -06002543 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
Simon Glassed39a3c2019-07-08 14:25:45 -06002544 image = control.images['image']
2545 entries = image.GetEntries()
2546 entry = entries['fdtmap']
2547 # The header should point to the FDT map
2548 self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data))
2549
2550 def testFindImageHeaderStart(self):
2551 """Test locating a image header located at the start of an image"""
Simon Glassb8424fa2019-07-08 14:25:46 -06002552 data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
Simon Glassed39a3c2019-07-08 14:25:45 -06002553 image = control.images['image']
2554 entries = image.GetEntries()
2555 entry = entries['fdtmap']
2556 # The header should point to the FDT map
2557 self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data))
2558
2559 def testFindImageHeaderMissing(self):
2560 """Test failing to locate an image header"""
2561 data = self._DoReadFile('005_simple.dts')
2562 self.assertEqual(None, image_header.LocateHeaderOffset(data))
2563
Simon Glassb8424fa2019-07-08 14:25:46 -06002564 def testReadImage(self):
2565 """Test reading an image and accessing its FDT map"""
2566 self._CheckLz4()
2567 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
2568 image_fname = tools.GetOutputFilename('image.bin')
2569 orig_image = control.images['image']
2570 image = Image.FromFile(image_fname)
2571 self.assertEqual(orig_image.GetEntries().keys(),
2572 image.GetEntries().keys())
2573
2574 orig_entry = orig_image.GetEntries()['fdtmap']
2575 entry = image.GetEntries()['fdtmap']
2576 self.assertEquals(orig_entry.offset, entry.offset)
2577 self.assertEquals(orig_entry.size, entry.size)
2578 self.assertEquals(orig_entry.image_pos, entry.image_pos)
2579
2580 def testReadImageNoHeader(self):
2581 """Test accessing an image's FDT map without an image header"""
2582 self._CheckLz4()
2583 data = self._DoReadFileRealDtb('129_decode_image_nohdr.dts')
2584 image_fname = tools.GetOutputFilename('image.bin')
2585 image = Image.FromFile(image_fname)
2586 self.assertTrue(isinstance(image, Image))
Simon Glass072959a2019-07-20 12:23:50 -06002587 self.assertEqual('image', image.image_name[-5:])
Simon Glassb8424fa2019-07-08 14:25:46 -06002588
2589 def testReadImageFail(self):
2590 """Test failing to read an image image's FDT map"""
2591 self._DoReadFile('005_simple.dts')
2592 image_fname = tools.GetOutputFilename('image.bin')
2593 with self.assertRaises(ValueError) as e:
2594 image = Image.FromFile(image_fname)
2595 self.assertIn("Cannot find FDT map in image", str(e.exception))
Simon Glassc2f1aed2019-07-08 13:18:56 -06002596
Simon Glassb2fd11d2019-07-08 14:25:48 -06002597 def testListCmd(self):
2598 """Test listing the files in an image using an Fdtmap"""
2599 self._CheckLz4()
2600 data = self._DoReadFileRealDtb('130_list_fdtmap.dts')
2601
2602 # lz4 compression size differs depending on the version
2603 image = control.images['image']
2604 entries = image.GetEntries()
2605 section_size = entries['section'].size
2606 fdt_size = entries['section'].GetEntries()['u-boot-dtb'].size
2607 fdtmap_offset = entries['fdtmap'].offset
2608
Simon Glassb3d6fc72019-07-20 12:24:10 -06002609 try:
2610 tmpdir, updated_fname = self._SetupImageInTmpdir()
2611 with test_util.capture_sys_output() as (stdout, stderr):
2612 self._DoBinman('ls', '-i', updated_fname)
2613 finally:
2614 shutil.rmtree(tmpdir)
Simon Glassb2fd11d2019-07-08 14:25:48 -06002615 lines = stdout.getvalue().splitlines()
2616 expected = [
2617'Name Image-pos Size Entry-type Offset Uncomp-size',
2618'----------------------------------------------------------------------',
2619'main-section 0 c00 section 0',
2620' u-boot 0 4 u-boot 0',
2621' section 100 %x section 100' % section_size,
2622' cbfs 100 400 cbfs 0',
2623' u-boot 138 4 u-boot 38',
Simon Glassc5fd10a2019-10-31 07:43:03 -06002624' u-boot-dtb 180 105 u-boot-dtb 80 3c9',
Simon Glassb2fd11d2019-07-08 14:25:48 -06002625' u-boot-dtb 500 %x u-boot-dtb 400 3c9' % fdt_size,
Simon Glassc5fd10a2019-10-31 07:43:03 -06002626' fdtmap %x 3bd fdtmap %x' %
Simon Glassb2fd11d2019-07-08 14:25:48 -06002627 (fdtmap_offset, fdtmap_offset),
2628' image-header bf8 8 image-header bf8',
2629 ]
2630 self.assertEqual(expected, lines)
2631
2632 def testListCmdFail(self):
2633 """Test failing to list an image"""
2634 self._DoReadFile('005_simple.dts')
Simon Glassb3d6fc72019-07-20 12:24:10 -06002635 try:
2636 tmpdir, updated_fname = self._SetupImageInTmpdir()
2637 with self.assertRaises(ValueError) as e:
2638 self._DoBinman('ls', '-i', updated_fname)
2639 finally:
2640 shutil.rmtree(tmpdir)
Simon Glassb2fd11d2019-07-08 14:25:48 -06002641 self.assertIn("Cannot find FDT map in image", str(e.exception))
2642
2643 def _RunListCmd(self, paths, expected):
2644 """List out entries and check the result
2645
2646 Args:
2647 paths: List of paths to pass to the list command
2648 expected: Expected list of filenames to be returned, in order
2649 """
2650 self._CheckLz4()
2651 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2652 image_fname = tools.GetOutputFilename('image.bin')
2653 image = Image.FromFile(image_fname)
2654 lines = image.GetListEntries(paths)[1]
2655 files = [line[0].strip() for line in lines[1:]]
2656 self.assertEqual(expected, files)
2657
2658 def testListCmdSection(self):
2659 """Test listing the files in a section"""
2660 self._RunListCmd(['section'],
2661 ['section', 'cbfs', 'u-boot', 'u-boot-dtb', 'u-boot-dtb'])
2662
2663 def testListCmdFile(self):
2664 """Test listing a particular file"""
2665 self._RunListCmd(['*u-boot-dtb'], ['u-boot-dtb', 'u-boot-dtb'])
2666
2667 def testListCmdWildcard(self):
2668 """Test listing a wildcarded file"""
2669 self._RunListCmd(['*boot*'],
2670 ['u-boot', 'u-boot', 'u-boot-dtb', 'u-boot-dtb'])
2671
2672 def testListCmdWildcardMulti(self):
2673 """Test listing a wildcarded file"""
2674 self._RunListCmd(['*cb*', '*head*'],
2675 ['cbfs', 'u-boot', 'u-boot-dtb', 'image-header'])
2676
2677 def testListCmdEmpty(self):
2678 """Test listing a wildcarded file"""
2679 self._RunListCmd(['nothing'], [])
2680
2681 def testListCmdPath(self):
2682 """Test listing the files in a sub-entry of a section"""
2683 self._RunListCmd(['section/cbfs'], ['cbfs', 'u-boot', 'u-boot-dtb'])
2684
Simon Glass4c613bf2019-07-08 14:25:50 -06002685 def _RunExtractCmd(self, entry_name, decomp=True):
2686 """Extract an entry from an image
2687
2688 Args:
2689 entry_name: Entry name to extract
2690 decomp: True to decompress the data if compressed, False to leave
2691 it in its raw uncompressed format
2692
2693 Returns:
2694 data from entry
2695 """
2696 self._CheckLz4()
2697 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2698 image_fname = tools.GetOutputFilename('image.bin')
2699 return control.ReadEntry(image_fname, entry_name, decomp)
2700
2701 def testExtractSimple(self):
2702 """Test extracting a single file"""
2703 data = self._RunExtractCmd('u-boot')
2704 self.assertEqual(U_BOOT_DATA, data)
2705
Simon Glass980a2842019-07-08 14:25:52 -06002706 def testExtractSection(self):
2707 """Test extracting the files in a section"""
2708 data = self._RunExtractCmd('section')
2709 cbfs_data = data[:0x400]
2710 cbfs = cbfs_util.CbfsReader(cbfs_data)
Simon Glassc5fd10a2019-10-31 07:43:03 -06002711 self.assertEqual(['u-boot', 'u-boot-dtb', ''], list(cbfs.files.keys()))
Simon Glass980a2842019-07-08 14:25:52 -06002712 dtb_data = data[0x400:]
2713 dtb = self._decompress(dtb_data)
2714 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2715
2716 def testExtractCompressed(self):
2717 """Test extracting compressed data"""
2718 data = self._RunExtractCmd('section/u-boot-dtb')
2719 self.assertEqual(EXTRACT_DTB_SIZE, len(data))
2720
2721 def testExtractRaw(self):
2722 """Test extracting compressed data without decompressing it"""
2723 data = self._RunExtractCmd('section/u-boot-dtb', decomp=False)
2724 dtb = self._decompress(data)
2725 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2726
2727 def testExtractCbfs(self):
2728 """Test extracting CBFS data"""
2729 data = self._RunExtractCmd('section/cbfs/u-boot')
2730 self.assertEqual(U_BOOT_DATA, data)
2731
2732 def testExtractCbfsCompressed(self):
2733 """Test extracting CBFS compressed data"""
2734 data = self._RunExtractCmd('section/cbfs/u-boot-dtb')
2735 self.assertEqual(EXTRACT_DTB_SIZE, len(data))
2736
2737 def testExtractCbfsRaw(self):
2738 """Test extracting CBFS compressed data without decompressing it"""
2739 data = self._RunExtractCmd('section/cbfs/u-boot-dtb', decomp=False)
Simon Glass37fdd142019-07-20 12:24:06 -06002740 dtb = tools.Decompress(data, 'lzma', with_header=False)
Simon Glass980a2842019-07-08 14:25:52 -06002741 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2742
Simon Glass4c613bf2019-07-08 14:25:50 -06002743 def testExtractBadEntry(self):
2744 """Test extracting a bad section path"""
2745 with self.assertRaises(ValueError) as e:
2746 self._RunExtractCmd('section/does-not-exist')
2747 self.assertIn("Entry 'does-not-exist' not found in '/section'",
2748 str(e.exception))
2749
2750 def testExtractMissingFile(self):
2751 """Test extracting file that does not exist"""
2752 with self.assertRaises(IOError) as e:
2753 control.ReadEntry('missing-file', 'name')
2754
2755 def testExtractBadFile(self):
2756 """Test extracting an invalid file"""
2757 fname = os.path.join(self._indir, 'badfile')
2758 tools.WriteFile(fname, b'')
2759 with self.assertRaises(ValueError) as e:
2760 control.ReadEntry(fname, 'name')
2761
Simon Glass980a2842019-07-08 14:25:52 -06002762 def testExtractCmd(self):
2763 """Test extracting a file fron an image on the command line"""
2764 self._CheckLz4()
2765 self._DoReadFileRealDtb('130_list_fdtmap.dts')
Simon Glass980a2842019-07-08 14:25:52 -06002766 fname = os.path.join(self._indir, 'output.extact')
Simon Glassb3d6fc72019-07-20 12:24:10 -06002767 try:
2768 tmpdir, updated_fname = self._SetupImageInTmpdir()
2769 with test_util.capture_sys_output() as (stdout, stderr):
2770 self._DoBinman('extract', '-i', updated_fname, 'u-boot',
2771 '-f', fname)
2772 finally:
2773 shutil.rmtree(tmpdir)
Simon Glass980a2842019-07-08 14:25:52 -06002774 data = tools.ReadFile(fname)
2775 self.assertEqual(U_BOOT_DATA, data)
2776
2777 def testExtractOneEntry(self):
2778 """Test extracting a single entry fron an image """
2779 self._CheckLz4()
2780 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2781 image_fname = tools.GetOutputFilename('image.bin')
2782 fname = os.path.join(self._indir, 'output.extact')
2783 control.ExtractEntries(image_fname, fname, None, ['u-boot'])
2784 data = tools.ReadFile(fname)
2785 self.assertEqual(U_BOOT_DATA, data)
2786
2787 def _CheckExtractOutput(self, decomp):
2788 """Helper to test file output with and without decompression
2789
2790 Args:
2791 decomp: True to decompress entry data, False to output it raw
2792 """
2793 def _CheckPresent(entry_path, expect_data, expect_size=None):
2794 """Check and remove expected file
2795
2796 This checks the data/size of a file and removes the file both from
2797 the outfiles set and from the output directory. Once all files are
2798 processed, both the set and directory should be empty.
2799
2800 Args:
2801 entry_path: Entry path
2802 expect_data: Data to expect in file, or None to skip check
2803 expect_size: Size of data to expect in file, or None to skip
2804 """
2805 path = os.path.join(outdir, entry_path)
2806 data = tools.ReadFile(path)
2807 os.remove(path)
2808 if expect_data:
2809 self.assertEqual(expect_data, data)
2810 elif expect_size:
2811 self.assertEqual(expect_size, len(data))
2812 outfiles.remove(path)
2813
2814 def _CheckDirPresent(name):
2815 """Remove expected directory
2816
2817 This gives an error if the directory does not exist as expected
2818
2819 Args:
2820 name: Name of directory to remove
2821 """
2822 path = os.path.join(outdir, name)
2823 os.rmdir(path)
2824
2825 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2826 image_fname = tools.GetOutputFilename('image.bin')
2827 outdir = os.path.join(self._indir, 'extract')
2828 einfos = control.ExtractEntries(image_fname, None, outdir, [], decomp)
2829
2830 # Create a set of all file that were output (should be 9)
2831 outfiles = set()
2832 for root, dirs, files in os.walk(outdir):
2833 outfiles |= set([os.path.join(root, fname) for fname in files])
2834 self.assertEqual(9, len(outfiles))
2835 self.assertEqual(9, len(einfos))
2836
2837 image = control.images['image']
2838 entries = image.GetEntries()
2839
2840 # Check the 9 files in various ways
2841 section = entries['section']
2842 section_entries = section.GetEntries()
2843 cbfs_entries = section_entries['cbfs'].GetEntries()
2844 _CheckPresent('u-boot', U_BOOT_DATA)
2845 _CheckPresent('section/cbfs/u-boot', U_BOOT_DATA)
2846 dtb_len = EXTRACT_DTB_SIZE
2847 if not decomp:
2848 dtb_len = cbfs_entries['u-boot-dtb'].size
2849 _CheckPresent('section/cbfs/u-boot-dtb', None, dtb_len)
2850 if not decomp:
2851 dtb_len = section_entries['u-boot-dtb'].size
2852 _CheckPresent('section/u-boot-dtb', None, dtb_len)
2853
2854 fdtmap = entries['fdtmap']
2855 _CheckPresent('fdtmap', fdtmap.data)
2856 hdr = entries['image-header']
2857 _CheckPresent('image-header', hdr.data)
2858
2859 _CheckPresent('section/root', section.data)
2860 cbfs = section_entries['cbfs']
2861 _CheckPresent('section/cbfs/root', cbfs.data)
2862 data = tools.ReadFile(image_fname)
2863 _CheckPresent('root', data)
2864
2865 # There should be no files left. Remove all the directories to check.
2866 # If there are any files/dirs remaining, one of these checks will fail.
2867 self.assertEqual(0, len(outfiles))
2868 _CheckDirPresent('section/cbfs')
2869 _CheckDirPresent('section')
2870 _CheckDirPresent('')
2871 self.assertFalse(os.path.exists(outdir))
2872
2873 def testExtractAllEntries(self):
2874 """Test extracting all entries"""
2875 self._CheckLz4()
2876 self._CheckExtractOutput(decomp=True)
2877
2878 def testExtractAllEntriesRaw(self):
2879 """Test extracting all entries without decompressing them"""
2880 self._CheckLz4()
2881 self._CheckExtractOutput(decomp=False)
2882
2883 def testExtractSelectedEntries(self):
2884 """Test extracting some entries"""
2885 self._CheckLz4()
2886 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2887 image_fname = tools.GetOutputFilename('image.bin')
2888 outdir = os.path.join(self._indir, 'extract')
2889 einfos = control.ExtractEntries(image_fname, None, outdir,
2890 ['*cb*', '*head*'])
2891
2892 # File output is tested by testExtractAllEntries(), so just check that
2893 # the expected entries are selected
2894 names = [einfo.name for einfo in einfos]
2895 self.assertEqual(names,
2896 ['cbfs', 'u-boot', 'u-boot-dtb', 'image-header'])
2897
2898 def testExtractNoEntryPaths(self):
2899 """Test extracting some entries"""
2900 self._CheckLz4()
2901 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2902 image_fname = tools.GetOutputFilename('image.bin')
2903 with self.assertRaises(ValueError) as e:
2904 control.ExtractEntries(image_fname, 'fname', None, [])
Simon Glassa772d3f2019-07-20 12:24:14 -06002905 self.assertIn('Must specify an entry path to write with -f',
Simon Glass980a2842019-07-08 14:25:52 -06002906 str(e.exception))
2907
2908 def testExtractTooManyEntryPaths(self):
2909 """Test extracting some entries"""
2910 self._CheckLz4()
2911 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2912 image_fname = tools.GetOutputFilename('image.bin')
2913 with self.assertRaises(ValueError) as e:
2914 control.ExtractEntries(image_fname, 'fname', None, ['a', 'b'])
Simon Glassa772d3f2019-07-20 12:24:14 -06002915 self.assertIn('Must specify exactly one entry path to write with -f',
Simon Glass980a2842019-07-08 14:25:52 -06002916 str(e.exception))
2917
Simon Glass52d06212019-07-08 14:25:53 -06002918 def testPackAlignSection(self):
2919 """Test that sections can have alignment"""
2920 self._DoReadFile('131_pack_align_section.dts')
2921
2922 self.assertIn('image', control.images)
2923 image = control.images['image']
2924 entries = image.GetEntries()
2925 self.assertEqual(3, len(entries))
2926
2927 # First u-boot
2928 self.assertIn('u-boot', entries)
2929 entry = entries['u-boot']
2930 self.assertEqual(0, entry.offset)
2931 self.assertEqual(0, entry.image_pos)
2932 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2933 self.assertEqual(len(U_BOOT_DATA), entry.size)
2934
2935 # Section0
2936 self.assertIn('section0', entries)
2937 section0 = entries['section0']
2938 self.assertEqual(0x10, section0.offset)
2939 self.assertEqual(0x10, section0.image_pos)
2940 self.assertEqual(len(U_BOOT_DATA), section0.size)
2941
2942 # Second u-boot
2943 section_entries = section0.GetEntries()
2944 self.assertIn('u-boot', section_entries)
2945 entry = section_entries['u-boot']
2946 self.assertEqual(0, entry.offset)
2947 self.assertEqual(0x10, entry.image_pos)
2948 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2949 self.assertEqual(len(U_BOOT_DATA), entry.size)
2950
2951 # Section1
2952 self.assertIn('section1', entries)
2953 section1 = entries['section1']
2954 self.assertEqual(0x14, section1.offset)
2955 self.assertEqual(0x14, section1.image_pos)
2956 self.assertEqual(0x20, section1.size)
2957
2958 # Second u-boot
2959 section_entries = section1.GetEntries()
2960 self.assertIn('u-boot', section_entries)
2961 entry = section_entries['u-boot']
2962 self.assertEqual(0, entry.offset)
2963 self.assertEqual(0x14, entry.image_pos)
2964 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2965 self.assertEqual(len(U_BOOT_DATA), entry.size)
2966
2967 # Section2
2968 self.assertIn('section2', section_entries)
2969 section2 = section_entries['section2']
2970 self.assertEqual(0x4, section2.offset)
2971 self.assertEqual(0x18, section2.image_pos)
2972 self.assertEqual(4, section2.size)
2973
2974 # Third u-boot
2975 section_entries = section2.GetEntries()
2976 self.assertIn('u-boot', section_entries)
2977 entry = section_entries['u-boot']
2978 self.assertEqual(0, entry.offset)
2979 self.assertEqual(0x18, entry.image_pos)
2980 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2981 self.assertEqual(len(U_BOOT_DATA), entry.size)
2982
Simon Glassf8a54bc2019-07-20 12:23:56 -06002983 def _RunReplaceCmd(self, entry_name, data, decomp=True, allow_resize=True,
2984 dts='132_replace.dts'):
Simon Glass072959a2019-07-20 12:23:50 -06002985 """Replace an entry in an image
2986
2987 This writes the entry data to update it, then opens the updated file and
2988 returns the value that it now finds there.
2989
2990 Args:
2991 entry_name: Entry name to replace
2992 data: Data to replace it with
2993 decomp: True to compress the data if needed, False if data is
2994 already compressed so should be used as is
Simon Glassf8a54bc2019-07-20 12:23:56 -06002995 allow_resize: True to allow entries to change size, False to raise
2996 an exception
Simon Glass072959a2019-07-20 12:23:50 -06002997
2998 Returns:
2999 Tuple:
3000 data from entry
3001 data from fdtmap (excluding header)
Simon Glassf8a54bc2019-07-20 12:23:56 -06003002 Image object that was modified
Simon Glass072959a2019-07-20 12:23:50 -06003003 """
Simon Glassf8a54bc2019-07-20 12:23:56 -06003004 dtb_data = self._DoReadFileDtb(dts, use_real_dtb=True,
Simon Glass072959a2019-07-20 12:23:50 -06003005 update_dtb=True)[1]
3006
3007 self.assertIn('image', control.images)
3008 image = control.images['image']
3009 entries = image.GetEntries()
3010 orig_dtb_data = entries['u-boot-dtb'].data
3011 orig_fdtmap_data = entries['fdtmap'].data
3012
3013 image_fname = tools.GetOutputFilename('image.bin')
3014 updated_fname = tools.GetOutputFilename('image-updated.bin')
3015 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
Simon Glassf8a54bc2019-07-20 12:23:56 -06003016 image = control.WriteEntry(updated_fname, entry_name, data, decomp,
3017 allow_resize)
Simon Glass072959a2019-07-20 12:23:50 -06003018 data = control.ReadEntry(updated_fname, entry_name, decomp)
3019
Simon Glassf8a54bc2019-07-20 12:23:56 -06003020 # The DT data should not change unless resized:
3021 if not allow_resize:
3022 new_dtb_data = entries['u-boot-dtb'].data
3023 self.assertEqual(new_dtb_data, orig_dtb_data)
3024 new_fdtmap_data = entries['fdtmap'].data
3025 self.assertEqual(new_fdtmap_data, orig_fdtmap_data)
Simon Glass072959a2019-07-20 12:23:50 -06003026
Simon Glassf8a54bc2019-07-20 12:23:56 -06003027 return data, orig_fdtmap_data[fdtmap.FDTMAP_HDR_LEN:], image
Simon Glass072959a2019-07-20 12:23:50 -06003028
3029 def testReplaceSimple(self):
3030 """Test replacing a single file"""
3031 expected = b'x' * len(U_BOOT_DATA)
Simon Glassf8a54bc2019-07-20 12:23:56 -06003032 data, expected_fdtmap, _ = self._RunReplaceCmd('u-boot', expected,
3033 allow_resize=False)
Simon Glass072959a2019-07-20 12:23:50 -06003034 self.assertEqual(expected, data)
3035
3036 # Test that the state looks right. There should be an FDT for the fdtmap
3037 # that we jsut read back in, and it should match what we find in the
3038 # 'control' tables. Checking for an FDT that does not exist should
3039 # return None.
3040 path, fdtmap = state.GetFdtContents('fdtmap')
Simon Glassf8a54bc2019-07-20 12:23:56 -06003041 self.assertIsNotNone(path)
Simon Glass072959a2019-07-20 12:23:50 -06003042 self.assertEqual(expected_fdtmap, fdtmap)
3043
3044 dtb = state.GetFdtForEtype('fdtmap')
3045 self.assertEqual(dtb.GetContents(), fdtmap)
3046
3047 missing_path, missing_fdtmap = state.GetFdtContents('missing')
3048 self.assertIsNone(missing_path)
3049 self.assertIsNone(missing_fdtmap)
3050
3051 missing_dtb = state.GetFdtForEtype('missing')
3052 self.assertIsNone(missing_dtb)
3053
3054 self.assertEqual('/binman', state.fdt_path_prefix)
3055
3056 def testReplaceResizeFail(self):
3057 """Test replacing a file by something larger"""
3058 expected = U_BOOT_DATA + b'x'
3059 with self.assertRaises(ValueError) as e:
Simon Glassf8a54bc2019-07-20 12:23:56 -06003060 self._RunReplaceCmd('u-boot', expected, allow_resize=False,
3061 dts='139_replace_repack.dts')
Simon Glass072959a2019-07-20 12:23:50 -06003062 self.assertIn("Node '/u-boot': Entry data size does not match, but resize is disabled",
3063 str(e.exception))
3064
3065 def testReplaceMulti(self):
3066 """Test replacing entry data where multiple images are generated"""
3067 data = self._DoReadFileDtb('133_replace_multi.dts', use_real_dtb=True,
3068 update_dtb=True)[0]
3069 expected = b'x' * len(U_BOOT_DATA)
3070 updated_fname = tools.GetOutputFilename('image-updated.bin')
3071 tools.WriteFile(updated_fname, data)
3072 entry_name = 'u-boot'
Simon Glassf8a54bc2019-07-20 12:23:56 -06003073 control.WriteEntry(updated_fname, entry_name, expected,
3074 allow_resize=False)
Simon Glass072959a2019-07-20 12:23:50 -06003075 data = control.ReadEntry(updated_fname, entry_name)
3076 self.assertEqual(expected, data)
3077
3078 # Check the state looks right.
3079 self.assertEqual('/binman/image', state.fdt_path_prefix)
3080
3081 # Now check we can write the first image
3082 image_fname = tools.GetOutputFilename('first-image.bin')
3083 updated_fname = tools.GetOutputFilename('first-updated.bin')
3084 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
3085 entry_name = 'u-boot'
Simon Glassf8a54bc2019-07-20 12:23:56 -06003086 control.WriteEntry(updated_fname, entry_name, expected,
3087 allow_resize=False)
Simon Glass072959a2019-07-20 12:23:50 -06003088 data = control.ReadEntry(updated_fname, entry_name)
3089 self.assertEqual(expected, data)
3090
3091 # Check the state looks right.
3092 self.assertEqual('/binman/first-image', state.fdt_path_prefix)
Simon Glass39dd2152019-07-08 14:25:47 -06003093
Simon Glassfb30e292019-07-20 12:23:51 -06003094 def testUpdateFdtAllRepack(self):
3095 """Test that all device trees are updated with offset/size info"""
3096 data = self._DoReadFileRealDtb('134_fdt_update_all_repack.dts')
3097 SECTION_SIZE = 0x300
3098 DTB_SIZE = 602
3099 FDTMAP_SIZE = 608
3100 base_expected = {
3101 'offset': 0,
3102 'size': SECTION_SIZE + DTB_SIZE * 2 + FDTMAP_SIZE,
3103 'image-pos': 0,
3104 'section:offset': 0,
3105 'section:size': SECTION_SIZE,
3106 'section:image-pos': 0,
3107 'section/u-boot-dtb:offset': 4,
3108 'section/u-boot-dtb:size': 636,
3109 'section/u-boot-dtb:image-pos': 4,
3110 'u-boot-spl-dtb:offset': SECTION_SIZE,
3111 'u-boot-spl-dtb:size': DTB_SIZE,
3112 'u-boot-spl-dtb:image-pos': SECTION_SIZE,
3113 'u-boot-tpl-dtb:offset': SECTION_SIZE + DTB_SIZE,
3114 'u-boot-tpl-dtb:image-pos': SECTION_SIZE + DTB_SIZE,
3115 'u-boot-tpl-dtb:size': DTB_SIZE,
3116 'fdtmap:offset': SECTION_SIZE + DTB_SIZE * 2,
3117 'fdtmap:size': FDTMAP_SIZE,
3118 'fdtmap:image-pos': SECTION_SIZE + DTB_SIZE * 2,
3119 }
3120 main_expected = {
3121 'section:orig-size': SECTION_SIZE,
3122 'section/u-boot-dtb:orig-offset': 4,
3123 }
3124
3125 # We expect three device-tree files in the output, with the first one
3126 # within a fixed-size section.
3127 # Read them in sequence. We look for an 'spl' property in the SPL tree,
3128 # and 'tpl' in the TPL tree, to make sure they are distinct from the
3129 # main U-Boot tree. All three should have the same positions and offset
3130 # except that the main tree should include the main_expected properties
3131 start = 4
3132 for item in ['', 'spl', 'tpl', None]:
3133 if item is None:
3134 start += 16 # Move past fdtmap header
3135 dtb = fdt.Fdt.FromData(data[start:])
3136 dtb.Scan()
3137 props = self._GetPropTree(dtb,
3138 BASE_DTB_PROPS + REPACK_DTB_PROPS + ['spl', 'tpl'],
3139 prefix='/' if item is None else '/binman/')
3140 expected = dict(base_expected)
3141 if item:
3142 expected[item] = 0
3143 else:
3144 # Main DTB and fdtdec should include the 'orig-' properties
3145 expected.update(main_expected)
3146 # Helpful for debugging:
3147 #for prop in sorted(props):
3148 #print('prop %s %s %s' % (prop, props[prop], expected[prop]))
3149 self.assertEqual(expected, props)
3150 if item == '':
3151 start = SECTION_SIZE
3152 else:
3153 start += dtb._fdt_obj.totalsize()
3154
Simon Glass11453762019-07-20 12:23:55 -06003155 def testFdtmapHeaderMiddle(self):
3156 """Test an FDT map in the middle of an image when it should be at end"""
3157 with self.assertRaises(ValueError) as e:
3158 self._DoReadFileRealDtb('135_fdtmap_hdr_middle.dts')
3159 self.assertIn("Invalid sibling order 'middle' for image-header: Must be at 'end' to match location",
3160 str(e.exception))
3161
3162 def testFdtmapHeaderStartBad(self):
3163 """Test an FDT map in middle of an image when it should be at start"""
3164 with self.assertRaises(ValueError) as e:
3165 self._DoReadFileRealDtb('136_fdtmap_hdr_startbad.dts')
3166 self.assertIn("Invalid sibling order 'end' for image-header: Must be at 'start' to match location",
3167 str(e.exception))
3168
3169 def testFdtmapHeaderEndBad(self):
3170 """Test an FDT map at the start of an image when it should be at end"""
3171 with self.assertRaises(ValueError) as e:
3172 self._DoReadFileRealDtb('137_fdtmap_hdr_endbad.dts')
3173 self.assertIn("Invalid sibling order 'start' for image-header: Must be at 'end' to match location",
3174 str(e.exception))
3175
3176 def testFdtmapHeaderNoSize(self):
3177 """Test an image header at the end of an image with undefined size"""
3178 self._DoReadFileRealDtb('138_fdtmap_hdr_nosize.dts')
3179
Simon Glassf8a54bc2019-07-20 12:23:56 -06003180 def testReplaceResize(self):
3181 """Test replacing a single file in an entry with a larger file"""
3182 expected = U_BOOT_DATA + b'x'
3183 data, _, image = self._RunReplaceCmd('u-boot', expected,
3184 dts='139_replace_repack.dts')
3185 self.assertEqual(expected, data)
3186
3187 entries = image.GetEntries()
3188 dtb_data = entries['u-boot-dtb'].data
3189 dtb = fdt.Fdt.FromData(dtb_data)
3190 dtb.Scan()
3191
3192 # The u-boot section should now be larger in the dtb
3193 node = dtb.GetNode('/binman/u-boot')
3194 self.assertEqual(len(expected), fdt_util.GetInt(node, 'size'))
3195
3196 # Same for the fdtmap
3197 fdata = entries['fdtmap'].data
3198 fdtb = fdt.Fdt.FromData(fdata[fdtmap.FDTMAP_HDR_LEN:])
3199 fdtb.Scan()
3200 fnode = fdtb.GetNode('/u-boot')
3201 self.assertEqual(len(expected), fdt_util.GetInt(fnode, 'size'))
3202
3203 def testReplaceResizeNoRepack(self):
3204 """Test replacing an entry with a larger file when not allowed"""
3205 expected = U_BOOT_DATA + b'x'
3206 with self.assertRaises(ValueError) as e:
3207 self._RunReplaceCmd('u-boot', expected)
3208 self.assertIn('Entry data size does not match, but allow-repack is not present for this image',
3209 str(e.exception))
3210
Simon Glass9d8ee322019-07-20 12:23:58 -06003211 def testEntryShrink(self):
3212 """Test contracting an entry after it is packed"""
3213 try:
3214 state.SetAllowEntryContraction(True)
3215 data = self._DoReadFileDtb('140_entry_shrink.dts',
3216 update_dtb=True)[0]
3217 finally:
3218 state.SetAllowEntryContraction(False)
3219 self.assertEqual(b'a', data[:1])
3220 self.assertEqual(U_BOOT_DATA, data[1:1 + len(U_BOOT_DATA)])
3221 self.assertEqual(b'a', data[-1:])
3222
3223 def testEntryShrinkFail(self):
3224 """Test not being allowed to contract an entry after it is packed"""
3225 data = self._DoReadFileDtb('140_entry_shrink.dts', update_dtb=True)[0]
3226
3227 # In this case there is a spare byte at the end of the data. The size of
3228 # the contents is only 1 byte but we still have the size before it
3229 # shrunk.
3230 self.assertEqual(b'a\0', data[:2])
3231 self.assertEqual(U_BOOT_DATA, data[2:2 + len(U_BOOT_DATA)])
3232 self.assertEqual(b'a\0', data[-2:])
3233
Simon Glass70e32982019-07-20 12:24:01 -06003234 def testDescriptorOffset(self):
3235 """Test that the Intel descriptor is always placed at at the start"""
3236 data = self._DoReadFileDtb('141_descriptor_offset.dts')
3237 image = control.images['image']
3238 entries = image.GetEntries()
3239 desc = entries['intel-descriptor']
3240 self.assertEqual(0xff800000, desc.offset);
3241 self.assertEqual(0xff800000, desc.image_pos);
3242
Simon Glass37fdd142019-07-20 12:24:06 -06003243 def testReplaceCbfs(self):
3244 """Test replacing a single file in CBFS without changing the size"""
3245 self._CheckLz4()
3246 expected = b'x' * len(U_BOOT_DATA)
3247 data = self._DoReadFileRealDtb('142_replace_cbfs.dts')
3248 updated_fname = tools.GetOutputFilename('image-updated.bin')
3249 tools.WriteFile(updated_fname, data)
3250 entry_name = 'section/cbfs/u-boot'
3251 control.WriteEntry(updated_fname, entry_name, expected,
3252 allow_resize=True)
3253 data = control.ReadEntry(updated_fname, entry_name)
3254 self.assertEqual(expected, data)
3255
3256 def testReplaceResizeCbfs(self):
3257 """Test replacing a single file in CBFS with one of a different size"""
3258 self._CheckLz4()
3259 expected = U_BOOT_DATA + b'x'
3260 data = self._DoReadFileRealDtb('142_replace_cbfs.dts')
3261 updated_fname = tools.GetOutputFilename('image-updated.bin')
3262 tools.WriteFile(updated_fname, data)
3263 entry_name = 'section/cbfs/u-boot'
3264 control.WriteEntry(updated_fname, entry_name, expected,
3265 allow_resize=True)
3266 data = control.ReadEntry(updated_fname, entry_name)
3267 self.assertEqual(expected, data)
3268
Simon Glass30033c22019-07-20 12:24:15 -06003269 def _SetupForReplace(self):
3270 """Set up some files to use to replace entries
3271
3272 This generates an image, copies it to a new file, extracts all the files
3273 in it and updates some of them
3274
3275 Returns:
3276 List
3277 Image filename
3278 Output directory
3279 Expected values for updated entries, each a string
3280 """
3281 data = self._DoReadFileRealDtb('143_replace_all.dts')
3282
3283 updated_fname = tools.GetOutputFilename('image-updated.bin')
3284 tools.WriteFile(updated_fname, data)
3285
3286 outdir = os.path.join(self._indir, 'extract')
3287 einfos = control.ExtractEntries(updated_fname, None, outdir, [])
3288
3289 expected1 = b'x' + U_BOOT_DATA + b'y'
3290 u_boot_fname1 = os.path.join(outdir, 'u-boot')
3291 tools.WriteFile(u_boot_fname1, expected1)
3292
3293 expected2 = b'a' + U_BOOT_DATA + b'b'
3294 u_boot_fname2 = os.path.join(outdir, 'u-boot2')
3295 tools.WriteFile(u_boot_fname2, expected2)
3296
3297 expected_text = b'not the same text'
3298 text_fname = os.path.join(outdir, 'text')
3299 tools.WriteFile(text_fname, expected_text)
3300
3301 dtb_fname = os.path.join(outdir, 'u-boot-dtb')
3302 dtb = fdt.FdtScan(dtb_fname)
3303 node = dtb.GetNode('/binman/text')
3304 node.AddString('my-property', 'the value')
3305 dtb.Sync(auto_resize=True)
3306 dtb.Flush()
3307
3308 return updated_fname, outdir, expected1, expected2, expected_text
3309
3310 def _CheckReplaceMultiple(self, entry_paths):
3311 """Handle replacing the contents of multiple entries
3312
3313 Args:
3314 entry_paths: List of entry paths to replace
3315
3316 Returns:
3317 List
3318 Dict of entries in the image:
3319 key: Entry name
3320 Value: Entry object
3321 Expected values for updated entries, each a string
3322 """
3323 updated_fname, outdir, expected1, expected2, expected_text = (
3324 self._SetupForReplace())
3325 control.ReplaceEntries(updated_fname, None, outdir, entry_paths)
3326
3327 image = Image.FromFile(updated_fname)
3328 image.LoadData()
3329 return image.GetEntries(), expected1, expected2, expected_text
3330
3331 def testReplaceAll(self):
3332 """Test replacing the contents of all entries"""
3333 entries, expected1, expected2, expected_text = (
3334 self._CheckReplaceMultiple([]))
3335 data = entries['u-boot'].data
3336 self.assertEqual(expected1, data)
3337
3338 data = entries['u-boot2'].data
3339 self.assertEqual(expected2, data)
3340
3341 data = entries['text'].data
3342 self.assertEqual(expected_text, data)
3343
3344 # Check that the device tree is updated
3345 data = entries['u-boot-dtb'].data
3346 dtb = fdt.Fdt.FromData(data)
3347 dtb.Scan()
3348 node = dtb.GetNode('/binman/text')
3349 self.assertEqual('the value', node.props['my-property'].value)
3350
3351 def testReplaceSome(self):
3352 """Test replacing the contents of a few entries"""
3353 entries, expected1, expected2, expected_text = (
3354 self._CheckReplaceMultiple(['u-boot2', 'text']))
3355
3356 # This one should not change
3357 data = entries['u-boot'].data
3358 self.assertEqual(U_BOOT_DATA, data)
3359
3360 data = entries['u-boot2'].data
3361 self.assertEqual(expected2, data)
3362
3363 data = entries['text'].data
3364 self.assertEqual(expected_text, data)
3365
3366 def testReplaceCmd(self):
3367 """Test replacing a file fron an image on the command line"""
3368 self._DoReadFileRealDtb('143_replace_all.dts')
3369
3370 try:
3371 tmpdir, updated_fname = self._SetupImageInTmpdir()
3372
3373 fname = os.path.join(tmpdir, 'update-u-boot.bin')
3374 expected = b'x' * len(U_BOOT_DATA)
3375 tools.WriteFile(fname, expected)
3376
3377 self._DoBinman('replace', '-i', updated_fname, 'u-boot', '-f', fname)
3378 data = tools.ReadFile(updated_fname)
3379 self.assertEqual(expected, data[:len(expected)])
3380 map_fname = os.path.join(tmpdir, 'image-updated.map')
3381 self.assertFalse(os.path.exists(map_fname))
3382 finally:
3383 shutil.rmtree(tmpdir)
3384
3385 def testReplaceCmdSome(self):
3386 """Test replacing some files fron an image on the command line"""
3387 updated_fname, outdir, expected1, expected2, expected_text = (
3388 self._SetupForReplace())
3389
3390 self._DoBinman('replace', '-i', updated_fname, '-I', outdir,
3391 'u-boot2', 'text')
3392
3393 tools.PrepareOutputDir(None)
3394 image = Image.FromFile(updated_fname)
3395 image.LoadData()
3396 entries = image.GetEntries()
3397
3398 # This one should not change
3399 data = entries['u-boot'].data
3400 self.assertEqual(U_BOOT_DATA, data)
3401
3402 data = entries['u-boot2'].data
3403 self.assertEqual(expected2, data)
3404
3405 data = entries['text'].data
3406 self.assertEqual(expected_text, data)
3407
3408 def testReplaceMissing(self):
3409 """Test replacing entries where the file is missing"""
3410 updated_fname, outdir, expected1, expected2, expected_text = (
3411 self._SetupForReplace())
3412
3413 # Remove one of the files, to generate a warning
3414 u_boot_fname1 = os.path.join(outdir, 'u-boot')
3415 os.remove(u_boot_fname1)
3416
3417 with test_util.capture_sys_output() as (stdout, stderr):
3418 control.ReplaceEntries(updated_fname, None, outdir, [])
3419 self.assertIn("Skipping entry '/u-boot' from missing file",
Simon Glass6e02f7c2020-07-09 18:39:39 -06003420 stderr.getvalue())
Simon Glass30033c22019-07-20 12:24:15 -06003421
3422 def testReplaceCmdMap(self):
3423 """Test replacing a file fron an image on the command line"""
3424 self._DoReadFileRealDtb('143_replace_all.dts')
3425
3426 try:
3427 tmpdir, updated_fname = self._SetupImageInTmpdir()
3428
3429 fname = os.path.join(self._indir, 'update-u-boot.bin')
3430 expected = b'x' * len(U_BOOT_DATA)
3431 tools.WriteFile(fname, expected)
3432
3433 self._DoBinman('replace', '-i', updated_fname, 'u-boot',
3434 '-f', fname, '-m')
3435 map_fname = os.path.join(tmpdir, 'image-updated.map')
3436 self.assertTrue(os.path.exists(map_fname))
3437 finally:
3438 shutil.rmtree(tmpdir)
3439
3440 def testReplaceNoEntryPaths(self):
3441 """Test replacing an entry without an entry path"""
3442 self._DoReadFileRealDtb('143_replace_all.dts')
3443 image_fname = tools.GetOutputFilename('image.bin')
3444 with self.assertRaises(ValueError) as e:
3445 control.ReplaceEntries(image_fname, 'fname', None, [])
3446 self.assertIn('Must specify an entry path to read with -f',
3447 str(e.exception))
3448
3449 def testReplaceTooManyEntryPaths(self):
3450 """Test extracting some entries"""
3451 self._DoReadFileRealDtb('143_replace_all.dts')
3452 image_fname = tools.GetOutputFilename('image.bin')
3453 with self.assertRaises(ValueError) as e:
3454 control.ReplaceEntries(image_fname, 'fname', None, ['a', 'b'])
3455 self.assertIn('Must specify exactly one entry path to write with -f',
3456 str(e.exception))
3457
Simon Glass0b074d62019-08-24 07:22:48 -06003458 def testPackReset16(self):
3459 """Test that an image with an x86 reset16 region can be created"""
3460 data = self._DoReadFile('144_x86_reset16.dts')
3461 self.assertEqual(X86_RESET16_DATA, data[:len(X86_RESET16_DATA)])
3462
3463 def testPackReset16Spl(self):
3464 """Test that an image with an x86 reset16-spl region can be created"""
3465 data = self._DoReadFile('145_x86_reset16_spl.dts')
3466 self.assertEqual(X86_RESET16_SPL_DATA, data[:len(X86_RESET16_SPL_DATA)])
3467
3468 def testPackReset16Tpl(self):
3469 """Test that an image with an x86 reset16-tpl region can be created"""
3470 data = self._DoReadFile('146_x86_reset16_tpl.dts')
3471 self.assertEqual(X86_RESET16_TPL_DATA, data[:len(X86_RESET16_TPL_DATA)])
3472
Simon Glass232f90c2019-08-24 07:22:50 -06003473 def testPackIntelFit(self):
3474 """Test that an image with an Intel FIT and pointer can be created"""
3475 data = self._DoReadFile('147_intel_fit.dts')
3476 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3477 fit = data[16:32];
3478 self.assertEqual(b'_FIT_ \x01\x00\x00\x00\x00\x01\x80}' , fit)
3479 ptr = struct.unpack('<i', data[0x40:0x44])[0]
3480
3481 image = control.images['image']
3482 entries = image.GetEntries()
3483 expected_ptr = entries['intel-fit'].image_pos - (1 << 32)
3484 self.assertEqual(expected_ptr, ptr)
3485
3486 def testPackIntelFitMissing(self):
3487 """Test detection of a FIT pointer with not FIT region"""
3488 with self.assertRaises(ValueError) as e:
3489 self._DoReadFile('148_intel_fit_missing.dts')
3490 self.assertIn("'intel-fit-ptr' section must have an 'intel-fit' sibling",
3491 str(e.exception))
3492
Simon Glass72555fa2019-11-06 17:22:44 -07003493 def _CheckSymbolsTplSection(self, dts, expected_vals):
3494 data = self._DoReadFile(dts)
3495 sym_values = struct.pack('<LQLL', *expected_vals)
Simon Glass3eb5b202019-08-24 07:23:00 -06003496 upto1 = 4 + len(U_BOOT_SPL_DATA)
Simon Glass3f8ff012019-08-24 07:23:05 -06003497 expected1 = tools.GetBytes(0xff, 4) + sym_values + U_BOOT_SPL_DATA[20:]
Simon Glass3eb5b202019-08-24 07:23:00 -06003498 self.assertEqual(expected1, data[:upto1])
3499
3500 upto2 = upto1 + 1 + len(U_BOOT_SPL_DATA)
Simon Glass3f8ff012019-08-24 07:23:05 -06003501 expected2 = tools.GetBytes(0xff, 1) + sym_values + U_BOOT_SPL_DATA[20:]
Simon Glass3eb5b202019-08-24 07:23:00 -06003502 self.assertEqual(expected2, data[upto1:upto2])
3503
Simon Glass4e353e22019-08-24 07:23:04 -06003504 upto3 = 0x34 + len(U_BOOT_DATA)
3505 expected3 = tools.GetBytes(0xff, 1) + U_BOOT_DATA
Simon Glass3eb5b202019-08-24 07:23:00 -06003506 self.assertEqual(expected3, data[upto2:upto3])
3507
Simon Glass3f8ff012019-08-24 07:23:05 -06003508 expected4 = sym_values + U_BOOT_TPL_DATA[20:]
Simon Glass72555fa2019-11-06 17:22:44 -07003509 self.assertEqual(expected4, data[upto3:upto3 + len(U_BOOT_TPL_DATA)])
3510
3511 def testSymbolsTplSection(self):
3512 """Test binman can assign symbols embedded in U-Boot TPL in a section"""
3513 self._SetupSplElf('u_boot_binman_syms')
3514 self._SetupTplElf('u_boot_binman_syms')
3515 self._CheckSymbolsTplSection('149_symbols_tpl.dts',
3516 [0x04, 0x1c, 0x10 + 0x34, 0x04])
3517
3518 def testSymbolsTplSectionX86(self):
3519 """Test binman can assign symbols in a section with end-at-4gb"""
3520 self._SetupSplElf('u_boot_binman_syms_x86')
3521 self._SetupTplElf('u_boot_binman_syms_x86')
3522 self._CheckSymbolsTplSection('155_symbols_tpl_x86.dts',
3523 [0xffffff04, 0xffffff1c, 0xffffff34,
3524 0x04])
Simon Glass3eb5b202019-08-24 07:23:00 -06003525
Simon Glass98c59572019-08-24 07:23:03 -06003526 def testPackX86RomIfwiSectiom(self):
3527 """Test that a section can be placed in an IFWI region"""
3528 self._SetupIfwi('fitimage.bin')
3529 data = self._DoReadFile('151_x86_rom_ifwi_section.dts')
3530 self._CheckIfwi(data)
3531
Simon Glassba7985d2019-08-24 07:23:07 -06003532 def testPackFspM(self):
3533 """Test that an image with a FSP memory-init binary can be created"""
3534 data = self._DoReadFile('152_intel_fsp_m.dts')
3535 self.assertEqual(FSP_M_DATA, data[:len(FSP_M_DATA)])
3536
Simon Glass4d9086d2019-10-20 21:31:35 -06003537 def testPackFspS(self):
3538 """Test that an image with a FSP silicon-init binary can be created"""
3539 data = self._DoReadFile('153_intel_fsp_s.dts')
3540 self.assertEqual(FSP_S_DATA, data[:len(FSP_S_DATA)])
Simon Glassba7985d2019-08-24 07:23:07 -06003541
Simon Glass9ea87b22019-10-20 21:31:36 -06003542 def testPackFspT(self):
3543 """Test that an image with a FSP temp-ram-init binary can be created"""
3544 data = self._DoReadFile('154_intel_fsp_t.dts')
3545 self.assertEqual(FSP_T_DATA, data[:len(FSP_T_DATA)])
3546
Simon Glass48f3aad2020-07-09 18:39:31 -06003547 def testMkimage(self):
3548 """Test using mkimage to build an image"""
3549 data = self._DoReadFile('156_mkimage.dts')
3550
3551 # Just check that the data appears in the file somewhere
3552 self.assertIn(U_BOOT_SPL_DATA, data)
3553
Simon Glass5e560182020-07-09 18:39:36 -06003554 def testExtblob(self):
3555 """Test an image with an external blob"""
3556 data = self._DoReadFile('157_blob_ext.dts')
3557 self.assertEqual(REFCODE_DATA, data)
3558
3559 def testExtblobMissing(self):
3560 """Test an image with a missing external blob"""
3561 with self.assertRaises(ValueError) as e:
3562 self._DoReadFile('158_blob_ext_missing.dts')
3563 self.assertIn("Filename 'missing-file' not found in input path",
3564 str(e.exception))
3565
Simon Glass5d94cc62020-07-09 18:39:38 -06003566 def testExtblobMissingOk(self):
3567 """Test an image with an missing external blob that is allowed"""
Simon Glassa003cd32020-07-09 18:39:40 -06003568 with test_util.capture_sys_output() as (stdout, stderr):
3569 self._DoTestFile('158_blob_ext_missing.dts', allow_missing=True)
3570 err = stderr.getvalue()
3571 self.assertRegex(err, "Image 'main-section'.*missing.*: blob-ext")
3572
3573 def testExtblobMissingOkSect(self):
3574 """Test an image with an missing external blob that is allowed"""
3575 with test_util.capture_sys_output() as (stdout, stderr):
3576 self._DoTestFile('159_blob_ext_missing_sect.dts',
3577 allow_missing=True)
3578 err = stderr.getvalue()
3579 self.assertRegex(err, "Image 'main-section'.*missing.*: "
3580 "blob-ext blob-ext2")
Simon Glass5d94cc62020-07-09 18:39:38 -06003581
Simon Glasse88cef92020-07-09 18:39:41 -06003582 def testPackX86RomMeMissingDesc(self):
3583 """Test that an missing Intel descriptor entry is allowed"""
Simon Glasse88cef92020-07-09 18:39:41 -06003584 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass14c596c2020-07-25 15:11:19 -06003585 self._DoTestFile('164_x86_rom_me_missing.dts', allow_missing=True)
Simon Glasse88cef92020-07-09 18:39:41 -06003586 err = stderr.getvalue()
3587 self.assertRegex(err,
3588 "Image 'main-section'.*missing.*: intel-descriptor")
3589
3590 def testPackX86RomMissingIfwi(self):
3591 """Test that an x86 ROM with Integrated Firmware Image can be created"""
3592 self._SetupIfwi('fitimage.bin')
3593 pathname = os.path.join(self._indir, 'fitimage.bin')
3594 os.remove(pathname)
3595 with test_util.capture_sys_output() as (stdout, stderr):
3596 self._DoTestFile('111_x86_rom_ifwi.dts', allow_missing=True)
3597 err = stderr.getvalue()
3598 self.assertRegex(err, "Image 'main-section'.*missing.*: intel-ifwi")
3599
Simon Glassd70829a2020-07-09 18:39:42 -06003600 def testPackOverlap(self):
3601 """Test that zero-size overlapping regions are ignored"""
3602 self._DoTestFile('160_pack_overlap_zero.dts')
3603
Simon Glass45d556d2020-07-09 18:39:45 -06003604 def testSimpleFit(self):
3605 """Test an image with a FIT inside"""
3606 data = self._DoReadFile('161_fit.dts')
3607 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3608 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3609 fit_data = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3610
3611 # The data should be inside the FIT
3612 dtb = fdt.Fdt.FromData(fit_data)
3613 dtb.Scan()
3614 fnode = dtb.GetNode('/images/kernel')
3615 self.assertIn('data', fnode.props)
3616
3617 fname = os.path.join(self._indir, 'fit_data.fit')
3618 tools.WriteFile(fname, fit_data)
3619 out = tools.Run('dumpimage', '-l', fname)
3620
3621 # Check a few features to make sure the plumbing works. We don't need
3622 # to test the operation of mkimage or dumpimage here. First convert the
3623 # output into a dict where the keys are the fields printed by dumpimage
3624 # and the values are a list of values for each field
3625 lines = out.splitlines()
3626
3627 # Converts "Compression: gzip compressed" into two groups:
3628 # 'Compression' and 'gzip compressed'
3629 re_line = re.compile(r'^ *([^:]*)(?:: *(.*))?$')
3630 vals = collections.defaultdict(list)
3631 for line in lines:
3632 mat = re_line.match(line)
3633 vals[mat.group(1)].append(mat.group(2))
3634
3635 self.assertEquals('FIT description: test-desc', lines[0])
3636 self.assertIn('Created:', lines[1])
3637 self.assertIn('Image 0 (kernel)', vals)
3638 self.assertIn('Hash value', vals)
3639 data_sizes = vals.get('Data Size')
3640 self.assertIsNotNone(data_sizes)
3641 self.assertEqual(2, len(data_sizes))
3642 # Format is "4 Bytes = 0.00 KiB = 0.00 MiB" so take the first word
3643 self.assertEqual(len(U_BOOT_DATA), int(data_sizes[0].split()[0]))
3644 self.assertEqual(len(U_BOOT_SPL_DTB_DATA), int(data_sizes[1].split()[0]))
3645
3646 def testFitExternal(self):
Simon Glass31ee50f2020-09-01 05:13:55 -06003647 """Test an image with an FIT with external images"""
Simon Glass45d556d2020-07-09 18:39:45 -06003648 data = self._DoReadFile('162_fit_external.dts')
3649 fit_data = data[len(U_BOOT_DATA):-2] # _testing is 2 bytes
3650
3651 # The data should be outside the FIT
3652 dtb = fdt.Fdt.FromData(fit_data)
3653 dtb.Scan()
3654 fnode = dtb.GetNode('/images/kernel')
3655 self.assertNotIn('data', fnode.props)
Simon Glassfb30e292019-07-20 12:23:51 -06003656
Alper Nebi Yasak6aae2392020-08-31 12:58:18 +03003657 def testSectionIgnoreHashSignature(self):
3658 """Test that sections ignore hash, signature nodes for its data"""
3659 data = self._DoReadFile('165_section_ignore_hash_signature.dts')
3660 expected = (U_BOOT_DATA + U_BOOT_DATA)
3661 self.assertEqual(expected, data)
3662
Alper Nebi Yasakc5030602020-08-31 12:58:19 +03003663 def testPadInSections(self):
3664 """Test pad-before, pad-after for entries in sections"""
Simon Glassd12599d2020-10-26 17:40:09 -06003665 data, _, _, out_dtb_fname = self._DoReadFileDtb(
3666 '166_pad_in_sections.dts', update_dtb=True)
Alper Nebi Yasakc5030602020-08-31 12:58:19 +03003667 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
3668 U_BOOT_DATA + tools.GetBytes(ord('!'), 6) +
3669 U_BOOT_DATA)
3670 self.assertEqual(expected, data)
3671
Simon Glassd12599d2020-10-26 17:40:09 -06003672 dtb = fdt.Fdt(out_dtb_fname)
3673 dtb.Scan()
3674 props = self._GetPropTree(dtb, ['size', 'image-pos', 'offset'])
3675 expected = {
3676 'image-pos': 0,
3677 'offset': 0,
3678 'size': 12 + 6 + 3 * len(U_BOOT_DATA),
3679
3680 'section:image-pos': 0,
3681 'section:offset': 0,
3682 'section:size': 12 + 6 + 3 * len(U_BOOT_DATA),
3683
3684 'section/before:image-pos': 0,
3685 'section/before:offset': 0,
3686 'section/before:size': len(U_BOOT_DATA),
3687
3688 'section/u-boot:image-pos': 4,
3689 'section/u-boot:offset': 4,
3690 'section/u-boot:size': 12 + len(U_BOOT_DATA) + 6,
3691
3692 'section/after:image-pos': 26,
3693 'section/after:offset': 26,
3694 'section/after:size': len(U_BOOT_DATA),
3695 }
3696 self.assertEqual(expected, props)
3697
Alper Nebi Yasakc261ec12020-08-31 12:58:20 +03003698 def testFitImageSubentryAlignment(self):
3699 """Test relative alignability of FIT image subentries"""
3700 entry_args = {
3701 'test-id': TEXT_DATA,
3702 }
3703 data, _, _, _ = self._DoReadFileDtb('167_fit_image_subentry_alignment.dts',
3704 entry_args=entry_args)
3705 dtb = fdt.Fdt.FromData(data)
3706 dtb.Scan()
3707
3708 node = dtb.GetNode('/images/kernel')
3709 data = dtb.GetProps(node)["data"].bytes
3710 align_pad = 0x10 - (len(U_BOOT_SPL_DATA) % 0x10)
3711 expected = (tools.GetBytes(0, 0x20) + U_BOOT_SPL_DATA +
3712 tools.GetBytes(0, align_pad) + U_BOOT_DATA)
3713 self.assertEqual(expected, data)
3714
3715 node = dtb.GetNode('/images/fdt-1')
3716 data = dtb.GetProps(node)["data"].bytes
3717 expected = (U_BOOT_SPL_DTB_DATA + tools.GetBytes(0, 20) +
3718 tools.ToBytes(TEXT_DATA) + tools.GetBytes(0, 30) +
3719 U_BOOT_DTB_DATA)
3720 self.assertEqual(expected, data)
3721
3722 def testFitExtblobMissingOk(self):
3723 """Test a FIT with a missing external blob that is allowed"""
3724 with test_util.capture_sys_output() as (stdout, stderr):
3725 self._DoTestFile('168_fit_missing_blob.dts',
3726 allow_missing=True)
3727 err = stderr.getvalue()
Simon Glassa820af72020-09-06 10:39:09 -06003728 self.assertRegex(err, "Image 'main-section'.*missing.*: atf-bl31")
Alper Nebi Yasakc261ec12020-08-31 12:58:20 +03003729
Simon Glass21db0ff2020-09-01 05:13:54 -06003730 def testBlobNamedByArgMissing(self):
3731 """Test handling of a missing entry arg"""
3732 with self.assertRaises(ValueError) as e:
3733 self._DoReadFile('068_blob_named_by_arg.dts')
3734 self.assertIn("Missing required properties/entry args: cros-ec-rw-path",
3735 str(e.exception))
3736
Simon Glass559c4de2020-09-01 05:13:58 -06003737 def testPackBl31(self):
3738 """Test that an image with an ATF BL31 binary can be created"""
3739 data = self._DoReadFile('169_atf_bl31.dts')
3740 self.assertEqual(ATF_BL31_DATA, data[:len(ATF_BL31_DATA)])
3741
Samuel Holland9d8cc632020-10-21 21:12:15 -05003742 def testPackScp(self):
3743 """Test that an image with an SCP binary can be created"""
3744 data = self._DoReadFile('172_scp.dts')
3745 self.assertEqual(SCP_DATA, data[:len(SCP_DATA)])
3746
Simon Glassa435cd12020-09-01 05:13:59 -06003747 def testFitFdt(self):
3748 """Test an image with an FIT with multiple FDT images"""
3749 def _CheckFdt(seq, expected_data):
3750 """Check the FDT nodes
3751
3752 Args:
3753 seq: Sequence number to check (0 or 1)
3754 expected_data: Expected contents of 'data' property
3755 """
3756 name = 'fdt-%d' % seq
3757 fnode = dtb.GetNode('/images/%s' % name)
3758 self.assertIsNotNone(fnode)
3759 self.assertEqual({'description','type', 'compression', 'data'},
3760 set(fnode.props.keys()))
3761 self.assertEqual(expected_data, fnode.props['data'].bytes)
3762 self.assertEqual('fdt-test-fdt%d.dtb' % seq,
3763 fnode.props['description'].value)
3764
3765 def _CheckConfig(seq, expected_data):
3766 """Check the configuration nodes
3767
3768 Args:
3769 seq: Sequence number to check (0 or 1)
3770 expected_data: Expected contents of 'data' property
3771 """
3772 cnode = dtb.GetNode('/configurations')
3773 self.assertIn('default', cnode.props)
Simon Glass1032acc2020-09-06 10:39:08 -06003774 self.assertEqual('config-2', cnode.props['default'].value)
Simon Glassa435cd12020-09-01 05:13:59 -06003775
3776 name = 'config-%d' % seq
3777 fnode = dtb.GetNode('/configurations/%s' % name)
3778 self.assertIsNotNone(fnode)
3779 self.assertEqual({'description','firmware', 'loadables', 'fdt'},
3780 set(fnode.props.keys()))
3781 self.assertEqual('conf-test-fdt%d.dtb' % seq,
3782 fnode.props['description'].value)
3783 self.assertEqual('fdt-%d' % seq, fnode.props['fdt'].value)
3784
3785 entry_args = {
3786 'of-list': 'test-fdt1 test-fdt2',
Simon Glass1032acc2020-09-06 10:39:08 -06003787 'default-dt': 'test-fdt2',
Simon Glassa435cd12020-09-01 05:13:59 -06003788 }
3789 data = self._DoReadFileDtb(
Simon Glass1032acc2020-09-06 10:39:08 -06003790 '172_fit_fdt.dts',
Simon Glassa435cd12020-09-01 05:13:59 -06003791 entry_args=entry_args,
3792 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3793 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3794 fit_data = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3795
3796 dtb = fdt.Fdt.FromData(fit_data)
3797 dtb.Scan()
3798 fnode = dtb.GetNode('/images/kernel')
3799 self.assertIn('data', fnode.props)
3800
3801 # Check all the properties in fdt-1 and fdt-2
3802 _CheckFdt(1, TEST_FDT1_DATA)
3803 _CheckFdt(2, TEST_FDT2_DATA)
3804
3805 # Check configurations
3806 _CheckConfig(1, TEST_FDT1_DATA)
3807 _CheckConfig(2, TEST_FDT2_DATA)
3808
3809 def testFitFdtMissingList(self):
3810 """Test handling of a missing 'of-list' entry arg"""
3811 with self.assertRaises(ValueError) as e:
Simon Glass1032acc2020-09-06 10:39:08 -06003812 self._DoReadFile('172_fit_fdt.dts')
Simon Glassa435cd12020-09-01 05:13:59 -06003813 self.assertIn("Generator node requires 'of-list' entry argument",
3814 str(e.exception))
3815
3816 def testFitFdtEmptyList(self):
3817 """Test handling of an empty 'of-list' entry arg"""
3818 entry_args = {
3819 'of-list': '',
3820 }
3821 data = self._DoReadFileDtb('170_fit_fdt.dts', entry_args=entry_args)[0]
3822
3823 def testFitFdtMissingProp(self):
3824 """Test handling of a missing 'fit,fdt-list' property"""
3825 with self.assertRaises(ValueError) as e:
3826 self._DoReadFile('171_fit_fdt_missing_prop.dts')
3827 self.assertIn("Generator node requires 'fit,fdt-list' property",
3828 str(e.exception))
Simon Glass559c4de2020-09-01 05:13:58 -06003829
Simon Glass1032acc2020-09-06 10:39:08 -06003830 def testFitFdtEmptyList(self):
3831 """Test handling of an empty 'of-list' entry arg"""
3832 entry_args = {
3833 'of-list': '',
3834 }
3835 data = self._DoReadFileDtb('172_fit_fdt.dts', entry_args=entry_args)[0]
3836
3837 def testFitFdtMissing(self):
3838 """Test handling of a missing 'default-dt' entry arg"""
3839 entry_args = {
3840 'of-list': 'test-fdt1 test-fdt2',
3841 }
3842 with self.assertRaises(ValueError) as e:
3843 self._DoReadFileDtb(
3844 '172_fit_fdt.dts',
3845 entry_args=entry_args,
3846 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3847 self.assertIn("Generated 'default' node requires default-dt entry argument",
3848 str(e.exception))
3849
3850 def testFitFdtNotInList(self):
3851 """Test handling of a default-dt that is not in the of-list"""
3852 entry_args = {
3853 'of-list': 'test-fdt1 test-fdt2',
3854 'default-dt': 'test-fdt3',
3855 }
3856 with self.assertRaises(ValueError) as e:
3857 self._DoReadFileDtb(
3858 '172_fit_fdt.dts',
3859 entry_args=entry_args,
3860 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3861 self.assertIn("default-dt entry argument 'test-fdt3' not found in fdt list: test-fdt1, test-fdt2",
3862 str(e.exception))
3863
Simon Glassa820af72020-09-06 10:39:09 -06003864 def testFitExtblobMissingHelp(self):
3865 """Test display of help messages when an external blob is missing"""
3866 control.missing_blob_help = control._ReadMissingBlobHelp()
3867 control.missing_blob_help['wibble'] = 'Wibble test'
3868 control.missing_blob_help['another'] = 'Another test'
3869 with test_util.capture_sys_output() as (stdout, stderr):
3870 self._DoTestFile('168_fit_missing_blob.dts',
3871 allow_missing=True)
3872 err = stderr.getvalue()
3873
3874 # We can get the tag from the name, the type or the missing-msg
3875 # property. Check all three.
3876 self.assertIn('You may need to build ARM Trusted', err)
3877 self.assertIn('Wibble test', err)
3878 self.assertIn('Another test', err)
3879
Simon Glass6f1f4d42020-09-06 10:35:32 -06003880 def testMissingBlob(self):
3881 """Test handling of a blob containing a missing file"""
3882 with self.assertRaises(ValueError) as e:
3883 self._DoTestFile('173_missing_blob.dts', allow_missing=True)
3884 self.assertIn("Filename 'missing' not found in input path",
3885 str(e.exception))
3886
Simon Glassa0729502020-09-06 10:35:33 -06003887 def testEnvironment(self):
3888 """Test adding a U-Boot environment"""
3889 data = self._DoReadFile('174_env.dts')
3890 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3891 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3892 env = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3893 self.assertEqual(b'\x1b\x97\x22\x7c\x01var1=1\0var2="2"\0\0\xff\xff',
3894 env)
3895
3896 def testEnvironmentNoSize(self):
3897 """Test that a missing 'size' property is detected"""
3898 with self.assertRaises(ValueError) as e:
Simon Glass8cdc08a2020-10-26 17:40:00 -06003899 self._DoTestFile('175_env_no_size.dts')
Simon Glassa0729502020-09-06 10:35:33 -06003900 self.assertIn("'u-boot-env' entry must have a size property",
3901 str(e.exception))
3902
3903 def testEnvironmentTooSmall(self):
3904 """Test handling of an environment that does not fit"""
3905 with self.assertRaises(ValueError) as e:
Simon Glass8cdc08a2020-10-26 17:40:00 -06003906 self._DoTestFile('176_env_too_small.dts')
Simon Glassa0729502020-09-06 10:35:33 -06003907
3908 # checksum, start byte, environment with \0 terminator, final \0
3909 need = 4 + 1 + len(ENV_DATA) + 1 + 1
3910 short = need - 0x8
3911 self.assertIn("too small to hold data (need %#x more bytes)" % short,
3912 str(e.exception))
3913
Simon Glassd1fdf752020-10-26 17:40:01 -06003914 def testSkipAtStart(self):
3915 """Test handling of skip-at-start section"""
3916 data = self._DoReadFile('177_skip_at_start.dts')
3917 self.assertEqual(U_BOOT_DATA, data)
3918
3919 image = control.images['image']
3920 entries = image.GetEntries()
3921 section = entries['section']
3922 self.assertEqual(0, section.offset)
3923 self.assertEqual(len(U_BOOT_DATA), section.size)
3924 self.assertEqual(U_BOOT_DATA, section.GetData())
3925
3926 entry = section.GetEntries()['u-boot']
3927 self.assertEqual(16, entry.offset)
3928 self.assertEqual(len(U_BOOT_DATA), entry.size)
3929 self.assertEqual(U_BOOT_DATA, entry.data)
3930
3931 def testSkipAtStartPad(self):
3932 """Test handling of skip-at-start section with padded entry"""
3933 data = self._DoReadFile('178_skip_at_start_pad.dts')
3934 before = tools.GetBytes(0, 8)
3935 after = tools.GetBytes(0, 4)
3936 all = before + U_BOOT_DATA + after
3937 self.assertEqual(all, data)
3938
3939 image = control.images['image']
3940 entries = image.GetEntries()
3941 section = entries['section']
3942 self.assertEqual(0, section.offset)
3943 self.assertEqual(len(all), section.size)
3944 self.assertEqual(all, section.GetData())
3945
3946 entry = section.GetEntries()['u-boot']
3947 self.assertEqual(16, entry.offset)
3948 self.assertEqual(len(all), entry.size)
3949 self.assertEqual(U_BOOT_DATA, entry.data)
3950
3951 def testSkipAtStartSectionPad(self):
3952 """Test handling of skip-at-start section with padding"""
3953 data = self._DoReadFile('179_skip_at_start_section_pad.dts')
3954 before = tools.GetBytes(0, 8)
3955 after = tools.GetBytes(0, 4)
3956 all = before + U_BOOT_DATA + after
Simon Glass510ef0f2020-10-26 17:40:13 -06003957 self.assertEqual(all, data)
Simon Glassd1fdf752020-10-26 17:40:01 -06003958
3959 image = control.images['image']
3960 entries = image.GetEntries()
3961 section = entries['section']
3962 self.assertEqual(0, section.offset)
3963 self.assertEqual(len(all), section.size)
Simon Glass72eeff12020-10-26 17:40:16 -06003964 self.assertEqual(U_BOOT_DATA, section.data)
Simon Glass510ef0f2020-10-26 17:40:13 -06003965 self.assertEqual(all, section.GetPaddedData())
Simon Glassd1fdf752020-10-26 17:40:01 -06003966
3967 entry = section.GetEntries()['u-boot']
3968 self.assertEqual(16, entry.offset)
3969 self.assertEqual(len(U_BOOT_DATA), entry.size)
3970 self.assertEqual(U_BOOT_DATA, entry.data)
Simon Glassa0729502020-09-06 10:35:33 -06003971
Simon Glassbb395742020-10-26 17:40:14 -06003972 def testSectionPad(self):
3973 """Testing padding with sections"""
3974 data = self._DoReadFile('180_section_pad.dts')
3975 expected = (tools.GetBytes(ord('&'), 3) +
3976 tools.GetBytes(ord('!'), 5) +
3977 U_BOOT_DATA +
3978 tools.GetBytes(ord('!'), 1) +
3979 tools.GetBytes(ord('&'), 2))
3980 self.assertEqual(expected, data)
3981
3982 def testSectionAlign(self):
3983 """Testing alignment with sections"""
3984 data = self._DoReadFileDtb('181_section_align.dts', map=True)[0]
3985 expected = (b'\0' + # fill section
3986 tools.GetBytes(ord('&'), 1) + # padding to section align
3987 b'\0' + # fill section
3988 tools.GetBytes(ord('!'), 3) + # padding to u-boot align
3989 U_BOOT_DATA +
3990 tools.GetBytes(ord('!'), 4) + # padding to u-boot size
3991 tools.GetBytes(ord('!'), 4)) # padding to section size
3992 self.assertEqual(expected, data)
3993
Simon Glassd92c8362020-10-26 17:40:25 -06003994 def testCompressImage(self):
3995 """Test compression of the entire image"""
3996 self._CheckLz4()
3997 data, _, _, out_dtb_fname = self._DoReadFileDtb(
3998 '182_compress_image.dts', use_real_dtb=True, update_dtb=True)
3999 dtb = fdt.Fdt(out_dtb_fname)
4000 dtb.Scan()
4001 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4002 'uncomp-size'])
4003 orig = self._decompress(data)
4004 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4005
4006 # Do a sanity check on various fields
4007 image = control.images['image']
4008 entries = image.GetEntries()
4009 self.assertEqual(2, len(entries))
4010
4011 entry = entries['blob']
4012 self.assertEqual(COMPRESS_DATA, entry.data)
4013 self.assertEqual(len(COMPRESS_DATA), entry.size)
4014
4015 entry = entries['u-boot']
4016 self.assertEqual(U_BOOT_DATA, entry.data)
4017 self.assertEqual(len(U_BOOT_DATA), entry.size)
4018
4019 self.assertEqual(len(data), image.size)
4020 self.assertEqual(COMPRESS_DATA + U_BOOT_DATA, image.uncomp_data)
4021 self.assertEqual(len(COMPRESS_DATA + U_BOOT_DATA), image.uncomp_size)
4022 orig = self._decompress(image.data)
4023 self.assertEqual(orig, image.uncomp_data)
4024
4025 expected = {
4026 'blob:offset': 0,
4027 'blob:size': len(COMPRESS_DATA),
4028 'u-boot:offset': len(COMPRESS_DATA),
4029 'u-boot:size': len(U_BOOT_DATA),
4030 'uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4031 'offset': 0,
4032 'image-pos': 0,
4033 'size': len(data),
4034 }
4035 self.assertEqual(expected, props)
4036
4037 def testCompressImageLess(self):
4038 """Test compression where compression reduces the image size"""
4039 self._CheckLz4()
4040 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4041 '183_compress_image_less.dts', use_real_dtb=True, update_dtb=True)
4042 dtb = fdt.Fdt(out_dtb_fname)
4043 dtb.Scan()
4044 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4045 'uncomp-size'])
4046 orig = self._decompress(data)
4047
4048 self.assertEquals(COMPRESS_DATA + COMPRESS_DATA + U_BOOT_DATA, orig)
4049
4050 # Do a sanity check on various fields
4051 image = control.images['image']
4052 entries = image.GetEntries()
4053 self.assertEqual(2, len(entries))
4054
4055 entry = entries['blob']
4056 self.assertEqual(COMPRESS_DATA_BIG, entry.data)
4057 self.assertEqual(len(COMPRESS_DATA_BIG), entry.size)
4058
4059 entry = entries['u-boot']
4060 self.assertEqual(U_BOOT_DATA, entry.data)
4061 self.assertEqual(len(U_BOOT_DATA), entry.size)
4062
4063 self.assertEqual(len(data), image.size)
4064 self.assertEqual(COMPRESS_DATA_BIG + U_BOOT_DATA, image.uncomp_data)
4065 self.assertEqual(len(COMPRESS_DATA_BIG + U_BOOT_DATA),
4066 image.uncomp_size)
4067 orig = self._decompress(image.data)
4068 self.assertEqual(orig, image.uncomp_data)
4069
4070 expected = {
4071 'blob:offset': 0,
4072 'blob:size': len(COMPRESS_DATA_BIG),
4073 'u-boot:offset': len(COMPRESS_DATA_BIG),
4074 'u-boot:size': len(U_BOOT_DATA),
4075 'uncomp-size': len(COMPRESS_DATA_BIG + U_BOOT_DATA),
4076 'offset': 0,
4077 'image-pos': 0,
4078 'size': len(data),
4079 }
4080 self.assertEqual(expected, props)
4081
4082 def testCompressSectionSize(self):
4083 """Test compression of a section with a fixed size"""
4084 self._CheckLz4()
4085 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4086 '184_compress_section_size.dts', use_real_dtb=True, update_dtb=True)
4087 dtb = fdt.Fdt(out_dtb_fname)
4088 dtb.Scan()
4089 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4090 'uncomp-size'])
4091 orig = self._decompress(data)
4092 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4093 expected = {
4094 'section/blob:offset': 0,
4095 'section/blob:size': len(COMPRESS_DATA),
4096 'section/u-boot:offset': len(COMPRESS_DATA),
4097 'section/u-boot:size': len(U_BOOT_DATA),
4098 'section:offset': 0,
4099 'section:image-pos': 0,
4100 'section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4101 'section:size': 0x30,
4102 'offset': 0,
4103 'image-pos': 0,
4104 'size': 0x30,
4105 }
4106 self.assertEqual(expected, props)
4107
4108 def testCompressSection(self):
4109 """Test compression of a section with no fixed size"""
4110 self._CheckLz4()
4111 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4112 '185_compress_section.dts', use_real_dtb=True, update_dtb=True)
4113 dtb = fdt.Fdt(out_dtb_fname)
4114 dtb.Scan()
4115 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4116 'uncomp-size'])
4117 orig = self._decompress(data)
4118 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4119 expected = {
4120 'section/blob:offset': 0,
4121 'section/blob:size': len(COMPRESS_DATA),
4122 'section/u-boot:offset': len(COMPRESS_DATA),
4123 'section/u-boot:size': len(U_BOOT_DATA),
4124 'section:offset': 0,
4125 'section:image-pos': 0,
4126 'section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4127 'section:size': len(data),
4128 'offset': 0,
4129 'image-pos': 0,
4130 'size': len(data),
4131 }
4132 self.assertEqual(expected, props)
4133
4134 def testCompressExtra(self):
4135 """Test compression of a section with no fixed size"""
4136 self._CheckLz4()
4137 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4138 '186_compress_extra.dts', use_real_dtb=True, update_dtb=True)
4139 dtb = fdt.Fdt(out_dtb_fname)
4140 dtb.Scan()
4141 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4142 'uncomp-size'])
4143
4144 base = data[len(U_BOOT_DATA):]
4145 self.assertEquals(U_BOOT_DATA, base[:len(U_BOOT_DATA)])
4146 rest = base[len(U_BOOT_DATA):]
4147
4148 # Check compressed data
4149 section1 = self._decompress(rest)
4150 expect1 = tools.Compress(COMPRESS_DATA + U_BOOT_DATA, 'lz4')
4151 self.assertEquals(expect1, rest[:len(expect1)])
4152 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, section1)
4153 rest1 = rest[len(expect1):]
4154
4155 section2 = self._decompress(rest1)
4156 expect2 = tools.Compress(COMPRESS_DATA + COMPRESS_DATA, 'lz4')
4157 self.assertEquals(expect2, rest1[:len(expect2)])
4158 self.assertEquals(COMPRESS_DATA + COMPRESS_DATA, section2)
4159 rest2 = rest1[len(expect2):]
4160
4161 expect_size = (len(U_BOOT_DATA) + len(U_BOOT_DATA) + len(expect1) +
4162 len(expect2) + len(U_BOOT_DATA))
4163 #self.assertEquals(expect_size, len(data))
4164
4165 #self.assertEquals(U_BOOT_DATA, rest2)
4166
4167 self.maxDiff = None
4168 expected = {
4169 'u-boot:offset': 0,
4170 'u-boot:image-pos': 0,
4171 'u-boot:size': len(U_BOOT_DATA),
4172
4173 'base:offset': len(U_BOOT_DATA),
4174 'base:image-pos': len(U_BOOT_DATA),
4175 'base:size': len(data) - len(U_BOOT_DATA),
4176 'base/u-boot:offset': 0,
4177 'base/u-boot:image-pos': len(U_BOOT_DATA),
4178 'base/u-boot:size': len(U_BOOT_DATA),
4179 'base/u-boot2:offset': len(U_BOOT_DATA) + len(expect1) +
4180 len(expect2),
4181 'base/u-boot2:image-pos': len(U_BOOT_DATA) * 2 + len(expect1) +
4182 len(expect2),
4183 'base/u-boot2:size': len(U_BOOT_DATA),
4184
4185 'base/section:offset': len(U_BOOT_DATA),
4186 'base/section:image-pos': len(U_BOOT_DATA) * 2,
4187 'base/section:size': len(expect1),
4188 'base/section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4189 'base/section/blob:offset': 0,
4190 'base/section/blob:size': len(COMPRESS_DATA),
4191 'base/section/u-boot:offset': len(COMPRESS_DATA),
4192 'base/section/u-boot:size': len(U_BOOT_DATA),
4193
4194 'base/section2:offset': len(U_BOOT_DATA) + len(expect1),
4195 'base/section2:image-pos': len(U_BOOT_DATA) * 2 + len(expect1),
4196 'base/section2:size': len(expect2),
4197 'base/section2:uncomp-size': len(COMPRESS_DATA + COMPRESS_DATA),
4198 'base/section2/blob:offset': 0,
4199 'base/section2/blob:size': len(COMPRESS_DATA),
4200 'base/section2/blob2:offset': len(COMPRESS_DATA),
4201 'base/section2/blob2:size': len(COMPRESS_DATA),
4202
4203 'offset': 0,
4204 'image-pos': 0,
4205 'size': len(data),
4206 }
4207 self.assertEqual(expected, props)
4208
Simon Glassecbe4732021-01-06 21:35:15 -07004209 def testSymbolsSubsection(self):
4210 """Test binman can assign symbols from a subsection"""
Simon Glass31e04cb2021-03-18 20:24:56 +13004211 self.checkSymbols('187_symbols_sub.dts', U_BOOT_SPL_DATA, 0x18)
Simon Glassecbe4732021-01-06 21:35:15 -07004212
Simon Glass3fb25402021-01-06 21:35:16 -07004213 def testReadImageEntryArg(self):
4214 """Test reading an image that would need an entry arg to generate"""
4215 entry_args = {
4216 'cros-ec-rw-path': 'ecrw.bin',
4217 }
4218 data = self.data = self._DoReadFileDtb(
4219 '188_image_entryarg.dts',use_real_dtb=True, update_dtb=True,
4220 entry_args=entry_args)
4221
4222 image_fname = tools.GetOutputFilename('image.bin')
4223 orig_image = control.images['image']
4224
4225 # This should not generate an error about the missing 'cros-ec-rw-path'
4226 # since we are reading the image from a file. Compare with
4227 # testEntryArgsRequired()
4228 image = Image.FromFile(image_fname)
4229 self.assertEqual(orig_image.GetEntries().keys(),
4230 image.GetEntries().keys())
4231
Simon Glassa2af7302021-01-06 21:35:18 -07004232 def testFilesAlign(self):
4233 """Test alignment with files"""
4234 data = self._DoReadFile('190_files_align.dts')
4235
4236 # The first string is 15 bytes so will align to 16
4237 expect = FILES_DATA[:15] + b'\0' + FILES_DATA[15:]
4238 self.assertEqual(expect, data)
4239
Simon Glassdb84b562021-01-06 21:35:19 -07004240 def testReadImageSkip(self):
4241 """Test reading an image and accessing its FDT map"""
4242 data = self.data = self._DoReadFileRealDtb('191_read_image_skip.dts')
4243 image_fname = tools.GetOutputFilename('image.bin')
4244 orig_image = control.images['image']
4245 image = Image.FromFile(image_fname)
4246 self.assertEqual(orig_image.GetEntries().keys(),
4247 image.GetEntries().keys())
4248
4249 orig_entry = orig_image.GetEntries()['fdtmap']
4250 entry = image.GetEntries()['fdtmap']
4251 self.assertEqual(orig_entry.offset, entry.offset)
4252 self.assertEqual(orig_entry.size, entry.size)
4253 self.assertEqual(16, entry.image_pos)
4254
4255 u_boot = image.GetEntries()['section'].GetEntries()['u-boot']
4256
4257 self.assertEquals(U_BOOT_DATA, u_boot.ReadData())
4258
Simon Glassc98de972021-03-18 20:24:57 +13004259 def testTplNoDtb(self):
4260 """Test that an image with tpl/u-boot-tpl-nodtb.bin can be created"""
4261 data = self._DoReadFile('192_u_boot_tpl_nodtb.dts')
4262 self.assertEqual(U_BOOT_TPL_NODTB_DATA,
4263 data[:len(U_BOOT_TPL_NODTB_DATA)])
4264
Simon Glass63f41d42021-03-18 20:24:58 +13004265 def testTplBssPad(self):
4266 """Test that we can pad TPL's BSS with zeros"""
4267 # ELF file with a '__bss_size' symbol
4268 self._SetupTplElf()
4269 data = self._DoReadFile('193_tpl_bss_pad.dts')
4270 self.assertEqual(U_BOOT_TPL_DATA + tools.GetBytes(0, 10) + U_BOOT_DATA,
4271 data)
4272
4273 def testTplBssPadMissing(self):
4274 """Test that a missing symbol is detected"""
4275 self._SetupTplElf('u_boot_ucode_ptr')
4276 with self.assertRaises(ValueError) as e:
4277 self._DoReadFile('193_tpl_bss_pad.dts')
4278 self.assertIn('Expected __bss_size symbol in tpl/u-boot-tpl',
4279 str(e.exception))
4280
Simon Glassbb395742020-10-26 17:40:14 -06004281
Simon Glassac599912017-11-12 21:52:22 -07004282if __name__ == "__main__":
4283 unittest.main()