blob: 6a7647311ba37818955d5899dcbb3be691a8d717 [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
Simon Glass3efb2972021-11-23 21:08:59 -070026from binman import fip_util
Simon Glassc585dd42020-04-17 18:09:03 -060027from binman import fmap_util
Simon Glassc585dd42020-04-17 18:09:03 -060028from binman import state
29from dtoc import fdt
30from dtoc import fdt_util
31from binman.etype import fdtmap
32from binman.etype import image_header
Simon Glass90cd6f02020-08-05 13:27:47 -060033from binman.image import Image
Simon Glassa997ea52020-04-17 18:09:04 -060034from patman import command
35from patman import test_util
36from patman import tools
37from patman import tout
Simon Glass57454f42016-11-25 20:15:52 -070038
39# Contents of test files, corresponding to different entry types
Simon Glass303f62f2019-05-17 22:00:46 -060040U_BOOT_DATA = b'1234'
41U_BOOT_IMG_DATA = b'img'
Simon Glass4e353e22019-08-24 07:23:04 -060042U_BOOT_SPL_DATA = b'56780123456789abcdefghi'
43U_BOOT_TPL_DATA = b'tpl9876543210fedcbazyw'
Simon Glass303f62f2019-05-17 22:00:46 -060044BLOB_DATA = b'89'
45ME_DATA = b'0abcd'
46VGA_DATA = b'vga'
47U_BOOT_DTB_DATA = b'udtb'
48U_BOOT_SPL_DTB_DATA = b'spldtb'
49U_BOOT_TPL_DTB_DATA = b'tpldtb'
50X86_START16_DATA = b'start16'
51X86_START16_SPL_DATA = b'start16spl'
52X86_START16_TPL_DATA = b'start16tpl'
Simon Glass0b074d62019-08-24 07:22:48 -060053X86_RESET16_DATA = b'reset16'
54X86_RESET16_SPL_DATA = b'reset16spl'
55X86_RESET16_TPL_DATA = b'reset16tpl'
Simon Glass303f62f2019-05-17 22:00:46 -060056PPC_MPC85XX_BR_DATA = b'ppcmpc85xxbr'
57U_BOOT_NODTB_DATA = b'nodtb with microcode pointer somewhere in here'
58U_BOOT_SPL_NODTB_DATA = b'splnodtb with microcode pointer somewhere in here'
59U_BOOT_TPL_NODTB_DATA = b'tplnodtb with microcode pointer somewhere in here'
60FSP_DATA = b'fsp'
61CMC_DATA = b'cmc'
62VBT_DATA = b'vbt'
63MRC_DATA = b'mrc'
Simon Glass2ca52032018-07-17 13:25:33 -060064TEXT_DATA = 'text'
65TEXT_DATA2 = 'text2'
66TEXT_DATA3 = 'text3'
Simon Glass303f62f2019-05-17 22:00:46 -060067CROS_EC_RW_DATA = b'ecrw'
68GBB_DATA = b'gbbd'
69BMPBLK_DATA = b'bmp'
70VBLOCK_DATA = b'vblk'
71FILES_DATA = (b"sorry I'm late\nOh, don't bother apologising, I'm " +
72 b"sorry you're alive\n")
Simon Glassccec0262019-07-08 13:18:42 -060073COMPRESS_DATA = b'compress xxxxxxxxxxxxxxxxxxxxxx data'
Simon Glassd92c8362020-10-26 17:40:25 -060074COMPRESS_DATA_BIG = COMPRESS_DATA * 2
Simon Glass303f62f2019-05-17 22:00:46 -060075REFCODE_DATA = b'refcode'
Simon Glassba7985d2019-08-24 07:23:07 -060076FSP_M_DATA = b'fsp_m'
Simon Glass4d9086d2019-10-20 21:31:35 -060077FSP_S_DATA = b'fsp_s'
Simon Glass9ea87b22019-10-20 21:31:36 -060078FSP_T_DATA = b'fsp_t'
Simon Glass559c4de2020-09-01 05:13:58 -060079ATF_BL31_DATA = b'bl31'
Simon Glass3efb2972021-11-23 21:08:59 -070080ATF_BL2U_DATA = b'bl2u'
Bin Mengc0b15742021-05-10 20:23:33 +080081OPENSBI_DATA = b'opensbi'
Samuel Holland9d8cc632020-10-21 21:12:15 -050082SCP_DATA = b'scp'
Simon Glassa435cd12020-09-01 05:13:59 -060083TEST_FDT1_DATA = b'fdt1'
84TEST_FDT2_DATA = b'test-fdt2'
Simon Glassa0729502020-09-06 10:35:33 -060085ENV_DATA = b'var1=1\nvar2="2"'
Simon Glassa435cd12020-09-01 05:13:59 -060086
87# Subdirectory of the input dir to use to put test FDTs
88TEST_FDT_SUBDIR = 'fdts'
Simon Glassdb168d42018-07-17 13:25:39 -060089
Simon Glass2c6adba2019-07-20 12:23:47 -060090# The expected size for the device tree in some tests
Simon Glass4c613bf2019-07-08 14:25:50 -060091EXTRACT_DTB_SIZE = 0x3c9
92
Simon Glass2c6adba2019-07-20 12:23:47 -060093# Properties expected to be in the device tree when update_dtb is used
94BASE_DTB_PROPS = ['offset', 'size', 'image-pos']
95
Simon Glassfb30e292019-07-20 12:23:51 -060096# Extra properties expected to be in the device tree when allow-repack is used
97REPACK_DTB_PROPS = ['orig-offset', 'orig-size']
98
Simon Glass57454f42016-11-25 20:15:52 -070099
100class TestFunctional(unittest.TestCase):
101 """Functional tests for binman
102
103 Most of these use a sample .dts file to build an image and then check
104 that it looks correct. The sample files are in the test/ subdirectory
105 and are numbered.
106
107 For each entry type a very small test file is created using fixed
108 string contents. This makes it easy to test that things look right, and
109 debug problems.
110
111 In some cases a 'real' file must be used - these are also supplied in
112 the test/ diurectory.
113 """
114 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600115 def setUpClass(cls):
Simon Glassb3393262017-11-12 21:52:20 -0700116 global entry
Simon Glassc585dd42020-04-17 18:09:03 -0600117 from binman import entry
Simon Glassb3393262017-11-12 21:52:20 -0700118
Simon Glass57454f42016-11-25 20:15:52 -0700119 # Handle the case where argv[0] is 'python'
Simon Glass862f8e22019-08-24 07:22:43 -0600120 cls._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
121 cls._binman_pathname = os.path.join(cls._binman_dir, 'binman')
Simon Glass57454f42016-11-25 20:15:52 -0700122
123 # Create a temporary directory for input files
Simon Glass862f8e22019-08-24 07:22:43 -0600124 cls._indir = tempfile.mkdtemp(prefix='binmant.')
Simon Glass57454f42016-11-25 20:15:52 -0700125
126 # Create some test files
127 TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
128 TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
129 TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
Simon Glass8425a1f2018-07-17 13:25:48 -0600130 TestFunctional._MakeInputFile('tpl/u-boot-tpl.bin', U_BOOT_TPL_DATA)
Simon Glass57454f42016-11-25 20:15:52 -0700131 TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
Simon Glass72232452016-11-25 20:15:53 -0700132 TestFunctional._MakeInputFile('me.bin', ME_DATA)
133 TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
Simon Glass862f8e22019-08-24 07:22:43 -0600134 cls._ResetDtbs()
Simon Glass0b074d62019-08-24 07:22:48 -0600135
Jagdish Gediya311d4842018-09-03 21:35:08 +0530136 TestFunctional._MakeInputFile('u-boot-br.bin', PPC_MPC85XX_BR_DATA)
Simon Glass0b074d62019-08-24 07:22:48 -0600137
Simon Glassabab18c2019-08-24 07:22:49 -0600138 TestFunctional._MakeInputFile('u-boot-x86-start16.bin', X86_START16_DATA)
139 TestFunctional._MakeInputFile('spl/u-boot-x86-start16-spl.bin',
Simon Glasse83679d2017-11-12 21:52:26 -0700140 X86_START16_SPL_DATA)
Simon Glassabab18c2019-08-24 07:22:49 -0600141 TestFunctional._MakeInputFile('tpl/u-boot-x86-start16-tpl.bin',
Simon Glassed40e962018-09-14 04:57:10 -0600142 X86_START16_TPL_DATA)
Simon Glass0b074d62019-08-24 07:22:48 -0600143
144 TestFunctional._MakeInputFile('u-boot-x86-reset16.bin',
145 X86_RESET16_DATA)
146 TestFunctional._MakeInputFile('spl/u-boot-x86-reset16-spl.bin',
147 X86_RESET16_SPL_DATA)
148 TestFunctional._MakeInputFile('tpl/u-boot-x86-reset16-tpl.bin',
149 X86_RESET16_TPL_DATA)
150
Simon Glass57454f42016-11-25 20:15:52 -0700151 TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
Simon Glass3d274232017-11-12 21:52:27 -0700152 TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
153 U_BOOT_SPL_NODTB_DATA)
Simon Glass3fb4f422018-09-14 04:57:32 -0600154 TestFunctional._MakeInputFile('tpl/u-boot-tpl-nodtb.bin',
155 U_BOOT_TPL_NODTB_DATA)
Simon Glassb4176d42016-11-25 20:15:56 -0700156 TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
157 TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
Bin Mengd7bcdf52017-08-15 22:41:54 -0700158 TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
Simon Glassa409c932017-11-12 21:52:28 -0700159 TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
Simon Glassdb168d42018-07-17 13:25:39 -0600160 TestFunctional._MakeInputFile('ecrw.bin', CROS_EC_RW_DATA)
Simon Glassc1ae83c2018-07-17 13:25:44 -0600161 TestFunctional._MakeInputDir('devkeys')
162 TestFunctional._MakeInputFile('bmpblk.bin', BMPBLK_DATA)
Simon Glass41902e42018-10-01 12:22:31 -0600163 TestFunctional._MakeInputFile('refcode.bin', REFCODE_DATA)
Simon Glassba7985d2019-08-24 07:23:07 -0600164 TestFunctional._MakeInputFile('fsp_m.bin', FSP_M_DATA)
Simon Glass4d9086d2019-10-20 21:31:35 -0600165 TestFunctional._MakeInputFile('fsp_s.bin', FSP_S_DATA)
Simon Glass9ea87b22019-10-20 21:31:36 -0600166 TestFunctional._MakeInputFile('fsp_t.bin', FSP_T_DATA)
Simon Glass57454f42016-11-25 20:15:52 -0700167
Simon Glassf6290892019-08-24 07:22:53 -0600168 cls._elf_testdir = os.path.join(cls._indir, 'elftest')
169 elf_test.BuildElfTestFiles(cls._elf_testdir)
170
Simon Glass72232452016-11-25 20:15:53 -0700171 # ELF file with a '_dt_ucode_base_size' symbol
Simon Glass4affd4b2019-08-24 07:22:54 -0600172 TestFunctional._MakeInputFile('u-boot',
173 tools.ReadFile(cls.ElfTestFile('u_boot_ucode_ptr')))
Simon Glass72232452016-11-25 20:15:53 -0700174
175 # Intel flash descriptor file
Simon Glasse88cef92020-07-09 18:39:41 -0600176 cls._SetupDescriptor()
Simon Glass72232452016-11-25 20:15:53 -0700177
Simon Glass862f8e22019-08-24 07:22:43 -0600178 shutil.copytree(cls.TestFile('files'),
179 os.path.join(cls._indir, 'files'))
Simon Glassac6328c2018-09-14 04:57:28 -0600180
Simon Glass7ba33592018-09-14 04:57:26 -0600181 TestFunctional._MakeInputFile('compress', COMPRESS_DATA)
Simon Glassd92c8362020-10-26 17:40:25 -0600182 TestFunctional._MakeInputFile('compress_big', COMPRESS_DATA_BIG)
Simon Glass559c4de2020-09-01 05:13:58 -0600183 TestFunctional._MakeInputFile('bl31.bin', ATF_BL31_DATA)
Simon Glass3efb2972021-11-23 21:08:59 -0700184 TestFunctional._MakeInputFile('bl2u.bin', ATF_BL2U_DATA)
Bin Mengc0b15742021-05-10 20:23:33 +0800185 TestFunctional._MakeInputFile('fw_dynamic.bin', OPENSBI_DATA)
Samuel Holland9d8cc632020-10-21 21:12:15 -0500186 TestFunctional._MakeInputFile('scp.bin', SCP_DATA)
Simon Glass7ba33592018-09-14 04:57:26 -0600187
Simon Glassa435cd12020-09-01 05:13:59 -0600188 # Add a few .dtb files for testing
189 TestFunctional._MakeInputFile('%s/test-fdt1.dtb' % TEST_FDT_SUBDIR,
190 TEST_FDT1_DATA)
191 TestFunctional._MakeInputFile('%s/test-fdt2.dtb' % TEST_FDT_SUBDIR,
192 TEST_FDT2_DATA)
193
Simon Glassa0729502020-09-06 10:35:33 -0600194 TestFunctional._MakeInputFile('env.txt', ENV_DATA)
195
Simon Glass1de34482019-07-08 13:18:53 -0600196 # Travis-CI may have an old lz4
Simon Glass862f8e22019-08-24 07:22:43 -0600197 cls.have_lz4 = True
Simon Glass1de34482019-07-08 13:18:53 -0600198 try:
199 tools.Run('lz4', '--no-frame-crc', '-c',
Simon Glasscc311ac2019-10-31 07:42:50 -0600200 os.path.join(cls._indir, 'u-boot.bin'), binary=True)
Simon Glass1de34482019-07-08 13:18:53 -0600201 except:
Simon Glass862f8e22019-08-24 07:22:43 -0600202 cls.have_lz4 = False
Simon Glass1de34482019-07-08 13:18:53 -0600203
Simon Glass57454f42016-11-25 20:15:52 -0700204 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600205 def tearDownClass(cls):
Simon Glass57454f42016-11-25 20:15:52 -0700206 """Remove the temporary input directory and its contents"""
Simon Glass862f8e22019-08-24 07:22:43 -0600207 if cls.preserve_indir:
208 print('Preserving input dir: %s' % cls._indir)
Simon Glass1c420c92019-07-08 13:18:49 -0600209 else:
Simon Glass862f8e22019-08-24 07:22:43 -0600210 if cls._indir:
211 shutil.rmtree(cls._indir)
212 cls._indir = None
Simon Glass57454f42016-11-25 20:15:52 -0700213
Simon Glass1c420c92019-07-08 13:18:49 -0600214 @classmethod
Simon Glasscebfab22019-07-08 13:18:50 -0600215 def setup_test_args(cls, preserve_indir=False, preserve_outdirs=False,
Simon Glassf46732a2019-07-08 14:25:29 -0600216 toolpath=None, verbosity=None):
Simon Glass1c420c92019-07-08 13:18:49 -0600217 """Accept arguments controlling test execution
218
219 Args:
220 preserve_indir: Preserve the shared input directory used by all
221 tests in this class.
222 preserve_outdir: Preserve the output directories used by tests. Each
223 test has its own, so this is normally only useful when running a
224 single test.
Simon Glasscebfab22019-07-08 13:18:50 -0600225 toolpath: ist of paths to use for tools
Simon Glass1c420c92019-07-08 13:18:49 -0600226 """
227 cls.preserve_indir = preserve_indir
228 cls.preserve_outdirs = preserve_outdirs
Simon Glasscebfab22019-07-08 13:18:50 -0600229 cls.toolpath = toolpath
Simon Glassf46732a2019-07-08 14:25:29 -0600230 cls.verbosity = verbosity
Simon Glass1c420c92019-07-08 13:18:49 -0600231
Simon Glass1de34482019-07-08 13:18:53 -0600232 def _CheckLz4(self):
233 if not self.have_lz4:
234 self.skipTest('lz4 --no-frame-crc not available')
235
Simon Glassee9d10d2019-07-20 12:24:09 -0600236 def _CleanupOutputDir(self):
237 """Remove the temporary output directory"""
238 if self.preserve_outdirs:
239 print('Preserving output dir: %s' % tools.outdir)
240 else:
241 tools._FinaliseForTest()
242
Simon Glass57454f42016-11-25 20:15:52 -0700243 def setUp(self):
244 # Enable this to turn on debugging output
245 # tout.Init(tout.DEBUG)
246 command.test_result = None
247
248 def tearDown(self):
249 """Remove the temporary output directory"""
Simon Glassee9d10d2019-07-20 12:24:09 -0600250 self._CleanupOutputDir()
Simon Glass57454f42016-11-25 20:15:52 -0700251
Simon Glassb3d6fc72019-07-20 12:24:10 -0600252 def _SetupImageInTmpdir(self):
253 """Set up the output image in a new temporary directory
254
255 This is used when an image has been generated in the output directory,
256 but we want to run binman again. This will create a new output
257 directory and fail to delete the original one.
258
259 This creates a new temporary directory, copies the image to it (with a
260 new name) and removes the old output directory.
261
262 Returns:
263 Tuple:
264 Temporary directory to use
265 New image filename
266 """
267 image_fname = tools.GetOutputFilename('image.bin')
268 tmpdir = tempfile.mkdtemp(prefix='binman.')
269 updated_fname = os.path.join(tmpdir, 'image-updated.bin')
270 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
271 self._CleanupOutputDir()
272 return tmpdir, updated_fname
273
Simon Glass8425a1f2018-07-17 13:25:48 -0600274 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600275 def _ResetDtbs(cls):
Simon Glass8425a1f2018-07-17 13:25:48 -0600276 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
277 TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
278 TestFunctional._MakeInputFile('tpl/u-boot-tpl.dtb', U_BOOT_TPL_DTB_DATA)
279
Simon Glass57454f42016-11-25 20:15:52 -0700280 def _RunBinman(self, *args, **kwargs):
281 """Run binman using the command line
282
283 Args:
284 Arguments to pass, as a list of strings
285 kwargs: Arguments to pass to Command.RunPipe()
286 """
287 result = command.RunPipe([[self._binman_pathname] + list(args)],
288 capture=True, capture_stderr=True, raise_on_error=False)
289 if result.return_code and kwargs.get('raise_on_error', True):
290 raise Exception("Error running '%s': %s" % (' '.join(args),
291 result.stdout + result.stderr))
292 return result
293
Simon Glassf46732a2019-07-08 14:25:29 -0600294 def _DoBinman(self, *argv):
Simon Glass57454f42016-11-25 20:15:52 -0700295 """Run binman using directly (in the same process)
296
297 Args:
298 Arguments to pass, as a list of strings
299 Returns:
300 Return value (0 for success)
301 """
Simon Glassf46732a2019-07-08 14:25:29 -0600302 argv = list(argv)
303 args = cmdline.ParseArgs(argv)
304 args.pager = 'binman-invalid-pager'
305 args.build_dir = self._indir
Simon Glass57454f42016-11-25 20:15:52 -0700306
307 # For testing, you can force an increase in verbosity here
Simon Glassf46732a2019-07-08 14:25:29 -0600308 # args.verbosity = tout.DEBUG
309 return control.Binman(args)
Simon Glass57454f42016-11-25 20:15:52 -0700310
Simon Glass91710b32018-07-17 13:25:32 -0600311 def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
Simon Glassb4595d82019-04-25 21:58:34 -0600312 entry_args=None, images=None, use_real_dtb=False,
Simon Glassed930672021-03-18 20:25:05 +1300313 use_expanded=False, verbosity=None, allow_missing=False,
Heiko Thiery6d451362022-01-06 11:49:41 +0100314 allow_fake_blobs=False, extra_indirs=None, threads=None,
Simon Glassadfb8492021-11-03 21:09:18 -0600315 test_section_timeout=False, update_fdt_in_elf=None):
Simon Glass57454f42016-11-25 20:15:52 -0700316 """Run binman with a given test file
317
318 Args:
Simon Glass511f6582018-10-01 12:22:30 -0600319 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass1e324002018-06-01 09:38:19 -0600320 debug: True to enable debugging output
Simon Glass30732662018-06-01 09:38:20 -0600321 map: True to output map files for the images
Simon Glasse8561af2018-08-01 15:22:37 -0600322 update_dtb: Update the offset and size of each entry in the device
Simon Glassa87014e2018-07-06 10:27:42 -0600323 tree before packing it into the image
Simon Glass3b376c32018-09-14 04:57:12 -0600324 entry_args: Dict of entry args to supply to binman
325 key: arg name
326 value: value of that arg
327 images: List of image names to build
Simon Glass31ee50f2020-09-01 05:13:55 -0600328 use_real_dtb: True to use the test file as the contents of
329 the u-boot-dtb entry. Normally this is not needed and the
330 test contents (the U_BOOT_DTB_DATA string) can be used.
331 But in some test we need the real contents.
Simon Glassed930672021-03-18 20:25:05 +1300332 use_expanded: True to use expanded entries where available, e.g.
333 'u-boot-expanded' instead of 'u-boot'
Simon Glass31ee50f2020-09-01 05:13:55 -0600334 verbosity: Verbosity level to use (0-3, None=don't set it)
335 allow_missing: Set the '--allow-missing' flag so that missing
336 external binaries just produce a warning instead of an error
Heiko Thiery6d451362022-01-06 11:49:41 +0100337 allow_fake_blobs: Set the '--fake-ext-blobs' flag
Simon Glassa435cd12020-09-01 05:13:59 -0600338 extra_indirs: Extra input directories to add using -I
Simon Glass76f496d2021-07-06 10:36:37 -0600339 threads: Number of threads to use (None for default, 0 for
340 single-threaded)
Simon Glass9a798402021-11-03 21:09:17 -0600341 test_section_timeout: True to force the first time to timeout, as
342 used in testThreadTimeout()
Simon Glassadfb8492021-11-03 21:09:18 -0600343 update_fdt_in_elf: Value to pass with --update-fdt-in-elf=xxx
Simon Glass9a798402021-11-03 21:09:17 -0600344
345 Returns:
346 int return code, 0 on success
Simon Glass57454f42016-11-25 20:15:52 -0700347 """
Simon Glassf46732a2019-07-08 14:25:29 -0600348 args = []
Simon Glass075a45c2017-11-13 18:55:00 -0700349 if debug:
350 args.append('-D')
Simon Glassf46732a2019-07-08 14:25:29 -0600351 if verbosity is not None:
352 args.append('-v%d' % verbosity)
353 elif self.verbosity:
354 args.append('-v%d' % self.verbosity)
355 if self.toolpath:
356 for path in self.toolpath:
357 args += ['--toolpath', path]
Simon Glass76f496d2021-07-06 10:36:37 -0600358 if threads is not None:
359 args.append('-T%d' % threads)
360 if test_section_timeout:
361 args.append('--test-section-timeout')
Simon Glassf46732a2019-07-08 14:25:29 -0600362 args += ['build', '-p', '-I', self._indir, '-d', self.TestFile(fname)]
Simon Glass30732662018-06-01 09:38:20 -0600363 if map:
364 args.append('-m')
Simon Glassa87014e2018-07-06 10:27:42 -0600365 if update_dtb:
Simon Glass38a411c2019-07-08 13:18:47 -0600366 args.append('-u')
Simon Glass31402012018-09-14 04:57:23 -0600367 if not use_real_dtb:
368 args.append('--fake-dtb')
Simon Glassed930672021-03-18 20:25:05 +1300369 if not use_expanded:
370 args.append('--no-expanded')
Simon Glass91710b32018-07-17 13:25:32 -0600371 if entry_args:
Simon Glass5f3645b2019-05-14 15:53:41 -0600372 for arg, value in entry_args.items():
Simon Glass91710b32018-07-17 13:25:32 -0600373 args.append('-a%s=%s' % (arg, value))
Simon Glass5d94cc62020-07-09 18:39:38 -0600374 if allow_missing:
375 args.append('-M')
Heiko Thiery6d451362022-01-06 11:49:41 +0100376 if allow_fake_blobs:
377 args.append('--fake-ext-blobs')
Simon Glassadfb8492021-11-03 21:09:18 -0600378 if update_fdt_in_elf:
379 args += ['--update-fdt-in-elf', update_fdt_in_elf]
Simon Glass3b376c32018-09-14 04:57:12 -0600380 if images:
381 for image in images:
382 args += ['-i', image]
Simon Glassa435cd12020-09-01 05:13:59 -0600383 if extra_indirs:
384 for indir in extra_indirs:
385 args += ['-I', indir]
Simon Glass075a45c2017-11-13 18:55:00 -0700386 return self._DoBinman(*args)
Simon Glass57454f42016-11-25 20:15:52 -0700387
388 def _SetupDtb(self, fname, outfile='u-boot.dtb'):
Simon Glass72232452016-11-25 20:15:53 -0700389 """Set up a new test device-tree file
390
391 The given file is compiled and set up as the device tree to be used
392 for ths test.
393
394 Args:
395 fname: Filename of .dts file to read
Simon Glass1e324002018-06-01 09:38:19 -0600396 outfile: Output filename for compiled device-tree binary
Simon Glass72232452016-11-25 20:15:53 -0700397
398 Returns:
Simon Glass1e324002018-06-01 09:38:19 -0600399 Contents of device-tree binary
Simon Glass72232452016-11-25 20:15:53 -0700400 """
Simon Glassb8d2daa2019-07-20 12:23:49 -0600401 tmpdir = tempfile.mkdtemp(prefix='binmant.')
402 dtb = fdt_util.EnsureCompiled(self.TestFile(fname), tmpdir)
Simon Glass33486662019-05-14 15:53:42 -0600403 with open(dtb, 'rb') as fd:
Simon Glass57454f42016-11-25 20:15:52 -0700404 data = fd.read()
405 TestFunctional._MakeInputFile(outfile, data)
Simon Glassb8d2daa2019-07-20 12:23:49 -0600406 shutil.rmtree(tmpdir)
Simon Glass752e7552018-10-01 21:12:41 -0600407 return data
Simon Glass57454f42016-11-25 20:15:52 -0700408
Simon Glasse219aa42018-09-14 04:57:24 -0600409 def _GetDtbContentsForSplTpl(self, dtb_data, name):
410 """Create a version of the main DTB for SPL or SPL
411
412 For testing we don't actually have different versions of the DTB. With
413 U-Boot we normally run fdtgrep to remove unwanted nodes, but for tests
414 we don't normally have any unwanted nodes.
415
416 We still want the DTBs for SPL and TPL to be different though, since
417 otherwise it is confusing to know which one we are looking at. So add
418 an 'spl' or 'tpl' property to the top-level node.
Simon Glass31ee50f2020-09-01 05:13:55 -0600419
420 Args:
421 dtb_data: dtb data to modify (this should be a value devicetree)
422 name: Name of a new property to add
423
424 Returns:
425 New dtb data with the property added
Simon Glasse219aa42018-09-14 04:57:24 -0600426 """
427 dtb = fdt.Fdt.FromData(dtb_data)
428 dtb.Scan()
429 dtb.GetNode('/binman').AddZeroProp(name)
430 dtb.Sync(auto_resize=True)
431 dtb.Pack()
432 return dtb.GetContents()
433
Simon Glassed930672021-03-18 20:25:05 +1300434 def _DoReadFileDtb(self, fname, use_real_dtb=False, use_expanded=False,
435 map=False, update_dtb=False, entry_args=None,
Simon Glass76f496d2021-07-06 10:36:37 -0600436 reset_dtbs=True, extra_indirs=None, threads=None):
Simon Glass57454f42016-11-25 20:15:52 -0700437 """Run binman and return the resulting image
438
439 This runs binman with a given test file and then reads the resulting
440 output file. It is a shortcut function since most tests need to do
441 these steps.
442
443 Raises an assertion failure if binman returns a non-zero exit code.
444
445 Args:
Simon Glass511f6582018-10-01 12:22:30 -0600446 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass57454f42016-11-25 20:15:52 -0700447 use_real_dtb: True to use the test file as the contents of
448 the u-boot-dtb entry. Normally this is not needed and the
449 test contents (the U_BOOT_DTB_DATA string) can be used.
450 But in some test we need the real contents.
Simon Glassed930672021-03-18 20:25:05 +1300451 use_expanded: True to use expanded entries where available, e.g.
452 'u-boot-expanded' instead of 'u-boot'
Simon Glass30732662018-06-01 09:38:20 -0600453 map: True to output map files for the images
Simon Glasse8561af2018-08-01 15:22:37 -0600454 update_dtb: Update the offset and size of each entry in the device
Simon Glassa87014e2018-07-06 10:27:42 -0600455 tree before packing it into the image
Simon Glass31ee50f2020-09-01 05:13:55 -0600456 entry_args: Dict of entry args to supply to binman
457 key: arg name
458 value: value of that arg
459 reset_dtbs: With use_real_dtb the test dtb is overwritten by this
460 function. If reset_dtbs is True, then the original test dtb
461 is written back before this function finishes
Simon Glassa435cd12020-09-01 05:13:59 -0600462 extra_indirs: Extra input directories to add using -I
Simon Glass76f496d2021-07-06 10:36:37 -0600463 threads: Number of threads to use (None for default, 0 for
464 single-threaded)
Simon Glass72232452016-11-25 20:15:53 -0700465
466 Returns:
467 Tuple:
468 Resulting image contents
469 Device tree contents
Simon Glass30732662018-06-01 09:38:20 -0600470 Map data showing contents of image (or None if none)
Simon Glassdef77b52018-07-17 13:25:27 -0600471 Output device tree binary filename ('u-boot.dtb' path)
Simon Glass57454f42016-11-25 20:15:52 -0700472 """
Simon Glass72232452016-11-25 20:15:53 -0700473 dtb_data = None
Simon Glass57454f42016-11-25 20:15:52 -0700474 # Use the compiled test file as the u-boot-dtb input
475 if use_real_dtb:
Simon Glass72232452016-11-25 20:15:53 -0700476 dtb_data = self._SetupDtb(fname)
Simon Glasse219aa42018-09-14 04:57:24 -0600477
478 # For testing purposes, make a copy of the DT for SPL and TPL. Add
479 # a node indicating which it is, so aid verification.
480 for name in ['spl', 'tpl']:
481 dtb_fname = '%s/u-boot-%s.dtb' % (name, name)
482 outfile = os.path.join(self._indir, dtb_fname)
483 TestFunctional._MakeInputFile(dtb_fname,
484 self._GetDtbContentsForSplTpl(dtb_data, name))
Simon Glass57454f42016-11-25 20:15:52 -0700485
486 try:
Simon Glass91710b32018-07-17 13:25:32 -0600487 retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
Simon Glassa435cd12020-09-01 05:13:59 -0600488 entry_args=entry_args, use_real_dtb=use_real_dtb,
Simon Glass76f496d2021-07-06 10:36:37 -0600489 use_expanded=use_expanded, extra_indirs=extra_indirs,
490 threads=threads)
Simon Glass57454f42016-11-25 20:15:52 -0700491 self.assertEqual(0, retcode)
Simon Glasse219aa42018-09-14 04:57:24 -0600492 out_dtb_fname = tools.GetOutputFilename('u-boot.dtb.out')
Simon Glass57454f42016-11-25 20:15:52 -0700493
494 # Find the (only) image, read it and return its contents
495 image = control.images['image']
Simon Glassa87014e2018-07-06 10:27:42 -0600496 image_fname = tools.GetOutputFilename('image.bin')
497 self.assertTrue(os.path.exists(image_fname))
Simon Glass30732662018-06-01 09:38:20 -0600498 if map:
499 map_fname = tools.GetOutputFilename('image.map')
500 with open(map_fname) as fd:
501 map_data = fd.read()
502 else:
503 map_data = None
Simon Glass33486662019-05-14 15:53:42 -0600504 with open(image_fname, 'rb') as fd:
Simon Glassa87014e2018-07-06 10:27:42 -0600505 return fd.read(), dtb_data, map_data, out_dtb_fname
Simon Glass57454f42016-11-25 20:15:52 -0700506 finally:
507 # Put the test file back
Simon Glasse219aa42018-09-14 04:57:24 -0600508 if reset_dtbs and use_real_dtb:
Simon Glass8425a1f2018-07-17 13:25:48 -0600509 self._ResetDtbs()
Simon Glass57454f42016-11-25 20:15:52 -0700510
Simon Glass5b4bce32019-07-08 14:25:26 -0600511 def _DoReadFileRealDtb(self, fname):
512 """Run binman with a real .dtb file and return the resulting data
513
514 Args:
515 fname: DT source filename to use (e.g. 082_fdt_update_all.dts)
516
517 Returns:
518 Resulting image contents
519 """
520 return self._DoReadFileDtb(fname, use_real_dtb=True, update_dtb=True)[0]
521
Simon Glass72232452016-11-25 20:15:53 -0700522 def _DoReadFile(self, fname, use_real_dtb=False):
Simon Glass1e324002018-06-01 09:38:19 -0600523 """Helper function which discards the device-tree binary
524
525 Args:
Simon Glass511f6582018-10-01 12:22:30 -0600526 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass1e324002018-06-01 09:38:19 -0600527 use_real_dtb: True to use the test file as the contents of
528 the u-boot-dtb entry. Normally this is not needed and the
529 test contents (the U_BOOT_DTB_DATA string) can be used.
530 But in some test we need the real contents.
Simon Glassdef77b52018-07-17 13:25:27 -0600531
532 Returns:
533 Resulting image contents
Simon Glass1e324002018-06-01 09:38:19 -0600534 """
Simon Glass72232452016-11-25 20:15:53 -0700535 return self._DoReadFileDtb(fname, use_real_dtb)[0]
536
Simon Glass57454f42016-11-25 20:15:52 -0700537 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600538 def _MakeInputFile(cls, fname, contents):
Simon Glass57454f42016-11-25 20:15:52 -0700539 """Create a new test input file, creating directories as needed
540
541 Args:
Simon Glasse8561af2018-08-01 15:22:37 -0600542 fname: Filename to create
Simon Glass57454f42016-11-25 20:15:52 -0700543 contents: File contents to write in to the file
544 Returns:
545 Full pathname of file created
546 """
Simon Glass862f8e22019-08-24 07:22:43 -0600547 pathname = os.path.join(cls._indir, fname)
Simon Glass57454f42016-11-25 20:15:52 -0700548 dirname = os.path.dirname(pathname)
549 if dirname and not os.path.exists(dirname):
550 os.makedirs(dirname)
551 with open(pathname, 'wb') as fd:
552 fd.write(contents)
553 return pathname
554
555 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600556 def _MakeInputDir(cls, dirname):
Simon Glassc1ae83c2018-07-17 13:25:44 -0600557 """Create a new test input directory, creating directories as needed
558
559 Args:
560 dirname: Directory name to create
561
562 Returns:
563 Full pathname of directory created
564 """
Simon Glass862f8e22019-08-24 07:22:43 -0600565 pathname = os.path.join(cls._indir, dirname)
Simon Glassc1ae83c2018-07-17 13:25:44 -0600566 if not os.path.exists(pathname):
567 os.makedirs(pathname)
568 return pathname
569
570 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600571 def _SetupSplElf(cls, src_fname='bss_data'):
Simon Glass7057d022018-10-01 21:12:47 -0600572 """Set up an ELF file with a '_dt_ucode_base_size' symbol
573
574 Args:
575 Filename of ELF file to use as SPL
576 """
Simon Glass93a806f2019-08-24 07:22:59 -0600577 TestFunctional._MakeInputFile('spl/u-boot-spl',
578 tools.ReadFile(cls.ElfTestFile(src_fname)))
Simon Glass7057d022018-10-01 21:12:47 -0600579
580 @classmethod
Simon Glass3eb5b202019-08-24 07:23:00 -0600581 def _SetupTplElf(cls, src_fname='bss_data'):
582 """Set up an ELF file with a '_dt_ucode_base_size' symbol
583
584 Args:
585 Filename of ELF file to use as TPL
586 """
587 TestFunctional._MakeInputFile('tpl/u-boot-tpl',
588 tools.ReadFile(cls.ElfTestFile(src_fname)))
589
590 @classmethod
Simon Glasse88cef92020-07-09 18:39:41 -0600591 def _SetupDescriptor(cls):
592 with open(cls.TestFile('descriptor.bin'), 'rb') as fd:
593 TestFunctional._MakeInputFile('descriptor.bin', fd.read())
594
595 @classmethod
Simon Glass862f8e22019-08-24 07:22:43 -0600596 def TestFile(cls, fname):
597 return os.path.join(cls._binman_dir, 'test', fname)
Simon Glass57454f42016-11-25 20:15:52 -0700598
Simon Glassf6290892019-08-24 07:22:53 -0600599 @classmethod
600 def ElfTestFile(cls, fname):
601 return os.path.join(cls._elf_testdir, fname)
602
Simon Glass57454f42016-11-25 20:15:52 -0700603 def AssertInList(self, grep_list, target):
604 """Assert that at least one of a list of things is in a target
605
606 Args:
607 grep_list: List of strings to check
608 target: Target string
609 """
610 for grep in grep_list:
611 if grep in target:
612 return
Simon Glass848cdb52019-05-17 22:00:50 -0600613 self.fail("Error: '%s' not found in '%s'" % (grep_list, target))
Simon Glass57454f42016-11-25 20:15:52 -0700614
615 def CheckNoGaps(self, entries):
616 """Check that all entries fit together without gaps
617
618 Args:
619 entries: List of entries to check
620 """
Simon Glasse8561af2018-08-01 15:22:37 -0600621 offset = 0
Simon Glass57454f42016-11-25 20:15:52 -0700622 for entry in entries.values():
Simon Glasse8561af2018-08-01 15:22:37 -0600623 self.assertEqual(offset, entry.offset)
624 offset += entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700625
Simon Glass72232452016-11-25 20:15:53 -0700626 def GetFdtLen(self, dtb):
Simon Glass1e324002018-06-01 09:38:19 -0600627 """Get the totalsize field from a device-tree binary
Simon Glass72232452016-11-25 20:15:53 -0700628
629 Args:
Simon Glass1e324002018-06-01 09:38:19 -0600630 dtb: Device-tree binary contents
Simon Glass72232452016-11-25 20:15:53 -0700631
632 Returns:
Simon Glass1e324002018-06-01 09:38:19 -0600633 Total size of device-tree binary, from the header
Simon Glass72232452016-11-25 20:15:53 -0700634 """
635 return struct.unpack('>L', dtb[4:8])[0]
636
Simon Glass0f621332019-07-08 14:25:27 -0600637 def _GetPropTree(self, dtb, prop_names, prefix='/binman/'):
Simon Glassa87014e2018-07-06 10:27:42 -0600638 def AddNode(node, path):
639 if node.name != '/':
640 path += '/' + node.name
Simon Glass0f621332019-07-08 14:25:27 -0600641 for prop in node.props.values():
642 if prop.name in prop_names:
643 prop_path = path + ':' + prop.name
644 tree[prop_path[len(prefix):]] = fdt_util.fdt32_to_cpu(
645 prop.value)
Simon Glassa87014e2018-07-06 10:27:42 -0600646 for subnode in node.subnodes:
Simon Glassa87014e2018-07-06 10:27:42 -0600647 AddNode(subnode, path)
648
649 tree = {}
Simon Glassa87014e2018-07-06 10:27:42 -0600650 AddNode(dtb.GetRoot(), '')
651 return tree
652
Simon Glass57454f42016-11-25 20:15:52 -0700653 def testRun(self):
654 """Test a basic run with valid args"""
655 result = self._RunBinman('-h')
656
657 def testFullHelp(self):
658 """Test that the full help is displayed with -H"""
659 result = self._RunBinman('-H')
Simon Glass75ead662021-03-18 20:25:13 +1300660 help_file = os.path.join(self._binman_dir, 'README.rst')
Tom Rinic3c0b6d2018-01-16 15:29:50 -0500661 # Remove possible extraneous strings
662 extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
663 gothelp = result.stdout.replace(extra, '')
664 self.assertEqual(len(gothelp), os.path.getsize(help_file))
Simon Glass57454f42016-11-25 20:15:52 -0700665 self.assertEqual(0, len(result.stderr))
666 self.assertEqual(0, result.return_code)
667
668 def testFullHelpInternal(self):
669 """Test that the full help is displayed with -H"""
670 try:
671 command.test_result = command.CommandResult()
672 result = self._DoBinman('-H')
Simon Glass75ead662021-03-18 20:25:13 +1300673 help_file = os.path.join(self._binman_dir, 'README.rst')
Simon Glass57454f42016-11-25 20:15:52 -0700674 finally:
675 command.test_result = None
676
677 def testHelp(self):
678 """Test that the basic help is displayed with -h"""
679 result = self._RunBinman('-h')
680 self.assertTrue(len(result.stdout) > 200)
681 self.assertEqual(0, len(result.stderr))
682 self.assertEqual(0, result.return_code)
683
Simon Glass57454f42016-11-25 20:15:52 -0700684 def testBoard(self):
685 """Test that we can run it with a specific board"""
Simon Glass511f6582018-10-01 12:22:30 -0600686 self._SetupDtb('005_simple.dts', 'sandbox/u-boot.dtb')
Simon Glass57454f42016-11-25 20:15:52 -0700687 TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
Simon Glassed930672021-03-18 20:25:05 +1300688 result = self._DoBinman('build', '-n', '-b', 'sandbox')
Simon Glass57454f42016-11-25 20:15:52 -0700689 self.assertEqual(0, result)
690
691 def testNeedBoard(self):
692 """Test that we get an error when no board ius supplied"""
693 with self.assertRaises(ValueError) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600694 result = self._DoBinman('build')
Simon Glass57454f42016-11-25 20:15:52 -0700695 self.assertIn("Must provide a board to process (use -b <board>)",
696 str(e.exception))
697
698 def testMissingDt(self):
Simon Glass1e324002018-06-01 09:38:19 -0600699 """Test that an invalid device-tree file generates an error"""
Simon Glass57454f42016-11-25 20:15:52 -0700700 with self.assertRaises(Exception) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600701 self._RunBinman('build', '-d', 'missing_file')
Simon Glass57454f42016-11-25 20:15:52 -0700702 # We get one error from libfdt, and a different one from fdtget.
703 self.AssertInList(["Couldn't open blob from 'missing_file'",
704 'No such file or directory'], str(e.exception))
705
706 def testBrokenDt(self):
Simon Glass1e324002018-06-01 09:38:19 -0600707 """Test that an invalid device-tree source file generates an error
Simon Glass57454f42016-11-25 20:15:52 -0700708
709 Since this is a source file it should be compiled and the error
710 will come from the device-tree compiler (dtc).
711 """
712 with self.assertRaises(Exception) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600713 self._RunBinman('build', '-d', self.TestFile('001_invalid.dts'))
Simon Glass57454f42016-11-25 20:15:52 -0700714 self.assertIn("FATAL ERROR: Unable to parse input tree",
715 str(e.exception))
716
717 def testMissingNode(self):
718 """Test that a device tree without a 'binman' node generates an error"""
719 with self.assertRaises(Exception) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600720 self._DoBinman('build', '-d', self.TestFile('002_missing_node.dts'))
Simon Glass57454f42016-11-25 20:15:52 -0700721 self.assertIn("does not have a 'binman' node", str(e.exception))
722
723 def testEmpty(self):
724 """Test that an empty binman node works OK (i.e. does nothing)"""
Simon Glassf46732a2019-07-08 14:25:29 -0600725 result = self._RunBinman('build', '-d', self.TestFile('003_empty.dts'))
Simon Glass57454f42016-11-25 20:15:52 -0700726 self.assertEqual(0, len(result.stderr))
727 self.assertEqual(0, result.return_code)
728
729 def testInvalidEntry(self):
730 """Test that an invalid entry is flagged"""
731 with self.assertRaises(Exception) as e:
Simon Glassf46732a2019-07-08 14:25:29 -0600732 result = self._RunBinman('build', '-d',
Simon Glass511f6582018-10-01 12:22:30 -0600733 self.TestFile('004_invalid_entry.dts'))
Simon Glass57454f42016-11-25 20:15:52 -0700734 self.assertIn("Unknown entry type 'not-a-valid-type' in node "
735 "'/binman/not-a-valid-type'", str(e.exception))
736
737 def testSimple(self):
738 """Test a simple binman with a single file"""
Simon Glass511f6582018-10-01 12:22:30 -0600739 data = self._DoReadFile('005_simple.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700740 self.assertEqual(U_BOOT_DATA, data)
741
Simon Glass075a45c2017-11-13 18:55:00 -0700742 def testSimpleDebug(self):
743 """Test a simple binman run with debugging enabled"""
Simon Glass52d06212019-07-08 14:25:53 -0600744 self._DoTestFile('005_simple.dts', debug=True)
Simon Glass075a45c2017-11-13 18:55:00 -0700745
Simon Glass57454f42016-11-25 20:15:52 -0700746 def testDual(self):
747 """Test that we can handle creating two images
748
749 This also tests image padding.
750 """
Simon Glass511f6582018-10-01 12:22:30 -0600751 retcode = self._DoTestFile('006_dual_image.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700752 self.assertEqual(0, retcode)
753
754 image = control.images['image1']
Simon Glass39dd2152019-07-08 14:25:47 -0600755 self.assertEqual(len(U_BOOT_DATA), image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700756 fname = tools.GetOutputFilename('image1.bin')
757 self.assertTrue(os.path.exists(fname))
Simon Glass33486662019-05-14 15:53:42 -0600758 with open(fname, 'rb') as fd:
Simon Glass57454f42016-11-25 20:15:52 -0700759 data = fd.read()
760 self.assertEqual(U_BOOT_DATA, data)
761
762 image = control.images['image2']
Simon Glass39dd2152019-07-08 14:25:47 -0600763 self.assertEqual(3 + len(U_BOOT_DATA) + 5, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700764 fname = tools.GetOutputFilename('image2.bin')
765 self.assertTrue(os.path.exists(fname))
Simon Glass33486662019-05-14 15:53:42 -0600766 with open(fname, 'rb') as fd:
Simon Glass57454f42016-11-25 20:15:52 -0700767 data = fd.read()
768 self.assertEqual(U_BOOT_DATA, data[3:7])
Simon Glassac0d4952019-05-14 15:53:47 -0600769 self.assertEqual(tools.GetBytes(0, 3), data[:3])
770 self.assertEqual(tools.GetBytes(0, 5), data[7:])
Simon Glass57454f42016-11-25 20:15:52 -0700771
772 def testBadAlign(self):
773 """Test that an invalid alignment value is detected"""
774 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600775 self._DoTestFile('007_bad_align.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700776 self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
777 "of two", str(e.exception))
778
779 def testPackSimple(self):
780 """Test that packing works as expected"""
Simon Glass511f6582018-10-01 12:22:30 -0600781 retcode = self._DoTestFile('008_pack.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700782 self.assertEqual(0, retcode)
783 self.assertIn('image', control.images)
784 image = control.images['image']
Simon Glasseca32212018-06-01 09:38:12 -0600785 entries = image.GetEntries()
Simon Glass57454f42016-11-25 20:15:52 -0700786 self.assertEqual(5, len(entries))
787
788 # First u-boot
789 self.assertIn('u-boot', entries)
790 entry = entries['u-boot']
Simon Glasse8561af2018-08-01 15:22:37 -0600791 self.assertEqual(0, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700792 self.assertEqual(len(U_BOOT_DATA), entry.size)
793
794 # Second u-boot, aligned to 16-byte boundary
795 self.assertIn('u-boot-align', entries)
796 entry = entries['u-boot-align']
Simon Glasse8561af2018-08-01 15:22:37 -0600797 self.assertEqual(16, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700798 self.assertEqual(len(U_BOOT_DATA), entry.size)
799
800 # Third u-boot, size 23 bytes
801 self.assertIn('u-boot-size', entries)
802 entry = entries['u-boot-size']
Simon Glasse8561af2018-08-01 15:22:37 -0600803 self.assertEqual(20, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700804 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
805 self.assertEqual(23, entry.size)
806
807 # Fourth u-boot, placed immediate after the above
808 self.assertIn('u-boot-next', entries)
809 entry = entries['u-boot-next']
Simon Glasse8561af2018-08-01 15:22:37 -0600810 self.assertEqual(43, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700811 self.assertEqual(len(U_BOOT_DATA), entry.size)
812
Simon Glasse8561af2018-08-01 15:22:37 -0600813 # Fifth u-boot, placed at a fixed offset
Simon Glass57454f42016-11-25 20:15:52 -0700814 self.assertIn('u-boot-fixed', entries)
815 entry = entries['u-boot-fixed']
Simon Glasse8561af2018-08-01 15:22:37 -0600816 self.assertEqual(61, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700817 self.assertEqual(len(U_BOOT_DATA), entry.size)
818
Simon Glass39dd2152019-07-08 14:25:47 -0600819 self.assertEqual(65, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700820
821 def testPackExtra(self):
822 """Test that extra packing feature works as expected"""
Simon Glassafb9caa2020-10-26 17:40:10 -0600823 data, _, _, out_dtb_fname = self._DoReadFileDtb('009_pack_extra.dts',
824 update_dtb=True)
Simon Glass57454f42016-11-25 20:15:52 -0700825
Simon Glass57454f42016-11-25 20:15:52 -0700826 self.assertIn('image', control.images)
827 image = control.images['image']
Simon Glasseca32212018-06-01 09:38:12 -0600828 entries = image.GetEntries()
Simon Glass57454f42016-11-25 20:15:52 -0700829 self.assertEqual(5, len(entries))
830
831 # First u-boot with padding before and after
832 self.assertIn('u-boot', entries)
833 entry = entries['u-boot']
Simon Glasse8561af2018-08-01 15:22:37 -0600834 self.assertEqual(0, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700835 self.assertEqual(3, entry.pad_before)
836 self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
Simon Glass187202f2020-10-26 17:40:08 -0600837 self.assertEqual(U_BOOT_DATA, entry.data)
838 self.assertEqual(tools.GetBytes(0, 3) + U_BOOT_DATA +
839 tools.GetBytes(0, 5), data[:entry.size])
840 pos = entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700841
842 # Second u-boot has an aligned size, but it has no effect
843 self.assertIn('u-boot-align-size-nop', entries)
844 entry = entries['u-boot-align-size-nop']
Simon Glass187202f2020-10-26 17:40:08 -0600845 self.assertEqual(pos, entry.offset)
846 self.assertEqual(len(U_BOOT_DATA), entry.size)
847 self.assertEqual(U_BOOT_DATA, entry.data)
848 self.assertEqual(U_BOOT_DATA, data[pos:pos + entry.size])
849 pos += entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700850
851 # Third u-boot has an aligned size too
852 self.assertIn('u-boot-align-size', entries)
853 entry = entries['u-boot-align-size']
Simon Glass187202f2020-10-26 17:40:08 -0600854 self.assertEqual(pos, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700855 self.assertEqual(32, entry.size)
Simon Glass187202f2020-10-26 17:40:08 -0600856 self.assertEqual(U_BOOT_DATA, entry.data)
857 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 32 - len(U_BOOT_DATA)),
858 data[pos:pos + entry.size])
859 pos += entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700860
861 # Fourth u-boot has an aligned end
862 self.assertIn('u-boot-align-end', entries)
863 entry = entries['u-boot-align-end']
Simon Glasse8561af2018-08-01 15:22:37 -0600864 self.assertEqual(48, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700865 self.assertEqual(16, entry.size)
Simon Glass187202f2020-10-26 17:40:08 -0600866 self.assertEqual(U_BOOT_DATA, entry.data[:len(U_BOOT_DATA)])
867 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 16 - len(U_BOOT_DATA)),
868 data[pos:pos + entry.size])
869 pos += entry.size
Simon Glass57454f42016-11-25 20:15:52 -0700870
871 # Fifth u-boot immediately afterwards
872 self.assertIn('u-boot-align-both', entries)
873 entry = entries['u-boot-align-both']
Simon Glasse8561af2018-08-01 15:22:37 -0600874 self.assertEqual(64, entry.offset)
Simon Glass57454f42016-11-25 20:15:52 -0700875 self.assertEqual(64, entry.size)
Simon Glass187202f2020-10-26 17:40:08 -0600876 self.assertEqual(U_BOOT_DATA, entry.data[:len(U_BOOT_DATA)])
877 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 64 - len(U_BOOT_DATA)),
878 data[pos:pos + entry.size])
Simon Glass57454f42016-11-25 20:15:52 -0700879
880 self.CheckNoGaps(entries)
Simon Glass39dd2152019-07-08 14:25:47 -0600881 self.assertEqual(128, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700882
Simon Glassafb9caa2020-10-26 17:40:10 -0600883 dtb = fdt.Fdt(out_dtb_fname)
884 dtb.Scan()
885 props = self._GetPropTree(dtb, ['size', 'offset', 'image-pos'])
886 expected = {
887 'image-pos': 0,
888 'offset': 0,
889 'size': 128,
890
891 'u-boot:image-pos': 0,
892 'u-boot:offset': 0,
893 'u-boot:size': 3 + 5 + len(U_BOOT_DATA),
894
895 'u-boot-align-size-nop:image-pos': 12,
896 'u-boot-align-size-nop:offset': 12,
897 'u-boot-align-size-nop:size': 4,
898
899 'u-boot-align-size:image-pos': 16,
900 'u-boot-align-size:offset': 16,
901 'u-boot-align-size:size': 32,
902
903 'u-boot-align-end:image-pos': 48,
904 'u-boot-align-end:offset': 48,
905 'u-boot-align-end:size': 16,
906
907 'u-boot-align-both:image-pos': 64,
908 'u-boot-align-both:offset': 64,
909 'u-boot-align-both:size': 64,
910 }
911 self.assertEqual(expected, props)
912
Simon Glass57454f42016-11-25 20:15:52 -0700913 def testPackAlignPowerOf2(self):
914 """Test that invalid entry alignment is detected"""
915 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600916 self._DoTestFile('010_pack_align_power2.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700917 self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
918 "of two", str(e.exception))
919
920 def testPackAlignSizePowerOf2(self):
921 """Test that invalid entry size alignment is detected"""
922 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600923 self._DoTestFile('011_pack_align_size_power2.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700924 self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
925 "power of two", str(e.exception))
926
927 def testPackInvalidAlign(self):
Simon Glasse8561af2018-08-01 15:22:37 -0600928 """Test detection of an offset that does not match its alignment"""
Simon Glass57454f42016-11-25 20:15:52 -0700929 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600930 self._DoTestFile('012_pack_inv_align.dts')
Simon Glasse8561af2018-08-01 15:22:37 -0600931 self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
Simon Glass57454f42016-11-25 20:15:52 -0700932 "align 0x4 (4)", str(e.exception))
933
934 def testPackInvalidSizeAlign(self):
935 """Test that invalid entry size alignment is detected"""
936 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600937 self._DoTestFile('013_pack_inv_size_align.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700938 self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
939 "align-size 0x4 (4)", str(e.exception))
940
941 def testPackOverlap(self):
942 """Test that overlapping regions are detected"""
943 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600944 self._DoTestFile('014_pack_overlap.dts')
Simon Glasse8561af2018-08-01 15:22:37 -0600945 self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
Simon Glass57454f42016-11-25 20:15:52 -0700946 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
947 str(e.exception))
948
949 def testPackEntryOverflow(self):
950 """Test that entries that overflow their size are detected"""
951 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600952 self._DoTestFile('015_pack_overflow.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700953 self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
954 "but entry size is 0x3 (3)", str(e.exception))
955
956 def testPackImageOverflow(self):
957 """Test that entries which overflow the image size are detected"""
958 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600959 self._DoTestFile('016_pack_image_overflow.dts')
Simon Glasseca32212018-06-01 09:38:12 -0600960 self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
Simon Glass57454f42016-11-25 20:15:52 -0700961 "size 0x3 (3)", str(e.exception))
962
963 def testPackImageSize(self):
964 """Test that the image size can be set"""
Simon Glass511f6582018-10-01 12:22:30 -0600965 retcode = self._DoTestFile('017_pack_image_size.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700966 self.assertEqual(0, retcode)
967 self.assertIn('image', control.images)
968 image = control.images['image']
Simon Glass39dd2152019-07-08 14:25:47 -0600969 self.assertEqual(7, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700970
971 def testPackImageSizeAlign(self):
972 """Test that image size alignemnt works as expected"""
Simon Glass511f6582018-10-01 12:22:30 -0600973 retcode = self._DoTestFile('018_pack_image_align.dts')
Simon Glass57454f42016-11-25 20:15:52 -0700974 self.assertEqual(0, retcode)
975 self.assertIn('image', control.images)
976 image = control.images['image']
Simon Glass39dd2152019-07-08 14:25:47 -0600977 self.assertEqual(16, image.size)
Simon Glass57454f42016-11-25 20:15:52 -0700978
979 def testPackInvalidImageAlign(self):
980 """Test that invalid image alignment is detected"""
981 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600982 self._DoTestFile('019_pack_inv_image_align.dts')
Simon Glasseca32212018-06-01 09:38:12 -0600983 self.assertIn("Section '/binman': Size 0x7 (7) does not match "
Simon Glass57454f42016-11-25 20:15:52 -0700984 "align-size 0x8 (8)", str(e.exception))
985
986 def testPackAlignPowerOf2(self):
987 """Test that invalid image alignment is detected"""
988 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -0600989 self._DoTestFile('020_pack_inv_image_align_power2.dts')
Simon Glass39dd2152019-07-08 14:25:47 -0600990 self.assertIn("Image '/binman': Alignment size 131 must be a power of "
Simon Glass57454f42016-11-25 20:15:52 -0700991 "two", str(e.exception))
992
993 def testImagePadByte(self):
994 """Test that the image pad byte can be specified"""
Simon Glass7057d022018-10-01 21:12:47 -0600995 self._SetupSplElf()
Simon Glass511f6582018-10-01 12:22:30 -0600996 data = self._DoReadFile('021_image_pad.dts')
Simon Glassac0d4952019-05-14 15:53:47 -0600997 self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0xff, 1) +
998 U_BOOT_DATA, data)
Simon Glass57454f42016-11-25 20:15:52 -0700999
1000 def testImageName(self):
1001 """Test that image files can be named"""
Simon Glass511f6582018-10-01 12:22:30 -06001002 retcode = self._DoTestFile('022_image_name.dts')
Simon Glass57454f42016-11-25 20:15:52 -07001003 self.assertEqual(0, retcode)
1004 image = control.images['image1']
1005 fname = tools.GetOutputFilename('test-name')
1006 self.assertTrue(os.path.exists(fname))
1007
1008 image = control.images['image2']
1009 fname = tools.GetOutputFilename('test-name.xx')
1010 self.assertTrue(os.path.exists(fname))
1011
1012 def testBlobFilename(self):
1013 """Test that generic blobs can be provided by filename"""
Simon Glass511f6582018-10-01 12:22:30 -06001014 data = self._DoReadFile('023_blob.dts')
Simon Glass57454f42016-11-25 20:15:52 -07001015 self.assertEqual(BLOB_DATA, data)
1016
1017 def testPackSorted(self):
1018 """Test that entries can be sorted"""
Simon Glass7057d022018-10-01 21:12:47 -06001019 self._SetupSplElf()
Simon Glass511f6582018-10-01 12:22:30 -06001020 data = self._DoReadFile('024_sorted.dts')
Simon Glassac0d4952019-05-14 15:53:47 -06001021 self.assertEqual(tools.GetBytes(0, 1) + U_BOOT_SPL_DATA +
1022 tools.GetBytes(0, 2) + U_BOOT_DATA, data)
Simon Glass57454f42016-11-25 20:15:52 -07001023
Simon Glasse8561af2018-08-01 15:22:37 -06001024 def testPackZeroOffset(self):
1025 """Test that an entry at offset 0 is not given a new offset"""
Simon Glass57454f42016-11-25 20:15:52 -07001026 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001027 self._DoTestFile('025_pack_zero_size.dts')
Simon Glasse8561af2018-08-01 15:22:37 -06001028 self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
Simon Glass57454f42016-11-25 20:15:52 -07001029 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
1030 str(e.exception))
1031
1032 def testPackUbootDtb(self):
1033 """Test that a device tree can be added to U-Boot"""
Simon Glass511f6582018-10-01 12:22:30 -06001034 data = self._DoReadFile('026_pack_u_boot_dtb.dts')
Simon Glass57454f42016-11-25 20:15:52 -07001035 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
Simon Glass72232452016-11-25 20:15:53 -07001036
1037 def testPackX86RomNoSize(self):
1038 """Test that the end-at-4gb property requires a size property"""
1039 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001040 self._DoTestFile('027_pack_4gb_no_size.dts')
Simon Glass39dd2152019-07-08 14:25:47 -06001041 self.assertIn("Image '/binman': Section size must be provided when "
Simon Glass72232452016-11-25 20:15:53 -07001042 "using end-at-4gb", str(e.exception))
1043
Jagdish Gediya0fb978c2018-09-03 21:35:07 +05301044 def test4gbAndSkipAtStartTogether(self):
1045 """Test that the end-at-4gb and skip-at-size property can't be used
1046 together"""
1047 with self.assertRaises(ValueError) as e:
Simon Glass11f2bd02019-08-24 07:23:02 -06001048 self._DoTestFile('098_4gb_and_skip_at_start_together.dts')
Simon Glass39dd2152019-07-08 14:25:47 -06001049 self.assertIn("Image '/binman': Provide either 'end-at-4gb' or "
Jagdish Gediya0fb978c2018-09-03 21:35:07 +05301050 "'skip-at-start'", str(e.exception))
1051
Simon Glass72232452016-11-25 20:15:53 -07001052 def testPackX86RomOutside(self):
Simon Glasse8561af2018-08-01 15:22:37 -06001053 """Test that the end-at-4gb property checks for offset boundaries"""
Simon Glass72232452016-11-25 20:15:53 -07001054 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001055 self._DoTestFile('028_pack_4gb_outside.dts')
Simon Glassd6179862020-10-26 17:40:05 -06001056 self.assertIn("Node '/binman/u-boot': Offset 0x0 (0) size 0x4 (4) "
1057 "is outside the section '/binman' starting at "
1058 '0xffffffe0 (4294967264) of size 0x20 (32)',
Simon Glass72232452016-11-25 20:15:53 -07001059 str(e.exception))
1060
1061 def testPackX86Rom(self):
1062 """Test that a basic x86 ROM can be created"""
Simon Glass7057d022018-10-01 21:12:47 -06001063 self._SetupSplElf()
Simon Glass1d167762019-08-24 07:23:01 -06001064 data = self._DoReadFile('029_x86_rom.dts')
Simon Glass4e353e22019-08-24 07:23:04 -06001065 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 3) + U_BOOT_SPL_DATA +
Simon Glassac0d4952019-05-14 15:53:47 -06001066 tools.GetBytes(0, 2), data)
Simon Glass72232452016-11-25 20:15:53 -07001067
1068 def testPackX86RomMeNoDesc(self):
1069 """Test that an invalid Intel descriptor entry is detected"""
Simon Glasse88cef92020-07-09 18:39:41 -06001070 try:
Simon Glass14c596c2020-07-25 15:11:19 -06001071 TestFunctional._MakeInputFile('descriptor-empty.bin', b'')
Simon Glasse88cef92020-07-09 18:39:41 -06001072 with self.assertRaises(ValueError) as e:
Simon Glass14c596c2020-07-25 15:11:19 -06001073 self._DoTestFile('163_x86_rom_me_empty.dts')
Simon Glasse88cef92020-07-09 18:39:41 -06001074 self.assertIn("Node '/binman/intel-descriptor': Cannot find Intel Flash Descriptor (FD) signature",
1075 str(e.exception))
1076 finally:
1077 self._SetupDescriptor()
Simon Glass72232452016-11-25 20:15:53 -07001078
1079 def testPackX86RomBadDesc(self):
1080 """Test that the Intel requires a descriptor entry"""
1081 with self.assertRaises(ValueError) as e:
Simon Glass1d167762019-08-24 07:23:01 -06001082 self._DoTestFile('030_x86_rom_me_no_desc.dts')
Simon Glasse8561af2018-08-01 15:22:37 -06001083 self.assertIn("Node '/binman/intel-me': No offset set with "
1084 "offset-unset: should another entry provide this correct "
1085 "offset?", str(e.exception))
Simon Glass72232452016-11-25 20:15:53 -07001086
1087 def testPackX86RomMe(self):
1088 """Test that an x86 ROM with an ME region can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001089 data = self._DoReadFile('031_x86_rom_me.dts')
Simon Glass759af872019-07-08 13:18:54 -06001090 expected_desc = tools.ReadFile(self.TestFile('descriptor.bin'))
1091 if data[:0x1000] != expected_desc:
1092 self.fail('Expected descriptor binary at start of image')
Simon Glass72232452016-11-25 20:15:53 -07001093 self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
1094
1095 def testPackVga(self):
1096 """Test that an image with a VGA binary can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001097 data = self._DoReadFile('032_intel_vga.dts')
Simon Glass72232452016-11-25 20:15:53 -07001098 self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
1099
1100 def testPackStart16(self):
1101 """Test that an image with an x86 start16 region can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001102 data = self._DoReadFile('033_x86_start16.dts')
Simon Glass72232452016-11-25 20:15:53 -07001103 self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
1104
Jagdish Gediya311d4842018-09-03 21:35:08 +05301105 def testPackPowerpcMpc85xxBootpgResetvec(self):
1106 """Test that an image with powerpc-mpc85xx-bootpg-resetvec can be
1107 created"""
Simon Glass11f2bd02019-08-24 07:23:02 -06001108 data = self._DoReadFile('150_powerpc_mpc85xx_bootpg_resetvec.dts')
Jagdish Gediya311d4842018-09-03 21:35:08 +05301109 self.assertEqual(PPC_MPC85XX_BR_DATA, data[:len(PPC_MPC85XX_BR_DATA)])
1110
Simon Glass6ba679c2018-07-06 10:27:17 -06001111 def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
Simon Glass820af1d2018-07-06 10:27:16 -06001112 """Handle running a test for insertion of microcode
1113
1114 Args:
1115 dts_fname: Name of test .dts file
1116 nodtb_data: Data that we expect in the first section
Simon Glass6ba679c2018-07-06 10:27:17 -06001117 ucode_second: True if the microsecond entry is second instead of
1118 third
Simon Glass820af1d2018-07-06 10:27:16 -06001119
1120 Returns:
1121 Tuple:
1122 Contents of first region (U-Boot or SPL)
Simon Glasse8561af2018-08-01 15:22:37 -06001123 Offset and size components of microcode pointer, as inserted
Simon Glass820af1d2018-07-06 10:27:16 -06001124 in the above (two 4-byte words)
1125 """
Simon Glass3d274232017-11-12 21:52:27 -07001126 data = self._DoReadFile(dts_fname, True)
Simon Glass72232452016-11-25 20:15:53 -07001127
1128 # Now check the device tree has no microcode
Simon Glass6ba679c2018-07-06 10:27:17 -06001129 if ucode_second:
1130 ucode_content = data[len(nodtb_data):]
1131 ucode_pos = len(nodtb_data)
1132 dtb_with_ucode = ucode_content[16:]
1133 fdt_len = self.GetFdtLen(dtb_with_ucode)
1134 else:
1135 dtb_with_ucode = data[len(nodtb_data):]
1136 fdt_len = self.GetFdtLen(dtb_with_ucode)
1137 ucode_content = dtb_with_ucode[fdt_len:]
1138 ucode_pos = len(nodtb_data) + fdt_len
Simon Glass72232452016-11-25 20:15:53 -07001139 fname = tools.GetOutputFilename('test.dtb')
1140 with open(fname, 'wb') as fd:
Simon Glass820af1d2018-07-06 10:27:16 -06001141 fd.write(dtb_with_ucode)
Simon Glass22c92ca2017-05-27 07:38:29 -06001142 dtb = fdt.FdtScan(fname)
1143 ucode = dtb.GetNode('/microcode')
Simon Glass72232452016-11-25 20:15:53 -07001144 self.assertTrue(ucode)
1145 for node in ucode.subnodes:
1146 self.assertFalse(node.props.get('data'))
1147
Simon Glass72232452016-11-25 20:15:53 -07001148 # Check that the microcode appears immediately after the Fdt
1149 # This matches the concatenation of the data properties in
Simon Glasse83679d2017-11-12 21:52:26 -07001150 # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
Simon Glass72232452016-11-25 20:15:53 -07001151 ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
1152 0x78235609)
Simon Glass820af1d2018-07-06 10:27:16 -06001153 self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
Simon Glass72232452016-11-25 20:15:53 -07001154
1155 # Check that the microcode pointer was inserted. It should match the
Simon Glasse8561af2018-08-01 15:22:37 -06001156 # expected offset and size
Simon Glass72232452016-11-25 20:15:53 -07001157 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
1158 len(ucode_data))
Simon Glass6ba679c2018-07-06 10:27:17 -06001159 u_boot = data[:len(nodtb_data)]
1160 return u_boot, pos_and_size
Simon Glass3d274232017-11-12 21:52:27 -07001161
1162 def testPackUbootMicrocode(self):
1163 """Test that x86 microcode can be handled correctly
1164
1165 We expect to see the following in the image, in order:
1166 u-boot-nodtb.bin with a microcode pointer inserted at the correct
1167 place
1168 u-boot.dtb with the microcode removed
1169 the microcode
1170 """
Simon Glass511f6582018-10-01 12:22:30 -06001171 first, pos_and_size = self._RunMicrocodeTest('034_x86_ucode.dts',
Simon Glass3d274232017-11-12 21:52:27 -07001172 U_BOOT_NODTB_DATA)
Simon Glass303f62f2019-05-17 22:00:46 -06001173 self.assertEqual(b'nodtb with microcode' + pos_and_size +
1174 b' somewhere in here', first)
Simon Glass72232452016-11-25 20:15:53 -07001175
Simon Glassbac25c82017-05-27 07:38:26 -06001176 def _RunPackUbootSingleMicrocode(self):
Simon Glass72232452016-11-25 20:15:53 -07001177 """Test that x86 microcode can be handled correctly
1178
1179 We expect to see the following in the image, in order:
1180 u-boot-nodtb.bin with a microcode pointer inserted at the correct
1181 place
1182 u-boot.dtb with the microcode
1183 an empty microcode region
1184 """
1185 # We need the libfdt library to run this test since only that allows
1186 # finding the offset of a property. This is required by
1187 # Entry_u_boot_dtb_with_ucode.ObtainContents().
Simon Glass511f6582018-10-01 12:22:30 -06001188 data = self._DoReadFile('035_x86_single_ucode.dts', True)
Simon Glass72232452016-11-25 20:15:53 -07001189
1190 second = data[len(U_BOOT_NODTB_DATA):]
1191
1192 fdt_len = self.GetFdtLen(second)
1193 third = second[fdt_len:]
1194 second = second[:fdt_len]
1195
Simon Glassbac25c82017-05-27 07:38:26 -06001196 ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
1197 self.assertIn(ucode_data, second)
1198 ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
Simon Glass72232452016-11-25 20:15:53 -07001199
Simon Glassbac25c82017-05-27 07:38:26 -06001200 # Check that the microcode pointer was inserted. It should match the
Simon Glasse8561af2018-08-01 15:22:37 -06001201 # expected offset and size
Simon Glassbac25c82017-05-27 07:38:26 -06001202 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
1203 len(ucode_data))
1204 first = data[:len(U_BOOT_NODTB_DATA)]
Simon Glass303f62f2019-05-17 22:00:46 -06001205 self.assertEqual(b'nodtb with microcode' + pos_and_size +
1206 b' somewhere in here', first)
Simon Glass996021e2016-11-25 20:15:54 -07001207
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001208 def testPackUbootSingleMicrocode(self):
1209 """Test that x86 microcode can be handled correctly with fdt_normal.
1210 """
Simon Glassbac25c82017-05-27 07:38:26 -06001211 self._RunPackUbootSingleMicrocode()
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001212
Simon Glass996021e2016-11-25 20:15:54 -07001213 def testUBootImg(self):
1214 """Test that u-boot.img can be put in a file"""
Simon Glass511f6582018-10-01 12:22:30 -06001215 data = self._DoReadFile('036_u_boot_img.dts')
Simon Glass996021e2016-11-25 20:15:54 -07001216 self.assertEqual(U_BOOT_IMG_DATA, data)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001217
1218 def testNoMicrocode(self):
1219 """Test that a missing microcode region is detected"""
1220 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001221 self._DoReadFile('037_x86_no_ucode.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001222 self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
1223 "node found in ", str(e.exception))
1224
1225 def testMicrocodeWithoutNode(self):
1226 """Test that a missing u-boot-dtb-with-ucode node is detected"""
1227 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001228 self._DoReadFile('038_x86_ucode_missing_node.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001229 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
1230 "microcode region u-boot-dtb-with-ucode", str(e.exception))
1231
1232 def testMicrocodeWithoutNode2(self):
1233 """Test that a missing u-boot-ucode node is detected"""
1234 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001235 self._DoReadFile('039_x86_ucode_missing_node2.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001236 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
1237 "microcode region u-boot-ucode", str(e.exception))
1238
1239 def testMicrocodeWithoutPtrInElf(self):
1240 """Test that a U-Boot binary without the microcode symbol is detected"""
1241 # ELF file without a '_dt_ucode_base_size' symbol
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001242 try:
Simon Glassfaaaa162019-08-24 07:22:55 -06001243 TestFunctional._MakeInputFile('u-boot',
1244 tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001245
1246 with self.assertRaises(ValueError) as e:
Simon Glassbac25c82017-05-27 07:38:26 -06001247 self._RunPackUbootSingleMicrocode()
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001248 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
1249 "_dt_ucode_base_size symbol in u-boot", str(e.exception))
1250
1251 finally:
1252 # Put the original file back
Simon Glass4affd4b2019-08-24 07:22:54 -06001253 TestFunctional._MakeInputFile('u-boot',
1254 tools.ReadFile(self.ElfTestFile('u_boot_ucode_ptr')))
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001255
1256 def testMicrocodeNotInImage(self):
1257 """Test that microcode must be placed within the image"""
1258 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001259 self._DoReadFile('040_x86_ucode_not_in_image.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001260 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
1261 "pointer _dt_ucode_base_size at fffffe14 is outside the "
Simon Glassad5a7712018-06-01 09:38:14 -06001262 "section ranging from 00000000 to 0000002e", str(e.exception))
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001263
1264 def testWithoutMicrocode(self):
1265 """Test that we can cope with an image without microcode (e.g. qemu)"""
Simon Glassfaaaa162019-08-24 07:22:55 -06001266 TestFunctional._MakeInputFile('u-boot',
1267 tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
Simon Glass511f6582018-10-01 12:22:30 -06001268 data, dtb, _, _ = self._DoReadFileDtb('044_x86_optional_ucode.dts', True)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001269
1270 # Now check the device tree has no microcode
1271 self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
1272 second = data[len(U_BOOT_NODTB_DATA):]
1273
1274 fdt_len = self.GetFdtLen(second)
1275 self.assertEqual(dtb, second[:fdt_len])
1276
1277 used_len = len(U_BOOT_NODTB_DATA) + fdt_len
1278 third = data[used_len:]
Simon Glassac0d4952019-05-14 15:53:47 -06001279 self.assertEqual(tools.GetBytes(0, 0x200 - used_len), third)
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001280
1281 def testUnknownPosSize(self):
1282 """Test that microcode must be placed within the image"""
1283 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001284 self._DoReadFile('041_unknown_pos_size.dts', True)
Simon Glasse8561af2018-08-01 15:22:37 -06001285 self.assertIn("Section '/binman': Unable to set offset/size for unknown "
Simon Glassd2dfb5f2016-11-25 20:15:55 -07001286 "entry 'invalid-entry'", str(e.exception))
Simon Glassb4176d42016-11-25 20:15:56 -07001287
1288 def testPackFsp(self):
1289 """Test that an image with a FSP binary can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001290 data = self._DoReadFile('042_intel_fsp.dts')
Simon Glassb4176d42016-11-25 20:15:56 -07001291 self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
1292
1293 def testPackCmc(self):
Bin Mengd7bcdf52017-08-15 22:41:54 -07001294 """Test that an image with a CMC binary can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001295 data = self._DoReadFile('043_intel_cmc.dts')
Simon Glassb4176d42016-11-25 20:15:56 -07001296 self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
Bin Mengd7bcdf52017-08-15 22:41:54 -07001297
1298 def testPackVbt(self):
1299 """Test that an image with a VBT binary can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001300 data = self._DoReadFile('046_intel_vbt.dts')
Bin Mengd7bcdf52017-08-15 22:41:54 -07001301 self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
Simon Glassac599912017-11-12 21:52:22 -07001302
Simon Glass7f94e832017-11-12 21:52:25 -07001303 def testSplBssPad(self):
1304 """Test that we can pad SPL's BSS with zeros"""
Simon Glass3d274232017-11-12 21:52:27 -07001305 # ELF file with a '__bss_size' symbol
Simon Glass7057d022018-10-01 21:12:47 -06001306 self._SetupSplElf()
Simon Glass511f6582018-10-01 12:22:30 -06001307 data = self._DoReadFile('047_spl_bss_pad.dts')
Simon Glassac0d4952019-05-14 15:53:47 -06001308 self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0, 10) + U_BOOT_DATA,
1309 data)
Simon Glass7f94e832017-11-12 21:52:25 -07001310
Simon Glass04cda032018-10-01 21:12:42 -06001311 def testSplBssPadMissing(self):
1312 """Test that a missing symbol is detected"""
Simon Glass7057d022018-10-01 21:12:47 -06001313 self._SetupSplElf('u_boot_ucode_ptr')
Simon Glass24ad3652017-11-13 18:54:54 -07001314 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001315 self._DoReadFile('047_spl_bss_pad.dts')
Simon Glass24ad3652017-11-13 18:54:54 -07001316 self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
1317 str(e.exception))
1318
Simon Glasse83679d2017-11-12 21:52:26 -07001319 def testPackStart16Spl(self):
Simon Glassed40e962018-09-14 04:57:10 -06001320 """Test that an image with an x86 start16 SPL region can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001321 data = self._DoReadFile('048_x86_start16_spl.dts')
Simon Glasse83679d2017-11-12 21:52:26 -07001322 self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
1323
Simon Glass6ba679c2018-07-06 10:27:17 -06001324 def _PackUbootSplMicrocode(self, dts, ucode_second=False):
1325 """Helper function for microcode tests
Simon Glass3d274232017-11-12 21:52:27 -07001326
1327 We expect to see the following in the image, in order:
1328 u-boot-spl-nodtb.bin with a microcode pointer inserted at the
1329 correct place
1330 u-boot.dtb with the microcode removed
1331 the microcode
Simon Glass6ba679c2018-07-06 10:27:17 -06001332
1333 Args:
1334 dts: Device tree file to use for test
1335 ucode_second: True if the microsecond entry is second instead of
1336 third
Simon Glass3d274232017-11-12 21:52:27 -07001337 """
Simon Glass7057d022018-10-01 21:12:47 -06001338 self._SetupSplElf('u_boot_ucode_ptr')
Simon Glass6ba679c2018-07-06 10:27:17 -06001339 first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
1340 ucode_second=ucode_second)
Simon Glass303f62f2019-05-17 22:00:46 -06001341 self.assertEqual(b'splnodtb with microc' + pos_and_size +
1342 b'ter somewhere in here', first)
Simon Glass3d274232017-11-12 21:52:27 -07001343
Simon Glass6ba679c2018-07-06 10:27:17 -06001344 def testPackUbootSplMicrocode(self):
1345 """Test that x86 microcode can be handled correctly in SPL"""
Simon Glass511f6582018-10-01 12:22:30 -06001346 self._PackUbootSplMicrocode('049_x86_ucode_spl.dts')
Simon Glass6ba679c2018-07-06 10:27:17 -06001347
1348 def testPackUbootSplMicrocodeReorder(self):
1349 """Test that order doesn't matter for microcode entries
1350
1351 This is the same as testPackUbootSplMicrocode but when we process the
1352 u-boot-ucode entry we have not yet seen the u-boot-dtb-with-ucode
1353 entry, so we reply on binman to try later.
1354 """
Simon Glass511f6582018-10-01 12:22:30 -06001355 self._PackUbootSplMicrocode('058_x86_ucode_spl_needs_retry.dts',
Simon Glass6ba679c2018-07-06 10:27:17 -06001356 ucode_second=True)
1357
Simon Glassa409c932017-11-12 21:52:28 -07001358 def testPackMrc(self):
1359 """Test that an image with an MRC binary can be created"""
Simon Glass511f6582018-10-01 12:22:30 -06001360 data = self._DoReadFile('050_intel_mrc.dts')
Simon Glassa409c932017-11-12 21:52:28 -07001361 self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
1362
Simon Glass9aa6a6f2017-11-13 18:54:55 -07001363 def testSplDtb(self):
1364 """Test that an image with spl/u-boot-spl.dtb can be created"""
Simon Glass511f6582018-10-01 12:22:30 -06001365 data = self._DoReadFile('051_u_boot_spl_dtb.dts')
Simon Glass9aa6a6f2017-11-13 18:54:55 -07001366 self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
1367
Simon Glass0a6da312017-11-13 18:54:56 -07001368 def testSplNoDtb(self):
1369 """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
Simon Glass13089cc2021-04-25 08:39:32 +12001370 self._SetupSplElf()
Simon Glass511f6582018-10-01 12:22:30 -06001371 data = self._DoReadFile('052_u_boot_spl_nodtb.dts')
Simon Glass0a6da312017-11-13 18:54:56 -07001372 self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
1373
Simon Glass7098b7f2021-03-21 18:24:30 +13001374 def checkSymbols(self, dts, base_data, u_boot_offset, entry_args=None,
1375 use_expanded=False):
Simon Glass31e04cb2021-03-18 20:24:56 +13001376 """Check the image contains the expected symbol values
1377
1378 Args:
1379 dts: Device tree file to use for test
1380 base_data: Data before and after 'u-boot' section
1381 u_boot_offset: Offset of 'u-boot' section in image
Simon Glass7098b7f2021-03-21 18:24:30 +13001382 entry_args: Dict of entry args to supply to binman
1383 key: arg name
1384 value: value of that arg
1385 use_expanded: True to use expanded entries where available, e.g.
1386 'u-boot-expanded' instead of 'u-boot'
Simon Glass31e04cb2021-03-18 20:24:56 +13001387 """
Simon Glass5d0c0262019-08-24 07:22:56 -06001388 elf_fname = self.ElfTestFile('u_boot_binman_syms')
Simon Glass4ca8e042017-11-13 18:55:01 -07001389 syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
1390 addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
Simon Glass31e04cb2021-03-18 20:24:56 +13001391 self.assertEqual(syms['_binman_u_boot_spl_any_prop_offset'].address,
1392 addr)
Simon Glass4ca8e042017-11-13 18:55:01 -07001393
Simon Glass7057d022018-10-01 21:12:47 -06001394 self._SetupSplElf('u_boot_binman_syms')
Simon Glass7098b7f2021-03-21 18:24:30 +13001395 data = self._DoReadFileDtb(dts, entry_args=entry_args,
1396 use_expanded=use_expanded)[0]
Simon Glass31e04cb2021-03-18 20:24:56 +13001397 # The image should contain the symbols from u_boot_binman_syms.c
1398 # Note that image_pos is adjusted by the base address of the image,
1399 # which is 0x10 in our test image
1400 sym_values = struct.pack('<LQLL', 0x00,
1401 u_boot_offset + len(U_BOOT_DATA),
1402 0x10 + u_boot_offset, 0x04)
1403 expected = (sym_values + base_data[20:] +
Simon Glassac0d4952019-05-14 15:53:47 -06001404 tools.GetBytes(0xff, 1) + U_BOOT_DATA + sym_values +
Simon Glass31e04cb2021-03-18 20:24:56 +13001405 base_data[20:])
Simon Glass4ca8e042017-11-13 18:55:01 -07001406 self.assertEqual(expected, data)
1407
Simon Glass31e04cb2021-03-18 20:24:56 +13001408 def testSymbols(self):
1409 """Test binman can assign symbols embedded in U-Boot"""
1410 self.checkSymbols('053_symbols.dts', U_BOOT_SPL_DATA, 0x18)
1411
1412 def testSymbolsNoDtb(self):
1413 """Test binman can assign symbols embedded in U-Boot SPL"""
Simon Glass3bbc9932021-03-21 18:24:29 +13001414 self.checkSymbols('196_symbols_nodtb.dts',
Simon Glass31e04cb2021-03-18 20:24:56 +13001415 U_BOOT_SPL_NODTB_DATA + U_BOOT_SPL_DTB_DATA,
1416 0x38)
1417
Simon Glasse76a3e62018-06-01 09:38:11 -06001418 def testPackUnitAddress(self):
1419 """Test that we support multiple binaries with the same name"""
Simon Glass511f6582018-10-01 12:22:30 -06001420 data = self._DoReadFile('054_unit_address.dts')
Simon Glasse76a3e62018-06-01 09:38:11 -06001421 self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
1422
Simon Glassa91e1152018-06-01 09:38:16 -06001423 def testSections(self):
1424 """Basic test of sections"""
Simon Glass511f6582018-10-01 12:22:30 -06001425 data = self._DoReadFile('055_sections.dts')
Simon Glass303f62f2019-05-17 22:00:46 -06001426 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
1427 U_BOOT_DATA + tools.GetBytes(ord('a'), 12) +
1428 U_BOOT_DATA + tools.GetBytes(ord('&'), 4))
Simon Glassa91e1152018-06-01 09:38:16 -06001429 self.assertEqual(expected, data)
Simon Glassac599912017-11-12 21:52:22 -07001430
Simon Glass30732662018-06-01 09:38:20 -06001431 def testMap(self):
1432 """Tests outputting a map of the images"""
Simon Glass511f6582018-10-01 12:22:30 -06001433 _, _, map_data, _ = self._DoReadFileDtb('055_sections.dts', map=True)
Simon Glass7eca7922018-07-17 13:25:49 -06001434 self.assertEqual('''ImagePos Offset Size Name
143500000000 00000000 00000028 main-section
143600000000 00000000 00000010 section@0
143700000000 00000000 00000004 u-boot
143800000010 00000010 00000010 section@1
143900000010 00000000 00000004 u-boot
144000000020 00000020 00000004 section@2
144100000020 00000000 00000004 u-boot
Simon Glass30732662018-06-01 09:38:20 -06001442''', map_data)
1443
Simon Glass3b78d532018-06-01 09:38:21 -06001444 def testNamePrefix(self):
1445 """Tests that name prefixes are used"""
Simon Glass511f6582018-10-01 12:22:30 -06001446 _, _, map_data, _ = self._DoReadFileDtb('056_name_prefix.dts', map=True)
Simon Glass7eca7922018-07-17 13:25:49 -06001447 self.assertEqual('''ImagePos Offset Size Name
144800000000 00000000 00000028 main-section
144900000000 00000000 00000010 section@0
145000000000 00000000 00000004 ro-u-boot
145100000010 00000010 00000010 section@1
145200000010 00000000 00000004 rw-u-boot
Simon Glass3b78d532018-06-01 09:38:21 -06001453''', map_data)
1454
Simon Glass6ba679c2018-07-06 10:27:17 -06001455 def testUnknownContents(self):
1456 """Test that obtaining the contents works as expected"""
1457 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001458 self._DoReadFile('057_unknown_contents.dts', True)
Simon Glass39dd2152019-07-08 14:25:47 -06001459 self.assertIn("Image '/binman': Internal error: Could not complete "
Simon Glassc585dd42020-04-17 18:09:03 -06001460 "processing of contents: remaining ["
1461 "<binman.etype._testing.Entry__testing ", str(e.exception))
Simon Glass6ba679c2018-07-06 10:27:17 -06001462
Simon Glass2e1169f2018-07-06 10:27:19 -06001463 def testBadChangeSize(self):
1464 """Test that trying to change the size of an entry fails"""
Simon Glasse61b6f62019-07-08 14:25:37 -06001465 try:
1466 state.SetAllowEntryExpansion(False)
1467 with self.assertRaises(ValueError) as e:
1468 self._DoReadFile('059_change_size.dts', True)
Simon Glass8c702fb2019-07-20 12:23:57 -06001469 self.assertIn("Node '/binman/_testing': Cannot update entry size from 2 to 3",
Simon Glasse61b6f62019-07-08 14:25:37 -06001470 str(e.exception))
1471 finally:
1472 state.SetAllowEntryExpansion(True)
Simon Glass2e1169f2018-07-06 10:27:19 -06001473
Simon Glassa87014e2018-07-06 10:27:42 -06001474 def testUpdateFdt(self):
Simon Glasse8561af2018-08-01 15:22:37 -06001475 """Test that we can update the device tree with offset/size info"""
Simon Glass511f6582018-10-01 12:22:30 -06001476 _, _, _, out_dtb_fname = self._DoReadFileDtb('060_fdt_update.dts',
Simon Glassa87014e2018-07-06 10:27:42 -06001477 update_dtb=True)
Simon Glass5463a6a2018-07-17 13:25:52 -06001478 dtb = fdt.Fdt(out_dtb_fname)
1479 dtb.Scan()
Simon Glassfb30e292019-07-20 12:23:51 -06001480 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS)
Simon Glassa87014e2018-07-06 10:27:42 -06001481 self.assertEqual({
Simon Glass9dcc8612018-08-01 15:22:42 -06001482 'image-pos': 0,
Simon Glass3a9a2b82018-07-17 13:25:28 -06001483 'offset': 0,
Simon Glasse8561af2018-08-01 15:22:37 -06001484 '_testing:offset': 32,
Simon Glass8c702fb2019-07-20 12:23:57 -06001485 '_testing:size': 2,
Simon Glass9dcc8612018-08-01 15:22:42 -06001486 '_testing:image-pos': 32,
Simon Glasse8561af2018-08-01 15:22:37 -06001487 'section@0/u-boot:offset': 0,
Simon Glassa87014e2018-07-06 10:27:42 -06001488 'section@0/u-boot:size': len(U_BOOT_DATA),
Simon Glass9dcc8612018-08-01 15:22:42 -06001489 'section@0/u-boot:image-pos': 0,
Simon Glasse8561af2018-08-01 15:22:37 -06001490 'section@0:offset': 0,
Simon Glassa87014e2018-07-06 10:27:42 -06001491 'section@0:size': 16,
Simon Glass9dcc8612018-08-01 15:22:42 -06001492 'section@0:image-pos': 0,
Simon Glassa87014e2018-07-06 10:27:42 -06001493
Simon Glasse8561af2018-08-01 15:22:37 -06001494 'section@1/u-boot:offset': 0,
Simon Glassa87014e2018-07-06 10:27:42 -06001495 'section@1/u-boot:size': len(U_BOOT_DATA),
Simon Glass9dcc8612018-08-01 15:22:42 -06001496 'section@1/u-boot:image-pos': 16,
Simon Glasse8561af2018-08-01 15:22:37 -06001497 'section@1:offset': 16,
Simon Glassa87014e2018-07-06 10:27:42 -06001498 'section@1:size': 16,
Simon Glass9dcc8612018-08-01 15:22:42 -06001499 'section@1:image-pos': 16,
Simon Glassa87014e2018-07-06 10:27:42 -06001500 'size': 40
1501 }, props)
1502
1503 def testUpdateFdtBad(self):
1504 """Test that we detect when ProcessFdt never completes"""
1505 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001506 self._DoReadFileDtb('061_fdt_update_bad.dts', update_dtb=True)
Simon Glassa87014e2018-07-06 10:27:42 -06001507 self.assertIn('Could not complete processing of Fdt: remaining '
Simon Glassc585dd42020-04-17 18:09:03 -06001508 '[<binman.etype._testing.Entry__testing',
1509 str(e.exception))
Simon Glass2e1169f2018-07-06 10:27:19 -06001510
Simon Glass91710b32018-07-17 13:25:32 -06001511 def testEntryArgs(self):
1512 """Test passing arguments to entries from the command line"""
1513 entry_args = {
1514 'test-str-arg': 'test1',
1515 'test-int-arg': '456',
1516 }
Simon Glass511f6582018-10-01 12:22:30 -06001517 self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
Simon Glass91710b32018-07-17 13:25:32 -06001518 self.assertIn('image', control.images)
1519 entry = control.images['image'].GetEntries()['_testing']
1520 self.assertEqual('test0', entry.test_str_fdt)
1521 self.assertEqual('test1', entry.test_str_arg)
1522 self.assertEqual(123, entry.test_int_fdt)
1523 self.assertEqual(456, entry.test_int_arg)
1524
1525 def testEntryArgsMissing(self):
1526 """Test missing arguments and properties"""
1527 entry_args = {
1528 'test-int-arg': '456',
1529 }
Simon Glass511f6582018-10-01 12:22:30 -06001530 self._DoReadFileDtb('063_entry_args_missing.dts', entry_args=entry_args)
Simon Glass91710b32018-07-17 13:25:32 -06001531 entry = control.images['image'].GetEntries()['_testing']
1532 self.assertEqual('test0', entry.test_str_fdt)
1533 self.assertEqual(None, entry.test_str_arg)
1534 self.assertEqual(None, entry.test_int_fdt)
1535 self.assertEqual(456, entry.test_int_arg)
1536
1537 def testEntryArgsRequired(self):
1538 """Test missing arguments and properties"""
1539 entry_args = {
1540 'test-int-arg': '456',
1541 }
1542 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001543 self._DoReadFileDtb('064_entry_args_required.dts')
Simon Glass21db0ff2020-09-01 05:13:54 -06001544 self.assertIn("Node '/binman/_testing': "
1545 'Missing required properties/entry args: test-str-arg, '
1546 'test-int-fdt, test-int-arg',
Simon Glass91710b32018-07-17 13:25:32 -06001547 str(e.exception))
1548
1549 def testEntryArgsInvalidFormat(self):
1550 """Test that an invalid entry-argument format is detected"""
Simon Glassf46732a2019-07-08 14:25:29 -06001551 args = ['build', '-d', self.TestFile('064_entry_args_required.dts'),
1552 '-ano-value']
Simon Glass91710b32018-07-17 13:25:32 -06001553 with self.assertRaises(ValueError) as e:
1554 self._DoBinman(*args)
1555 self.assertIn("Invalid entry arguemnt 'no-value'", str(e.exception))
1556
1557 def testEntryArgsInvalidInteger(self):
1558 """Test that an invalid entry-argument integer is detected"""
1559 entry_args = {
1560 'test-int-arg': 'abc',
1561 }
1562 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001563 self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
Simon Glass91710b32018-07-17 13:25:32 -06001564 self.assertIn("Node '/binman/_testing': Cannot convert entry arg "
1565 "'test-int-arg' (value 'abc') to integer",
1566 str(e.exception))
1567
1568 def testEntryArgsInvalidDatatype(self):
1569 """Test that an invalid entry-argument datatype is detected
1570
1571 This test could be written in entry_test.py except that it needs
1572 access to control.entry_args, which seems more than that module should
1573 be able to see.
1574 """
1575 entry_args = {
1576 'test-bad-datatype-arg': '12',
1577 }
1578 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001579 self._DoReadFileDtb('065_entry_args_unknown_datatype.dts',
Simon Glass91710b32018-07-17 13:25:32 -06001580 entry_args=entry_args)
1581 self.assertIn('GetArg() internal error: Unknown data type ',
1582 str(e.exception))
1583
Simon Glass2ca52032018-07-17 13:25:33 -06001584 def testText(self):
1585 """Test for a text entry type"""
1586 entry_args = {
1587 'test-id': TEXT_DATA,
1588 'test-id2': TEXT_DATA2,
1589 'test-id3': TEXT_DATA3,
1590 }
Simon Glass511f6582018-10-01 12:22:30 -06001591 data, _, _, _ = self._DoReadFileDtb('066_text.dts',
Simon Glass2ca52032018-07-17 13:25:33 -06001592 entry_args=entry_args)
Simon Glass303f62f2019-05-17 22:00:46 -06001593 expected = (tools.ToBytes(TEXT_DATA) +
1594 tools.GetBytes(0, 8 - len(TEXT_DATA)) +
1595 tools.ToBytes(TEXT_DATA2) + tools.ToBytes(TEXT_DATA3) +
Simon Glass47f6a622019-07-08 13:18:40 -06001596 b'some text' + b'more text')
Simon Glass2ca52032018-07-17 13:25:33 -06001597 self.assertEqual(expected, data)
1598
Simon Glass969616c2018-07-17 13:25:36 -06001599 def testEntryDocs(self):
1600 """Test for creation of entry documentation"""
1601 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass220ff5f2020-08-05 13:27:46 -06001602 control.WriteEntryDocs(control.GetEntryModules())
Simon Glass969616c2018-07-17 13:25:36 -06001603 self.assertTrue(len(stdout.getvalue()) > 0)
1604
1605 def testEntryDocsMissing(self):
1606 """Test handling of missing entry documentation"""
1607 with self.assertRaises(ValueError) as e:
1608 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass220ff5f2020-08-05 13:27:46 -06001609 control.WriteEntryDocs(control.GetEntryModules(), 'u_boot')
Simon Glass969616c2018-07-17 13:25:36 -06001610 self.assertIn('Documentation is missing for modules: u_boot',
1611 str(e.exception))
1612
Simon Glass704784b2018-07-17 13:25:38 -06001613 def testFmap(self):
1614 """Basic test of generation of a flashrom fmap"""
Simon Glass511f6582018-10-01 12:22:30 -06001615 data = self._DoReadFile('067_fmap.dts')
Simon Glass704784b2018-07-17 13:25:38 -06001616 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
Simon Glass303f62f2019-05-17 22:00:46 -06001617 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
1618 U_BOOT_DATA + tools.GetBytes(ord('a'), 12))
Simon Glass704784b2018-07-17 13:25:38 -06001619 self.assertEqual(expected, data[:32])
Simon Glass303f62f2019-05-17 22:00:46 -06001620 self.assertEqual(b'__FMAP__', fhdr.signature)
Simon Glass704784b2018-07-17 13:25:38 -06001621 self.assertEqual(1, fhdr.ver_major)
1622 self.assertEqual(0, fhdr.ver_minor)
1623 self.assertEqual(0, fhdr.base)
Simon Glassb1d414c2021-04-03 11:05:10 +13001624 expect_size = fmap_util.FMAP_HEADER_LEN + fmap_util.FMAP_AREA_LEN * 5
Simon Glass82059c22021-04-03 11:05:09 +13001625 self.assertEqual(16 + 16 + expect_size, fhdr.image_size)
Simon Glass303f62f2019-05-17 22:00:46 -06001626 self.assertEqual(b'FMAP', fhdr.name)
Simon Glassb1d414c2021-04-03 11:05:10 +13001627 self.assertEqual(5, fhdr.nareas)
Simon Glass82059c22021-04-03 11:05:09 +13001628 fiter = iter(fentries)
Simon Glass704784b2018-07-17 13:25:38 -06001629
Simon Glass82059c22021-04-03 11:05:09 +13001630 fentry = next(fiter)
Simon Glassb1d414c2021-04-03 11:05:10 +13001631 self.assertEqual(b'SECTION0', fentry.name)
1632 self.assertEqual(0, fentry.offset)
1633 self.assertEqual(16, fentry.size)
1634 self.assertEqual(0, fentry.flags)
1635
1636 fentry = next(fiter)
Simon Glass82059c22021-04-03 11:05:09 +13001637 self.assertEqual(b'RO_U_BOOT', fentry.name)
1638 self.assertEqual(0, fentry.offset)
1639 self.assertEqual(4, fentry.size)
1640 self.assertEqual(0, fentry.flags)
Simon Glass704784b2018-07-17 13:25:38 -06001641
Simon Glass82059c22021-04-03 11:05:09 +13001642 fentry = next(fiter)
Simon Glassb1d414c2021-04-03 11:05:10 +13001643 self.assertEqual(b'SECTION1', fentry.name)
1644 self.assertEqual(16, fentry.offset)
1645 self.assertEqual(16, fentry.size)
1646 self.assertEqual(0, fentry.flags)
1647
1648 fentry = next(fiter)
Simon Glass82059c22021-04-03 11:05:09 +13001649 self.assertEqual(b'RW_U_BOOT', fentry.name)
1650 self.assertEqual(16, fentry.offset)
1651 self.assertEqual(4, fentry.size)
1652 self.assertEqual(0, fentry.flags)
Simon Glass704784b2018-07-17 13:25:38 -06001653
Simon Glass82059c22021-04-03 11:05:09 +13001654 fentry = next(fiter)
1655 self.assertEqual(b'FMAP', fentry.name)
1656 self.assertEqual(32, fentry.offset)
1657 self.assertEqual(expect_size, fentry.size)
1658 self.assertEqual(0, fentry.flags)
Simon Glass704784b2018-07-17 13:25:38 -06001659
Simon Glassdb168d42018-07-17 13:25:39 -06001660 def testBlobNamedByArg(self):
1661 """Test we can add a blob with the filename coming from an entry arg"""
1662 entry_args = {
1663 'cros-ec-rw-path': 'ecrw.bin',
1664 }
Simon Glass21db0ff2020-09-01 05:13:54 -06001665 self._DoReadFileDtb('068_blob_named_by_arg.dts', entry_args=entry_args)
Simon Glassdb168d42018-07-17 13:25:39 -06001666
Simon Glass53f53992018-07-17 13:25:40 -06001667 def testFill(self):
1668 """Test for an fill entry type"""
Simon Glass511f6582018-10-01 12:22:30 -06001669 data = self._DoReadFile('069_fill.dts')
Simon Glassac0d4952019-05-14 15:53:47 -06001670 expected = tools.GetBytes(0xff, 8) + tools.GetBytes(0, 8)
Simon Glass53f53992018-07-17 13:25:40 -06001671 self.assertEqual(expected, data)
1672
1673 def testFillNoSize(self):
1674 """Test for an fill entry type with no size"""
1675 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001676 self._DoReadFile('070_fill_no_size.dts')
Simon Glass53f53992018-07-17 13:25:40 -06001677 self.assertIn("'fill' entry must have a size property",
1678 str(e.exception))
1679
Simon Glassc1ae83c2018-07-17 13:25:44 -06001680 def _HandleGbbCommand(self, pipe_list):
1681 """Fake calls to the futility utility"""
1682 if pipe_list[0][0] == 'futility':
1683 fname = pipe_list[0][-1]
1684 # Append our GBB data to the file, which will happen every time the
1685 # futility command is called.
Simon Glass33486662019-05-14 15:53:42 -06001686 with open(fname, 'ab') as fd:
Simon Glassc1ae83c2018-07-17 13:25:44 -06001687 fd.write(GBB_DATA)
1688 return command.CommandResult()
1689
1690 def testGbb(self):
1691 """Test for the Chromium OS Google Binary Block"""
1692 command.test_result = self._HandleGbbCommand
1693 entry_args = {
1694 'keydir': 'devkeys',
1695 'bmpblk': 'bmpblk.bin',
1696 }
Simon Glass511f6582018-10-01 12:22:30 -06001697 data, _, _, _ = self._DoReadFileDtb('071_gbb.dts', entry_args=entry_args)
Simon Glassc1ae83c2018-07-17 13:25:44 -06001698
1699 # Since futility
Simon Glassac0d4952019-05-14 15:53:47 -06001700 expected = (GBB_DATA + GBB_DATA + tools.GetBytes(0, 8) +
1701 tools.GetBytes(0, 0x2180 - 16))
Simon Glassc1ae83c2018-07-17 13:25:44 -06001702 self.assertEqual(expected, data)
1703
1704 def testGbbTooSmall(self):
1705 """Test for the Chromium OS Google Binary Block being large enough"""
1706 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001707 self._DoReadFileDtb('072_gbb_too_small.dts')
Simon Glassc1ae83c2018-07-17 13:25:44 -06001708 self.assertIn("Node '/binman/gbb': GBB is too small",
1709 str(e.exception))
1710
1711 def testGbbNoSize(self):
1712 """Test for the Chromium OS Google Binary Block having a size"""
1713 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001714 self._DoReadFileDtb('073_gbb_no_size.dts')
Simon Glassc1ae83c2018-07-17 13:25:44 -06001715 self.assertIn("Node '/binman/gbb': GBB must have a fixed size",
1716 str(e.exception))
1717
Simon Glass5c350162018-07-17 13:25:47 -06001718 def _HandleVblockCommand(self, pipe_list):
Simon Glass220c6222021-01-06 21:35:17 -07001719 """Fake calls to the futility utility
1720
1721 The expected pipe is:
1722
1723 [('futility', 'vbutil_firmware', '--vblock',
1724 'vblock.vblock', '--keyblock', 'devkeys/firmware.keyblock',
1725 '--signprivate', 'devkeys/firmware_data_key.vbprivk',
1726 '--version', '1', '--fv', 'input.vblock', '--kernelkey',
1727 'devkeys/kernel_subkey.vbpubk', '--flags', '1')]
1728
1729 This writes to the output file (here, 'vblock.vblock'). If
1730 self._hash_data is False, it writes VBLOCK_DATA, else it writes a hash
1731 of the input data (here, 'input.vblock').
1732 """
Simon Glass5c350162018-07-17 13:25:47 -06001733 if pipe_list[0][0] == 'futility':
1734 fname = pipe_list[0][3]
Simon Glass639505b2018-09-14 04:57:11 -06001735 with open(fname, 'wb') as fd:
Simon Glass220c6222021-01-06 21:35:17 -07001736 if self._hash_data:
1737 infile = pipe_list[0][11]
1738 m = hashlib.sha256()
1739 data = tools.ReadFile(infile)
1740 m.update(data)
1741 fd.write(m.digest())
1742 else:
1743 fd.write(VBLOCK_DATA)
1744
Simon Glass5c350162018-07-17 13:25:47 -06001745 return command.CommandResult()
1746
1747 def testVblock(self):
1748 """Test for the Chromium OS Verified Boot Block"""
Simon Glass220c6222021-01-06 21:35:17 -07001749 self._hash_data = False
Simon Glass5c350162018-07-17 13:25:47 -06001750 command.test_result = self._HandleVblockCommand
1751 entry_args = {
1752 'keydir': 'devkeys',
1753 }
Simon Glass511f6582018-10-01 12:22:30 -06001754 data, _, _, _ = self._DoReadFileDtb('074_vblock.dts',
Simon Glass5c350162018-07-17 13:25:47 -06001755 entry_args=entry_args)
1756 expected = U_BOOT_DATA + VBLOCK_DATA + U_BOOT_DTB_DATA
1757 self.assertEqual(expected, data)
1758
1759 def testVblockNoContent(self):
1760 """Test we detect a vblock which has no content to sign"""
1761 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001762 self._DoReadFile('075_vblock_no_content.dts')
Simon Glasse1915782021-03-21 18:24:31 +13001763 self.assertIn("Node '/binman/vblock': Collection must have a 'content' "
Simon Glass5c350162018-07-17 13:25:47 -06001764 'property', str(e.exception))
1765
1766 def testVblockBadPhandle(self):
1767 """Test that we detect a vblock with an invalid phandle in contents"""
1768 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001769 self._DoReadFile('076_vblock_bad_phandle.dts')
Simon Glass5c350162018-07-17 13:25:47 -06001770 self.assertIn("Node '/binman/vblock': Cannot find node for phandle "
1771 '1000', str(e.exception))
1772
1773 def testVblockBadEntry(self):
1774 """Test that we detect an entry that points to a non-entry"""
1775 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001776 self._DoReadFile('077_vblock_bad_entry.dts')
Simon Glass5c350162018-07-17 13:25:47 -06001777 self.assertIn("Node '/binman/vblock': Cannot find entry for node "
1778 "'other'", str(e.exception))
1779
Simon Glass220c6222021-01-06 21:35:17 -07001780 def testVblockContent(self):
1781 """Test that the vblock signs the right data"""
1782 self._hash_data = True
1783 command.test_result = self._HandleVblockCommand
1784 entry_args = {
1785 'keydir': 'devkeys',
1786 }
1787 data = self._DoReadFileDtb(
1788 '189_vblock_content.dts', use_real_dtb=True, update_dtb=True,
1789 entry_args=entry_args)[0]
1790 hashlen = 32 # SHA256 hash is 32 bytes
1791 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
1792 hashval = data[-hashlen:]
1793 dtb = data[len(U_BOOT_DATA):-hashlen]
1794
1795 expected_data = U_BOOT_DATA + dtb
1796
1797 # The hashval should be a hash of the dtb
1798 m = hashlib.sha256()
1799 m.update(expected_data)
1800 expected_hashval = m.digest()
1801 self.assertEqual(expected_hashval, hashval)
1802
Simon Glass8425a1f2018-07-17 13:25:48 -06001803 def testTpl(self):
Simon Glass3eb5b202019-08-24 07:23:00 -06001804 """Test that an image with TPL and its device tree can be created"""
Simon Glass8425a1f2018-07-17 13:25:48 -06001805 # ELF file with a '__bss_size' symbol
Simon Glass3eb5b202019-08-24 07:23:00 -06001806 self._SetupTplElf()
Simon Glass511f6582018-10-01 12:22:30 -06001807 data = self._DoReadFile('078_u_boot_tpl.dts')
Simon Glass8425a1f2018-07-17 13:25:48 -06001808 self.assertEqual(U_BOOT_TPL_DATA + U_BOOT_TPL_DTB_DATA, data)
1809
Simon Glass24b97442018-07-17 13:25:51 -06001810 def testUsesPos(self):
1811 """Test that the 'pos' property cannot be used anymore"""
1812 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001813 data = self._DoReadFile('079_uses_pos.dts')
Simon Glass24b97442018-07-17 13:25:51 -06001814 self.assertIn("Node '/binman/u-boot': Please use 'offset' instead of "
1815 "'pos'", str(e.exception))
1816
Simon Glass274bf092018-09-14 04:57:08 -06001817 def testFillZero(self):
1818 """Test for an fill entry type with a size of 0"""
Simon Glass511f6582018-10-01 12:22:30 -06001819 data = self._DoReadFile('080_fill_empty.dts')
Simon Glassac0d4952019-05-14 15:53:47 -06001820 self.assertEqual(tools.GetBytes(0, 16), data)
Simon Glass274bf092018-09-14 04:57:08 -06001821
Simon Glass267de432018-09-14 04:57:09 -06001822 def testTextMissing(self):
1823 """Test for a text entry type where there is no text"""
1824 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001825 self._DoReadFileDtb('066_text.dts',)
Simon Glass267de432018-09-14 04:57:09 -06001826 self.assertIn("Node '/binman/text': No value provided for text label "
1827 "'test-id'", str(e.exception))
1828
Simon Glassed40e962018-09-14 04:57:10 -06001829 def testPackStart16Tpl(self):
1830 """Test that an image with an x86 start16 TPL region can be created"""
Simon Glass1d167762019-08-24 07:23:01 -06001831 data = self._DoReadFile('081_x86_start16_tpl.dts')
Simon Glassed40e962018-09-14 04:57:10 -06001832 self.assertEqual(X86_START16_TPL_DATA, data[:len(X86_START16_TPL_DATA)])
1833
Simon Glass3b376c32018-09-14 04:57:12 -06001834 def testSelectImage(self):
1835 """Test that we can select which images to build"""
Simon Glassb4595d82019-04-25 21:58:34 -06001836 expected = 'Skipping images: image1'
1837
1838 # We should only get the expected message in verbose mode
Simon Glass8a50b4a2019-07-08 13:18:48 -06001839 for verbosity in (0, 2):
Simon Glassb4595d82019-04-25 21:58:34 -06001840 with test_util.capture_sys_output() as (stdout, stderr):
1841 retcode = self._DoTestFile('006_dual_image.dts',
1842 verbosity=verbosity,
1843 images=['image2'])
1844 self.assertEqual(0, retcode)
1845 if verbosity:
1846 self.assertIn(expected, stdout.getvalue())
1847 else:
1848 self.assertNotIn(expected, stdout.getvalue())
Simon Glass3b376c32018-09-14 04:57:12 -06001849
Simon Glassb4595d82019-04-25 21:58:34 -06001850 self.assertFalse(os.path.exists(tools.GetOutputFilename('image1.bin')))
1851 self.assertTrue(os.path.exists(tools.GetOutputFilename('image2.bin')))
Simon Glassb3d6fc72019-07-20 12:24:10 -06001852 self._CleanupOutputDir()
Simon Glass3b376c32018-09-14 04:57:12 -06001853
Simon Glasse219aa42018-09-14 04:57:24 -06001854 def testUpdateFdtAll(self):
1855 """Test that all device trees are updated with offset/size info"""
Simon Glass5b4bce32019-07-08 14:25:26 -06001856 data = self._DoReadFileRealDtb('082_fdt_update_all.dts')
Simon Glasse219aa42018-09-14 04:57:24 -06001857
1858 base_expected = {
1859 'section:image-pos': 0,
1860 'u-boot-tpl-dtb:size': 513,
1861 'u-boot-spl-dtb:size': 513,
1862 'u-boot-spl-dtb:offset': 493,
1863 'image-pos': 0,
1864 'section/u-boot-dtb:image-pos': 0,
1865 'u-boot-spl-dtb:image-pos': 493,
1866 'section/u-boot-dtb:size': 493,
1867 'u-boot-tpl-dtb:image-pos': 1006,
1868 'section/u-boot-dtb:offset': 0,
1869 'section:size': 493,
1870 'offset': 0,
1871 'section:offset': 0,
1872 'u-boot-tpl-dtb:offset': 1006,
1873 'size': 1519
1874 }
1875
1876 # We expect three device-tree files in the output, one after the other.
1877 # Read them in sequence. We look for an 'spl' property in the SPL tree,
1878 # and 'tpl' in the TPL tree, to make sure they are distinct from the
1879 # main U-Boot tree. All three should have the same postions and offset.
1880 start = 0
1881 for item in ['', 'spl', 'tpl']:
1882 dtb = fdt.Fdt.FromData(data[start:])
1883 dtb.Scan()
Simon Glassfb30e292019-07-20 12:23:51 -06001884 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS +
1885 ['spl', 'tpl'])
Simon Glasse219aa42018-09-14 04:57:24 -06001886 expected = dict(base_expected)
1887 if item:
1888 expected[item] = 0
1889 self.assertEqual(expected, props)
1890 start += dtb._fdt_obj.totalsize()
1891
1892 def testUpdateFdtOutput(self):
1893 """Test that output DTB files are updated"""
1894 try:
Simon Glass511f6582018-10-01 12:22:30 -06001895 data, dtb_data, _, _ = self._DoReadFileDtb('082_fdt_update_all.dts',
Simon Glasse219aa42018-09-14 04:57:24 -06001896 use_real_dtb=True, update_dtb=True, reset_dtbs=False)
1897
1898 # Unfortunately, compiling a source file always results in a file
1899 # called source.dtb (see fdt_util.EnsureCompiled()). The test
Simon Glass511f6582018-10-01 12:22:30 -06001900 # source file (e.g. test/075_fdt_update_all.dts) thus does not enter
Simon Glasse219aa42018-09-14 04:57:24 -06001901 # binman as a file called u-boot.dtb. To fix this, copy the file
1902 # over to the expected place.
Simon Glasse219aa42018-09-14 04:57:24 -06001903 start = 0
1904 for fname in ['u-boot.dtb.out', 'spl/u-boot-spl.dtb.out',
1905 'tpl/u-boot-tpl.dtb.out']:
1906 dtb = fdt.Fdt.FromData(data[start:])
1907 size = dtb._fdt_obj.totalsize()
1908 pathname = tools.GetOutputFilename(os.path.split(fname)[1])
1909 outdata = tools.ReadFile(pathname)
1910 name = os.path.split(fname)[0]
1911
1912 if name:
1913 orig_indata = self._GetDtbContentsForSplTpl(dtb_data, name)
1914 else:
1915 orig_indata = dtb_data
1916 self.assertNotEqual(outdata, orig_indata,
1917 "Expected output file '%s' be updated" % pathname)
1918 self.assertEqual(outdata, data[start:start + size],
1919 "Expected output file '%s' to match output image" %
1920 pathname)
1921 start += size
1922 finally:
1923 self._ResetDtbs()
1924
Simon Glass7ba33592018-09-14 04:57:26 -06001925 def _decompress(self, data):
Simon Glassccec0262019-07-08 13:18:42 -06001926 return tools.Decompress(data, 'lz4')
Simon Glass7ba33592018-09-14 04:57:26 -06001927
1928 def testCompress(self):
1929 """Test compression of blobs"""
Simon Glass1de34482019-07-08 13:18:53 -06001930 self._CheckLz4()
Simon Glass511f6582018-10-01 12:22:30 -06001931 data, _, _, out_dtb_fname = self._DoReadFileDtb('083_compress.dts',
Simon Glass7ba33592018-09-14 04:57:26 -06001932 use_real_dtb=True, update_dtb=True)
1933 dtb = fdt.Fdt(out_dtb_fname)
1934 dtb.Scan()
1935 props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
1936 orig = self._decompress(data)
1937 self.assertEquals(COMPRESS_DATA, orig)
Simon Glass789b34402020-10-26 17:40:15 -06001938
1939 # Do a sanity check on various fields
1940 image = control.images['image']
1941 entries = image.GetEntries()
1942 self.assertEqual(1, len(entries))
1943
1944 entry = entries['blob']
1945 self.assertEqual(COMPRESS_DATA, entry.uncomp_data)
1946 self.assertEqual(len(COMPRESS_DATA), entry.uncomp_size)
1947 orig = self._decompress(entry.data)
1948 self.assertEqual(orig, entry.uncomp_data)
1949
Simon Glass72eeff12020-10-26 17:40:16 -06001950 self.assertEqual(image.data, entry.data)
1951
Simon Glass7ba33592018-09-14 04:57:26 -06001952 expected = {
1953 'blob:uncomp-size': len(COMPRESS_DATA),
1954 'blob:size': len(data),
1955 'size': len(data),
1956 }
1957 self.assertEqual(expected, props)
1958
Simon Glassac6328c2018-09-14 04:57:28 -06001959 def testFiles(self):
1960 """Test bringing in multiple files"""
Simon Glass511f6582018-10-01 12:22:30 -06001961 data = self._DoReadFile('084_files.dts')
Simon Glassac6328c2018-09-14 04:57:28 -06001962 self.assertEqual(FILES_DATA, data)
1963
1964 def testFilesCompress(self):
1965 """Test bringing in multiple files and compressing them"""
Simon Glass1de34482019-07-08 13:18:53 -06001966 self._CheckLz4()
Simon Glass511f6582018-10-01 12:22:30 -06001967 data = self._DoReadFile('085_files_compress.dts')
Simon Glassac6328c2018-09-14 04:57:28 -06001968
1969 image = control.images['image']
1970 entries = image.GetEntries()
1971 files = entries['files']
Simon Glass39dd2152019-07-08 14:25:47 -06001972 entries = files._entries
Simon Glassac6328c2018-09-14 04:57:28 -06001973
Simon Glass303f62f2019-05-17 22:00:46 -06001974 orig = b''
Simon Glassac6328c2018-09-14 04:57:28 -06001975 for i in range(1, 3):
1976 key = '%d.dat' % i
1977 start = entries[key].image_pos
1978 len = entries[key].size
1979 chunk = data[start:start + len]
1980 orig += self._decompress(chunk)
1981
1982 self.assertEqual(FILES_DATA, orig)
1983
1984 def testFilesMissing(self):
1985 """Test missing files"""
1986 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001987 data = self._DoReadFile('086_files_none.dts')
Simon Glassac6328c2018-09-14 04:57:28 -06001988 self.assertIn("Node '/binman/files': Pattern \'files/*.none\' matched "
1989 'no files', str(e.exception))
1990
1991 def testFilesNoPattern(self):
1992 """Test missing files"""
1993 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06001994 data = self._DoReadFile('087_files_no_pattern.dts')
Simon Glassac6328c2018-09-14 04:57:28 -06001995 self.assertIn("Node '/binman/files': Missing 'pattern' property",
1996 str(e.exception))
1997
Simon Glassfa79a812018-09-14 04:57:29 -06001998 def testExpandSize(self):
1999 """Test an expanding entry"""
Simon Glass511f6582018-10-01 12:22:30 -06002000 data, _, map_data, _ = self._DoReadFileDtb('088_expand_size.dts',
Simon Glassfa79a812018-09-14 04:57:29 -06002001 map=True)
Simon Glass303f62f2019-05-17 22:00:46 -06002002 expect = (tools.GetBytes(ord('a'), 8) + U_BOOT_DATA +
2003 MRC_DATA + tools.GetBytes(ord('b'), 1) + U_BOOT_DATA +
2004 tools.GetBytes(ord('c'), 8) + U_BOOT_DATA +
2005 tools.GetBytes(ord('d'), 8))
Simon Glassfa79a812018-09-14 04:57:29 -06002006 self.assertEqual(expect, data)
2007 self.assertEqual('''ImagePos Offset Size Name
200800000000 00000000 00000028 main-section
200900000000 00000000 00000008 fill
201000000008 00000008 00000004 u-boot
20110000000c 0000000c 00000004 section
20120000000c 00000000 00000003 intel-mrc
201300000010 00000010 00000004 u-boot2
201400000014 00000014 0000000c section2
201500000014 00000000 00000008 fill
20160000001c 00000008 00000004 u-boot
201700000020 00000020 00000008 fill2
2018''', map_data)
2019
2020 def testExpandSizeBad(self):
2021 """Test an expanding entry which fails to provide contents"""
Simon Glasscd817d52018-09-14 04:57:36 -06002022 with test_util.capture_sys_output() as (stdout, stderr):
2023 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06002024 self._DoReadFileDtb('089_expand_size_bad.dts', map=True)
Simon Glassfa79a812018-09-14 04:57:29 -06002025 self.assertIn("Node '/binman/_testing': Cannot obtain contents when "
2026 'expanding entry', str(e.exception))
2027
Simon Glassae7cf032018-09-14 04:57:31 -06002028 def testHash(self):
2029 """Test hashing of the contents of an entry"""
Simon Glass511f6582018-10-01 12:22:30 -06002030 _, _, _, out_dtb_fname = self._DoReadFileDtb('090_hash.dts',
Simon Glassae7cf032018-09-14 04:57:31 -06002031 use_real_dtb=True, update_dtb=True)
2032 dtb = fdt.Fdt(out_dtb_fname)
2033 dtb.Scan()
2034 hash_node = dtb.GetNode('/binman/u-boot/hash').props['value']
2035 m = hashlib.sha256()
2036 m.update(U_BOOT_DATA)
Simon Glass303f62f2019-05-17 22:00:46 -06002037 self.assertEqual(m.digest(), b''.join(hash_node.value))
Simon Glassae7cf032018-09-14 04:57:31 -06002038
2039 def testHashNoAlgo(self):
2040 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06002041 self._DoReadFileDtb('091_hash_no_algo.dts', update_dtb=True)
Simon Glassae7cf032018-09-14 04:57:31 -06002042 self.assertIn("Node \'/binman/u-boot\': Missing \'algo\' property for "
2043 'hash node', str(e.exception))
2044
2045 def testHashBadAlgo(self):
2046 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06002047 self._DoReadFileDtb('092_hash_bad_algo.dts', update_dtb=True)
Simon Glassae7cf032018-09-14 04:57:31 -06002048 self.assertIn("Node '/binman/u-boot': Unknown hash algorithm",
2049 str(e.exception))
2050
2051 def testHashSection(self):
2052 """Test hashing of the contents of an entry"""
Simon Glass511f6582018-10-01 12:22:30 -06002053 _, _, _, out_dtb_fname = self._DoReadFileDtb('099_hash_section.dts',
Simon Glassae7cf032018-09-14 04:57:31 -06002054 use_real_dtb=True, update_dtb=True)
2055 dtb = fdt.Fdt(out_dtb_fname)
2056 dtb.Scan()
2057 hash_node = dtb.GetNode('/binman/section/hash').props['value']
2058 m = hashlib.sha256()
2059 m.update(U_BOOT_DATA)
Simon Glass303f62f2019-05-17 22:00:46 -06002060 m.update(tools.GetBytes(ord('a'), 16))
2061 self.assertEqual(m.digest(), b''.join(hash_node.value))
Simon Glassae7cf032018-09-14 04:57:31 -06002062
Simon Glass3fb4f422018-09-14 04:57:32 -06002063 def testPackUBootTplMicrocode(self):
2064 """Test that x86 microcode can be handled correctly in TPL
2065
2066 We expect to see the following in the image, in order:
2067 u-boot-tpl-nodtb.bin with a microcode pointer inserted at the correct
2068 place
2069 u-boot-tpl.dtb with the microcode removed
2070 the microcode
2071 """
Simon Glass3eb5b202019-08-24 07:23:00 -06002072 self._SetupTplElf('u_boot_ucode_ptr')
Simon Glass511f6582018-10-01 12:22:30 -06002073 first, pos_and_size = self._RunMicrocodeTest('093_x86_tpl_ucode.dts',
Simon Glass3fb4f422018-09-14 04:57:32 -06002074 U_BOOT_TPL_NODTB_DATA)
Simon Glass303f62f2019-05-17 22:00:46 -06002075 self.assertEqual(b'tplnodtb with microc' + pos_and_size +
2076 b'ter somewhere in here', first)
Simon Glass3fb4f422018-09-14 04:57:32 -06002077
Simon Glassc64aea52018-09-14 04:57:34 -06002078 def testFmapX86(self):
2079 """Basic test of generation of a flashrom fmap"""
Simon Glass511f6582018-10-01 12:22:30 -06002080 data = self._DoReadFile('094_fmap_x86.dts')
Simon Glassc64aea52018-09-14 04:57:34 -06002081 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
Simon Glass303f62f2019-05-17 22:00:46 -06002082 expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('a'), 32 - 7)
Simon Glassc64aea52018-09-14 04:57:34 -06002083 self.assertEqual(expected, data[:32])
2084 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
2085
2086 self.assertEqual(0x100, fhdr.image_size)
2087
2088 self.assertEqual(0, fentries[0].offset)
2089 self.assertEqual(4, fentries[0].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002090 self.assertEqual(b'U_BOOT', fentries[0].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002091
2092 self.assertEqual(4, fentries[1].offset)
2093 self.assertEqual(3, fentries[1].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002094 self.assertEqual(b'INTEL_MRC', fentries[1].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002095
2096 self.assertEqual(32, fentries[2].offset)
2097 self.assertEqual(fmap_util.FMAP_HEADER_LEN +
2098 fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
Simon Glass303f62f2019-05-17 22:00:46 -06002099 self.assertEqual(b'FMAP', fentries[2].name)
Simon Glassc64aea52018-09-14 04:57:34 -06002100
2101 def testFmapX86Section(self):
2102 """Basic test of generation of a flashrom fmap"""
Simon Glass511f6582018-10-01 12:22:30 -06002103 data = self._DoReadFile('095_fmap_x86_section.dts')
Simon Glass303f62f2019-05-17 22:00:46 -06002104 expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('b'), 32 - 7)
Simon Glassc64aea52018-09-14 04:57:34 -06002105 self.assertEqual(expected, data[:32])
2106 fhdr, fentries = fmap_util.DecodeFmap(data[36:])
2107
Simon Glassb1d414c2021-04-03 11:05:10 +13002108 self.assertEqual(0x180, fhdr.image_size)
2109 expect_size = fmap_util.FMAP_HEADER_LEN + fmap_util.FMAP_AREA_LEN * 4
Simon Glass82059c22021-04-03 11:05:09 +13002110 fiter = iter(fentries)
Simon Glassc64aea52018-09-14 04:57:34 -06002111
Simon Glass82059c22021-04-03 11:05:09 +13002112 fentry = next(fiter)
2113 self.assertEqual(b'U_BOOT', fentry.name)
2114 self.assertEqual(0, fentry.offset)
2115 self.assertEqual(4, fentry.size)
Simon Glassc64aea52018-09-14 04:57:34 -06002116
Simon Glass82059c22021-04-03 11:05:09 +13002117 fentry = next(fiter)
Simon Glassb1d414c2021-04-03 11:05:10 +13002118 self.assertEqual(b'SECTION', fentry.name)
2119 self.assertEqual(4, fentry.offset)
2120 self.assertEqual(0x20 + expect_size, fentry.size)
2121
2122 fentry = next(fiter)
Simon Glass82059c22021-04-03 11:05:09 +13002123 self.assertEqual(b'INTEL_MRC', fentry.name)
2124 self.assertEqual(4, fentry.offset)
2125 self.assertEqual(3, fentry.size)
Simon Glassc64aea52018-09-14 04:57:34 -06002126
Simon Glass82059c22021-04-03 11:05:09 +13002127 fentry = next(fiter)
2128 self.assertEqual(b'FMAP', fentry.name)
2129 self.assertEqual(36, fentry.offset)
2130 self.assertEqual(expect_size, fentry.size)
Simon Glassc64aea52018-09-14 04:57:34 -06002131
Simon Glassb1714232018-09-14 04:57:35 -06002132 def testElf(self):
2133 """Basic test of ELF entries"""
Simon Glass7057d022018-10-01 21:12:47 -06002134 self._SetupSplElf()
Simon Glass3eb5b202019-08-24 07:23:00 -06002135 self._SetupTplElf()
Simon Glassf6290892019-08-24 07:22:53 -06002136 with open(self.ElfTestFile('bss_data'), 'rb') as fd:
Simon Glassb1714232018-09-14 04:57:35 -06002137 TestFunctional._MakeInputFile('-boot', fd.read())
Simon Glass511f6582018-10-01 12:22:30 -06002138 data = self._DoReadFile('096_elf.dts')
Simon Glassb1714232018-09-14 04:57:35 -06002139
Simon Glass0d673792019-07-08 13:18:25 -06002140 def testElfStrip(self):
Simon Glassb1714232018-09-14 04:57:35 -06002141 """Basic test of ELF entries"""
Simon Glass7057d022018-10-01 21:12:47 -06002142 self._SetupSplElf()
Simon Glassf6290892019-08-24 07:22:53 -06002143 with open(self.ElfTestFile('bss_data'), 'rb') as fd:
Simon Glassb1714232018-09-14 04:57:35 -06002144 TestFunctional._MakeInputFile('-boot', fd.read())
Simon Glass511f6582018-10-01 12:22:30 -06002145 data = self._DoReadFile('097_elf_strip.dts')
Simon Glassb1714232018-09-14 04:57:35 -06002146
Simon Glasscd817d52018-09-14 04:57:36 -06002147 def testPackOverlapMap(self):
2148 """Test that overlapping regions are detected"""
2149 with test_util.capture_sys_output() as (stdout, stderr):
2150 with self.assertRaises(ValueError) as e:
Simon Glass511f6582018-10-01 12:22:30 -06002151 self._DoTestFile('014_pack_overlap.dts', map=True)
Simon Glasscd817d52018-09-14 04:57:36 -06002152 map_fname = tools.GetOutputFilename('image.map')
2153 self.assertEqual("Wrote map file '%s' to show errors\n" % map_fname,
2154 stdout.getvalue())
2155
2156 # We should not get an inmage, but there should be a map file
2157 self.assertFalse(os.path.exists(tools.GetOutputFilename('image.bin')))
2158 self.assertTrue(os.path.exists(map_fname))
Simon Glassb3774752019-05-17 22:00:51 -06002159 map_data = tools.ReadFile(map_fname, binary=False)
Simon Glasscd817d52018-09-14 04:57:36 -06002160 self.assertEqual('''ImagePos Offset Size Name
Simon Glassd99850b2020-10-26 17:40:24 -06002161<none> 00000000 00000008 main-section
Simon Glasscd817d52018-09-14 04:57:36 -06002162<none> 00000000 00000004 u-boot
2163<none> 00000003 00000004 u-boot-align
2164''', map_data)
2165
Simon Glass0d673792019-07-08 13:18:25 -06002166 def testPackRefCode(self):
Simon Glass41902e42018-10-01 12:22:31 -06002167 """Test that an image with an Intel Reference code binary works"""
2168 data = self._DoReadFile('100_intel_refcode.dts')
2169 self.assertEqual(REFCODE_DATA, data[:len(REFCODE_DATA)])
2170
Simon Glasseb023b32019-04-25 21:58:39 -06002171 def testSectionOffset(self):
2172 """Tests use of a section with an offset"""
2173 data, _, map_data, _ = self._DoReadFileDtb('101_sections_offset.dts',
2174 map=True)
2175 self.assertEqual('''ImagePos Offset Size Name
217600000000 00000000 00000038 main-section
217700000004 00000004 00000010 section@0
217800000004 00000000 00000004 u-boot
217900000018 00000018 00000010 section@1
218000000018 00000000 00000004 u-boot
21810000002c 0000002c 00000004 section@2
21820000002c 00000000 00000004 u-boot
2183''', map_data)
2184 self.assertEqual(data,
Simon Glassac0d4952019-05-14 15:53:47 -06002185 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
2186 tools.GetBytes(0x21, 12) +
2187 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
2188 tools.GetBytes(0x61, 12) +
2189 tools.GetBytes(0x26, 4) + U_BOOT_DATA +
2190 tools.GetBytes(0x26, 8))
Simon Glasseb023b32019-04-25 21:58:39 -06002191
Simon Glass1de34482019-07-08 13:18:53 -06002192 def testCbfsRaw(self):
2193 """Test base handling of a Coreboot Filesystem (CBFS)
2194
2195 The exact contents of the CBFS is verified by similar tests in
2196 cbfs_util_test.py. The tests here merely check that the files added to
2197 the CBFS can be found in the final image.
2198 """
2199 data = self._DoReadFile('102_cbfs_raw.dts')
2200 size = 0xb0
2201
2202 cbfs = cbfs_util.CbfsReader(data)
2203 self.assertEqual(size, cbfs.rom_size)
2204
2205 self.assertIn('u-boot-dtb', cbfs.files)
2206 cfile = cbfs.files['u-boot-dtb']
2207 self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
2208
2209 def testCbfsArch(self):
2210 """Test on non-x86 architecture"""
2211 data = self._DoReadFile('103_cbfs_raw_ppc.dts')
2212 size = 0x100
2213
2214 cbfs = cbfs_util.CbfsReader(data)
2215 self.assertEqual(size, cbfs.rom_size)
2216
2217 self.assertIn('u-boot-dtb', cbfs.files)
2218 cfile = cbfs.files['u-boot-dtb']
2219 self.assertEqual(U_BOOT_DTB_DATA, cfile.data)
2220
2221 def testCbfsStage(self):
2222 """Tests handling of a Coreboot Filesystem (CBFS)"""
2223 if not elf.ELF_TOOLS:
2224 self.skipTest('Python elftools not available')
2225 elf_fname = os.path.join(self._indir, 'cbfs-stage.elf')
2226 elf.MakeElf(elf_fname, U_BOOT_DATA, U_BOOT_DTB_DATA)
2227 size = 0xb0
2228
2229 data = self._DoReadFile('104_cbfs_stage.dts')
2230 cbfs = cbfs_util.CbfsReader(data)
2231 self.assertEqual(size, cbfs.rom_size)
2232
2233 self.assertIn('u-boot', cbfs.files)
2234 cfile = cbfs.files['u-boot']
2235 self.assertEqual(U_BOOT_DATA + U_BOOT_DTB_DATA, cfile.data)
2236
2237 def testCbfsRawCompress(self):
2238 """Test handling of compressing raw files"""
2239 self._CheckLz4()
2240 data = self._DoReadFile('105_cbfs_raw_compress.dts')
2241 size = 0x140
2242
2243 cbfs = cbfs_util.CbfsReader(data)
2244 self.assertIn('u-boot', cbfs.files)
2245 cfile = cbfs.files['u-boot']
2246 self.assertEqual(COMPRESS_DATA, cfile.data)
2247
2248 def testCbfsBadArch(self):
2249 """Test handling of a bad architecture"""
2250 with self.assertRaises(ValueError) as e:
2251 self._DoReadFile('106_cbfs_bad_arch.dts')
2252 self.assertIn("Invalid architecture 'bad-arch'", str(e.exception))
2253
2254 def testCbfsNoSize(self):
2255 """Test handling of a missing size property"""
2256 with self.assertRaises(ValueError) as e:
2257 self._DoReadFile('107_cbfs_no_size.dts')
2258 self.assertIn('entry must have a size property', str(e.exception))
2259
Simon Glass3e28f4f2021-11-23 11:03:54 -07002260 def testCbfsNoContents(self):
Simon Glass1de34482019-07-08 13:18:53 -06002261 """Test handling of a CBFS entry which does not provide contentsy"""
2262 with self.assertRaises(ValueError) as e:
2263 self._DoReadFile('108_cbfs_no_contents.dts')
2264 self.assertIn('Could not complete processing of contents',
2265 str(e.exception))
2266
2267 def testCbfsBadCompress(self):
2268 """Test handling of a bad architecture"""
2269 with self.assertRaises(ValueError) as e:
2270 self._DoReadFile('109_cbfs_bad_compress.dts')
2271 self.assertIn("Invalid compression in 'u-boot': 'invalid-algo'",
2272 str(e.exception))
2273
2274 def testCbfsNamedEntries(self):
2275 """Test handling of named entries"""
2276 data = self._DoReadFile('110_cbfs_name.dts')
2277
2278 cbfs = cbfs_util.CbfsReader(data)
2279 self.assertIn('FRED', cbfs.files)
2280 cfile1 = cbfs.files['FRED']
2281 self.assertEqual(U_BOOT_DATA, cfile1.data)
2282
2283 self.assertIn('hello', cbfs.files)
2284 cfile2 = cbfs.files['hello']
2285 self.assertEqual(U_BOOT_DTB_DATA, cfile2.data)
2286
Simon Glass759af872019-07-08 13:18:54 -06002287 def _SetupIfwi(self, fname):
2288 """Set up to run an IFWI test
2289
2290 Args:
2291 fname: Filename of input file to provide (fitimage.bin or ifwi.bin)
2292 """
2293 self._SetupSplElf()
Simon Glass3eb5b202019-08-24 07:23:00 -06002294 self._SetupTplElf()
Simon Glass759af872019-07-08 13:18:54 -06002295
2296 # Intel Integrated Firmware Image (IFWI) file
2297 with gzip.open(self.TestFile('%s.gz' % fname), 'rb') as fd:
2298 data = fd.read()
2299 TestFunctional._MakeInputFile(fname,data)
2300
2301 def _CheckIfwi(self, data):
2302 """Check that an image with an IFWI contains the correct output
2303
2304 Args:
2305 data: Conents of output file
2306 """
2307 expected_desc = tools.ReadFile(self.TestFile('descriptor.bin'))
2308 if data[:0x1000] != expected_desc:
2309 self.fail('Expected descriptor binary at start of image')
2310
2311 # We expect to find the TPL wil in subpart IBBP entry IBBL
2312 image_fname = tools.GetOutputFilename('image.bin')
2313 tpl_fname = tools.GetOutputFilename('tpl.out')
2314 tools.RunIfwiTool(image_fname, tools.CMD_EXTRACT, fname=tpl_fname,
2315 subpart='IBBP', entry_name='IBBL')
2316
2317 tpl_data = tools.ReadFile(tpl_fname)
Simon Glassf55bd692019-08-24 07:22:51 -06002318 self.assertEqual(U_BOOT_TPL_DATA, tpl_data[:len(U_BOOT_TPL_DATA)])
Simon Glass759af872019-07-08 13:18:54 -06002319
2320 def testPackX86RomIfwi(self):
2321 """Test that an x86 ROM with Integrated Firmware Image can be created"""
2322 self._SetupIfwi('fitimage.bin')
Simon Glass1d167762019-08-24 07:23:01 -06002323 data = self._DoReadFile('111_x86_rom_ifwi.dts')
Simon Glass759af872019-07-08 13:18:54 -06002324 self._CheckIfwi(data)
2325
2326 def testPackX86RomIfwiNoDesc(self):
2327 """Test that an x86 ROM with IFWI can be created from an ifwi.bin file"""
2328 self._SetupIfwi('ifwi.bin')
Simon Glass1d167762019-08-24 07:23:01 -06002329 data = self._DoReadFile('112_x86_rom_ifwi_nodesc.dts')
Simon Glass759af872019-07-08 13:18:54 -06002330 self._CheckIfwi(data)
2331
2332 def testPackX86RomIfwiNoData(self):
2333 """Test that an x86 ROM with IFWI handles missing data"""
2334 self._SetupIfwi('ifwi.bin')
2335 with self.assertRaises(ValueError) as e:
Simon Glass1d167762019-08-24 07:23:01 -06002336 data = self._DoReadFile('113_x86_rom_ifwi_nodata.dts')
Simon Glass759af872019-07-08 13:18:54 -06002337 self.assertIn('Could not complete processing of contents',
2338 str(e.exception))
Simon Glass91710b32018-07-17 13:25:32 -06002339
Simon Glassc2f1aed2019-07-08 13:18:56 -06002340 def testCbfsOffset(self):
2341 """Test a CBFS with files at particular offsets
2342
2343 Like all CFBS tests, this is just checking the logic that calls
2344 cbfs_util. See cbfs_util_test for fully tests (e.g. test_cbfs_offset()).
2345 """
2346 data = self._DoReadFile('114_cbfs_offset.dts')
2347 size = 0x200
2348
2349 cbfs = cbfs_util.CbfsReader(data)
2350 self.assertEqual(size, cbfs.rom_size)
2351
2352 self.assertIn('u-boot', cbfs.files)
2353 cfile = cbfs.files['u-boot']
2354 self.assertEqual(U_BOOT_DATA, cfile.data)
2355 self.assertEqual(0x40, cfile.cbfs_offset)
2356
2357 self.assertIn('u-boot-dtb', cbfs.files)
2358 cfile2 = cbfs.files['u-boot-dtb']
2359 self.assertEqual(U_BOOT_DTB_DATA, cfile2.data)
2360 self.assertEqual(0x140, cfile2.cbfs_offset)
2361
Simon Glass0f621332019-07-08 14:25:27 -06002362 def testFdtmap(self):
2363 """Test an FDT map can be inserted in the image"""
2364 data = self.data = self._DoReadFileRealDtb('115_fdtmap.dts')
2365 fdtmap_data = data[len(U_BOOT_DATA):]
2366 magic = fdtmap_data[:8]
Simon Glassc5fd10a2019-10-31 07:43:03 -06002367 self.assertEqual(b'_FDTMAP_', magic)
Simon Glass0f621332019-07-08 14:25:27 -06002368 self.assertEqual(tools.GetBytes(0, 8), fdtmap_data[8:16])
2369
2370 fdt_data = fdtmap_data[16:]
2371 dtb = fdt.Fdt.FromData(fdt_data)
2372 dtb.Scan()
Simon Glass2c6adba2019-07-20 12:23:47 -06002373 props = self._GetPropTree(dtb, BASE_DTB_PROPS, prefix='/')
Simon Glass0f621332019-07-08 14:25:27 -06002374 self.assertEqual({
2375 'image-pos': 0,
2376 'offset': 0,
2377 'u-boot:offset': 0,
2378 'u-boot:size': len(U_BOOT_DATA),
2379 'u-boot:image-pos': 0,
2380 'fdtmap:image-pos': 4,
2381 'fdtmap:offset': 4,
2382 'fdtmap:size': len(fdtmap_data),
2383 'size': len(data),
2384 }, props)
2385
2386 def testFdtmapNoMatch(self):
2387 """Check handling of an FDT map when the section cannot be found"""
2388 self.data = self._DoReadFileRealDtb('115_fdtmap.dts')
2389
2390 # Mangle the section name, which should cause a mismatch between the
2391 # correct FDT path and the one expected by the section
2392 image = control.images['image']
Simon Glasscec34ba2019-07-08 14:25:28 -06002393 image._node.path += '-suffix'
Simon Glass0f621332019-07-08 14:25:27 -06002394 entries = image.GetEntries()
2395 fdtmap = entries['fdtmap']
2396 with self.assertRaises(ValueError) as e:
2397 fdtmap._GetFdtmap()
2398 self.assertIn("Cannot locate node for path '/binman-suffix'",
2399 str(e.exception))
2400
Simon Glasscec34ba2019-07-08 14:25:28 -06002401 def testFdtmapHeader(self):
2402 """Test an FDT map and image header can be inserted in the image"""
2403 data = self.data = self._DoReadFileRealDtb('116_fdtmap_hdr.dts')
2404 fdtmap_pos = len(U_BOOT_DATA)
2405 fdtmap_data = data[fdtmap_pos:]
2406 fdt_data = fdtmap_data[16:]
2407 dtb = fdt.Fdt.FromData(fdt_data)
2408 fdt_size = dtb.GetFdtObj().totalsize()
2409 hdr_data = data[-8:]
Simon Glassc5fd10a2019-10-31 07:43:03 -06002410 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscec34ba2019-07-08 14:25:28 -06002411 offset = struct.unpack('<I', hdr_data[4:])[0] & 0xffffffff
2412 self.assertEqual(fdtmap_pos - 0x400, offset - (1 << 32))
2413
2414 def testFdtmapHeaderStart(self):
2415 """Test an image header can be inserted at the image start"""
2416 data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
2417 fdtmap_pos = 0x100 + len(U_BOOT_DATA)
2418 hdr_data = data[:8]
Simon Glassc5fd10a2019-10-31 07:43:03 -06002419 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscec34ba2019-07-08 14:25:28 -06002420 offset = struct.unpack('<I', hdr_data[4:])[0]
2421 self.assertEqual(fdtmap_pos, offset)
2422
2423 def testFdtmapHeaderPos(self):
2424 """Test an image header can be inserted at a chosen position"""
2425 data = self.data = self._DoReadFileRealDtb('118_fdtmap_hdr_pos.dts')
2426 fdtmap_pos = 0x100 + len(U_BOOT_DATA)
2427 hdr_data = data[0x80:0x88]
Simon Glassc5fd10a2019-10-31 07:43:03 -06002428 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscec34ba2019-07-08 14:25:28 -06002429 offset = struct.unpack('<I', hdr_data[4:])[0]
2430 self.assertEqual(fdtmap_pos, offset)
2431
2432 def testHeaderMissingFdtmap(self):
2433 """Test an image header requires an fdtmap"""
2434 with self.assertRaises(ValueError) as e:
2435 self.data = self._DoReadFileRealDtb('119_fdtmap_hdr_missing.dts')
2436 self.assertIn("'image_header' section must have an 'fdtmap' sibling",
2437 str(e.exception))
2438
2439 def testHeaderNoLocation(self):
2440 """Test an image header with a no specified location is detected"""
2441 with self.assertRaises(ValueError) as e:
2442 self.data = self._DoReadFileRealDtb('120_hdr_no_location.dts')
2443 self.assertIn("Invalid location 'None', expected 'start' or 'end'",
2444 str(e.exception))
2445
Simon Glasse61b6f62019-07-08 14:25:37 -06002446 def testEntryExpand(self):
2447 """Test expanding an entry after it is packed"""
2448 data = self._DoReadFile('121_entry_expand.dts')
Simon Glass8c702fb2019-07-20 12:23:57 -06002449 self.assertEqual(b'aaa', data[:3])
2450 self.assertEqual(U_BOOT_DATA, data[3:3 + len(U_BOOT_DATA)])
2451 self.assertEqual(b'aaa', data[-3:])
Simon Glasse61b6f62019-07-08 14:25:37 -06002452
2453 def testEntryExpandBad(self):
2454 """Test expanding an entry after it is packed, twice"""
2455 with self.assertRaises(ValueError) as e:
2456 self._DoReadFile('122_entry_expand_twice.dts')
Simon Glass9d8ee322019-07-20 12:23:58 -06002457 self.assertIn("Image '/binman': Entries changed size after packing",
Simon Glasse61b6f62019-07-08 14:25:37 -06002458 str(e.exception))
2459
2460 def testEntryExpandSection(self):
2461 """Test expanding an entry within a section after it is packed"""
2462 data = self._DoReadFile('123_entry_expand_section.dts')
Simon Glass8c702fb2019-07-20 12:23:57 -06002463 self.assertEqual(b'aaa', data[:3])
2464 self.assertEqual(U_BOOT_DATA, data[3:3 + len(U_BOOT_DATA)])
2465 self.assertEqual(b'aaa', data[-3:])
Simon Glasse61b6f62019-07-08 14:25:37 -06002466
Simon Glass90d29682019-07-08 14:25:38 -06002467 def testCompressDtb(self):
2468 """Test that compress of device-tree files is supported"""
2469 self._CheckLz4()
2470 data = self.data = self._DoReadFileRealDtb('124_compress_dtb.dts')
2471 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
2472 comp_data = data[len(U_BOOT_DATA):]
2473 orig = self._decompress(comp_data)
2474 dtb = fdt.Fdt.FromData(orig)
2475 dtb.Scan()
2476 props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
2477 expected = {
2478 'u-boot:size': len(U_BOOT_DATA),
2479 'u-boot-dtb:uncomp-size': len(orig),
2480 'u-boot-dtb:size': len(comp_data),
2481 'size': len(data),
2482 }
2483 self.assertEqual(expected, props)
2484
Simon Glass151bbbf2019-07-08 14:25:41 -06002485 def testCbfsUpdateFdt(self):
2486 """Test that we can update the device tree with CBFS offset/size info"""
2487 self._CheckLz4()
2488 data, _, _, out_dtb_fname = self._DoReadFileDtb('125_cbfs_update.dts',
2489 update_dtb=True)
2490 dtb = fdt.Fdt(out_dtb_fname)
2491 dtb.Scan()
Simon Glass2c6adba2019-07-20 12:23:47 -06002492 props = self._GetPropTree(dtb, BASE_DTB_PROPS + ['uncomp-size'])
Simon Glass151bbbf2019-07-08 14:25:41 -06002493 del props['cbfs/u-boot:size']
2494 self.assertEqual({
2495 'offset': 0,
2496 'size': len(data),
2497 'image-pos': 0,
2498 'cbfs:offset': 0,
2499 'cbfs:size': len(data),
2500 'cbfs:image-pos': 0,
2501 'cbfs/u-boot:offset': 0x38,
2502 'cbfs/u-boot:uncomp-size': len(U_BOOT_DATA),
2503 'cbfs/u-boot:image-pos': 0x38,
2504 'cbfs/u-boot-dtb:offset': 0xb8,
2505 'cbfs/u-boot-dtb:size': len(U_BOOT_DATA),
2506 'cbfs/u-boot-dtb:image-pos': 0xb8,
2507 }, props)
2508
Simon Glass3c9b4f22019-07-08 14:25:42 -06002509 def testCbfsBadType(self):
2510 """Test an image header with a no specified location is detected"""
2511 with self.assertRaises(ValueError) as e:
2512 self._DoReadFile('126_cbfs_bad_type.dts')
2513 self.assertIn("Unknown cbfs-type 'badtype'", str(e.exception))
2514
Simon Glass6b156f82019-07-08 14:25:43 -06002515 def testList(self):
2516 """Test listing the files in an image"""
2517 self._CheckLz4()
2518 data = self._DoReadFile('127_list.dts')
2519 image = control.images['image']
2520 entries = image.BuildEntryList()
2521 self.assertEqual(7, len(entries))
2522
2523 ent = entries[0]
2524 self.assertEqual(0, ent.indent)
2525 self.assertEqual('main-section', ent.name)
2526 self.assertEqual('section', ent.etype)
2527 self.assertEqual(len(data), ent.size)
2528 self.assertEqual(0, ent.image_pos)
2529 self.assertEqual(None, ent.uncomp_size)
Simon Glass39dd2152019-07-08 14:25:47 -06002530 self.assertEqual(0, ent.offset)
Simon Glass6b156f82019-07-08 14:25:43 -06002531
2532 ent = entries[1]
2533 self.assertEqual(1, ent.indent)
2534 self.assertEqual('u-boot', ent.name)
2535 self.assertEqual('u-boot', ent.etype)
2536 self.assertEqual(len(U_BOOT_DATA), ent.size)
2537 self.assertEqual(0, ent.image_pos)
2538 self.assertEqual(None, ent.uncomp_size)
2539 self.assertEqual(0, ent.offset)
2540
2541 ent = entries[2]
2542 self.assertEqual(1, ent.indent)
2543 self.assertEqual('section', ent.name)
2544 self.assertEqual('section', ent.etype)
2545 section_size = ent.size
2546 self.assertEqual(0x100, ent.image_pos)
2547 self.assertEqual(None, ent.uncomp_size)
Simon Glass39dd2152019-07-08 14:25:47 -06002548 self.assertEqual(0x100, ent.offset)
Simon Glass6b156f82019-07-08 14:25:43 -06002549
2550 ent = entries[3]
2551 self.assertEqual(2, ent.indent)
2552 self.assertEqual('cbfs', ent.name)
2553 self.assertEqual('cbfs', ent.etype)
2554 self.assertEqual(0x400, ent.size)
2555 self.assertEqual(0x100, ent.image_pos)
2556 self.assertEqual(None, ent.uncomp_size)
2557 self.assertEqual(0, ent.offset)
2558
2559 ent = entries[4]
2560 self.assertEqual(3, ent.indent)
2561 self.assertEqual('u-boot', ent.name)
2562 self.assertEqual('u-boot', ent.etype)
2563 self.assertEqual(len(U_BOOT_DATA), ent.size)
2564 self.assertEqual(0x138, ent.image_pos)
2565 self.assertEqual(None, ent.uncomp_size)
2566 self.assertEqual(0x38, ent.offset)
2567
2568 ent = entries[5]
2569 self.assertEqual(3, ent.indent)
2570 self.assertEqual('u-boot-dtb', ent.name)
2571 self.assertEqual('text', ent.etype)
2572 self.assertGreater(len(COMPRESS_DATA), ent.size)
2573 self.assertEqual(0x178, ent.image_pos)
2574 self.assertEqual(len(COMPRESS_DATA), ent.uncomp_size)
2575 self.assertEqual(0x78, ent.offset)
2576
2577 ent = entries[6]
2578 self.assertEqual(2, ent.indent)
2579 self.assertEqual('u-boot-dtb', ent.name)
2580 self.assertEqual('u-boot-dtb', ent.etype)
2581 self.assertEqual(0x500, ent.image_pos)
2582 self.assertEqual(len(U_BOOT_DTB_DATA), ent.uncomp_size)
2583 dtb_size = ent.size
2584 # Compressing this data expands it since headers are added
2585 self.assertGreater(dtb_size, len(U_BOOT_DTB_DATA))
2586 self.assertEqual(0x400, ent.offset)
2587
2588 self.assertEqual(len(data), 0x100 + section_size)
2589 self.assertEqual(section_size, 0x400 + dtb_size)
2590
Simon Glass8d8bf4e2019-07-08 14:25:44 -06002591 def testFindFdtmap(self):
2592 """Test locating an FDT map in an image"""
2593 self._CheckLz4()
2594 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
2595 image = control.images['image']
2596 entries = image.GetEntries()
2597 entry = entries['fdtmap']
2598 self.assertEqual(entry.image_pos, fdtmap.LocateFdtmap(data))
2599
2600 def testFindFdtmapMissing(self):
2601 """Test failing to locate an FDP map"""
2602 data = self._DoReadFile('005_simple.dts')
2603 self.assertEqual(None, fdtmap.LocateFdtmap(data))
2604
Simon Glassed39a3c2019-07-08 14:25:45 -06002605 def testFindImageHeader(self):
2606 """Test locating a image header"""
2607 self._CheckLz4()
Simon Glassb8424fa2019-07-08 14:25:46 -06002608 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
Simon Glassed39a3c2019-07-08 14:25:45 -06002609 image = control.images['image']
2610 entries = image.GetEntries()
2611 entry = entries['fdtmap']
2612 # The header should point to the FDT map
2613 self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data))
2614
2615 def testFindImageHeaderStart(self):
2616 """Test locating a image header located at the start of an image"""
Simon Glassb8424fa2019-07-08 14:25:46 -06002617 data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
Simon Glassed39a3c2019-07-08 14:25:45 -06002618 image = control.images['image']
2619 entries = image.GetEntries()
2620 entry = entries['fdtmap']
2621 # The header should point to the FDT map
2622 self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data))
2623
2624 def testFindImageHeaderMissing(self):
2625 """Test failing to locate an image header"""
2626 data = self._DoReadFile('005_simple.dts')
2627 self.assertEqual(None, image_header.LocateHeaderOffset(data))
2628
Simon Glassb8424fa2019-07-08 14:25:46 -06002629 def testReadImage(self):
2630 """Test reading an image and accessing its FDT map"""
2631 self._CheckLz4()
2632 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
2633 image_fname = tools.GetOutputFilename('image.bin')
2634 orig_image = control.images['image']
2635 image = Image.FromFile(image_fname)
2636 self.assertEqual(orig_image.GetEntries().keys(),
2637 image.GetEntries().keys())
2638
2639 orig_entry = orig_image.GetEntries()['fdtmap']
2640 entry = image.GetEntries()['fdtmap']
2641 self.assertEquals(orig_entry.offset, entry.offset)
2642 self.assertEquals(orig_entry.size, entry.size)
2643 self.assertEquals(orig_entry.image_pos, entry.image_pos)
2644
2645 def testReadImageNoHeader(self):
2646 """Test accessing an image's FDT map without an image header"""
2647 self._CheckLz4()
2648 data = self._DoReadFileRealDtb('129_decode_image_nohdr.dts')
2649 image_fname = tools.GetOutputFilename('image.bin')
2650 image = Image.FromFile(image_fname)
2651 self.assertTrue(isinstance(image, Image))
Simon Glass072959a2019-07-20 12:23:50 -06002652 self.assertEqual('image', image.image_name[-5:])
Simon Glassb8424fa2019-07-08 14:25:46 -06002653
2654 def testReadImageFail(self):
2655 """Test failing to read an image image's FDT map"""
2656 self._DoReadFile('005_simple.dts')
2657 image_fname = tools.GetOutputFilename('image.bin')
2658 with self.assertRaises(ValueError) as e:
2659 image = Image.FromFile(image_fname)
2660 self.assertIn("Cannot find FDT map in image", str(e.exception))
Simon Glassc2f1aed2019-07-08 13:18:56 -06002661
Simon Glassb2fd11d2019-07-08 14:25:48 -06002662 def testListCmd(self):
2663 """Test listing the files in an image using an Fdtmap"""
2664 self._CheckLz4()
2665 data = self._DoReadFileRealDtb('130_list_fdtmap.dts')
2666
2667 # lz4 compression size differs depending on the version
2668 image = control.images['image']
2669 entries = image.GetEntries()
2670 section_size = entries['section'].size
2671 fdt_size = entries['section'].GetEntries()['u-boot-dtb'].size
2672 fdtmap_offset = entries['fdtmap'].offset
2673
Simon Glassb3d6fc72019-07-20 12:24:10 -06002674 try:
2675 tmpdir, updated_fname = self._SetupImageInTmpdir()
2676 with test_util.capture_sys_output() as (stdout, stderr):
2677 self._DoBinman('ls', '-i', updated_fname)
2678 finally:
2679 shutil.rmtree(tmpdir)
Simon Glassb2fd11d2019-07-08 14:25:48 -06002680 lines = stdout.getvalue().splitlines()
2681 expected = [
2682'Name Image-pos Size Entry-type Offset Uncomp-size',
2683'----------------------------------------------------------------------',
2684'main-section 0 c00 section 0',
2685' u-boot 0 4 u-boot 0',
2686' section 100 %x section 100' % section_size,
2687' cbfs 100 400 cbfs 0',
2688' u-boot 138 4 u-boot 38',
Simon Glassc5fd10a2019-10-31 07:43:03 -06002689' u-boot-dtb 180 105 u-boot-dtb 80 3c9',
Simon Glassb2fd11d2019-07-08 14:25:48 -06002690' u-boot-dtb 500 %x u-boot-dtb 400 3c9' % fdt_size,
Simon Glassc5fd10a2019-10-31 07:43:03 -06002691' fdtmap %x 3bd fdtmap %x' %
Simon Glassb2fd11d2019-07-08 14:25:48 -06002692 (fdtmap_offset, fdtmap_offset),
2693' image-header bf8 8 image-header bf8',
2694 ]
2695 self.assertEqual(expected, lines)
2696
2697 def testListCmdFail(self):
2698 """Test failing to list an image"""
2699 self._DoReadFile('005_simple.dts')
Simon Glassb3d6fc72019-07-20 12:24:10 -06002700 try:
2701 tmpdir, updated_fname = self._SetupImageInTmpdir()
2702 with self.assertRaises(ValueError) as e:
2703 self._DoBinman('ls', '-i', updated_fname)
2704 finally:
2705 shutil.rmtree(tmpdir)
Simon Glassb2fd11d2019-07-08 14:25:48 -06002706 self.assertIn("Cannot find FDT map in image", str(e.exception))
2707
2708 def _RunListCmd(self, paths, expected):
2709 """List out entries and check the result
2710
2711 Args:
2712 paths: List of paths to pass to the list command
2713 expected: Expected list of filenames to be returned, in order
2714 """
2715 self._CheckLz4()
2716 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2717 image_fname = tools.GetOutputFilename('image.bin')
2718 image = Image.FromFile(image_fname)
2719 lines = image.GetListEntries(paths)[1]
2720 files = [line[0].strip() for line in lines[1:]]
2721 self.assertEqual(expected, files)
2722
2723 def testListCmdSection(self):
2724 """Test listing the files in a section"""
2725 self._RunListCmd(['section'],
2726 ['section', 'cbfs', 'u-boot', 'u-boot-dtb', 'u-boot-dtb'])
2727
2728 def testListCmdFile(self):
2729 """Test listing a particular file"""
2730 self._RunListCmd(['*u-boot-dtb'], ['u-boot-dtb', 'u-boot-dtb'])
2731
2732 def testListCmdWildcard(self):
2733 """Test listing a wildcarded file"""
2734 self._RunListCmd(['*boot*'],
2735 ['u-boot', 'u-boot', 'u-boot-dtb', 'u-boot-dtb'])
2736
2737 def testListCmdWildcardMulti(self):
2738 """Test listing a wildcarded file"""
2739 self._RunListCmd(['*cb*', '*head*'],
2740 ['cbfs', 'u-boot', 'u-boot-dtb', 'image-header'])
2741
2742 def testListCmdEmpty(self):
2743 """Test listing a wildcarded file"""
2744 self._RunListCmd(['nothing'], [])
2745
2746 def testListCmdPath(self):
2747 """Test listing the files in a sub-entry of a section"""
2748 self._RunListCmd(['section/cbfs'], ['cbfs', 'u-boot', 'u-boot-dtb'])
2749
Simon Glass4c613bf2019-07-08 14:25:50 -06002750 def _RunExtractCmd(self, entry_name, decomp=True):
2751 """Extract an entry from an image
2752
2753 Args:
2754 entry_name: Entry name to extract
2755 decomp: True to decompress the data if compressed, False to leave
2756 it in its raw uncompressed format
2757
2758 Returns:
2759 data from entry
2760 """
2761 self._CheckLz4()
2762 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2763 image_fname = tools.GetOutputFilename('image.bin')
2764 return control.ReadEntry(image_fname, entry_name, decomp)
2765
2766 def testExtractSimple(self):
2767 """Test extracting a single file"""
2768 data = self._RunExtractCmd('u-boot')
2769 self.assertEqual(U_BOOT_DATA, data)
2770
Simon Glass980a2842019-07-08 14:25:52 -06002771 def testExtractSection(self):
2772 """Test extracting the files in a section"""
2773 data = self._RunExtractCmd('section')
2774 cbfs_data = data[:0x400]
2775 cbfs = cbfs_util.CbfsReader(cbfs_data)
Simon Glassc5fd10a2019-10-31 07:43:03 -06002776 self.assertEqual(['u-boot', 'u-boot-dtb', ''], list(cbfs.files.keys()))
Simon Glass980a2842019-07-08 14:25:52 -06002777 dtb_data = data[0x400:]
2778 dtb = self._decompress(dtb_data)
2779 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2780
2781 def testExtractCompressed(self):
2782 """Test extracting compressed data"""
2783 data = self._RunExtractCmd('section/u-boot-dtb')
2784 self.assertEqual(EXTRACT_DTB_SIZE, len(data))
2785
2786 def testExtractRaw(self):
2787 """Test extracting compressed data without decompressing it"""
2788 data = self._RunExtractCmd('section/u-boot-dtb', decomp=False)
2789 dtb = self._decompress(data)
2790 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2791
2792 def testExtractCbfs(self):
2793 """Test extracting CBFS data"""
2794 data = self._RunExtractCmd('section/cbfs/u-boot')
2795 self.assertEqual(U_BOOT_DATA, data)
2796
2797 def testExtractCbfsCompressed(self):
2798 """Test extracting CBFS compressed data"""
2799 data = self._RunExtractCmd('section/cbfs/u-boot-dtb')
2800 self.assertEqual(EXTRACT_DTB_SIZE, len(data))
2801
2802 def testExtractCbfsRaw(self):
2803 """Test extracting CBFS compressed data without decompressing it"""
2804 data = self._RunExtractCmd('section/cbfs/u-boot-dtb', decomp=False)
Simon Glass37fdd142019-07-20 12:24:06 -06002805 dtb = tools.Decompress(data, 'lzma', with_header=False)
Simon Glass980a2842019-07-08 14:25:52 -06002806 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2807
Simon Glass4c613bf2019-07-08 14:25:50 -06002808 def testExtractBadEntry(self):
2809 """Test extracting a bad section path"""
2810 with self.assertRaises(ValueError) as e:
2811 self._RunExtractCmd('section/does-not-exist')
2812 self.assertIn("Entry 'does-not-exist' not found in '/section'",
2813 str(e.exception))
2814
2815 def testExtractMissingFile(self):
2816 """Test extracting file that does not exist"""
2817 with self.assertRaises(IOError) as e:
2818 control.ReadEntry('missing-file', 'name')
2819
2820 def testExtractBadFile(self):
2821 """Test extracting an invalid file"""
2822 fname = os.path.join(self._indir, 'badfile')
2823 tools.WriteFile(fname, b'')
2824 with self.assertRaises(ValueError) as e:
2825 control.ReadEntry(fname, 'name')
2826
Simon Glass980a2842019-07-08 14:25:52 -06002827 def testExtractCmd(self):
2828 """Test extracting a file fron an image on the command line"""
2829 self._CheckLz4()
2830 self._DoReadFileRealDtb('130_list_fdtmap.dts')
Simon Glass980a2842019-07-08 14:25:52 -06002831 fname = os.path.join(self._indir, 'output.extact')
Simon Glassb3d6fc72019-07-20 12:24:10 -06002832 try:
2833 tmpdir, updated_fname = self._SetupImageInTmpdir()
2834 with test_util.capture_sys_output() as (stdout, stderr):
2835 self._DoBinman('extract', '-i', updated_fname, 'u-boot',
2836 '-f', fname)
2837 finally:
2838 shutil.rmtree(tmpdir)
Simon Glass980a2842019-07-08 14:25:52 -06002839 data = tools.ReadFile(fname)
2840 self.assertEqual(U_BOOT_DATA, data)
2841
2842 def testExtractOneEntry(self):
2843 """Test extracting a single entry fron an image """
2844 self._CheckLz4()
2845 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2846 image_fname = tools.GetOutputFilename('image.bin')
2847 fname = os.path.join(self._indir, 'output.extact')
2848 control.ExtractEntries(image_fname, fname, None, ['u-boot'])
2849 data = tools.ReadFile(fname)
2850 self.assertEqual(U_BOOT_DATA, data)
2851
2852 def _CheckExtractOutput(self, decomp):
2853 """Helper to test file output with and without decompression
2854
2855 Args:
2856 decomp: True to decompress entry data, False to output it raw
2857 """
2858 def _CheckPresent(entry_path, expect_data, expect_size=None):
2859 """Check and remove expected file
2860
2861 This checks the data/size of a file and removes the file both from
2862 the outfiles set and from the output directory. Once all files are
2863 processed, both the set and directory should be empty.
2864
2865 Args:
2866 entry_path: Entry path
2867 expect_data: Data to expect in file, or None to skip check
2868 expect_size: Size of data to expect in file, or None to skip
2869 """
2870 path = os.path.join(outdir, entry_path)
2871 data = tools.ReadFile(path)
2872 os.remove(path)
2873 if expect_data:
2874 self.assertEqual(expect_data, data)
2875 elif expect_size:
2876 self.assertEqual(expect_size, len(data))
2877 outfiles.remove(path)
2878
2879 def _CheckDirPresent(name):
2880 """Remove expected directory
2881
2882 This gives an error if the directory does not exist as expected
2883
2884 Args:
2885 name: Name of directory to remove
2886 """
2887 path = os.path.join(outdir, name)
2888 os.rmdir(path)
2889
2890 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2891 image_fname = tools.GetOutputFilename('image.bin')
2892 outdir = os.path.join(self._indir, 'extract')
2893 einfos = control.ExtractEntries(image_fname, None, outdir, [], decomp)
2894
2895 # Create a set of all file that were output (should be 9)
2896 outfiles = set()
2897 for root, dirs, files in os.walk(outdir):
2898 outfiles |= set([os.path.join(root, fname) for fname in files])
2899 self.assertEqual(9, len(outfiles))
2900 self.assertEqual(9, len(einfos))
2901
2902 image = control.images['image']
2903 entries = image.GetEntries()
2904
2905 # Check the 9 files in various ways
2906 section = entries['section']
2907 section_entries = section.GetEntries()
2908 cbfs_entries = section_entries['cbfs'].GetEntries()
2909 _CheckPresent('u-boot', U_BOOT_DATA)
2910 _CheckPresent('section/cbfs/u-boot', U_BOOT_DATA)
2911 dtb_len = EXTRACT_DTB_SIZE
2912 if not decomp:
2913 dtb_len = cbfs_entries['u-boot-dtb'].size
2914 _CheckPresent('section/cbfs/u-boot-dtb', None, dtb_len)
2915 if not decomp:
2916 dtb_len = section_entries['u-boot-dtb'].size
2917 _CheckPresent('section/u-boot-dtb', None, dtb_len)
2918
2919 fdtmap = entries['fdtmap']
2920 _CheckPresent('fdtmap', fdtmap.data)
2921 hdr = entries['image-header']
2922 _CheckPresent('image-header', hdr.data)
2923
2924 _CheckPresent('section/root', section.data)
2925 cbfs = section_entries['cbfs']
2926 _CheckPresent('section/cbfs/root', cbfs.data)
2927 data = tools.ReadFile(image_fname)
2928 _CheckPresent('root', data)
2929
2930 # There should be no files left. Remove all the directories to check.
2931 # If there are any files/dirs remaining, one of these checks will fail.
2932 self.assertEqual(0, len(outfiles))
2933 _CheckDirPresent('section/cbfs')
2934 _CheckDirPresent('section')
2935 _CheckDirPresent('')
2936 self.assertFalse(os.path.exists(outdir))
2937
2938 def testExtractAllEntries(self):
2939 """Test extracting all entries"""
2940 self._CheckLz4()
2941 self._CheckExtractOutput(decomp=True)
2942
2943 def testExtractAllEntriesRaw(self):
2944 """Test extracting all entries without decompressing them"""
2945 self._CheckLz4()
2946 self._CheckExtractOutput(decomp=False)
2947
2948 def testExtractSelectedEntries(self):
2949 """Test extracting some entries"""
2950 self._CheckLz4()
2951 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2952 image_fname = tools.GetOutputFilename('image.bin')
2953 outdir = os.path.join(self._indir, 'extract')
2954 einfos = control.ExtractEntries(image_fname, None, outdir,
2955 ['*cb*', '*head*'])
2956
2957 # File output is tested by testExtractAllEntries(), so just check that
2958 # the expected entries are selected
2959 names = [einfo.name for einfo in einfos]
2960 self.assertEqual(names,
2961 ['cbfs', 'u-boot', 'u-boot-dtb', 'image-header'])
2962
2963 def testExtractNoEntryPaths(self):
2964 """Test extracting some entries"""
2965 self._CheckLz4()
2966 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2967 image_fname = tools.GetOutputFilename('image.bin')
2968 with self.assertRaises(ValueError) as e:
2969 control.ExtractEntries(image_fname, 'fname', None, [])
Simon Glassa772d3f2019-07-20 12:24:14 -06002970 self.assertIn('Must specify an entry path to write with -f',
Simon Glass980a2842019-07-08 14:25:52 -06002971 str(e.exception))
2972
2973 def testExtractTooManyEntryPaths(self):
2974 """Test extracting some entries"""
2975 self._CheckLz4()
2976 self._DoReadFileRealDtb('130_list_fdtmap.dts')
2977 image_fname = tools.GetOutputFilename('image.bin')
2978 with self.assertRaises(ValueError) as e:
2979 control.ExtractEntries(image_fname, 'fname', None, ['a', 'b'])
Simon Glassa772d3f2019-07-20 12:24:14 -06002980 self.assertIn('Must specify exactly one entry path to write with -f',
Simon Glass980a2842019-07-08 14:25:52 -06002981 str(e.exception))
2982
Simon Glass52d06212019-07-08 14:25:53 -06002983 def testPackAlignSection(self):
2984 """Test that sections can have alignment"""
2985 self._DoReadFile('131_pack_align_section.dts')
2986
2987 self.assertIn('image', control.images)
2988 image = control.images['image']
2989 entries = image.GetEntries()
2990 self.assertEqual(3, len(entries))
2991
2992 # First u-boot
2993 self.assertIn('u-boot', entries)
2994 entry = entries['u-boot']
2995 self.assertEqual(0, entry.offset)
2996 self.assertEqual(0, entry.image_pos)
2997 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
2998 self.assertEqual(len(U_BOOT_DATA), entry.size)
2999
3000 # Section0
3001 self.assertIn('section0', entries)
3002 section0 = entries['section0']
3003 self.assertEqual(0x10, section0.offset)
3004 self.assertEqual(0x10, section0.image_pos)
3005 self.assertEqual(len(U_BOOT_DATA), section0.size)
3006
3007 # Second u-boot
3008 section_entries = section0.GetEntries()
3009 self.assertIn('u-boot', section_entries)
3010 entry = section_entries['u-boot']
3011 self.assertEqual(0, entry.offset)
3012 self.assertEqual(0x10, entry.image_pos)
3013 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
3014 self.assertEqual(len(U_BOOT_DATA), entry.size)
3015
3016 # Section1
3017 self.assertIn('section1', entries)
3018 section1 = entries['section1']
3019 self.assertEqual(0x14, section1.offset)
3020 self.assertEqual(0x14, section1.image_pos)
3021 self.assertEqual(0x20, section1.size)
3022
3023 # Second u-boot
3024 section_entries = section1.GetEntries()
3025 self.assertIn('u-boot', section_entries)
3026 entry = section_entries['u-boot']
3027 self.assertEqual(0, entry.offset)
3028 self.assertEqual(0x14, entry.image_pos)
3029 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
3030 self.assertEqual(len(U_BOOT_DATA), entry.size)
3031
3032 # Section2
3033 self.assertIn('section2', section_entries)
3034 section2 = section_entries['section2']
3035 self.assertEqual(0x4, section2.offset)
3036 self.assertEqual(0x18, section2.image_pos)
3037 self.assertEqual(4, section2.size)
3038
3039 # Third u-boot
3040 section_entries = section2.GetEntries()
3041 self.assertIn('u-boot', section_entries)
3042 entry = section_entries['u-boot']
3043 self.assertEqual(0, entry.offset)
3044 self.assertEqual(0x18, entry.image_pos)
3045 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
3046 self.assertEqual(len(U_BOOT_DATA), entry.size)
3047
Simon Glassf8a54bc2019-07-20 12:23:56 -06003048 def _RunReplaceCmd(self, entry_name, data, decomp=True, allow_resize=True,
3049 dts='132_replace.dts'):
Simon Glass072959a2019-07-20 12:23:50 -06003050 """Replace an entry in an image
3051
3052 This writes the entry data to update it, then opens the updated file and
3053 returns the value that it now finds there.
3054
3055 Args:
3056 entry_name: Entry name to replace
3057 data: Data to replace it with
3058 decomp: True to compress the data if needed, False if data is
3059 already compressed so should be used as is
Simon Glassf8a54bc2019-07-20 12:23:56 -06003060 allow_resize: True to allow entries to change size, False to raise
3061 an exception
Simon Glass072959a2019-07-20 12:23:50 -06003062
3063 Returns:
3064 Tuple:
3065 data from entry
3066 data from fdtmap (excluding header)
Simon Glassf8a54bc2019-07-20 12:23:56 -06003067 Image object that was modified
Simon Glass072959a2019-07-20 12:23:50 -06003068 """
Simon Glassf8a54bc2019-07-20 12:23:56 -06003069 dtb_data = self._DoReadFileDtb(dts, use_real_dtb=True,
Simon Glass072959a2019-07-20 12:23:50 -06003070 update_dtb=True)[1]
3071
3072 self.assertIn('image', control.images)
3073 image = control.images['image']
3074 entries = image.GetEntries()
3075 orig_dtb_data = entries['u-boot-dtb'].data
3076 orig_fdtmap_data = entries['fdtmap'].data
3077
3078 image_fname = tools.GetOutputFilename('image.bin')
3079 updated_fname = tools.GetOutputFilename('image-updated.bin')
3080 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
Simon Glassf8a54bc2019-07-20 12:23:56 -06003081 image = control.WriteEntry(updated_fname, entry_name, data, decomp,
3082 allow_resize)
Simon Glass072959a2019-07-20 12:23:50 -06003083 data = control.ReadEntry(updated_fname, entry_name, decomp)
3084
Simon Glassf8a54bc2019-07-20 12:23:56 -06003085 # The DT data should not change unless resized:
3086 if not allow_resize:
3087 new_dtb_data = entries['u-boot-dtb'].data
3088 self.assertEqual(new_dtb_data, orig_dtb_data)
3089 new_fdtmap_data = entries['fdtmap'].data
3090 self.assertEqual(new_fdtmap_data, orig_fdtmap_data)
Simon Glass072959a2019-07-20 12:23:50 -06003091
Simon Glassf8a54bc2019-07-20 12:23:56 -06003092 return data, orig_fdtmap_data[fdtmap.FDTMAP_HDR_LEN:], image
Simon Glass072959a2019-07-20 12:23:50 -06003093
3094 def testReplaceSimple(self):
3095 """Test replacing a single file"""
3096 expected = b'x' * len(U_BOOT_DATA)
Simon Glassf8a54bc2019-07-20 12:23:56 -06003097 data, expected_fdtmap, _ = self._RunReplaceCmd('u-boot', expected,
3098 allow_resize=False)
Simon Glass072959a2019-07-20 12:23:50 -06003099 self.assertEqual(expected, data)
3100
3101 # Test that the state looks right. There should be an FDT for the fdtmap
3102 # that we jsut read back in, and it should match what we find in the
3103 # 'control' tables. Checking for an FDT that does not exist should
3104 # return None.
3105 path, fdtmap = state.GetFdtContents('fdtmap')
Simon Glassf8a54bc2019-07-20 12:23:56 -06003106 self.assertIsNotNone(path)
Simon Glass072959a2019-07-20 12:23:50 -06003107 self.assertEqual(expected_fdtmap, fdtmap)
3108
3109 dtb = state.GetFdtForEtype('fdtmap')
3110 self.assertEqual(dtb.GetContents(), fdtmap)
3111
3112 missing_path, missing_fdtmap = state.GetFdtContents('missing')
3113 self.assertIsNone(missing_path)
3114 self.assertIsNone(missing_fdtmap)
3115
3116 missing_dtb = state.GetFdtForEtype('missing')
3117 self.assertIsNone(missing_dtb)
3118
3119 self.assertEqual('/binman', state.fdt_path_prefix)
3120
3121 def testReplaceResizeFail(self):
3122 """Test replacing a file by something larger"""
3123 expected = U_BOOT_DATA + b'x'
3124 with self.assertRaises(ValueError) as e:
Simon Glassf8a54bc2019-07-20 12:23:56 -06003125 self._RunReplaceCmd('u-boot', expected, allow_resize=False,
3126 dts='139_replace_repack.dts')
Simon Glass072959a2019-07-20 12:23:50 -06003127 self.assertIn("Node '/u-boot': Entry data size does not match, but resize is disabled",
3128 str(e.exception))
3129
3130 def testReplaceMulti(self):
3131 """Test replacing entry data where multiple images are generated"""
3132 data = self._DoReadFileDtb('133_replace_multi.dts', use_real_dtb=True,
3133 update_dtb=True)[0]
3134 expected = b'x' * len(U_BOOT_DATA)
3135 updated_fname = tools.GetOutputFilename('image-updated.bin')
3136 tools.WriteFile(updated_fname, data)
3137 entry_name = 'u-boot'
Simon Glassf8a54bc2019-07-20 12:23:56 -06003138 control.WriteEntry(updated_fname, entry_name, expected,
3139 allow_resize=False)
Simon Glass072959a2019-07-20 12:23:50 -06003140 data = control.ReadEntry(updated_fname, entry_name)
3141 self.assertEqual(expected, data)
3142
3143 # Check the state looks right.
3144 self.assertEqual('/binman/image', state.fdt_path_prefix)
3145
3146 # Now check we can write the first image
3147 image_fname = tools.GetOutputFilename('first-image.bin')
3148 updated_fname = tools.GetOutputFilename('first-updated.bin')
3149 tools.WriteFile(updated_fname, tools.ReadFile(image_fname))
3150 entry_name = 'u-boot'
Simon Glassf8a54bc2019-07-20 12:23:56 -06003151 control.WriteEntry(updated_fname, entry_name, expected,
3152 allow_resize=False)
Simon Glass072959a2019-07-20 12:23:50 -06003153 data = control.ReadEntry(updated_fname, entry_name)
3154 self.assertEqual(expected, data)
3155
3156 # Check the state looks right.
3157 self.assertEqual('/binman/first-image', state.fdt_path_prefix)
Simon Glass39dd2152019-07-08 14:25:47 -06003158
Simon Glassfb30e292019-07-20 12:23:51 -06003159 def testUpdateFdtAllRepack(self):
3160 """Test that all device trees are updated with offset/size info"""
3161 data = self._DoReadFileRealDtb('134_fdt_update_all_repack.dts')
3162 SECTION_SIZE = 0x300
3163 DTB_SIZE = 602
3164 FDTMAP_SIZE = 608
3165 base_expected = {
3166 'offset': 0,
3167 'size': SECTION_SIZE + DTB_SIZE * 2 + FDTMAP_SIZE,
3168 'image-pos': 0,
3169 'section:offset': 0,
3170 'section:size': SECTION_SIZE,
3171 'section:image-pos': 0,
3172 'section/u-boot-dtb:offset': 4,
3173 'section/u-boot-dtb:size': 636,
3174 'section/u-boot-dtb:image-pos': 4,
3175 'u-boot-spl-dtb:offset': SECTION_SIZE,
3176 'u-boot-spl-dtb:size': DTB_SIZE,
3177 'u-boot-spl-dtb:image-pos': SECTION_SIZE,
3178 'u-boot-tpl-dtb:offset': SECTION_SIZE + DTB_SIZE,
3179 'u-boot-tpl-dtb:image-pos': SECTION_SIZE + DTB_SIZE,
3180 'u-boot-tpl-dtb:size': DTB_SIZE,
3181 'fdtmap:offset': SECTION_SIZE + DTB_SIZE * 2,
3182 'fdtmap:size': FDTMAP_SIZE,
3183 'fdtmap:image-pos': SECTION_SIZE + DTB_SIZE * 2,
3184 }
3185 main_expected = {
3186 'section:orig-size': SECTION_SIZE,
3187 'section/u-boot-dtb:orig-offset': 4,
3188 }
3189
3190 # We expect three device-tree files in the output, with the first one
3191 # within a fixed-size section.
3192 # Read them in sequence. We look for an 'spl' property in the SPL tree,
3193 # and 'tpl' in the TPL tree, to make sure they are distinct from the
3194 # main U-Boot tree. All three should have the same positions and offset
3195 # except that the main tree should include the main_expected properties
3196 start = 4
3197 for item in ['', 'spl', 'tpl', None]:
3198 if item is None:
3199 start += 16 # Move past fdtmap header
3200 dtb = fdt.Fdt.FromData(data[start:])
3201 dtb.Scan()
3202 props = self._GetPropTree(dtb,
3203 BASE_DTB_PROPS + REPACK_DTB_PROPS + ['spl', 'tpl'],
3204 prefix='/' if item is None else '/binman/')
3205 expected = dict(base_expected)
3206 if item:
3207 expected[item] = 0
3208 else:
3209 # Main DTB and fdtdec should include the 'orig-' properties
3210 expected.update(main_expected)
3211 # Helpful for debugging:
3212 #for prop in sorted(props):
3213 #print('prop %s %s %s' % (prop, props[prop], expected[prop]))
3214 self.assertEqual(expected, props)
3215 if item == '':
3216 start = SECTION_SIZE
3217 else:
3218 start += dtb._fdt_obj.totalsize()
3219
Simon Glass11453762019-07-20 12:23:55 -06003220 def testFdtmapHeaderMiddle(self):
3221 """Test an FDT map in the middle of an image when it should be at end"""
3222 with self.assertRaises(ValueError) as e:
3223 self._DoReadFileRealDtb('135_fdtmap_hdr_middle.dts')
3224 self.assertIn("Invalid sibling order 'middle' for image-header: Must be at 'end' to match location",
3225 str(e.exception))
3226
3227 def testFdtmapHeaderStartBad(self):
3228 """Test an FDT map in middle of an image when it should be at start"""
3229 with self.assertRaises(ValueError) as e:
3230 self._DoReadFileRealDtb('136_fdtmap_hdr_startbad.dts')
3231 self.assertIn("Invalid sibling order 'end' for image-header: Must be at 'start' to match location",
3232 str(e.exception))
3233
3234 def testFdtmapHeaderEndBad(self):
3235 """Test an FDT map at the start of an image when it should be at end"""
3236 with self.assertRaises(ValueError) as e:
3237 self._DoReadFileRealDtb('137_fdtmap_hdr_endbad.dts')
3238 self.assertIn("Invalid sibling order 'start' for image-header: Must be at 'end' to match location",
3239 str(e.exception))
3240
3241 def testFdtmapHeaderNoSize(self):
3242 """Test an image header at the end of an image with undefined size"""
3243 self._DoReadFileRealDtb('138_fdtmap_hdr_nosize.dts')
3244
Simon Glassf8a54bc2019-07-20 12:23:56 -06003245 def testReplaceResize(self):
3246 """Test replacing a single file in an entry with a larger file"""
3247 expected = U_BOOT_DATA + b'x'
3248 data, _, image = self._RunReplaceCmd('u-boot', expected,
3249 dts='139_replace_repack.dts')
3250 self.assertEqual(expected, data)
3251
3252 entries = image.GetEntries()
3253 dtb_data = entries['u-boot-dtb'].data
3254 dtb = fdt.Fdt.FromData(dtb_data)
3255 dtb.Scan()
3256
3257 # The u-boot section should now be larger in the dtb
3258 node = dtb.GetNode('/binman/u-boot')
3259 self.assertEqual(len(expected), fdt_util.GetInt(node, 'size'))
3260
3261 # Same for the fdtmap
3262 fdata = entries['fdtmap'].data
3263 fdtb = fdt.Fdt.FromData(fdata[fdtmap.FDTMAP_HDR_LEN:])
3264 fdtb.Scan()
3265 fnode = fdtb.GetNode('/u-boot')
3266 self.assertEqual(len(expected), fdt_util.GetInt(fnode, 'size'))
3267
3268 def testReplaceResizeNoRepack(self):
3269 """Test replacing an entry with a larger file when not allowed"""
3270 expected = U_BOOT_DATA + b'x'
3271 with self.assertRaises(ValueError) as e:
3272 self._RunReplaceCmd('u-boot', expected)
3273 self.assertIn('Entry data size does not match, but allow-repack is not present for this image',
3274 str(e.exception))
3275
Simon Glass9d8ee322019-07-20 12:23:58 -06003276 def testEntryShrink(self):
3277 """Test contracting an entry after it is packed"""
3278 try:
3279 state.SetAllowEntryContraction(True)
3280 data = self._DoReadFileDtb('140_entry_shrink.dts',
3281 update_dtb=True)[0]
3282 finally:
3283 state.SetAllowEntryContraction(False)
3284 self.assertEqual(b'a', data[:1])
3285 self.assertEqual(U_BOOT_DATA, data[1:1 + len(U_BOOT_DATA)])
3286 self.assertEqual(b'a', data[-1:])
3287
3288 def testEntryShrinkFail(self):
3289 """Test not being allowed to contract an entry after it is packed"""
3290 data = self._DoReadFileDtb('140_entry_shrink.dts', update_dtb=True)[0]
3291
3292 # In this case there is a spare byte at the end of the data. The size of
3293 # the contents is only 1 byte but we still have the size before it
3294 # shrunk.
3295 self.assertEqual(b'a\0', data[:2])
3296 self.assertEqual(U_BOOT_DATA, data[2:2 + len(U_BOOT_DATA)])
3297 self.assertEqual(b'a\0', data[-2:])
3298
Simon Glass70e32982019-07-20 12:24:01 -06003299 def testDescriptorOffset(self):
3300 """Test that the Intel descriptor is always placed at at the start"""
3301 data = self._DoReadFileDtb('141_descriptor_offset.dts')
3302 image = control.images['image']
3303 entries = image.GetEntries()
3304 desc = entries['intel-descriptor']
3305 self.assertEqual(0xff800000, desc.offset);
3306 self.assertEqual(0xff800000, desc.image_pos);
3307
Simon Glass37fdd142019-07-20 12:24:06 -06003308 def testReplaceCbfs(self):
3309 """Test replacing a single file in CBFS without changing the size"""
3310 self._CheckLz4()
3311 expected = b'x' * len(U_BOOT_DATA)
3312 data = self._DoReadFileRealDtb('142_replace_cbfs.dts')
3313 updated_fname = tools.GetOutputFilename('image-updated.bin')
3314 tools.WriteFile(updated_fname, data)
3315 entry_name = 'section/cbfs/u-boot'
3316 control.WriteEntry(updated_fname, entry_name, expected,
3317 allow_resize=True)
3318 data = control.ReadEntry(updated_fname, entry_name)
3319 self.assertEqual(expected, data)
3320
3321 def testReplaceResizeCbfs(self):
3322 """Test replacing a single file in CBFS with one of a different size"""
3323 self._CheckLz4()
3324 expected = U_BOOT_DATA + b'x'
3325 data = self._DoReadFileRealDtb('142_replace_cbfs.dts')
3326 updated_fname = tools.GetOutputFilename('image-updated.bin')
3327 tools.WriteFile(updated_fname, data)
3328 entry_name = 'section/cbfs/u-boot'
3329 control.WriteEntry(updated_fname, entry_name, expected,
3330 allow_resize=True)
3331 data = control.ReadEntry(updated_fname, entry_name)
3332 self.assertEqual(expected, data)
3333
Simon Glass30033c22019-07-20 12:24:15 -06003334 def _SetupForReplace(self):
3335 """Set up some files to use to replace entries
3336
3337 This generates an image, copies it to a new file, extracts all the files
3338 in it and updates some of them
3339
3340 Returns:
3341 List
3342 Image filename
3343 Output directory
3344 Expected values for updated entries, each a string
3345 """
3346 data = self._DoReadFileRealDtb('143_replace_all.dts')
3347
3348 updated_fname = tools.GetOutputFilename('image-updated.bin')
3349 tools.WriteFile(updated_fname, data)
3350
3351 outdir = os.path.join(self._indir, 'extract')
3352 einfos = control.ExtractEntries(updated_fname, None, outdir, [])
3353
3354 expected1 = b'x' + U_BOOT_DATA + b'y'
3355 u_boot_fname1 = os.path.join(outdir, 'u-boot')
3356 tools.WriteFile(u_boot_fname1, expected1)
3357
3358 expected2 = b'a' + U_BOOT_DATA + b'b'
3359 u_boot_fname2 = os.path.join(outdir, 'u-boot2')
3360 tools.WriteFile(u_boot_fname2, expected2)
3361
3362 expected_text = b'not the same text'
3363 text_fname = os.path.join(outdir, 'text')
3364 tools.WriteFile(text_fname, expected_text)
3365
3366 dtb_fname = os.path.join(outdir, 'u-boot-dtb')
3367 dtb = fdt.FdtScan(dtb_fname)
3368 node = dtb.GetNode('/binman/text')
3369 node.AddString('my-property', 'the value')
3370 dtb.Sync(auto_resize=True)
3371 dtb.Flush()
3372
3373 return updated_fname, outdir, expected1, expected2, expected_text
3374
3375 def _CheckReplaceMultiple(self, entry_paths):
3376 """Handle replacing the contents of multiple entries
3377
3378 Args:
3379 entry_paths: List of entry paths to replace
3380
3381 Returns:
3382 List
3383 Dict of entries in the image:
3384 key: Entry name
3385 Value: Entry object
3386 Expected values for updated entries, each a string
3387 """
3388 updated_fname, outdir, expected1, expected2, expected_text = (
3389 self._SetupForReplace())
3390 control.ReplaceEntries(updated_fname, None, outdir, entry_paths)
3391
3392 image = Image.FromFile(updated_fname)
3393 image.LoadData()
3394 return image.GetEntries(), expected1, expected2, expected_text
3395
3396 def testReplaceAll(self):
3397 """Test replacing the contents of all entries"""
3398 entries, expected1, expected2, expected_text = (
3399 self._CheckReplaceMultiple([]))
3400 data = entries['u-boot'].data
3401 self.assertEqual(expected1, data)
3402
3403 data = entries['u-boot2'].data
3404 self.assertEqual(expected2, data)
3405
3406 data = entries['text'].data
3407 self.assertEqual(expected_text, data)
3408
3409 # Check that the device tree is updated
3410 data = entries['u-boot-dtb'].data
3411 dtb = fdt.Fdt.FromData(data)
3412 dtb.Scan()
3413 node = dtb.GetNode('/binman/text')
3414 self.assertEqual('the value', node.props['my-property'].value)
3415
3416 def testReplaceSome(self):
3417 """Test replacing the contents of a few entries"""
3418 entries, expected1, expected2, expected_text = (
3419 self._CheckReplaceMultiple(['u-boot2', 'text']))
3420
3421 # This one should not change
3422 data = entries['u-boot'].data
3423 self.assertEqual(U_BOOT_DATA, data)
3424
3425 data = entries['u-boot2'].data
3426 self.assertEqual(expected2, data)
3427
3428 data = entries['text'].data
3429 self.assertEqual(expected_text, data)
3430
3431 def testReplaceCmd(self):
3432 """Test replacing a file fron an image on the command line"""
3433 self._DoReadFileRealDtb('143_replace_all.dts')
3434
3435 try:
3436 tmpdir, updated_fname = self._SetupImageInTmpdir()
3437
3438 fname = os.path.join(tmpdir, 'update-u-boot.bin')
3439 expected = b'x' * len(U_BOOT_DATA)
3440 tools.WriteFile(fname, expected)
3441
3442 self._DoBinman('replace', '-i', updated_fname, 'u-boot', '-f', fname)
3443 data = tools.ReadFile(updated_fname)
3444 self.assertEqual(expected, data[:len(expected)])
3445 map_fname = os.path.join(tmpdir, 'image-updated.map')
3446 self.assertFalse(os.path.exists(map_fname))
3447 finally:
3448 shutil.rmtree(tmpdir)
3449
3450 def testReplaceCmdSome(self):
3451 """Test replacing some files fron an image on the command line"""
3452 updated_fname, outdir, expected1, expected2, expected_text = (
3453 self._SetupForReplace())
3454
3455 self._DoBinman('replace', '-i', updated_fname, '-I', outdir,
3456 'u-boot2', 'text')
3457
3458 tools.PrepareOutputDir(None)
3459 image = Image.FromFile(updated_fname)
3460 image.LoadData()
3461 entries = image.GetEntries()
3462
3463 # This one should not change
3464 data = entries['u-boot'].data
3465 self.assertEqual(U_BOOT_DATA, data)
3466
3467 data = entries['u-boot2'].data
3468 self.assertEqual(expected2, data)
3469
3470 data = entries['text'].data
3471 self.assertEqual(expected_text, data)
3472
3473 def testReplaceMissing(self):
3474 """Test replacing entries where the file is missing"""
3475 updated_fname, outdir, expected1, expected2, expected_text = (
3476 self._SetupForReplace())
3477
3478 # Remove one of the files, to generate a warning
3479 u_boot_fname1 = os.path.join(outdir, 'u-boot')
3480 os.remove(u_boot_fname1)
3481
3482 with test_util.capture_sys_output() as (stdout, stderr):
3483 control.ReplaceEntries(updated_fname, None, outdir, [])
3484 self.assertIn("Skipping entry '/u-boot' from missing file",
Simon Glass6e02f7c2020-07-09 18:39:39 -06003485 stderr.getvalue())
Simon Glass30033c22019-07-20 12:24:15 -06003486
3487 def testReplaceCmdMap(self):
3488 """Test replacing a file fron an image on the command line"""
3489 self._DoReadFileRealDtb('143_replace_all.dts')
3490
3491 try:
3492 tmpdir, updated_fname = self._SetupImageInTmpdir()
3493
3494 fname = os.path.join(self._indir, 'update-u-boot.bin')
3495 expected = b'x' * len(U_BOOT_DATA)
3496 tools.WriteFile(fname, expected)
3497
3498 self._DoBinman('replace', '-i', updated_fname, 'u-boot',
3499 '-f', fname, '-m')
3500 map_fname = os.path.join(tmpdir, 'image-updated.map')
3501 self.assertTrue(os.path.exists(map_fname))
3502 finally:
3503 shutil.rmtree(tmpdir)
3504
3505 def testReplaceNoEntryPaths(self):
3506 """Test replacing an entry without an entry path"""
3507 self._DoReadFileRealDtb('143_replace_all.dts')
3508 image_fname = tools.GetOutputFilename('image.bin')
3509 with self.assertRaises(ValueError) as e:
3510 control.ReplaceEntries(image_fname, 'fname', None, [])
3511 self.assertIn('Must specify an entry path to read with -f',
3512 str(e.exception))
3513
3514 def testReplaceTooManyEntryPaths(self):
3515 """Test extracting some entries"""
3516 self._DoReadFileRealDtb('143_replace_all.dts')
3517 image_fname = tools.GetOutputFilename('image.bin')
3518 with self.assertRaises(ValueError) as e:
3519 control.ReplaceEntries(image_fname, 'fname', None, ['a', 'b'])
3520 self.assertIn('Must specify exactly one entry path to write with -f',
3521 str(e.exception))
3522
Simon Glass0b074d62019-08-24 07:22:48 -06003523 def testPackReset16(self):
3524 """Test that an image with an x86 reset16 region can be created"""
3525 data = self._DoReadFile('144_x86_reset16.dts')
3526 self.assertEqual(X86_RESET16_DATA, data[:len(X86_RESET16_DATA)])
3527
3528 def testPackReset16Spl(self):
3529 """Test that an image with an x86 reset16-spl region can be created"""
3530 data = self._DoReadFile('145_x86_reset16_spl.dts')
3531 self.assertEqual(X86_RESET16_SPL_DATA, data[:len(X86_RESET16_SPL_DATA)])
3532
3533 def testPackReset16Tpl(self):
3534 """Test that an image with an x86 reset16-tpl region can be created"""
3535 data = self._DoReadFile('146_x86_reset16_tpl.dts')
3536 self.assertEqual(X86_RESET16_TPL_DATA, data[:len(X86_RESET16_TPL_DATA)])
3537
Simon Glass232f90c2019-08-24 07:22:50 -06003538 def testPackIntelFit(self):
3539 """Test that an image with an Intel FIT and pointer can be created"""
3540 data = self._DoReadFile('147_intel_fit.dts')
3541 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3542 fit = data[16:32];
3543 self.assertEqual(b'_FIT_ \x01\x00\x00\x00\x00\x01\x80}' , fit)
3544 ptr = struct.unpack('<i', data[0x40:0x44])[0]
3545
3546 image = control.images['image']
3547 entries = image.GetEntries()
3548 expected_ptr = entries['intel-fit'].image_pos - (1 << 32)
3549 self.assertEqual(expected_ptr, ptr)
3550
3551 def testPackIntelFitMissing(self):
3552 """Test detection of a FIT pointer with not FIT region"""
3553 with self.assertRaises(ValueError) as e:
3554 self._DoReadFile('148_intel_fit_missing.dts')
3555 self.assertIn("'intel-fit-ptr' section must have an 'intel-fit' sibling",
3556 str(e.exception))
3557
Simon Glass72555fa2019-11-06 17:22:44 -07003558 def _CheckSymbolsTplSection(self, dts, expected_vals):
3559 data = self._DoReadFile(dts)
3560 sym_values = struct.pack('<LQLL', *expected_vals)
Simon Glass3eb5b202019-08-24 07:23:00 -06003561 upto1 = 4 + len(U_BOOT_SPL_DATA)
Simon Glass3f8ff012019-08-24 07:23:05 -06003562 expected1 = tools.GetBytes(0xff, 4) + sym_values + U_BOOT_SPL_DATA[20:]
Simon Glass3eb5b202019-08-24 07:23:00 -06003563 self.assertEqual(expected1, data[:upto1])
3564
3565 upto2 = upto1 + 1 + len(U_BOOT_SPL_DATA)
Simon Glass3f8ff012019-08-24 07:23:05 -06003566 expected2 = tools.GetBytes(0xff, 1) + sym_values + U_BOOT_SPL_DATA[20:]
Simon Glass3eb5b202019-08-24 07:23:00 -06003567 self.assertEqual(expected2, data[upto1:upto2])
3568
Simon Glass4e353e22019-08-24 07:23:04 -06003569 upto3 = 0x34 + len(U_BOOT_DATA)
3570 expected3 = tools.GetBytes(0xff, 1) + U_BOOT_DATA
Simon Glass3eb5b202019-08-24 07:23:00 -06003571 self.assertEqual(expected3, data[upto2:upto3])
3572
Simon Glass3f8ff012019-08-24 07:23:05 -06003573 expected4 = sym_values + U_BOOT_TPL_DATA[20:]
Simon Glass72555fa2019-11-06 17:22:44 -07003574 self.assertEqual(expected4, data[upto3:upto3 + len(U_BOOT_TPL_DATA)])
3575
3576 def testSymbolsTplSection(self):
3577 """Test binman can assign symbols embedded in U-Boot TPL in a section"""
3578 self._SetupSplElf('u_boot_binman_syms')
3579 self._SetupTplElf('u_boot_binman_syms')
3580 self._CheckSymbolsTplSection('149_symbols_tpl.dts',
3581 [0x04, 0x1c, 0x10 + 0x34, 0x04])
3582
3583 def testSymbolsTplSectionX86(self):
3584 """Test binman can assign symbols in a section with end-at-4gb"""
3585 self._SetupSplElf('u_boot_binman_syms_x86')
3586 self._SetupTplElf('u_boot_binman_syms_x86')
3587 self._CheckSymbolsTplSection('155_symbols_tpl_x86.dts',
3588 [0xffffff04, 0xffffff1c, 0xffffff34,
3589 0x04])
Simon Glass3eb5b202019-08-24 07:23:00 -06003590
Simon Glass98c59572019-08-24 07:23:03 -06003591 def testPackX86RomIfwiSectiom(self):
3592 """Test that a section can be placed in an IFWI region"""
3593 self._SetupIfwi('fitimage.bin')
3594 data = self._DoReadFile('151_x86_rom_ifwi_section.dts')
3595 self._CheckIfwi(data)
3596
Simon Glassba7985d2019-08-24 07:23:07 -06003597 def testPackFspM(self):
3598 """Test that an image with a FSP memory-init binary can be created"""
3599 data = self._DoReadFile('152_intel_fsp_m.dts')
3600 self.assertEqual(FSP_M_DATA, data[:len(FSP_M_DATA)])
3601
Simon Glass4d9086d2019-10-20 21:31:35 -06003602 def testPackFspS(self):
3603 """Test that an image with a FSP silicon-init binary can be created"""
3604 data = self._DoReadFile('153_intel_fsp_s.dts')
3605 self.assertEqual(FSP_S_DATA, data[:len(FSP_S_DATA)])
Simon Glassba7985d2019-08-24 07:23:07 -06003606
Simon Glass9ea87b22019-10-20 21:31:36 -06003607 def testPackFspT(self):
3608 """Test that an image with a FSP temp-ram-init binary can be created"""
3609 data = self._DoReadFile('154_intel_fsp_t.dts')
3610 self.assertEqual(FSP_T_DATA, data[:len(FSP_T_DATA)])
3611
Simon Glass48f3aad2020-07-09 18:39:31 -06003612 def testMkimage(self):
3613 """Test using mkimage to build an image"""
3614 data = self._DoReadFile('156_mkimage.dts')
3615
3616 # Just check that the data appears in the file somewhere
3617 self.assertIn(U_BOOT_SPL_DATA, data)
3618
Simon Glass5e560182020-07-09 18:39:36 -06003619 def testExtblob(self):
3620 """Test an image with an external blob"""
3621 data = self._DoReadFile('157_blob_ext.dts')
3622 self.assertEqual(REFCODE_DATA, data)
3623
3624 def testExtblobMissing(self):
3625 """Test an image with a missing external blob"""
3626 with self.assertRaises(ValueError) as e:
3627 self._DoReadFile('158_blob_ext_missing.dts')
3628 self.assertIn("Filename 'missing-file' not found in input path",
3629 str(e.exception))
3630
Simon Glass5d94cc62020-07-09 18:39:38 -06003631 def testExtblobMissingOk(self):
3632 """Test an image with an missing external blob that is allowed"""
Simon Glassa003cd32020-07-09 18:39:40 -06003633 with test_util.capture_sys_output() as (stdout, stderr):
3634 self._DoTestFile('158_blob_ext_missing.dts', allow_missing=True)
3635 err = stderr.getvalue()
3636 self.assertRegex(err, "Image 'main-section'.*missing.*: blob-ext")
3637
3638 def testExtblobMissingOkSect(self):
3639 """Test an image with an missing external blob that is allowed"""
3640 with test_util.capture_sys_output() as (stdout, stderr):
3641 self._DoTestFile('159_blob_ext_missing_sect.dts',
3642 allow_missing=True)
3643 err = stderr.getvalue()
3644 self.assertRegex(err, "Image 'main-section'.*missing.*: "
3645 "blob-ext blob-ext2")
Simon Glass5d94cc62020-07-09 18:39:38 -06003646
Simon Glasse88cef92020-07-09 18:39:41 -06003647 def testPackX86RomMeMissingDesc(self):
3648 """Test that an missing Intel descriptor entry is allowed"""
Simon Glasse88cef92020-07-09 18:39:41 -06003649 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass14c596c2020-07-25 15:11:19 -06003650 self._DoTestFile('164_x86_rom_me_missing.dts', allow_missing=True)
Simon Glasse88cef92020-07-09 18:39:41 -06003651 err = stderr.getvalue()
3652 self.assertRegex(err,
3653 "Image 'main-section'.*missing.*: intel-descriptor")
3654
3655 def testPackX86RomMissingIfwi(self):
3656 """Test that an x86 ROM with Integrated Firmware Image can be created"""
3657 self._SetupIfwi('fitimage.bin')
3658 pathname = os.path.join(self._indir, 'fitimage.bin')
3659 os.remove(pathname)
3660 with test_util.capture_sys_output() as (stdout, stderr):
3661 self._DoTestFile('111_x86_rom_ifwi.dts', allow_missing=True)
3662 err = stderr.getvalue()
3663 self.assertRegex(err, "Image 'main-section'.*missing.*: intel-ifwi")
3664
Simon Glassd70829a2020-07-09 18:39:42 -06003665 def testPackOverlap(self):
3666 """Test that zero-size overlapping regions are ignored"""
3667 self._DoTestFile('160_pack_overlap_zero.dts')
3668
Simon Glass45d556d2020-07-09 18:39:45 -06003669 def testSimpleFit(self):
3670 """Test an image with a FIT inside"""
3671 data = self._DoReadFile('161_fit.dts')
3672 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3673 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3674 fit_data = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3675
3676 # The data should be inside the FIT
3677 dtb = fdt.Fdt.FromData(fit_data)
3678 dtb.Scan()
3679 fnode = dtb.GetNode('/images/kernel')
3680 self.assertIn('data', fnode.props)
3681
3682 fname = os.path.join(self._indir, 'fit_data.fit')
3683 tools.WriteFile(fname, fit_data)
3684 out = tools.Run('dumpimage', '-l', fname)
3685
3686 # Check a few features to make sure the plumbing works. We don't need
3687 # to test the operation of mkimage or dumpimage here. First convert the
3688 # output into a dict where the keys are the fields printed by dumpimage
3689 # and the values are a list of values for each field
3690 lines = out.splitlines()
3691
3692 # Converts "Compression: gzip compressed" into two groups:
3693 # 'Compression' and 'gzip compressed'
3694 re_line = re.compile(r'^ *([^:]*)(?:: *(.*))?$')
3695 vals = collections.defaultdict(list)
3696 for line in lines:
3697 mat = re_line.match(line)
3698 vals[mat.group(1)].append(mat.group(2))
3699
3700 self.assertEquals('FIT description: test-desc', lines[0])
3701 self.assertIn('Created:', lines[1])
3702 self.assertIn('Image 0 (kernel)', vals)
3703 self.assertIn('Hash value', vals)
3704 data_sizes = vals.get('Data Size')
3705 self.assertIsNotNone(data_sizes)
3706 self.assertEqual(2, len(data_sizes))
3707 # Format is "4 Bytes = 0.00 KiB = 0.00 MiB" so take the first word
3708 self.assertEqual(len(U_BOOT_DATA), int(data_sizes[0].split()[0]))
3709 self.assertEqual(len(U_BOOT_SPL_DTB_DATA), int(data_sizes[1].split()[0]))
3710
3711 def testFitExternal(self):
Simon Glass31ee50f2020-09-01 05:13:55 -06003712 """Test an image with an FIT with external images"""
Simon Glass45d556d2020-07-09 18:39:45 -06003713 data = self._DoReadFile('162_fit_external.dts')
3714 fit_data = data[len(U_BOOT_DATA):-2] # _testing is 2 bytes
3715
Simon Glass7932c882022-01-09 20:13:39 -07003716 # Size of the external-data region as set up by mkimage
3717 external_data_size = len(U_BOOT_DATA) + 2
3718 expected_size = (len(U_BOOT_DATA) + 0x400 +
3719 tools.Align(external_data_size, 4) +
3720 len(U_BOOT_NODTB_DATA))
3721
Simon Glass45d556d2020-07-09 18:39:45 -06003722 # The data should be outside the FIT
3723 dtb = fdt.Fdt.FromData(fit_data)
3724 dtb.Scan()
3725 fnode = dtb.GetNode('/images/kernel')
3726 self.assertNotIn('data', fnode.props)
Simon Glass7932c882022-01-09 20:13:39 -07003727 self.assertEqual(len(U_BOOT_DATA),
3728 fdt_util.fdt32_to_cpu(fnode.props['data-size'].value))
3729 fit_pos = 0x400;
3730 self.assertEqual(
3731 fit_pos,
3732 fdt_util.fdt32_to_cpu(fnode.props['data-position'].value))
3733
3734 self.assertEquals(expected_size, len(data))
3735 actual_pos = len(U_BOOT_DATA) + fit_pos
3736 self.assertEqual(U_BOOT_DATA + b'aa',
3737 data[actual_pos:actual_pos + external_data_size])
Simon Glassfb30e292019-07-20 12:23:51 -06003738
Alper Nebi Yasak6aae2392020-08-31 12:58:18 +03003739 def testSectionIgnoreHashSignature(self):
3740 """Test that sections ignore hash, signature nodes for its data"""
3741 data = self._DoReadFile('165_section_ignore_hash_signature.dts')
3742 expected = (U_BOOT_DATA + U_BOOT_DATA)
3743 self.assertEqual(expected, data)
3744
Alper Nebi Yasakc5030602020-08-31 12:58:19 +03003745 def testPadInSections(self):
3746 """Test pad-before, pad-after for entries in sections"""
Simon Glassd12599d2020-10-26 17:40:09 -06003747 data, _, _, out_dtb_fname = self._DoReadFileDtb(
3748 '166_pad_in_sections.dts', update_dtb=True)
Alper Nebi Yasakc5030602020-08-31 12:58:19 +03003749 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
3750 U_BOOT_DATA + tools.GetBytes(ord('!'), 6) +
3751 U_BOOT_DATA)
3752 self.assertEqual(expected, data)
3753
Simon Glassd12599d2020-10-26 17:40:09 -06003754 dtb = fdt.Fdt(out_dtb_fname)
3755 dtb.Scan()
3756 props = self._GetPropTree(dtb, ['size', 'image-pos', 'offset'])
3757 expected = {
3758 'image-pos': 0,
3759 'offset': 0,
3760 'size': 12 + 6 + 3 * len(U_BOOT_DATA),
3761
3762 'section:image-pos': 0,
3763 'section:offset': 0,
3764 'section:size': 12 + 6 + 3 * len(U_BOOT_DATA),
3765
3766 'section/before:image-pos': 0,
3767 'section/before:offset': 0,
3768 'section/before:size': len(U_BOOT_DATA),
3769
3770 'section/u-boot:image-pos': 4,
3771 'section/u-boot:offset': 4,
3772 'section/u-boot:size': 12 + len(U_BOOT_DATA) + 6,
3773
3774 'section/after:image-pos': 26,
3775 'section/after:offset': 26,
3776 'section/after:size': len(U_BOOT_DATA),
3777 }
3778 self.assertEqual(expected, props)
3779
Alper Nebi Yasakc261ec12020-08-31 12:58:20 +03003780 def testFitImageSubentryAlignment(self):
3781 """Test relative alignability of FIT image subentries"""
3782 entry_args = {
3783 'test-id': TEXT_DATA,
3784 }
3785 data, _, _, _ = self._DoReadFileDtb('167_fit_image_subentry_alignment.dts',
3786 entry_args=entry_args)
3787 dtb = fdt.Fdt.FromData(data)
3788 dtb.Scan()
3789
3790 node = dtb.GetNode('/images/kernel')
3791 data = dtb.GetProps(node)["data"].bytes
3792 align_pad = 0x10 - (len(U_BOOT_SPL_DATA) % 0x10)
3793 expected = (tools.GetBytes(0, 0x20) + U_BOOT_SPL_DATA +
3794 tools.GetBytes(0, align_pad) + U_BOOT_DATA)
3795 self.assertEqual(expected, data)
3796
3797 node = dtb.GetNode('/images/fdt-1')
3798 data = dtb.GetProps(node)["data"].bytes
3799 expected = (U_BOOT_SPL_DTB_DATA + tools.GetBytes(0, 20) +
3800 tools.ToBytes(TEXT_DATA) + tools.GetBytes(0, 30) +
3801 U_BOOT_DTB_DATA)
3802 self.assertEqual(expected, data)
3803
3804 def testFitExtblobMissingOk(self):
3805 """Test a FIT with a missing external blob that is allowed"""
3806 with test_util.capture_sys_output() as (stdout, stderr):
3807 self._DoTestFile('168_fit_missing_blob.dts',
3808 allow_missing=True)
3809 err = stderr.getvalue()
Simon Glassa820af72020-09-06 10:39:09 -06003810 self.assertRegex(err, "Image 'main-section'.*missing.*: atf-bl31")
Alper Nebi Yasakc261ec12020-08-31 12:58:20 +03003811
Simon Glass21db0ff2020-09-01 05:13:54 -06003812 def testBlobNamedByArgMissing(self):
3813 """Test handling of a missing entry arg"""
3814 with self.assertRaises(ValueError) as e:
3815 self._DoReadFile('068_blob_named_by_arg.dts')
3816 self.assertIn("Missing required properties/entry args: cros-ec-rw-path",
3817 str(e.exception))
3818
Simon Glass559c4de2020-09-01 05:13:58 -06003819 def testPackBl31(self):
3820 """Test that an image with an ATF BL31 binary can be created"""
3821 data = self._DoReadFile('169_atf_bl31.dts')
3822 self.assertEqual(ATF_BL31_DATA, data[:len(ATF_BL31_DATA)])
3823
Samuel Holland9d8cc632020-10-21 21:12:15 -05003824 def testPackScp(self):
3825 """Test that an image with an SCP binary can be created"""
3826 data = self._DoReadFile('172_scp.dts')
3827 self.assertEqual(SCP_DATA, data[:len(SCP_DATA)])
3828
Simon Glassa435cd12020-09-01 05:13:59 -06003829 def testFitFdt(self):
3830 """Test an image with an FIT with multiple FDT images"""
3831 def _CheckFdt(seq, expected_data):
3832 """Check the FDT nodes
3833
3834 Args:
3835 seq: Sequence number to check (0 or 1)
3836 expected_data: Expected contents of 'data' property
3837 """
3838 name = 'fdt-%d' % seq
3839 fnode = dtb.GetNode('/images/%s' % name)
3840 self.assertIsNotNone(fnode)
3841 self.assertEqual({'description','type', 'compression', 'data'},
3842 set(fnode.props.keys()))
3843 self.assertEqual(expected_data, fnode.props['data'].bytes)
3844 self.assertEqual('fdt-test-fdt%d.dtb' % seq,
3845 fnode.props['description'].value)
3846
3847 def _CheckConfig(seq, expected_data):
3848 """Check the configuration nodes
3849
3850 Args:
3851 seq: Sequence number to check (0 or 1)
3852 expected_data: Expected contents of 'data' property
3853 """
3854 cnode = dtb.GetNode('/configurations')
3855 self.assertIn('default', cnode.props)
Simon Glass1032acc2020-09-06 10:39:08 -06003856 self.assertEqual('config-2', cnode.props['default'].value)
Simon Glassa435cd12020-09-01 05:13:59 -06003857
3858 name = 'config-%d' % seq
3859 fnode = dtb.GetNode('/configurations/%s' % name)
3860 self.assertIsNotNone(fnode)
3861 self.assertEqual({'description','firmware', 'loadables', 'fdt'},
3862 set(fnode.props.keys()))
3863 self.assertEqual('conf-test-fdt%d.dtb' % seq,
3864 fnode.props['description'].value)
3865 self.assertEqual('fdt-%d' % seq, fnode.props['fdt'].value)
3866
3867 entry_args = {
3868 'of-list': 'test-fdt1 test-fdt2',
Simon Glass1032acc2020-09-06 10:39:08 -06003869 'default-dt': 'test-fdt2',
Simon Glassa435cd12020-09-01 05:13:59 -06003870 }
3871 data = self._DoReadFileDtb(
Bin Meng16cf5662021-05-10 20:23:32 +08003872 '170_fit_fdt.dts',
Simon Glassa435cd12020-09-01 05:13:59 -06003873 entry_args=entry_args,
3874 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3875 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3876 fit_data = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3877
3878 dtb = fdt.Fdt.FromData(fit_data)
3879 dtb.Scan()
3880 fnode = dtb.GetNode('/images/kernel')
3881 self.assertIn('data', fnode.props)
3882
3883 # Check all the properties in fdt-1 and fdt-2
3884 _CheckFdt(1, TEST_FDT1_DATA)
3885 _CheckFdt(2, TEST_FDT2_DATA)
3886
3887 # Check configurations
3888 _CheckConfig(1, TEST_FDT1_DATA)
3889 _CheckConfig(2, TEST_FDT2_DATA)
3890
3891 def testFitFdtMissingList(self):
3892 """Test handling of a missing 'of-list' entry arg"""
3893 with self.assertRaises(ValueError) as e:
Bin Meng16cf5662021-05-10 20:23:32 +08003894 self._DoReadFile('170_fit_fdt.dts')
Simon Glassa435cd12020-09-01 05:13:59 -06003895 self.assertIn("Generator node requires 'of-list' entry argument",
3896 str(e.exception))
3897
3898 def testFitFdtEmptyList(self):
3899 """Test handling of an empty 'of-list' entry arg"""
3900 entry_args = {
3901 'of-list': '',
3902 }
3903 data = self._DoReadFileDtb('170_fit_fdt.dts', entry_args=entry_args)[0]
3904
3905 def testFitFdtMissingProp(self):
3906 """Test handling of a missing 'fit,fdt-list' property"""
3907 with self.assertRaises(ValueError) as e:
3908 self._DoReadFile('171_fit_fdt_missing_prop.dts')
3909 self.assertIn("Generator node requires 'fit,fdt-list' property",
3910 str(e.exception))
Simon Glass559c4de2020-09-01 05:13:58 -06003911
Simon Glass1032acc2020-09-06 10:39:08 -06003912 def testFitFdtEmptyList(self):
3913 """Test handling of an empty 'of-list' entry arg"""
3914 entry_args = {
3915 'of-list': '',
3916 }
Bin Meng16cf5662021-05-10 20:23:32 +08003917 data = self._DoReadFileDtb('170_fit_fdt.dts', entry_args=entry_args)[0]
Simon Glass1032acc2020-09-06 10:39:08 -06003918
3919 def testFitFdtMissing(self):
3920 """Test handling of a missing 'default-dt' entry arg"""
3921 entry_args = {
3922 'of-list': 'test-fdt1 test-fdt2',
3923 }
3924 with self.assertRaises(ValueError) as e:
3925 self._DoReadFileDtb(
Bin Meng16cf5662021-05-10 20:23:32 +08003926 '170_fit_fdt.dts',
Simon Glass1032acc2020-09-06 10:39:08 -06003927 entry_args=entry_args,
3928 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3929 self.assertIn("Generated 'default' node requires default-dt entry argument",
3930 str(e.exception))
3931
3932 def testFitFdtNotInList(self):
3933 """Test handling of a default-dt that is not in the of-list"""
3934 entry_args = {
3935 'of-list': 'test-fdt1 test-fdt2',
3936 'default-dt': 'test-fdt3',
3937 }
3938 with self.assertRaises(ValueError) as e:
3939 self._DoReadFileDtb(
Bin Meng16cf5662021-05-10 20:23:32 +08003940 '170_fit_fdt.dts',
Simon Glass1032acc2020-09-06 10:39:08 -06003941 entry_args=entry_args,
3942 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3943 self.assertIn("default-dt entry argument 'test-fdt3' not found in fdt list: test-fdt1, test-fdt2",
3944 str(e.exception))
3945
Simon Glassa820af72020-09-06 10:39:09 -06003946 def testFitExtblobMissingHelp(self):
3947 """Test display of help messages when an external blob is missing"""
3948 control.missing_blob_help = control._ReadMissingBlobHelp()
3949 control.missing_blob_help['wibble'] = 'Wibble test'
3950 control.missing_blob_help['another'] = 'Another test'
3951 with test_util.capture_sys_output() as (stdout, stderr):
3952 self._DoTestFile('168_fit_missing_blob.dts',
3953 allow_missing=True)
3954 err = stderr.getvalue()
3955
3956 # We can get the tag from the name, the type or the missing-msg
3957 # property. Check all three.
3958 self.assertIn('You may need to build ARM Trusted', err)
3959 self.assertIn('Wibble test', err)
3960 self.assertIn('Another test', err)
3961
Simon Glass6f1f4d42020-09-06 10:35:32 -06003962 def testMissingBlob(self):
3963 """Test handling of a blob containing a missing file"""
3964 with self.assertRaises(ValueError) as e:
3965 self._DoTestFile('173_missing_blob.dts', allow_missing=True)
3966 self.assertIn("Filename 'missing' not found in input path",
3967 str(e.exception))
3968
Simon Glassa0729502020-09-06 10:35:33 -06003969 def testEnvironment(self):
3970 """Test adding a U-Boot environment"""
3971 data = self._DoReadFile('174_env.dts')
3972 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3973 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3974 env = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3975 self.assertEqual(b'\x1b\x97\x22\x7c\x01var1=1\0var2="2"\0\0\xff\xff',
3976 env)
3977
3978 def testEnvironmentNoSize(self):
3979 """Test that a missing 'size' property is detected"""
3980 with self.assertRaises(ValueError) as e:
Simon Glass8cdc08a2020-10-26 17:40:00 -06003981 self._DoTestFile('175_env_no_size.dts')
Simon Glassa0729502020-09-06 10:35:33 -06003982 self.assertIn("'u-boot-env' entry must have a size property",
3983 str(e.exception))
3984
3985 def testEnvironmentTooSmall(self):
3986 """Test handling of an environment that does not fit"""
3987 with self.assertRaises(ValueError) as e:
Simon Glass8cdc08a2020-10-26 17:40:00 -06003988 self._DoTestFile('176_env_too_small.dts')
Simon Glassa0729502020-09-06 10:35:33 -06003989
3990 # checksum, start byte, environment with \0 terminator, final \0
3991 need = 4 + 1 + len(ENV_DATA) + 1 + 1
3992 short = need - 0x8
3993 self.assertIn("too small to hold data (need %#x more bytes)" % short,
3994 str(e.exception))
3995
Simon Glassd1fdf752020-10-26 17:40:01 -06003996 def testSkipAtStart(self):
3997 """Test handling of skip-at-start section"""
3998 data = self._DoReadFile('177_skip_at_start.dts')
3999 self.assertEqual(U_BOOT_DATA, data)
4000
4001 image = control.images['image']
4002 entries = image.GetEntries()
4003 section = entries['section']
4004 self.assertEqual(0, section.offset)
4005 self.assertEqual(len(U_BOOT_DATA), section.size)
4006 self.assertEqual(U_BOOT_DATA, section.GetData())
4007
4008 entry = section.GetEntries()['u-boot']
4009 self.assertEqual(16, entry.offset)
4010 self.assertEqual(len(U_BOOT_DATA), entry.size)
4011 self.assertEqual(U_BOOT_DATA, entry.data)
4012
4013 def testSkipAtStartPad(self):
4014 """Test handling of skip-at-start section with padded entry"""
4015 data = self._DoReadFile('178_skip_at_start_pad.dts')
4016 before = tools.GetBytes(0, 8)
4017 after = tools.GetBytes(0, 4)
4018 all = before + U_BOOT_DATA + after
4019 self.assertEqual(all, data)
4020
4021 image = control.images['image']
4022 entries = image.GetEntries()
4023 section = entries['section']
4024 self.assertEqual(0, section.offset)
4025 self.assertEqual(len(all), section.size)
4026 self.assertEqual(all, section.GetData())
4027
4028 entry = section.GetEntries()['u-boot']
4029 self.assertEqual(16, entry.offset)
4030 self.assertEqual(len(all), entry.size)
4031 self.assertEqual(U_BOOT_DATA, entry.data)
4032
4033 def testSkipAtStartSectionPad(self):
4034 """Test handling of skip-at-start section with padding"""
4035 data = self._DoReadFile('179_skip_at_start_section_pad.dts')
4036 before = tools.GetBytes(0, 8)
4037 after = tools.GetBytes(0, 4)
4038 all = before + U_BOOT_DATA + after
Simon Glass510ef0f2020-10-26 17:40:13 -06004039 self.assertEqual(all, data)
Simon Glassd1fdf752020-10-26 17:40:01 -06004040
4041 image = control.images['image']
4042 entries = image.GetEntries()
4043 section = entries['section']
4044 self.assertEqual(0, section.offset)
4045 self.assertEqual(len(all), section.size)
Simon Glass72eeff12020-10-26 17:40:16 -06004046 self.assertEqual(U_BOOT_DATA, section.data)
Simon Glass510ef0f2020-10-26 17:40:13 -06004047 self.assertEqual(all, section.GetPaddedData())
Simon Glassd1fdf752020-10-26 17:40:01 -06004048
4049 entry = section.GetEntries()['u-boot']
4050 self.assertEqual(16, entry.offset)
4051 self.assertEqual(len(U_BOOT_DATA), entry.size)
4052 self.assertEqual(U_BOOT_DATA, entry.data)
Simon Glassa0729502020-09-06 10:35:33 -06004053
Simon Glassbb395742020-10-26 17:40:14 -06004054 def testSectionPad(self):
4055 """Testing padding with sections"""
4056 data = self._DoReadFile('180_section_pad.dts')
4057 expected = (tools.GetBytes(ord('&'), 3) +
4058 tools.GetBytes(ord('!'), 5) +
4059 U_BOOT_DATA +
4060 tools.GetBytes(ord('!'), 1) +
4061 tools.GetBytes(ord('&'), 2))
4062 self.assertEqual(expected, data)
4063
4064 def testSectionAlign(self):
4065 """Testing alignment with sections"""
4066 data = self._DoReadFileDtb('181_section_align.dts', map=True)[0]
4067 expected = (b'\0' + # fill section
4068 tools.GetBytes(ord('&'), 1) + # padding to section align
4069 b'\0' + # fill section
4070 tools.GetBytes(ord('!'), 3) + # padding to u-boot align
4071 U_BOOT_DATA +
4072 tools.GetBytes(ord('!'), 4) + # padding to u-boot size
4073 tools.GetBytes(ord('!'), 4)) # padding to section size
4074 self.assertEqual(expected, data)
4075
Simon Glassd92c8362020-10-26 17:40:25 -06004076 def testCompressImage(self):
4077 """Test compression of the entire image"""
4078 self._CheckLz4()
4079 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4080 '182_compress_image.dts', use_real_dtb=True, update_dtb=True)
4081 dtb = fdt.Fdt(out_dtb_fname)
4082 dtb.Scan()
4083 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4084 'uncomp-size'])
4085 orig = self._decompress(data)
4086 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4087
4088 # Do a sanity check on various fields
4089 image = control.images['image']
4090 entries = image.GetEntries()
4091 self.assertEqual(2, len(entries))
4092
4093 entry = entries['blob']
4094 self.assertEqual(COMPRESS_DATA, entry.data)
4095 self.assertEqual(len(COMPRESS_DATA), entry.size)
4096
4097 entry = entries['u-boot']
4098 self.assertEqual(U_BOOT_DATA, entry.data)
4099 self.assertEqual(len(U_BOOT_DATA), entry.size)
4100
4101 self.assertEqual(len(data), image.size)
4102 self.assertEqual(COMPRESS_DATA + U_BOOT_DATA, image.uncomp_data)
4103 self.assertEqual(len(COMPRESS_DATA + U_BOOT_DATA), image.uncomp_size)
4104 orig = self._decompress(image.data)
4105 self.assertEqual(orig, image.uncomp_data)
4106
4107 expected = {
4108 'blob:offset': 0,
4109 'blob:size': len(COMPRESS_DATA),
4110 'u-boot:offset': len(COMPRESS_DATA),
4111 'u-boot:size': len(U_BOOT_DATA),
4112 'uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4113 'offset': 0,
4114 'image-pos': 0,
4115 'size': len(data),
4116 }
4117 self.assertEqual(expected, props)
4118
4119 def testCompressImageLess(self):
4120 """Test compression where compression reduces the image size"""
4121 self._CheckLz4()
4122 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4123 '183_compress_image_less.dts', use_real_dtb=True, update_dtb=True)
4124 dtb = fdt.Fdt(out_dtb_fname)
4125 dtb.Scan()
4126 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4127 'uncomp-size'])
4128 orig = self._decompress(data)
4129
4130 self.assertEquals(COMPRESS_DATA + COMPRESS_DATA + U_BOOT_DATA, orig)
4131
4132 # Do a sanity check on various fields
4133 image = control.images['image']
4134 entries = image.GetEntries()
4135 self.assertEqual(2, len(entries))
4136
4137 entry = entries['blob']
4138 self.assertEqual(COMPRESS_DATA_BIG, entry.data)
4139 self.assertEqual(len(COMPRESS_DATA_BIG), entry.size)
4140
4141 entry = entries['u-boot']
4142 self.assertEqual(U_BOOT_DATA, entry.data)
4143 self.assertEqual(len(U_BOOT_DATA), entry.size)
4144
4145 self.assertEqual(len(data), image.size)
4146 self.assertEqual(COMPRESS_DATA_BIG + U_BOOT_DATA, image.uncomp_data)
4147 self.assertEqual(len(COMPRESS_DATA_BIG + U_BOOT_DATA),
4148 image.uncomp_size)
4149 orig = self._decompress(image.data)
4150 self.assertEqual(orig, image.uncomp_data)
4151
4152 expected = {
4153 'blob:offset': 0,
4154 'blob:size': len(COMPRESS_DATA_BIG),
4155 'u-boot:offset': len(COMPRESS_DATA_BIG),
4156 'u-boot:size': len(U_BOOT_DATA),
4157 'uncomp-size': len(COMPRESS_DATA_BIG + U_BOOT_DATA),
4158 'offset': 0,
4159 'image-pos': 0,
4160 'size': len(data),
4161 }
4162 self.assertEqual(expected, props)
4163
4164 def testCompressSectionSize(self):
4165 """Test compression of a section with a fixed size"""
4166 self._CheckLz4()
4167 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4168 '184_compress_section_size.dts', use_real_dtb=True, update_dtb=True)
4169 dtb = fdt.Fdt(out_dtb_fname)
4170 dtb.Scan()
4171 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4172 'uncomp-size'])
4173 orig = self._decompress(data)
4174 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4175 expected = {
4176 'section/blob:offset': 0,
4177 'section/blob:size': len(COMPRESS_DATA),
4178 'section/u-boot:offset': len(COMPRESS_DATA),
4179 'section/u-boot:size': len(U_BOOT_DATA),
4180 'section:offset': 0,
4181 'section:image-pos': 0,
4182 'section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4183 'section:size': 0x30,
4184 'offset': 0,
4185 'image-pos': 0,
4186 'size': 0x30,
4187 }
4188 self.assertEqual(expected, props)
4189
4190 def testCompressSection(self):
4191 """Test compression of a section with no fixed size"""
4192 self._CheckLz4()
4193 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4194 '185_compress_section.dts', use_real_dtb=True, update_dtb=True)
4195 dtb = fdt.Fdt(out_dtb_fname)
4196 dtb.Scan()
4197 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4198 'uncomp-size'])
4199 orig = self._decompress(data)
4200 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4201 expected = {
4202 'section/blob:offset': 0,
4203 'section/blob:size': len(COMPRESS_DATA),
4204 'section/u-boot:offset': len(COMPRESS_DATA),
4205 'section/u-boot:size': len(U_BOOT_DATA),
4206 'section:offset': 0,
4207 'section:image-pos': 0,
4208 'section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4209 'section:size': len(data),
4210 'offset': 0,
4211 'image-pos': 0,
4212 'size': len(data),
4213 }
4214 self.assertEqual(expected, props)
4215
4216 def testCompressExtra(self):
4217 """Test compression of a section with no fixed size"""
4218 self._CheckLz4()
4219 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4220 '186_compress_extra.dts', use_real_dtb=True, update_dtb=True)
4221 dtb = fdt.Fdt(out_dtb_fname)
4222 dtb.Scan()
4223 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4224 'uncomp-size'])
4225
4226 base = data[len(U_BOOT_DATA):]
4227 self.assertEquals(U_BOOT_DATA, base[:len(U_BOOT_DATA)])
4228 rest = base[len(U_BOOT_DATA):]
4229
4230 # Check compressed data
4231 section1 = self._decompress(rest)
4232 expect1 = tools.Compress(COMPRESS_DATA + U_BOOT_DATA, 'lz4')
4233 self.assertEquals(expect1, rest[:len(expect1)])
4234 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, section1)
4235 rest1 = rest[len(expect1):]
4236
4237 section2 = self._decompress(rest1)
4238 expect2 = tools.Compress(COMPRESS_DATA + COMPRESS_DATA, 'lz4')
4239 self.assertEquals(expect2, rest1[:len(expect2)])
4240 self.assertEquals(COMPRESS_DATA + COMPRESS_DATA, section2)
4241 rest2 = rest1[len(expect2):]
4242
4243 expect_size = (len(U_BOOT_DATA) + len(U_BOOT_DATA) + len(expect1) +
4244 len(expect2) + len(U_BOOT_DATA))
4245 #self.assertEquals(expect_size, len(data))
4246
4247 #self.assertEquals(U_BOOT_DATA, rest2)
4248
4249 self.maxDiff = None
4250 expected = {
4251 'u-boot:offset': 0,
4252 'u-boot:image-pos': 0,
4253 'u-boot:size': len(U_BOOT_DATA),
4254
4255 'base:offset': len(U_BOOT_DATA),
4256 'base:image-pos': len(U_BOOT_DATA),
4257 'base:size': len(data) - len(U_BOOT_DATA),
4258 'base/u-boot:offset': 0,
4259 'base/u-boot:image-pos': len(U_BOOT_DATA),
4260 'base/u-boot:size': len(U_BOOT_DATA),
4261 'base/u-boot2:offset': len(U_BOOT_DATA) + len(expect1) +
4262 len(expect2),
4263 'base/u-boot2:image-pos': len(U_BOOT_DATA) * 2 + len(expect1) +
4264 len(expect2),
4265 'base/u-boot2:size': len(U_BOOT_DATA),
4266
4267 'base/section:offset': len(U_BOOT_DATA),
4268 'base/section:image-pos': len(U_BOOT_DATA) * 2,
4269 'base/section:size': len(expect1),
4270 'base/section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4271 'base/section/blob:offset': 0,
4272 'base/section/blob:size': len(COMPRESS_DATA),
4273 'base/section/u-boot:offset': len(COMPRESS_DATA),
4274 'base/section/u-boot:size': len(U_BOOT_DATA),
4275
4276 'base/section2:offset': len(U_BOOT_DATA) + len(expect1),
4277 'base/section2:image-pos': len(U_BOOT_DATA) * 2 + len(expect1),
4278 'base/section2:size': len(expect2),
4279 'base/section2:uncomp-size': len(COMPRESS_DATA + COMPRESS_DATA),
4280 'base/section2/blob:offset': 0,
4281 'base/section2/blob:size': len(COMPRESS_DATA),
4282 'base/section2/blob2:offset': len(COMPRESS_DATA),
4283 'base/section2/blob2:size': len(COMPRESS_DATA),
4284
4285 'offset': 0,
4286 'image-pos': 0,
4287 'size': len(data),
4288 }
4289 self.assertEqual(expected, props)
4290
Simon Glassecbe4732021-01-06 21:35:15 -07004291 def testSymbolsSubsection(self):
4292 """Test binman can assign symbols from a subsection"""
Simon Glass31e04cb2021-03-18 20:24:56 +13004293 self.checkSymbols('187_symbols_sub.dts', U_BOOT_SPL_DATA, 0x18)
Simon Glassecbe4732021-01-06 21:35:15 -07004294
Simon Glass3fb25402021-01-06 21:35:16 -07004295 def testReadImageEntryArg(self):
4296 """Test reading an image that would need an entry arg to generate"""
4297 entry_args = {
4298 'cros-ec-rw-path': 'ecrw.bin',
4299 }
4300 data = self.data = self._DoReadFileDtb(
4301 '188_image_entryarg.dts',use_real_dtb=True, update_dtb=True,
4302 entry_args=entry_args)
4303
4304 image_fname = tools.GetOutputFilename('image.bin')
4305 orig_image = control.images['image']
4306
4307 # This should not generate an error about the missing 'cros-ec-rw-path'
4308 # since we are reading the image from a file. Compare with
4309 # testEntryArgsRequired()
4310 image = Image.FromFile(image_fname)
4311 self.assertEqual(orig_image.GetEntries().keys(),
4312 image.GetEntries().keys())
4313
Simon Glassa2af7302021-01-06 21:35:18 -07004314 def testFilesAlign(self):
4315 """Test alignment with files"""
4316 data = self._DoReadFile('190_files_align.dts')
4317
4318 # The first string is 15 bytes so will align to 16
4319 expect = FILES_DATA[:15] + b'\0' + FILES_DATA[15:]
4320 self.assertEqual(expect, data)
4321
Simon Glassdb84b562021-01-06 21:35:19 -07004322 def testReadImageSkip(self):
4323 """Test reading an image and accessing its FDT map"""
4324 data = self.data = self._DoReadFileRealDtb('191_read_image_skip.dts')
4325 image_fname = tools.GetOutputFilename('image.bin')
4326 orig_image = control.images['image']
4327 image = Image.FromFile(image_fname)
4328 self.assertEqual(orig_image.GetEntries().keys(),
4329 image.GetEntries().keys())
4330
4331 orig_entry = orig_image.GetEntries()['fdtmap']
4332 entry = image.GetEntries()['fdtmap']
4333 self.assertEqual(orig_entry.offset, entry.offset)
4334 self.assertEqual(orig_entry.size, entry.size)
4335 self.assertEqual(16, entry.image_pos)
4336
4337 u_boot = image.GetEntries()['section'].GetEntries()['u-boot']
4338
4339 self.assertEquals(U_BOOT_DATA, u_boot.ReadData())
4340
Simon Glassc98de972021-03-18 20:24:57 +13004341 def testTplNoDtb(self):
4342 """Test that an image with tpl/u-boot-tpl-nodtb.bin can be created"""
Simon Glass13089cc2021-04-25 08:39:32 +12004343 self._SetupTplElf()
Simon Glassc98de972021-03-18 20:24:57 +13004344 data = self._DoReadFile('192_u_boot_tpl_nodtb.dts')
4345 self.assertEqual(U_BOOT_TPL_NODTB_DATA,
4346 data[:len(U_BOOT_TPL_NODTB_DATA)])
4347
Simon Glass63f41d42021-03-18 20:24:58 +13004348 def testTplBssPad(self):
4349 """Test that we can pad TPL's BSS with zeros"""
4350 # ELF file with a '__bss_size' symbol
4351 self._SetupTplElf()
4352 data = self._DoReadFile('193_tpl_bss_pad.dts')
4353 self.assertEqual(U_BOOT_TPL_DATA + tools.GetBytes(0, 10) + U_BOOT_DATA,
4354 data)
4355
4356 def testTplBssPadMissing(self):
4357 """Test that a missing symbol is detected"""
4358 self._SetupTplElf('u_boot_ucode_ptr')
4359 with self.assertRaises(ValueError) as e:
4360 self._DoReadFile('193_tpl_bss_pad.dts')
4361 self.assertIn('Expected __bss_size symbol in tpl/u-boot-tpl',
4362 str(e.exception))
4363
Simon Glass718b5292021-03-18 20:25:07 +13004364 def checkDtbSizes(self, data, pad_len, start):
4365 """Check the size arguments in a dtb embedded in an image
4366
4367 Args:
4368 data: The image data
4369 pad_len: Length of the pad section in the image, in bytes
4370 start: Start offset of the devicetree to examine, within the image
4371
4372 Returns:
4373 Size of the devicetree in bytes
4374 """
4375 dtb_data = data[start:]
4376 dtb = fdt.Fdt.FromData(dtb_data)
4377 fdt_size = dtb.GetFdtObj().totalsize()
4378 dtb.Scan()
4379 props = self._GetPropTree(dtb, 'size')
4380 self.assertEqual({
4381 'size': len(data),
4382 'u-boot-spl/u-boot-spl-bss-pad:size': pad_len,
4383 'u-boot-spl/u-boot-spl-dtb:size': 801,
4384 'u-boot-spl/u-boot-spl-nodtb:size': len(U_BOOT_SPL_NODTB_DATA),
4385 'u-boot-spl:size': 860,
4386 'u-boot-tpl:size': len(U_BOOT_TPL_DATA),
4387 'u-boot/u-boot-dtb:size': 781,
4388 'u-boot/u-boot-nodtb:size': len(U_BOOT_NODTB_DATA),
4389 'u-boot:size': 827,
4390 }, props)
4391 return fdt_size
4392
4393 def testExpanded(self):
4394 """Test that an expanded entry type is selected when needed"""
4395 self._SetupSplElf()
4396 self._SetupTplElf()
4397
4398 # SPL has a devicetree, TPL does not
4399 entry_args = {
4400 'spl-dtb': '1',
4401 'spl-bss-pad': 'y',
4402 'tpl-dtb': '',
4403 }
4404 self._DoReadFileDtb('194_fdt_incl.dts', use_expanded=True,
4405 entry_args=entry_args)
4406 image = control.images['image']
4407 entries = image.GetEntries()
4408 self.assertEqual(3, len(entries))
4409
4410 # First, u-boot, which should be expanded into u-boot-nodtb and dtb
4411 self.assertIn('u-boot', entries)
4412 entry = entries['u-boot']
4413 self.assertEqual('u-boot-expanded', entry.etype)
4414 subent = entry.GetEntries()
4415 self.assertEqual(2, len(subent))
4416 self.assertIn('u-boot-nodtb', subent)
4417 self.assertIn('u-boot-dtb', subent)
4418
4419 # Second, u-boot-spl, which should be expanded into three parts
4420 self.assertIn('u-boot-spl', entries)
4421 entry = entries['u-boot-spl']
4422 self.assertEqual('u-boot-spl-expanded', entry.etype)
4423 subent = entry.GetEntries()
4424 self.assertEqual(3, len(subent))
4425 self.assertIn('u-boot-spl-nodtb', subent)
4426 self.assertIn('u-boot-spl-bss-pad', subent)
4427 self.assertIn('u-boot-spl-dtb', subent)
4428
4429 # Third, u-boot-tpl, which should be not be expanded, since TPL has no
4430 # devicetree
4431 self.assertIn('u-boot-tpl', entries)
4432 entry = entries['u-boot-tpl']
4433 self.assertEqual('u-boot-tpl', entry.etype)
4434 self.assertEqual(None, entry.GetEntries())
4435
4436 def testExpandedTpl(self):
4437 """Test that an expanded entry type is selected for TPL when needed"""
4438 self._SetupTplElf()
4439
4440 entry_args = {
4441 'tpl-bss-pad': 'y',
4442 'tpl-dtb': 'y',
4443 }
4444 self._DoReadFileDtb('195_fdt_incl_tpl.dts', use_expanded=True,
4445 entry_args=entry_args)
4446 image = control.images['image']
4447 entries = image.GetEntries()
4448 self.assertEqual(1, len(entries))
4449
4450 # We only have u-boot-tpl, which be expanded
4451 self.assertIn('u-boot-tpl', entries)
4452 entry = entries['u-boot-tpl']
4453 self.assertEqual('u-boot-tpl-expanded', entry.etype)
4454 subent = entry.GetEntries()
4455 self.assertEqual(3, len(subent))
4456 self.assertIn('u-boot-tpl-nodtb', subent)
4457 self.assertIn('u-boot-tpl-bss-pad', subent)
4458 self.assertIn('u-boot-tpl-dtb', subent)
4459
4460 def testExpandedNoPad(self):
4461 """Test an expanded entry without BSS pad enabled"""
4462 self._SetupSplElf()
4463 self._SetupTplElf()
4464
4465 # SPL has a devicetree, TPL does not
4466 entry_args = {
4467 'spl-dtb': 'something',
4468 'spl-bss-pad': 'n',
4469 'tpl-dtb': '',
4470 }
4471 self._DoReadFileDtb('194_fdt_incl.dts', use_expanded=True,
4472 entry_args=entry_args)
4473 image = control.images['image']
4474 entries = image.GetEntries()
4475
4476 # Just check u-boot-spl, which should be expanded into two parts
4477 self.assertIn('u-boot-spl', entries)
4478 entry = entries['u-boot-spl']
4479 self.assertEqual('u-boot-spl-expanded', entry.etype)
4480 subent = entry.GetEntries()
4481 self.assertEqual(2, len(subent))
4482 self.assertIn('u-boot-spl-nodtb', subent)
4483 self.assertIn('u-boot-spl-dtb', subent)
4484
4485 def testExpandedTplNoPad(self):
4486 """Test that an expanded entry type with padding disabled in TPL"""
4487 self._SetupTplElf()
4488
4489 entry_args = {
4490 'tpl-bss-pad': '',
4491 'tpl-dtb': 'y',
4492 }
4493 self._DoReadFileDtb('195_fdt_incl_tpl.dts', use_expanded=True,
4494 entry_args=entry_args)
4495 image = control.images['image']
4496 entries = image.GetEntries()
4497 self.assertEqual(1, len(entries))
4498
4499 # We only have u-boot-tpl, which be expanded
4500 self.assertIn('u-boot-tpl', entries)
4501 entry = entries['u-boot-tpl']
4502 self.assertEqual('u-boot-tpl-expanded', entry.etype)
4503 subent = entry.GetEntries()
4504 self.assertEqual(2, len(subent))
4505 self.assertIn('u-boot-tpl-nodtb', subent)
4506 self.assertIn('u-boot-tpl-dtb', subent)
4507
4508 def testFdtInclude(self):
4509 """Test that an Fdt is update within all binaries"""
4510 self._SetupSplElf()
4511 self._SetupTplElf()
4512
4513 # SPL has a devicetree, TPL does not
4514 self.maxDiff = None
4515 entry_args = {
4516 'spl-dtb': '1',
4517 'spl-bss-pad': 'y',
4518 'tpl-dtb': '',
4519 }
4520 # Build the image. It includes two separate devicetree binaries, each
4521 # with their own contents, but all contain the binman definition.
4522 data = self._DoReadFileDtb(
4523 '194_fdt_incl.dts', use_real_dtb=True, use_expanded=True,
4524 update_dtb=True, entry_args=entry_args)[0]
4525 pad_len = 10
4526
4527 # Check the U-Boot dtb
4528 start = len(U_BOOT_NODTB_DATA)
4529 fdt_size = self.checkDtbSizes(data, pad_len, start)
4530
4531 # Now check SPL
4532 start += fdt_size + len(U_BOOT_SPL_NODTB_DATA) + pad_len
4533 fdt_size = self.checkDtbSizes(data, pad_len, start)
4534
4535 # TPL has no devicetree
4536 start += fdt_size + len(U_BOOT_TPL_DATA)
4537 self.assertEqual(len(data), start)
Simon Glassbb395742020-10-26 17:40:14 -06004538
Simon Glass7098b7f2021-03-21 18:24:30 +13004539 def testSymbolsExpanded(self):
4540 """Test binman can assign symbols in expanded entries"""
4541 entry_args = {
4542 'spl-dtb': '1',
4543 }
4544 self.checkSymbols('197_symbols_expand.dts', U_BOOT_SPL_NODTB_DATA +
4545 U_BOOT_SPL_DTB_DATA, 0x38,
4546 entry_args=entry_args, use_expanded=True)
4547
Simon Glasse1915782021-03-21 18:24:31 +13004548 def testCollection(self):
4549 """Test a collection"""
4550 data = self._DoReadFile('198_collection.dts')
4551 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA +
4552 tools.GetBytes(0xff, 2) + U_BOOT_NODTB_DATA +
4553 tools.GetBytes(0xfe, 3) + U_BOOT_DTB_DATA,
4554 data)
4555
Simon Glass27a7f772021-03-21 18:24:32 +13004556 def testCollectionSection(self):
4557 """Test a collection where a section must be built first"""
4558 # Sections never have their contents when GetData() is called, but when
Simon Glass7e3f89f2021-11-23 11:03:47 -07004559 # BuildSectionData() is called with required=True, a section will force
Simon Glass27a7f772021-03-21 18:24:32 +13004560 # building the contents, producing an error is anything is still
4561 # missing.
4562 data = self._DoReadFile('199_collection_section.dts')
4563 section = U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA
4564 self.assertEqual(section + U_BOOT_DATA + tools.GetBytes(0xff, 2) +
4565 section + tools.GetBytes(0xfe, 3) + U_BOOT_DATA,
4566 data)
4567
Simon Glassf427c5f2021-03-21 18:24:33 +13004568 def testAlignDefault(self):
4569 """Test that default alignment works on sections"""
4570 data = self._DoReadFile('200_align_default.dts')
4571 expected = (U_BOOT_DATA + tools.GetBytes(0, 8 - len(U_BOOT_DATA)) +
4572 U_BOOT_DATA)
4573 # Special alignment for section
4574 expected += tools.GetBytes(0, 32 - len(expected))
4575 # No alignment within the nested section
4576 expected += U_BOOT_DATA + U_BOOT_NODTB_DATA;
4577 # Now the final piece, which should be default-aligned
4578 expected += tools.GetBytes(0, 88 - len(expected)) + U_BOOT_NODTB_DATA
4579 self.assertEqual(expected, data)
Simon Glass27a7f772021-03-21 18:24:32 +13004580
Bin Mengc0b15742021-05-10 20:23:33 +08004581 def testPackOpenSBI(self):
4582 """Test that an image with an OpenSBI binary can be created"""
4583 data = self._DoReadFile('201_opensbi.dts')
4584 self.assertEqual(OPENSBI_DATA, data[:len(OPENSBI_DATA)])
4585
Simon Glass76f496d2021-07-06 10:36:37 -06004586 def testSectionsSingleThread(self):
4587 """Test sections without multithreading"""
4588 data = self._DoReadFileDtb('055_sections.dts', threads=0)[0]
4589 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
4590 U_BOOT_DATA + tools.GetBytes(ord('a'), 12) +
4591 U_BOOT_DATA + tools.GetBytes(ord('&'), 4))
4592 self.assertEqual(expected, data)
4593
4594 def testThreadTimeout(self):
4595 """Test handling a thread that takes too long"""
4596 with self.assertRaises(ValueError) as e:
4597 self._DoTestFile('202_section_timeout.dts',
4598 test_section_timeout=True)
Simon Glass2d59d152021-10-18 12:13:15 -06004599 self.assertIn("Timed out obtaining contents", str(e.exception))
Simon Glass76f496d2021-07-06 10:36:37 -06004600
Simon Glass748a1d42021-07-06 10:36:41 -06004601 def testTiming(self):
4602 """Test output of timing information"""
4603 data = self._DoReadFile('055_sections.dts')
4604 with test_util.capture_sys_output() as (stdout, stderr):
4605 state.TimingShow()
4606 self.assertIn('read:', stdout.getvalue())
4607 self.assertIn('compress:', stdout.getvalue())
4608
Simon Glassadfb8492021-11-03 21:09:18 -06004609 def testUpdateFdtInElf(self):
4610 """Test that we can update the devicetree in an ELF file"""
4611 infile = elf_fname = self.ElfTestFile('u_boot_binman_embed')
4612 outfile = os.path.join(self._indir, 'u-boot.out')
4613 begin_sym = 'dtb_embed_begin'
4614 end_sym = 'dtb_embed_end'
4615 retcode = self._DoTestFile(
4616 '060_fdt_update.dts', update_dtb=True,
4617 update_fdt_in_elf=','.join([infile,outfile,begin_sym,end_sym]))
4618 self.assertEqual(0, retcode)
4619
4620 # Check that the output file does in fact contact a dtb with the binman
4621 # definition in the correct place
4622 syms = elf.GetSymbolFileOffset(infile,
4623 ['dtb_embed_begin', 'dtb_embed_end'])
4624 data = tools.ReadFile(outfile)
4625 dtb_data = data[syms['dtb_embed_begin'].offset:
4626 syms['dtb_embed_end'].offset]
4627
4628 dtb = fdt.Fdt.FromData(dtb_data)
4629 dtb.Scan()
4630 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS)
4631 self.assertEqual({
4632 'image-pos': 0,
4633 'offset': 0,
4634 '_testing:offset': 32,
4635 '_testing:size': 2,
4636 '_testing:image-pos': 32,
4637 'section@0/u-boot:offset': 0,
4638 'section@0/u-boot:size': len(U_BOOT_DATA),
4639 'section@0/u-boot:image-pos': 0,
4640 'section@0:offset': 0,
4641 'section@0:size': 16,
4642 'section@0:image-pos': 0,
4643
4644 'section@1/u-boot:offset': 0,
4645 'section@1/u-boot:size': len(U_BOOT_DATA),
4646 'section@1/u-boot:image-pos': 16,
4647 'section@1:offset': 16,
4648 'section@1:size': 16,
4649 'section@1:image-pos': 16,
4650 'size': 40
4651 }, props)
4652
4653 def testUpdateFdtInElfInvalid(self):
4654 """Test that invalid args are detected with --update-fdt-in-elf"""
4655 with self.assertRaises(ValueError) as e:
4656 self._DoTestFile('060_fdt_update.dts', update_fdt_in_elf='fred')
4657 self.assertIn("Invalid args ['fred'] to --update-fdt-in-elf",
4658 str(e.exception))
4659
4660 def testUpdateFdtInElfNoSyms(self):
4661 """Test that missing symbols are detected with --update-fdt-in-elf"""
4662 infile = elf_fname = self.ElfTestFile('u_boot_binman_embed')
4663 outfile = ''
4664 begin_sym = 'wrong_begin'
4665 end_sym = 'wrong_end'
4666 with self.assertRaises(ValueError) as e:
4667 self._DoTestFile(
4668 '060_fdt_update.dts',
4669 update_fdt_in_elf=','.join([infile,outfile,begin_sym,end_sym]))
4670 self.assertIn("Expected two symbols 'wrong_begin' and 'wrong_end': got 0:",
4671 str(e.exception))
4672
4673 def testUpdateFdtInElfTooSmall(self):
4674 """Test that an over-large dtb is detected with --update-fdt-in-elf"""
4675 infile = elf_fname = self.ElfTestFile('u_boot_binman_embed_sm')
4676 outfile = os.path.join(self._indir, 'u-boot.out')
4677 begin_sym = 'dtb_embed_begin'
4678 end_sym = 'dtb_embed_end'
4679 with self.assertRaises(ValueError) as e:
4680 self._DoTestFile(
4681 '060_fdt_update.dts', update_dtb=True,
4682 update_fdt_in_elf=','.join([infile,outfile,begin_sym,end_sym]))
4683 self.assertRegex(
4684 str(e.exception),
4685 "Not enough space in '.*u_boot_binman_embed_sm' for data length.*")
4686
Simon Glass88e04da2021-11-23 11:03:42 -07004687 def testVersion(self):
4688 """Test we can get the binman version"""
4689 version = '(unreleased)'
4690 self.assertEqual(version, state.GetVersion(self._indir))
4691
4692 with self.assertRaises(SystemExit):
4693 with test_util.capture_sys_output() as (_, stderr):
4694 self._DoBinman('-V')
4695 self.assertEqual('Binman %s\n' % version, stderr.getvalue())
4696
4697 # Try running the tool too, just to be safe
4698 result = self._RunBinman('-V')
4699 self.assertEqual('Binman %s\n' % version, result.stderr)
4700
4701 # Set up a version file to make sure that works
4702 version = 'v2025.01-rc2'
4703 tools.WriteFile(os.path.join(self._indir, 'version'), version,
4704 binary=False)
4705 self.assertEqual(version, state.GetVersion(self._indir))
4706
Simon Glass637958f2021-11-23 21:09:50 -07004707 def testAltFormat(self):
4708 """Test that alternative formats can be used to extract"""
4709 self._DoReadFileRealDtb('213_fdtmap_alt_format.dts')
4710
4711 try:
4712 tmpdir, updated_fname = self._SetupImageInTmpdir()
4713 with test_util.capture_sys_output() as (stdout, _):
4714 self._DoBinman('extract', '-i', updated_fname, '-F', 'list')
4715 self.assertEqual(
4716 '''Flag (-F) Entry type Description
4717fdt fdtmap Extract the devicetree blob from the fdtmap
4718''',
4719 stdout.getvalue())
4720
4721 dtb = os.path.join(tmpdir, 'fdt.dtb')
4722 self._DoBinman('extract', '-i', updated_fname, '-F', 'fdt', '-f',
4723 dtb, 'fdtmap')
4724
4725 # Check that we can read it and it can be scanning, meaning it does
4726 # not have a 16-byte fdtmap header
4727 data = tools.ReadFile(dtb)
4728 dtb = fdt.Fdt.FromData(data)
4729 dtb.Scan()
4730
4731 # Now check u-boot which has no alt_format
4732 fname = os.path.join(tmpdir, 'fdt.dtb')
4733 self._DoBinman('extract', '-i', updated_fname, '-F', 'dummy',
4734 '-f', fname, 'u-boot')
4735 data = tools.ReadFile(fname)
4736 self.assertEqual(U_BOOT_DATA, data)
4737
4738 finally:
4739 shutil.rmtree(tmpdir)
4740
Simon Glass0b00ae62021-11-23 21:09:52 -07004741 def testExtblobList(self):
4742 """Test an image with an external blob list"""
4743 data = self._DoReadFile('215_blob_ext_list.dts')
4744 self.assertEqual(REFCODE_DATA + FSP_M_DATA, data)
4745
4746 def testExtblobListMissing(self):
4747 """Test an image with a missing external blob"""
4748 with self.assertRaises(ValueError) as e:
4749 self._DoReadFile('216_blob_ext_list_missing.dts')
4750 self.assertIn("Filename 'missing-file' not found in input path",
4751 str(e.exception))
4752
4753 def testExtblobListMissingOk(self):
4754 """Test an image with an missing external blob that is allowed"""
4755 with test_util.capture_sys_output() as (stdout, stderr):
4756 self._DoTestFile('216_blob_ext_list_missing.dts',
4757 allow_missing=True)
4758 err = stderr.getvalue()
4759 self.assertRegex(err, "Image 'main-section'.*missing.*: blob-ext")
4760
Simon Glass3efb2972021-11-23 21:08:59 -07004761 def testFip(self):
4762 """Basic test of generation of an ARM Firmware Image Package (FIP)"""
4763 data = self._DoReadFile('203_fip.dts')
4764 hdr, fents = fip_util.decode_fip(data)
4765 self.assertEqual(fip_util.HEADER_MAGIC, hdr.name)
4766 self.assertEqual(fip_util.HEADER_SERIAL, hdr.serial)
4767 self.assertEqual(0x123, hdr.flags)
4768
4769 self.assertEqual(2, len(fents))
4770
4771 fent = fents[0]
4772 self.assertEqual(
4773 bytes([0x47, 0xd4, 0x08, 0x6d, 0x4c, 0xfe, 0x98, 0x46,
4774 0x9b, 0x95, 0x29, 0x50, 0xcb, 0xbd, 0x5a, 0x0]), fent.uuid)
4775 self.assertEqual('soc-fw', fent.fip_type)
4776 self.assertEqual(0x88, fent.offset)
4777 self.assertEqual(len(ATF_BL31_DATA), fent.size)
4778 self.assertEqual(0x123456789abcdef, fent.flags)
4779 self.assertEqual(ATF_BL31_DATA, fent.data)
4780 self.assertEqual(True, fent.valid)
4781
4782 fent = fents[1]
4783 self.assertEqual(
4784 bytes([0x65, 0x92, 0x27, 0x03, 0x2f, 0x74, 0xe6, 0x44,
4785 0x8d, 0xff, 0x57, 0x9a, 0xc1, 0xff, 0x06, 0x10]), fent.uuid)
4786 self.assertEqual('scp-fwu-cfg', fent.fip_type)
4787 self.assertEqual(0x8c, fent.offset)
4788 self.assertEqual(len(ATF_BL31_DATA), fent.size)
4789 self.assertEqual(0, fent.flags)
4790 self.assertEqual(ATF_BL2U_DATA, fent.data)
4791 self.assertEqual(True, fent.valid)
4792
4793 def testFipOther(self):
4794 """Basic FIP with something that isn't a external blob"""
4795 data = self._DoReadFile('204_fip_other.dts')
4796 hdr, fents = fip_util.decode_fip(data)
4797
4798 self.assertEqual(2, len(fents))
4799 fent = fents[1]
4800 self.assertEqual('rot-cert', fent.fip_type)
4801 self.assertEqual(b'aa', fent.data)
4802
4803 def testFipOther(self):
4804 """Basic FIP with something that isn't a external blob"""
4805 data = self._DoReadFile('204_fip_other.dts')
4806 hdr, fents = fip_util.decode_fip(data)
4807
4808 self.assertEqual(2, len(fents))
4809 fent = fents[1]
4810 self.assertEqual('rot-cert', fent.fip_type)
4811 self.assertEqual(b'aa', fent.data)
4812
4813 def testFipNoType(self):
4814 """FIP with an entry of an unknown type"""
4815 with self.assertRaises(ValueError) as e:
4816 self._DoReadFile('205_fip_no_type.dts')
4817 self.assertIn("Must provide a fip-type (node name 'u-boot' is not a known FIP type)",
4818 str(e.exception))
4819
4820 def testFipUuid(self):
4821 """Basic FIP with a manual uuid"""
4822 data = self._DoReadFile('206_fip_uuid.dts')
4823 hdr, fents = fip_util.decode_fip(data)
4824
4825 self.assertEqual(2, len(fents))
4826 fent = fents[1]
4827 self.assertEqual(None, fent.fip_type)
4828 self.assertEqual(
4829 bytes([0xfc, 0x65, 0x13, 0x92, 0x4a, 0x5b, 0x11, 0xec,
4830 0x94, 0x35, 0xff, 0x2d, 0x1c, 0xfc, 0x79, 0x9c]),
4831 fent.uuid)
4832 self.assertEqual(U_BOOT_DATA, fent.data)
4833
4834 def testFipLs(self):
4835 """Test listing a FIP"""
4836 data = self._DoReadFileRealDtb('207_fip_ls.dts')
4837 hdr, fents = fip_util.decode_fip(data)
4838
4839 try:
4840 tmpdir, updated_fname = self._SetupImageInTmpdir()
4841 with test_util.capture_sys_output() as (stdout, stderr):
4842 self._DoBinman('ls', '-i', updated_fname)
4843 finally:
4844 shutil.rmtree(tmpdir)
4845 lines = stdout.getvalue().splitlines()
4846 expected = [
4847'Name Image-pos Size Entry-type Offset Uncomp-size',
4848'----------------------------------------------------------------',
4849'main-section 0 2d3 section 0',
4850' atf-fip 0 90 atf-fip 0',
4851' soc-fw 88 4 blob-ext 88',
4852' u-boot 8c 4 u-boot 8c',
4853' fdtmap 90 243 fdtmap 90',
4854]
4855 self.assertEqual(expected, lines)
4856
4857 image = control.images['image']
4858 entries = image.GetEntries()
4859 fdtmap = entries['fdtmap']
4860
4861 fdtmap_data = data[fdtmap.image_pos:fdtmap.image_pos + fdtmap.size]
4862 magic = fdtmap_data[:8]
4863 self.assertEqual(b'_FDTMAP_', magic)
4864 self.assertEqual(tools.GetBytes(0, 8), fdtmap_data[8:16])
4865
4866 fdt_data = fdtmap_data[16:]
4867 dtb = fdt.Fdt.FromData(fdt_data)
4868 dtb.Scan()
4869 props = self._GetPropTree(dtb, BASE_DTB_PROPS, prefix='/')
4870 self.assertEqual({
4871 'atf-fip/soc-fw:image-pos': 136,
4872 'atf-fip/soc-fw:offset': 136,
4873 'atf-fip/soc-fw:size': 4,
4874 'atf-fip/u-boot:image-pos': 140,
4875 'atf-fip/u-boot:offset': 140,
4876 'atf-fip/u-boot:size': 4,
4877 'atf-fip:image-pos': 0,
4878 'atf-fip:offset': 0,
4879 'atf-fip:size': 144,
4880 'image-pos': 0,
4881 'offset': 0,
4882 'fdtmap:image-pos': fdtmap.image_pos,
4883 'fdtmap:offset': fdtmap.offset,
4884 'fdtmap:size': len(fdtmap_data),
4885 'size': len(data),
4886 }, props)
4887
4888 def testFipExtractOneEntry(self):
4889 """Test extracting a single entry fron an FIP"""
4890 self._DoReadFileRealDtb('207_fip_ls.dts')
4891 image_fname = tools.GetOutputFilename('image.bin')
4892 fname = os.path.join(self._indir, 'output.extact')
4893 control.ExtractEntries(image_fname, fname, None, ['atf-fip/u-boot'])
4894 data = tools.ReadFile(fname)
4895 self.assertEqual(U_BOOT_DATA, data)
4896
4897 def testFipReplace(self):
4898 """Test replacing a single file in a FIP"""
4899 expected = U_BOOT_DATA + tools.GetBytes(0x78, 50)
4900 data = self._DoReadFileRealDtb('208_fip_replace.dts')
4901 updated_fname = tools.GetOutputFilename('image-updated.bin')
4902 tools.WriteFile(updated_fname, data)
4903 entry_name = 'atf-fip/u-boot'
4904 control.WriteEntry(updated_fname, entry_name, expected,
4905 allow_resize=True)
4906 actual = control.ReadEntry(updated_fname, entry_name)
4907 self.assertEqual(expected, actual)
4908
4909 new_data = tools.ReadFile(updated_fname)
4910 hdr, fents = fip_util.decode_fip(new_data)
4911
4912 self.assertEqual(2, len(fents))
4913
4914 # Check that the FIP entry is updated
4915 fent = fents[1]
4916 self.assertEqual(0x8c, fent.offset)
4917 self.assertEqual(len(expected), fent.size)
4918 self.assertEqual(0, fent.flags)
4919 self.assertEqual(expected, fent.data)
4920 self.assertEqual(True, fent.valid)
4921
4922 def testFipMissing(self):
4923 with test_util.capture_sys_output() as (stdout, stderr):
4924 self._DoTestFile('209_fip_missing.dts', allow_missing=True)
4925 err = stderr.getvalue()
4926 self.assertRegex(err, "Image 'main-section'.*missing.*: rmm-fw")
4927
4928 def testFipSize(self):
4929 """Test a FIP with a size property"""
4930 data = self._DoReadFile('210_fip_size.dts')
4931 self.assertEqual(0x100 + len(U_BOOT_DATA), len(data))
4932 hdr, fents = fip_util.decode_fip(data)
4933 self.assertEqual(fip_util.HEADER_MAGIC, hdr.name)
4934 self.assertEqual(fip_util.HEADER_SERIAL, hdr.serial)
4935
4936 self.assertEqual(1, len(fents))
4937
4938 fent = fents[0]
4939 self.assertEqual('soc-fw', fent.fip_type)
4940 self.assertEqual(0x60, fent.offset)
4941 self.assertEqual(len(ATF_BL31_DATA), fent.size)
4942 self.assertEqual(ATF_BL31_DATA, fent.data)
4943 self.assertEqual(True, fent.valid)
4944
4945 rest = data[0x60 + len(ATF_BL31_DATA):0x100]
4946 self.assertEqual(tools.GetBytes(0xff, len(rest)), rest)
4947
4948 def testFipBadAlign(self):
4949 """Test that an invalid alignment value in a FIP is detected"""
4950 with self.assertRaises(ValueError) as e:
4951 self._DoTestFile('211_fip_bad_align.dts')
4952 self.assertIn(
4953 "Node \'/binman/atf-fip\': FIP alignment 31 must be a power of two",
4954 str(e.exception))
4955
4956 def testFipCollection(self):
4957 """Test using a FIP in a collection"""
4958 data = self._DoReadFile('212_fip_collection.dts')
4959 entry1 = control.images['image'].GetEntries()['collection']
4960 data1 = data[:entry1.size]
4961 hdr1, fents2 = fip_util.decode_fip(data1)
4962
4963 entry2 = control.images['image'].GetEntries()['atf-fip']
4964 data2 = data[entry2.offset:entry2.offset + entry2.size]
4965 hdr1, fents2 = fip_util.decode_fip(data2)
4966
4967 # The 'collection' entry should have U-Boot included at the end
4968 self.assertEqual(entry1.size - len(U_BOOT_DATA), entry2.size)
4969 self.assertEqual(data1, data2 + U_BOOT_DATA)
4970 self.assertEqual(U_BOOT_DATA, data1[-4:])
4971
4972 # There should be a U-Boot after the final FIP
4973 self.assertEqual(U_BOOT_DATA, data[-4:])
Simon Glass76f496d2021-07-06 10:36:37 -06004974
Simon Glassccae6862022-01-12 13:10:35 -07004975 def testFakeBlob(self):
4976 """Test handling of faking an external blob"""
4977 with test_util.capture_sys_output() as (stdout, stderr):
4978 self._DoTestFile('217_fake_blob.dts', allow_missing=True,
4979 allow_fake_blobs=True)
4980 err = stderr.getvalue()
4981 self.assertRegex(
4982 err,
4983 "Image '.*' has faked external blobs and is non-functional: .*")
Simon Glassccae6862022-01-12 13:10:35 -07004984
4985
Simon Glassac599912017-11-12 21:52:22 -07004986if __name__ == "__main__":
4987 unittest.main()