blob: a9b7880f362f5702fa86d8d3e79b982be70bfe54 [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass4f443042016-11-25 20:15:52 -07002# Copyright (c) 2016 Google, Inc
3# Written by Simon Glass <sjg@chromium.org>
4#
Simon Glass4f443042016-11-25 20:15:52 -07005# To run a single test, change to this directory, and:
6#
7# python -m unittest func_test.TestFunctional.testHelp
8
Simon Glassfdc34362020-07-09 18:39:45 -06009import collections
Simon Glass16287932020-04-17 18:09:03 -060010import gzip
Simon Glasse0e5df92018-09-14 04:57:31 -060011import hashlib
Simon Glass4f443042016-11-25 20:15:52 -070012from optparse import OptionParser
13import os
Simon Glassfdc34362020-07-09 18:39:45 -060014import re
Simon Glass4f443042016-11-25 20:15:52 -070015import shutil
16import struct
17import sys
18import tempfile
19import unittest
20
Simon Glass16287932020-04-17 18:09:03 -060021from binman import cbfs_util
22from binman import cmdline
23from binman import control
24from binman import elf
25from binman import elf_test
Simon Glass75989722021-11-23 21:08:59 -070026from binman import fip_util
Simon Glass16287932020-04-17 18:09:03 -060027from binman import fmap_util
Simon Glass16287932020-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 Glass07237982020-08-05 13:27:47 -060033from binman.image import Image
Simon Glassbf776672020-04-17 18:09:04 -060034from patman import command
35from patman import test_util
36from patman import tools
37from patman import tout
Simon Glass4f443042016-11-25 20:15:52 -070038
39# Contents of test files, corresponding to different entry types
Simon Glassc6c10e72019-05-17 22:00:46 -060040U_BOOT_DATA = b'1234'
41U_BOOT_IMG_DATA = b'img'
Simon Glasseb0086f2019-08-24 07:23:04 -060042U_BOOT_SPL_DATA = b'56780123456789abcdefghi'
43U_BOOT_TPL_DATA = b'tpl9876543210fedcbazyw'
Simon Glassc6c10e72019-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 Glass2250ee62019-08-24 07:22:48 -060053X86_RESET16_DATA = b'reset16'
54X86_RESET16_SPL_DATA = b'reset16spl'
55X86_RESET16_TPL_DATA = b'reset16tpl'
Simon Glassc6c10e72019-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 Glassbb748372018-07-17 13:25:33 -060064TEXT_DATA = 'text'
65TEXT_DATA2 = 'text2'
66TEXT_DATA3 = 'text3'
Simon Glassc6c10e72019-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 Glassff5c7e32019-07-08 13:18:42 -060073COMPRESS_DATA = b'compress xxxxxxxxxxxxxxxxxxxxxx data'
Simon Glass8f5ef892020-10-26 17:40:25 -060074COMPRESS_DATA_BIG = COMPRESS_DATA * 2
Simon Glassc6c10e72019-05-17 22:00:46 -060075REFCODE_DATA = b'refcode'
Simon Glassea0fff92019-08-24 07:23:07 -060076FSP_M_DATA = b'fsp_m'
Simon Glassbc6a88f2019-10-20 21:31:35 -060077FSP_S_DATA = b'fsp_s'
Simon Glass998d1482019-10-20 21:31:36 -060078FSP_T_DATA = b'fsp_t'
Simon Glassdc2f81a2020-09-01 05:13:58 -060079ATF_BL31_DATA = b'bl31'
Simon Glass75989722021-11-23 21:08:59 -070080ATF_BL2U_DATA = b'bl2u'
Bin Meng4c4d6072021-05-10 20:23:33 +080081OPENSBI_DATA = b'opensbi'
Samuel Holland18bd4552020-10-21 21:12:15 -050082SCP_DATA = b'scp'
Simon Glass6cf99532020-09-01 05:13:59 -060083TEST_FDT1_DATA = b'fdt1'
84TEST_FDT2_DATA = b'test-fdt2'
Simon Glassfb91d562020-09-06 10:35:33 -060085ENV_DATA = b'var1=1\nvar2="2"'
Simon Glass6cf99532020-09-01 05:13:59 -060086
87# Subdirectory of the input dir to use to put test FDTs
88TEST_FDT_SUBDIR = 'fdts'
Simon Glassec127af2018-07-17 13:25:39 -060089
Simon Glass6ccbfcd2019-07-20 12:23:47 -060090# The expected size for the device tree in some tests
Simon Glassf667e452019-07-08 14:25:50 -060091EXTRACT_DTB_SIZE = 0x3c9
92
Simon Glass6ccbfcd2019-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 Glass12bb1a92019-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 Glass4f443042016-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 Glassb986b3b2019-08-24 07:22:43 -0600115 def setUpClass(cls):
Simon Glass4d5994f2017-11-12 21:52:20 -0700116 global entry
Simon Glass16287932020-04-17 18:09:03 -0600117 from binman import entry
Simon Glass4d5994f2017-11-12 21:52:20 -0700118
Simon Glass4f443042016-11-25 20:15:52 -0700119 # Handle the case where argv[0] is 'python'
Simon Glassb986b3b2019-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 Glass4f443042016-11-25 20:15:52 -0700122
123 # Create a temporary directory for input files
Simon Glassb986b3b2019-08-24 07:22:43 -0600124 cls._indir = tempfile.mkdtemp(prefix='binmant.')
Simon Glass4f443042016-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 Glassb8ef5b62018-07-17 13:25:48 -0600130 TestFunctional._MakeInputFile('tpl/u-boot-tpl.bin', U_BOOT_TPL_DATA)
Simon Glass4f443042016-11-25 20:15:52 -0700131 TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -0700132 TestFunctional._MakeInputFile('me.bin', ME_DATA)
133 TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
Simon Glassb986b3b2019-08-24 07:22:43 -0600134 cls._ResetDtbs()
Simon Glass2250ee62019-08-24 07:22:48 -0600135
Jagdish Gediya9d368f32018-09-03 21:35:08 +0530136 TestFunctional._MakeInputFile('u-boot-br.bin', PPC_MPC85XX_BR_DATA)
Simon Glass2250ee62019-08-24 07:22:48 -0600137
Simon Glass5e239182019-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 Glass87722132017-11-12 21:52:26 -0700140 X86_START16_SPL_DATA)
Simon Glass5e239182019-08-24 07:22:49 -0600141 TestFunctional._MakeInputFile('tpl/u-boot-x86-start16-tpl.bin',
Simon Glass35b384c2018-09-14 04:57:10 -0600142 X86_START16_TPL_DATA)
Simon Glass2250ee62019-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 Glass4f443042016-11-25 20:15:52 -0700151 TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
Simon Glass6b187df2017-11-12 21:52:27 -0700152 TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
153 U_BOOT_SPL_NODTB_DATA)
Simon Glassf0253632018-09-14 04:57:32 -0600154 TestFunctional._MakeInputFile('tpl/u-boot-tpl-nodtb.bin',
155 U_BOOT_TPL_NODTB_DATA)
Simon Glassda229092016-11-25 20:15:56 -0700156 TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
157 TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
Bin Meng59ea8c22017-08-15 22:41:54 -0700158 TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
Simon Glassca4f4ff2017-11-12 21:52:28 -0700159 TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
Simon Glassec127af2018-07-17 13:25:39 -0600160 TestFunctional._MakeInputFile('ecrw.bin', CROS_EC_RW_DATA)
Simon Glass0ef87aa2018-07-17 13:25:44 -0600161 TestFunctional._MakeInputDir('devkeys')
162 TestFunctional._MakeInputFile('bmpblk.bin', BMPBLK_DATA)
Simon Glass3ae192c2018-10-01 12:22:31 -0600163 TestFunctional._MakeInputFile('refcode.bin', REFCODE_DATA)
Simon Glassea0fff92019-08-24 07:23:07 -0600164 TestFunctional._MakeInputFile('fsp_m.bin', FSP_M_DATA)
Simon Glassbc6a88f2019-10-20 21:31:35 -0600165 TestFunctional._MakeInputFile('fsp_s.bin', FSP_S_DATA)
Simon Glass998d1482019-10-20 21:31:36 -0600166 TestFunctional._MakeInputFile('fsp_t.bin', FSP_T_DATA)
Simon Glass4f443042016-11-25 20:15:52 -0700167
Simon Glass53e22bf2019-08-24 07:22:53 -0600168 cls._elf_testdir = os.path.join(cls._indir, 'elftest')
169 elf_test.BuildElfTestFiles(cls._elf_testdir)
170
Simon Glasse0ff8552016-11-25 20:15:53 -0700171 # ELF file with a '_dt_ucode_base_size' symbol
Simon Glassf514d8f2019-08-24 07:22:54 -0600172 TestFunctional._MakeInputFile('u-boot',
173 tools.ReadFile(cls.ElfTestFile('u_boot_ucode_ptr')))
Simon Glasse0ff8552016-11-25 20:15:53 -0700174
175 # Intel flash descriptor file
Simon Glass0ba4b3d2020-07-09 18:39:41 -0600176 cls._SetupDescriptor()
Simon Glasse0ff8552016-11-25 20:15:53 -0700177
Simon Glassb986b3b2019-08-24 07:22:43 -0600178 shutil.copytree(cls.TestFile('files'),
179 os.path.join(cls._indir, 'files'))
Simon Glass0a98b282018-09-14 04:57:28 -0600180
Simon Glass83d73c22018-09-14 04:57:26 -0600181 TestFunctional._MakeInputFile('compress', COMPRESS_DATA)
Simon Glass8f5ef892020-10-26 17:40:25 -0600182 TestFunctional._MakeInputFile('compress_big', COMPRESS_DATA_BIG)
Simon Glassdc2f81a2020-09-01 05:13:58 -0600183 TestFunctional._MakeInputFile('bl31.bin', ATF_BL31_DATA)
Simon Glass75989722021-11-23 21:08:59 -0700184 TestFunctional._MakeInputFile('bl2u.bin', ATF_BL2U_DATA)
Bin Meng4c4d6072021-05-10 20:23:33 +0800185 TestFunctional._MakeInputFile('fw_dynamic.bin', OPENSBI_DATA)
Samuel Holland18bd4552020-10-21 21:12:15 -0500186 TestFunctional._MakeInputFile('scp.bin', SCP_DATA)
Simon Glass83d73c22018-09-14 04:57:26 -0600187
Simon Glass6cf99532020-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 Glassfb91d562020-09-06 10:35:33 -0600194 TestFunctional._MakeInputFile('env.txt', ENV_DATA)
195
Simon Glassac62fba2019-07-08 13:18:53 -0600196 # Travis-CI may have an old lz4
Simon Glassb986b3b2019-08-24 07:22:43 -0600197 cls.have_lz4 = True
Simon Glassac62fba2019-07-08 13:18:53 -0600198 try:
199 tools.Run('lz4', '--no-frame-crc', '-c',
Simon Glass3b3e3c02019-10-31 07:42:50 -0600200 os.path.join(cls._indir, 'u-boot.bin'), binary=True)
Simon Glassac62fba2019-07-08 13:18:53 -0600201 except:
Simon Glassb986b3b2019-08-24 07:22:43 -0600202 cls.have_lz4 = False
Simon Glassac62fba2019-07-08 13:18:53 -0600203
Simon Glass4f443042016-11-25 20:15:52 -0700204 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600205 def tearDownClass(cls):
Simon Glass4f443042016-11-25 20:15:52 -0700206 """Remove the temporary input directory and its contents"""
Simon Glassb986b3b2019-08-24 07:22:43 -0600207 if cls.preserve_indir:
208 print('Preserving input dir: %s' % cls._indir)
Simon Glassd5164a72019-07-08 13:18:49 -0600209 else:
Simon Glassb986b3b2019-08-24 07:22:43 -0600210 if cls._indir:
211 shutil.rmtree(cls._indir)
212 cls._indir = None
Simon Glass4f443042016-11-25 20:15:52 -0700213
Simon Glassd5164a72019-07-08 13:18:49 -0600214 @classmethod
Simon Glass8acce602019-07-08 13:18:50 -0600215 def setup_test_args(cls, preserve_indir=False, preserve_outdirs=False,
Simon Glass53cd5d92019-07-08 14:25:29 -0600216 toolpath=None, verbosity=None):
Simon Glassd5164a72019-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 Glass8acce602019-07-08 13:18:50 -0600225 toolpath: ist of paths to use for tools
Simon Glassd5164a72019-07-08 13:18:49 -0600226 """
227 cls.preserve_indir = preserve_indir
228 cls.preserve_outdirs = preserve_outdirs
Simon Glass8acce602019-07-08 13:18:50 -0600229 cls.toolpath = toolpath
Simon Glass53cd5d92019-07-08 14:25:29 -0600230 cls.verbosity = verbosity
Simon Glassd5164a72019-07-08 13:18:49 -0600231
Simon Glassac62fba2019-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 Glassbf574f12019-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 Glass4f443042016-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 Glassbf574f12019-07-20 12:24:09 -0600250 self._CleanupOutputDir()
Simon Glass4f443042016-11-25 20:15:52 -0700251
Simon Glassf86a7362019-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 Glassb8ef5b62018-07-17 13:25:48 -0600274 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600275 def _ResetDtbs(cls):
Simon Glassb8ef5b62018-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 Glass4f443042016-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 Glass53cd5d92019-07-08 14:25:29 -0600294 def _DoBinman(self, *argv):
Simon Glass4f443042016-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 Glass53cd5d92019-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 Glass4f443042016-11-25 20:15:52 -0700306
307 # For testing, you can force an increase in verbosity here
Simon Glass53cd5d92019-07-08 14:25:29 -0600308 # args.verbosity = tout.DEBUG
309 return control.Binman(args)
Simon Glass4f443042016-11-25 20:15:52 -0700310
Simon Glass53af22a2018-07-17 13:25:32 -0600311 def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
Simon Glasseb833d82019-04-25 21:58:34 -0600312 entry_args=None, images=None, use_real_dtb=False,
Simon Glass63aeaeb2021-03-18 20:25:05 +1300313 use_expanded=False, verbosity=None, allow_missing=False,
Heiko Thierya89c8f22022-01-06 11:49:41 +0100314 allow_fake_blobs=False, extra_indirs=None, threads=None,
Simon Glass0427bed2021-11-03 21:09:18 -0600315 test_section_timeout=False, update_fdt_in_elf=None):
Simon Glass4f443042016-11-25 20:15:52 -0700316 """Run binman with a given test file
317
318 Args:
Simon Glass741f2d62018-10-01 12:22:30 -0600319 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass7ae5f312018-06-01 09:38:19 -0600320 debug: True to enable debugging output
Simon Glass3b0c38212018-06-01 09:38:20 -0600321 map: True to output map files for the images
Simon Glass3ab95982018-08-01 15:22:37 -0600322 update_dtb: Update the offset and size of each entry in the device
Simon Glass16b8d6b2018-07-06 10:27:42 -0600323 tree before packing it into the image
Simon Glass0bfa7b02018-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 Glasse9d336d2020-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 Glass63aeaeb2021-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 Glasse9d336d2020-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 Thierya89c8f22022-01-06 11:49:41 +0100337 allow_fake_blobs: Set the '--fake-ext-blobs' flag
Simon Glass6cf99532020-09-01 05:13:59 -0600338 extra_indirs: Extra input directories to add using -I
Simon Glassc69d19c2021-07-06 10:36:37 -0600339 threads: Number of threads to use (None for default, 0 for
340 single-threaded)
Simon Glass7115f002021-11-03 21:09:17 -0600341 test_section_timeout: True to force the first time to timeout, as
342 used in testThreadTimeout()
Simon Glass0427bed2021-11-03 21:09:18 -0600343 update_fdt_in_elf: Value to pass with --update-fdt-in-elf=xxx
Simon Glass7115f002021-11-03 21:09:17 -0600344
345 Returns:
346 int return code, 0 on success
Simon Glass4f443042016-11-25 20:15:52 -0700347 """
Simon Glass53cd5d92019-07-08 14:25:29 -0600348 args = []
Simon Glass7fe91732017-11-13 18:55:00 -0700349 if debug:
350 args.append('-D')
Simon Glass53cd5d92019-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 Glassc69d19c2021-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 Glass53cd5d92019-07-08 14:25:29 -0600362 args += ['build', '-p', '-I', self._indir, '-d', self.TestFile(fname)]
Simon Glass3b0c38212018-06-01 09:38:20 -0600363 if map:
364 args.append('-m')
Simon Glass16b8d6b2018-07-06 10:27:42 -0600365 if update_dtb:
Simon Glass2569e102019-07-08 13:18:47 -0600366 args.append('-u')
Simon Glass93d17412018-09-14 04:57:23 -0600367 if not use_real_dtb:
368 args.append('--fake-dtb')
Simon Glass63aeaeb2021-03-18 20:25:05 +1300369 if not use_expanded:
370 args.append('--no-expanded')
Simon Glass53af22a2018-07-17 13:25:32 -0600371 if entry_args:
Simon Glass50979152019-05-14 15:53:41 -0600372 for arg, value in entry_args.items():
Simon Glass53af22a2018-07-17 13:25:32 -0600373 args.append('-a%s=%s' % (arg, value))
Simon Glass4f9f1052020-07-09 18:39:38 -0600374 if allow_missing:
375 args.append('-M')
Heiko Thierya89c8f22022-01-06 11:49:41 +0100376 if allow_fake_blobs:
377 args.append('--fake-ext-blobs')
Simon Glass0427bed2021-11-03 21:09:18 -0600378 if update_fdt_in_elf:
379 args += ['--update-fdt-in-elf', update_fdt_in_elf]
Simon Glass0bfa7b02018-09-14 04:57:12 -0600380 if images:
381 for image in images:
382 args += ['-i', image]
Simon Glass6cf99532020-09-01 05:13:59 -0600383 if extra_indirs:
384 for indir in extra_indirs:
385 args += ['-I', indir]
Simon Glass7fe91732017-11-13 18:55:00 -0700386 return self._DoBinman(*args)
Simon Glass4f443042016-11-25 20:15:52 -0700387
388 def _SetupDtb(self, fname, outfile='u-boot.dtb'):
Simon Glasse0ff8552016-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 Glass7ae5f312018-06-01 09:38:19 -0600396 outfile: Output filename for compiled device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700397
398 Returns:
Simon Glass7ae5f312018-06-01 09:38:19 -0600399 Contents of device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700400 """
Simon Glassa004f292019-07-20 12:23:49 -0600401 tmpdir = tempfile.mkdtemp(prefix='binmant.')
402 dtb = fdt_util.EnsureCompiled(self.TestFile(fname), tmpdir)
Simon Glass1d0ebf72019-05-14 15:53:42 -0600403 with open(dtb, 'rb') as fd:
Simon Glass4f443042016-11-25 20:15:52 -0700404 data = fd.read()
405 TestFunctional._MakeInputFile(outfile, data)
Simon Glassa004f292019-07-20 12:23:49 -0600406 shutil.rmtree(tmpdir)
Simon Glasse0e62752018-10-01 21:12:41 -0600407 return data
Simon Glass4f443042016-11-25 20:15:52 -0700408
Simon Glass6ed45ba2018-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 Glasse9d336d2020-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 Glass6ed45ba2018-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 Glass63aeaeb2021-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 Glassc69d19c2021-07-06 10:36:37 -0600436 reset_dtbs=True, extra_indirs=None, threads=None):
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600446 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass4f443042016-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 Glass63aeaeb2021-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 Glass3b0c38212018-06-01 09:38:20 -0600453 map: True to output map files for the images
Simon Glass3ab95982018-08-01 15:22:37 -0600454 update_dtb: Update the offset and size of each entry in the device
Simon Glass16b8d6b2018-07-06 10:27:42 -0600455 tree before packing it into the image
Simon Glasse9d336d2020-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 Glass6cf99532020-09-01 05:13:59 -0600462 extra_indirs: Extra input directories to add using -I
Simon Glassc69d19c2021-07-06 10:36:37 -0600463 threads: Number of threads to use (None for default, 0 for
464 single-threaded)
Simon Glasse0ff8552016-11-25 20:15:53 -0700465
466 Returns:
467 Tuple:
468 Resulting image contents
469 Device tree contents
Simon Glass3b0c38212018-06-01 09:38:20 -0600470 Map data showing contents of image (or None if none)
Simon Glassea6922e2018-07-17 13:25:27 -0600471 Output device tree binary filename ('u-boot.dtb' path)
Simon Glass4f443042016-11-25 20:15:52 -0700472 """
Simon Glasse0ff8552016-11-25 20:15:53 -0700473 dtb_data = None
Simon Glass4f443042016-11-25 20:15:52 -0700474 # Use the compiled test file as the u-boot-dtb input
475 if use_real_dtb:
Simon Glasse0ff8552016-11-25 20:15:53 -0700476 dtb_data = self._SetupDtb(fname)
Simon Glass6ed45ba2018-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 Glass4f443042016-11-25 20:15:52 -0700485
486 try:
Simon Glass53af22a2018-07-17 13:25:32 -0600487 retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
Simon Glass6cf99532020-09-01 05:13:59 -0600488 entry_args=entry_args, use_real_dtb=use_real_dtb,
Simon Glassc69d19c2021-07-06 10:36:37 -0600489 use_expanded=use_expanded, extra_indirs=extra_indirs,
490 threads=threads)
Simon Glass4f443042016-11-25 20:15:52 -0700491 self.assertEqual(0, retcode)
Simon Glass6ed45ba2018-09-14 04:57:24 -0600492 out_dtb_fname = tools.GetOutputFilename('u-boot.dtb.out')
Simon Glass4f443042016-11-25 20:15:52 -0700493
494 # Find the (only) image, read it and return its contents
495 image = control.images['image']
Simon Glass16b8d6b2018-07-06 10:27:42 -0600496 image_fname = tools.GetOutputFilename('image.bin')
497 self.assertTrue(os.path.exists(image_fname))
Simon Glass3b0c38212018-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 Glass1d0ebf72019-05-14 15:53:42 -0600504 with open(image_fname, 'rb') as fd:
Simon Glass16b8d6b2018-07-06 10:27:42 -0600505 return fd.read(), dtb_data, map_data, out_dtb_fname
Simon Glass4f443042016-11-25 20:15:52 -0700506 finally:
507 # Put the test file back
Simon Glass6ed45ba2018-09-14 04:57:24 -0600508 if reset_dtbs and use_real_dtb:
Simon Glassb8ef5b62018-07-17 13:25:48 -0600509 self._ResetDtbs()
Simon Glass4f443042016-11-25 20:15:52 -0700510
Simon Glass3c081312019-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 Glasse0ff8552016-11-25 20:15:53 -0700522 def _DoReadFile(self, fname, use_real_dtb=False):
Simon Glass7ae5f312018-06-01 09:38:19 -0600523 """Helper function which discards the device-tree binary
524
525 Args:
Simon Glass741f2d62018-10-01 12:22:30 -0600526 fname: Device-tree source filename to use (e.g. 005_simple.dts)
Simon Glass7ae5f312018-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 Glassea6922e2018-07-17 13:25:27 -0600531
532 Returns:
533 Resulting image contents
Simon Glass7ae5f312018-06-01 09:38:19 -0600534 """
Simon Glasse0ff8552016-11-25 20:15:53 -0700535 return self._DoReadFileDtb(fname, use_real_dtb)[0]
536
Simon Glass4f443042016-11-25 20:15:52 -0700537 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600538 def _MakeInputFile(cls, fname, contents):
Simon Glass4f443042016-11-25 20:15:52 -0700539 """Create a new test input file, creating directories as needed
540
541 Args:
Simon Glass3ab95982018-08-01 15:22:37 -0600542 fname: Filename to create
Simon Glass4f443042016-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 Glassb986b3b2019-08-24 07:22:43 -0600547 pathname = os.path.join(cls._indir, fname)
Simon Glass4f443042016-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 Glassb986b3b2019-08-24 07:22:43 -0600556 def _MakeInputDir(cls, dirname):
Simon Glass0ef87aa2018-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 Glassb986b3b2019-08-24 07:22:43 -0600565 pathname = os.path.join(cls._indir, dirname)
Simon Glass0ef87aa2018-07-17 13:25:44 -0600566 if not os.path.exists(pathname):
567 os.makedirs(pathname)
568 return pathname
569
570 @classmethod
Simon Glassb986b3b2019-08-24 07:22:43 -0600571 def _SetupSplElf(cls, src_fname='bss_data'):
Simon Glass11ae93e2018-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 Glassc9a0b272019-08-24 07:22:59 -0600577 TestFunctional._MakeInputFile('spl/u-boot-spl',
578 tools.ReadFile(cls.ElfTestFile(src_fname)))
Simon Glass11ae93e2018-10-01 21:12:47 -0600579
580 @classmethod
Simon Glass2090f1e2019-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 Glass0ba4b3d2020-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 Glassb986b3b2019-08-24 07:22:43 -0600596 def TestFile(cls, fname):
597 return os.path.join(cls._binman_dir, 'test', fname)
Simon Glass4f443042016-11-25 20:15:52 -0700598
Simon Glass53e22bf2019-08-24 07:22:53 -0600599 @classmethod
600 def ElfTestFile(cls, fname):
601 return os.path.join(cls._elf_testdir, fname)
602
Simon Glass4f443042016-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 Glass1fc62de2019-05-17 22:00:50 -0600613 self.fail("Error: '%s' not found in '%s'" % (grep_list, target))
Simon Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600621 offset = 0
Simon Glass4f443042016-11-25 20:15:52 -0700622 for entry in entries.values():
Simon Glass3ab95982018-08-01 15:22:37 -0600623 self.assertEqual(offset, entry.offset)
624 offset += entry.size
Simon Glass4f443042016-11-25 20:15:52 -0700625
Simon Glasse0ff8552016-11-25 20:15:53 -0700626 def GetFdtLen(self, dtb):
Simon Glass7ae5f312018-06-01 09:38:19 -0600627 """Get the totalsize field from a device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700628
629 Args:
Simon Glass7ae5f312018-06-01 09:38:19 -0600630 dtb: Device-tree binary contents
Simon Glasse0ff8552016-11-25 20:15:53 -0700631
632 Returns:
Simon Glass7ae5f312018-06-01 09:38:19 -0600633 Total size of device-tree binary, from the header
Simon Glasse0ff8552016-11-25 20:15:53 -0700634 """
635 return struct.unpack('>L', dtb[4:8])[0]
636
Simon Glass086cec92019-07-08 14:25:27 -0600637 def _GetPropTree(self, dtb, prop_names, prefix='/binman/'):
Simon Glass16b8d6b2018-07-06 10:27:42 -0600638 def AddNode(node, path):
639 if node.name != '/':
640 path += '/' + node.name
Simon Glass086cec92019-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 Glass16b8d6b2018-07-06 10:27:42 -0600646 for subnode in node.subnodes:
Simon Glass16b8d6b2018-07-06 10:27:42 -0600647 AddNode(subnode, path)
648
649 tree = {}
Simon Glass16b8d6b2018-07-06 10:27:42 -0600650 AddNode(dtb.GetRoot(), '')
651 return tree
652
Simon Glass4f443042016-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 Glass61adb2d2021-03-18 20:25:13 +1300660 help_file = os.path.join(self._binman_dir, 'README.rst')
Tom Rini3759df02018-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 Glass4f443042016-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 Glass61adb2d2021-03-18 20:25:13 +1300673 help_file = os.path.join(self._binman_dir, 'README.rst')
Simon Glass4f443042016-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 Glass4f443042016-11-25 20:15:52 -0700684 def testBoard(self):
685 """Test that we can run it with a specific board"""
Simon Glass741f2d62018-10-01 12:22:30 -0600686 self._SetupDtb('005_simple.dts', 'sandbox/u-boot.dtb')
Simon Glass4f443042016-11-25 20:15:52 -0700687 TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
Simon Glass63aeaeb2021-03-18 20:25:05 +1300688 result = self._DoBinman('build', '-n', '-b', 'sandbox')
Simon Glass4f443042016-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 Glass53cd5d92019-07-08 14:25:29 -0600694 result = self._DoBinman('build')
Simon Glass4f443042016-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 Glass7ae5f312018-06-01 09:38:19 -0600699 """Test that an invalid device-tree file generates an error"""
Simon Glass4f443042016-11-25 20:15:52 -0700700 with self.assertRaises(Exception) as e:
Simon Glass53cd5d92019-07-08 14:25:29 -0600701 self._RunBinman('build', '-d', 'missing_file')
Simon Glass4f443042016-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 Glass7ae5f312018-06-01 09:38:19 -0600707 """Test that an invalid device-tree source file generates an error
Simon Glass4f443042016-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 Glass53cd5d92019-07-08 14:25:29 -0600713 self._RunBinman('build', '-d', self.TestFile('001_invalid.dts'))
Simon Glass4f443042016-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 Glass53cd5d92019-07-08 14:25:29 -0600720 self._DoBinman('build', '-d', self.TestFile('002_missing_node.dts'))
Simon Glass4f443042016-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 Glass53cd5d92019-07-08 14:25:29 -0600725 result = self._RunBinman('build', '-d', self.TestFile('003_empty.dts'))
Simon Glass4f443042016-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 Glass53cd5d92019-07-08 14:25:29 -0600732 result = self._RunBinman('build', '-d',
Simon Glass741f2d62018-10-01 12:22:30 -0600733 self.TestFile('004_invalid_entry.dts'))
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600739 data = self._DoReadFile('005_simple.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700740 self.assertEqual(U_BOOT_DATA, data)
741
Simon Glass7fe91732017-11-13 18:55:00 -0700742 def testSimpleDebug(self):
743 """Test a simple binman run with debugging enabled"""
Simon Glasse2705fa2019-07-08 14:25:53 -0600744 self._DoTestFile('005_simple.dts', debug=True)
Simon Glass7fe91732017-11-13 18:55:00 -0700745
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600751 retcode = self._DoTestFile('006_dual_image.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700752 self.assertEqual(0, retcode)
753
754 image = control.images['image1']
Simon Glass8beb11e2019-07-08 14:25:47 -0600755 self.assertEqual(len(U_BOOT_DATA), image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700756 fname = tools.GetOutputFilename('image1.bin')
757 self.assertTrue(os.path.exists(fname))
Simon Glass1d0ebf72019-05-14 15:53:42 -0600758 with open(fname, 'rb') as fd:
Simon Glass4f443042016-11-25 20:15:52 -0700759 data = fd.read()
760 self.assertEqual(U_BOOT_DATA, data)
761
762 image = control.images['image2']
Simon Glass8beb11e2019-07-08 14:25:47 -0600763 self.assertEqual(3 + len(U_BOOT_DATA) + 5, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700764 fname = tools.GetOutputFilename('image2.bin')
765 self.assertTrue(os.path.exists(fname))
Simon Glass1d0ebf72019-05-14 15:53:42 -0600766 with open(fname, 'rb') as fd:
Simon Glass4f443042016-11-25 20:15:52 -0700767 data = fd.read()
768 self.assertEqual(U_BOOT_DATA, data[3:7])
Simon Glasse6d85ff2019-05-14 15:53:47 -0600769 self.assertEqual(tools.GetBytes(0, 3), data[:3])
770 self.assertEqual(tools.GetBytes(0, 5), data[7:])
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600775 self._DoTestFile('007_bad_align.dts')
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600781 retcode = self._DoTestFile('008_pack.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700782 self.assertEqual(0, retcode)
783 self.assertIn('image', control.images)
784 image = control.images['image']
Simon Glass8f1da502018-06-01 09:38:12 -0600785 entries = image.GetEntries()
Simon Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600791 self.assertEqual(0, entry.offset)
Simon Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600797 self.assertEqual(16, entry.offset)
Simon Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600803 self.assertEqual(20, entry.offset)
Simon Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600810 self.assertEqual(43, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700811 self.assertEqual(len(U_BOOT_DATA), entry.size)
812
Simon Glass3ab95982018-08-01 15:22:37 -0600813 # Fifth u-boot, placed at a fixed offset
Simon Glass4f443042016-11-25 20:15:52 -0700814 self.assertIn('u-boot-fixed', entries)
815 entry = entries['u-boot-fixed']
Simon Glass3ab95982018-08-01 15:22:37 -0600816 self.assertEqual(61, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700817 self.assertEqual(len(U_BOOT_DATA), entry.size)
818
Simon Glass8beb11e2019-07-08 14:25:47 -0600819 self.assertEqual(65, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700820
821 def testPackExtra(self):
822 """Test that extra packing feature works as expected"""
Simon Glass4eec34c2020-10-26 17:40:10 -0600823 data, _, _, out_dtb_fname = self._DoReadFileDtb('009_pack_extra.dts',
824 update_dtb=True)
Simon Glass4f443042016-11-25 20:15:52 -0700825
Simon Glass4f443042016-11-25 20:15:52 -0700826 self.assertIn('image', control.images)
827 image = control.images['image']
Simon Glass8f1da502018-06-01 09:38:12 -0600828 entries = image.GetEntries()
Simon Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600834 self.assertEqual(0, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700835 self.assertEqual(3, entry.pad_before)
836 self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
Simon Glassef439ed2020-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 Glass4f443042016-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 Glassef439ed2020-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 Glass4f443042016-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 Glassef439ed2020-10-26 17:40:08 -0600854 self.assertEqual(pos, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700855 self.assertEqual(32, entry.size)
Simon Glassef439ed2020-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 Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600864 self.assertEqual(48, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700865 self.assertEqual(16, entry.size)
Simon Glassef439ed2020-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 Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600874 self.assertEqual(64, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700875 self.assertEqual(64, entry.size)
Simon Glassef439ed2020-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 Glass4f443042016-11-25 20:15:52 -0700879
880 self.CheckNoGaps(entries)
Simon Glass8beb11e2019-07-08 14:25:47 -0600881 self.assertEqual(128, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700882
Simon Glass4eec34c2020-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 Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600916 self._DoTestFile('010_pack_align_power2.dts')
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600923 self._DoTestFile('011_pack_align_size_power2.dts')
Simon Glass4f443042016-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 Glass3ab95982018-08-01 15:22:37 -0600928 """Test detection of an offset that does not match its alignment"""
Simon Glass4f443042016-11-25 20:15:52 -0700929 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -0600930 self._DoTestFile('012_pack_inv_align.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600931 self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600937 self._DoTestFile('013_pack_inv_size_align.dts')
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600944 self._DoTestFile('014_pack_overlap.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600945 self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600952 self._DoTestFile('015_pack_overflow.dts')
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600959 self._DoTestFile('016_pack_image_overflow.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600960 self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600965 retcode = self._DoTestFile('017_pack_image_size.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700966 self.assertEqual(0, retcode)
967 self.assertIn('image', control.images)
968 image = control.images['image']
Simon Glass8beb11e2019-07-08 14:25:47 -0600969 self.assertEqual(7, image.size)
Simon Glass4f443042016-11-25 20:15:52 -0700970
971 def testPackImageSizeAlign(self):
972 """Test that image size alignemnt works as expected"""
Simon Glass741f2d62018-10-01 12:22:30 -0600973 retcode = self._DoTestFile('018_pack_image_align.dts')
Simon Glass4f443042016-11-25 20:15:52 -0700974 self.assertEqual(0, retcode)
975 self.assertIn('image', control.images)
976 image = control.images['image']
Simon Glass8beb11e2019-07-08 14:25:47 -0600977 self.assertEqual(16, image.size)
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600982 self._DoTestFile('019_pack_inv_image_align.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600983 self.assertIn("Section '/binman': Size 0x7 (7) does not match "
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -0600989 self._DoTestFile('020_pack_inv_image_align_power2.dts')
Simon Glass8beb11e2019-07-08 14:25:47 -0600990 self.assertIn("Image '/binman': Alignment size 131 must be a power of "
Simon Glass4f443042016-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 Glass11ae93e2018-10-01 21:12:47 -0600995 self._SetupSplElf()
Simon Glass741f2d62018-10-01 12:22:30 -0600996 data = self._DoReadFile('021_image_pad.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -0600997 self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0xff, 1) +
998 U_BOOT_DATA, data)
Simon Glass4f443042016-11-25 20:15:52 -0700999
1000 def testImageName(self):
1001 """Test that image files can be named"""
Simon Glass741f2d62018-10-01 12:22:30 -06001002 retcode = self._DoTestFile('022_image_name.dts')
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -06001014 data = self._DoReadFile('023_blob.dts')
Simon Glass4f443042016-11-25 20:15:52 -07001015 self.assertEqual(BLOB_DATA, data)
1016
1017 def testPackSorted(self):
1018 """Test that entries can be sorted"""
Simon Glass11ae93e2018-10-01 21:12:47 -06001019 self._SetupSplElf()
Simon Glass741f2d62018-10-01 12:22:30 -06001020 data = self._DoReadFile('024_sorted.dts')
Simon Glasse6d85ff2019-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 Glass4f443042016-11-25 20:15:52 -07001023
Simon Glass3ab95982018-08-01 15:22:37 -06001024 def testPackZeroOffset(self):
1025 """Test that an entry at offset 0 is not given a new offset"""
Simon Glass4f443042016-11-25 20:15:52 -07001026 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001027 self._DoTestFile('025_pack_zero_size.dts')
Simon Glass3ab95982018-08-01 15:22:37 -06001028 self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
Simon Glass4f443042016-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 Glass741f2d62018-10-01 12:22:30 -06001034 data = self._DoReadFile('026_pack_u_boot_dtb.dts')
Simon Glass4f443042016-11-25 20:15:52 -07001035 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
Simon Glasse0ff8552016-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 Glass741f2d62018-10-01 12:22:30 -06001040 self._DoTestFile('027_pack_4gb_no_size.dts')
Simon Glass8beb11e2019-07-08 14:25:47 -06001041 self.assertIn("Image '/binman': Section size must be provided when "
Simon Glasse0ff8552016-11-25 20:15:53 -07001042 "using end-at-4gb", str(e.exception))
1043
Jagdish Gediya94b57db2018-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 Glassdfdd2b62019-08-24 07:23:02 -06001048 self._DoTestFile('098_4gb_and_skip_at_start_together.dts')
Simon Glass8beb11e2019-07-08 14:25:47 -06001049 self.assertIn("Image '/binman': Provide either 'end-at-4gb' or "
Jagdish Gediya94b57db2018-09-03 21:35:07 +05301050 "'skip-at-start'", str(e.exception))
1051
Simon Glasse0ff8552016-11-25 20:15:53 -07001052 def testPackX86RomOutside(self):
Simon Glass3ab95982018-08-01 15:22:37 -06001053 """Test that the end-at-4gb property checks for offset boundaries"""
Simon Glasse0ff8552016-11-25 20:15:53 -07001054 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001055 self._DoTestFile('028_pack_4gb_outside.dts')
Simon Glasse6bed4f2020-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 Glasse0ff8552016-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 Glass11ae93e2018-10-01 21:12:47 -06001063 self._SetupSplElf()
Simon Glass9255f3c2019-08-24 07:23:01 -06001064 data = self._DoReadFile('029_x86_rom.dts')
Simon Glasseb0086f2019-08-24 07:23:04 -06001065 self.assertEqual(U_BOOT_DATA + tools.GetBytes(0, 3) + U_BOOT_SPL_DATA +
Simon Glasse6d85ff2019-05-14 15:53:47 -06001066 tools.GetBytes(0, 2), data)
Simon Glasse0ff8552016-11-25 20:15:53 -07001067
1068 def testPackX86RomMeNoDesc(self):
1069 """Test that an invalid Intel descriptor entry is detected"""
Simon Glass0ba4b3d2020-07-09 18:39:41 -06001070 try:
Simon Glass52b10dd2020-07-25 15:11:19 -06001071 TestFunctional._MakeInputFile('descriptor-empty.bin', b'')
Simon Glass0ba4b3d2020-07-09 18:39:41 -06001072 with self.assertRaises(ValueError) as e:
Simon Glass52b10dd2020-07-25 15:11:19 -06001073 self._DoTestFile('163_x86_rom_me_empty.dts')
Simon Glass0ba4b3d2020-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 Glasse0ff8552016-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 Glass9255f3c2019-08-24 07:23:01 -06001082 self._DoTestFile('030_x86_rom_me_no_desc.dts')
Simon Glass3ab95982018-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 Glasse0ff8552016-11-25 20:15:53 -07001086
1087 def testPackX86RomMe(self):
1088 """Test that an x86 ROM with an ME region can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001089 data = self._DoReadFile('031_x86_rom_me.dts')
Simon Glassc5ac1382019-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 Glasse0ff8552016-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 Glass9255f3c2019-08-24 07:23:01 -06001097 data = self._DoReadFile('032_intel_vga.dts')
Simon Glasse0ff8552016-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 Glass9255f3c2019-08-24 07:23:01 -06001102 data = self._DoReadFile('033_x86_start16.dts')
Simon Glasse0ff8552016-11-25 20:15:53 -07001103 self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
1104
Jagdish Gediya9d368f32018-09-03 21:35:08 +05301105 def testPackPowerpcMpc85xxBootpgResetvec(self):
1106 """Test that an image with powerpc-mpc85xx-bootpg-resetvec can be
1107 created"""
Simon Glassdfdd2b62019-08-24 07:23:02 -06001108 data = self._DoReadFile('150_powerpc_mpc85xx_bootpg_resetvec.dts')
Jagdish Gediya9d368f32018-09-03 21:35:08 +05301109 self.assertEqual(PPC_MPC85XX_BR_DATA, data[:len(PPC_MPC85XX_BR_DATA)])
1110
Simon Glass736bb0a2018-07-06 10:27:17 -06001111 def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
Simon Glassadc57012018-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 Glass736bb0a2018-07-06 10:27:17 -06001117 ucode_second: True if the microsecond entry is second instead of
1118 third
Simon Glassadc57012018-07-06 10:27:16 -06001119
1120 Returns:
1121 Tuple:
1122 Contents of first region (U-Boot or SPL)
Simon Glass3ab95982018-08-01 15:22:37 -06001123 Offset and size components of microcode pointer, as inserted
Simon Glassadc57012018-07-06 10:27:16 -06001124 in the above (two 4-byte words)
1125 """
Simon Glass6b187df2017-11-12 21:52:27 -07001126 data = self._DoReadFile(dts_fname, True)
Simon Glasse0ff8552016-11-25 20:15:53 -07001127
1128 # Now check the device tree has no microcode
Simon Glass736bb0a2018-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 Glasse0ff8552016-11-25 20:15:53 -07001139 fname = tools.GetOutputFilename('test.dtb')
1140 with open(fname, 'wb') as fd:
Simon Glassadc57012018-07-06 10:27:16 -06001141 fd.write(dtb_with_ucode)
Simon Glassec3f3782017-05-27 07:38:29 -06001142 dtb = fdt.FdtScan(fname)
1143 ucode = dtb.GetNode('/microcode')
Simon Glasse0ff8552016-11-25 20:15:53 -07001144 self.assertTrue(ucode)
1145 for node in ucode.subnodes:
1146 self.assertFalse(node.props.get('data'))
1147
Simon Glasse0ff8552016-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 Glass87722132017-11-12 21:52:26 -07001150 # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
Simon Glasse0ff8552016-11-25 20:15:53 -07001151 ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
1152 0x78235609)
Simon Glassadc57012018-07-06 10:27:16 -06001153 self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
Simon Glasse0ff8552016-11-25 20:15:53 -07001154
1155 # Check that the microcode pointer was inserted. It should match the
Simon Glass3ab95982018-08-01 15:22:37 -06001156 # expected offset and size
Simon Glasse0ff8552016-11-25 20:15:53 -07001157 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
1158 len(ucode_data))
Simon Glass736bb0a2018-07-06 10:27:17 -06001159 u_boot = data[:len(nodtb_data)]
1160 return u_boot, pos_and_size
Simon Glass6b187df2017-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 Glass741f2d62018-10-01 12:22:30 -06001171 first, pos_and_size = self._RunMicrocodeTest('034_x86_ucode.dts',
Simon Glass6b187df2017-11-12 21:52:27 -07001172 U_BOOT_NODTB_DATA)
Simon Glassc6c10e72019-05-17 22:00:46 -06001173 self.assertEqual(b'nodtb with microcode' + pos_and_size +
1174 b' somewhere in here', first)
Simon Glasse0ff8552016-11-25 20:15:53 -07001175
Simon Glass160a7662017-05-27 07:38:26 -06001176 def _RunPackUbootSingleMicrocode(self):
Simon Glasse0ff8552016-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 Glass741f2d62018-10-01 12:22:30 -06001188 data = self._DoReadFile('035_x86_single_ucode.dts', True)
Simon Glasse0ff8552016-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 Glass160a7662017-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 Glasse0ff8552016-11-25 20:15:53 -07001199
Simon Glass160a7662017-05-27 07:38:26 -06001200 # Check that the microcode pointer was inserted. It should match the
Simon Glass3ab95982018-08-01 15:22:37 -06001201 # expected offset and size
Simon Glass160a7662017-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 Glassc6c10e72019-05-17 22:00:46 -06001205 self.assertEqual(b'nodtb with microcode' + pos_and_size +
1206 b' somewhere in here', first)
Simon Glassc49deb82016-11-25 20:15:54 -07001207
Simon Glass75db0862016-11-25 20:15:55 -07001208 def testPackUbootSingleMicrocode(self):
1209 """Test that x86 microcode can be handled correctly with fdt_normal.
1210 """
Simon Glass160a7662017-05-27 07:38:26 -06001211 self._RunPackUbootSingleMicrocode()
Simon Glass75db0862016-11-25 20:15:55 -07001212
Simon Glassc49deb82016-11-25 20:15:54 -07001213 def testUBootImg(self):
1214 """Test that u-boot.img can be put in a file"""
Simon Glass741f2d62018-10-01 12:22:30 -06001215 data = self._DoReadFile('036_u_boot_img.dts')
Simon Glassc49deb82016-11-25 20:15:54 -07001216 self.assertEqual(U_BOOT_IMG_DATA, data)
Simon Glass75db0862016-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 Glass741f2d62018-10-01 12:22:30 -06001221 self._DoReadFile('037_x86_no_ucode.dts', True)
Simon Glass75db0862016-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 Glass741f2d62018-10-01 12:22:30 -06001228 self._DoReadFile('038_x86_ucode_missing_node.dts', True)
Simon Glass75db0862016-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 Glass741f2d62018-10-01 12:22:30 -06001235 self._DoReadFile('039_x86_ucode_missing_node2.dts', True)
Simon Glass75db0862016-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 Glass75db0862016-11-25 20:15:55 -07001242 try:
Simon Glassbccd91d2019-08-24 07:22:55 -06001243 TestFunctional._MakeInputFile('u-boot',
1244 tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
Simon Glass75db0862016-11-25 20:15:55 -07001245
1246 with self.assertRaises(ValueError) as e:
Simon Glass160a7662017-05-27 07:38:26 -06001247 self._RunPackUbootSingleMicrocode()
Simon Glass75db0862016-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 Glassf514d8f2019-08-24 07:22:54 -06001253 TestFunctional._MakeInputFile('u-boot',
1254 tools.ReadFile(self.ElfTestFile('u_boot_ucode_ptr')))
Simon Glass75db0862016-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 Glass741f2d62018-10-01 12:22:30 -06001259 self._DoReadFile('040_x86_ucode_not_in_image.dts', True)
Simon Glass75db0862016-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 Glass25ac0e62018-06-01 09:38:14 -06001262 "section ranging from 00000000 to 0000002e", str(e.exception))
Simon Glass75db0862016-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 Glassbccd91d2019-08-24 07:22:55 -06001266 TestFunctional._MakeInputFile('u-boot',
1267 tools.ReadFile(self.ElfTestFile('u_boot_no_ucode_ptr')))
Simon Glass741f2d62018-10-01 12:22:30 -06001268 data, dtb, _, _ = self._DoReadFileDtb('044_x86_optional_ucode.dts', True)
Simon Glass75db0862016-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 Glasse6d85ff2019-05-14 15:53:47 -06001279 self.assertEqual(tools.GetBytes(0, 0x200 - used_len), third)
Simon Glass75db0862016-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 Glass741f2d62018-10-01 12:22:30 -06001284 self._DoReadFile('041_unknown_pos_size.dts', True)
Simon Glass3ab95982018-08-01 15:22:37 -06001285 self.assertIn("Section '/binman': Unable to set offset/size for unknown "
Simon Glass75db0862016-11-25 20:15:55 -07001286 "entry 'invalid-entry'", str(e.exception))
Simon Glassda229092016-11-25 20:15:56 -07001287
1288 def testPackFsp(self):
1289 """Test that an image with a FSP binary can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001290 data = self._DoReadFile('042_intel_fsp.dts')
Simon Glassda229092016-11-25 20:15:56 -07001291 self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
1292
1293 def testPackCmc(self):
Bin Meng59ea8c22017-08-15 22:41:54 -07001294 """Test that an image with a CMC binary can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001295 data = self._DoReadFile('043_intel_cmc.dts')
Simon Glassda229092016-11-25 20:15:56 -07001296 self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
Bin Meng59ea8c22017-08-15 22:41:54 -07001297
1298 def testPackVbt(self):
1299 """Test that an image with a VBT binary can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001300 data = self._DoReadFile('046_intel_vbt.dts')
Bin Meng59ea8c22017-08-15 22:41:54 -07001301 self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
Simon Glass9fc60b42017-11-12 21:52:22 -07001302
Simon Glass56509842017-11-12 21:52:25 -07001303 def testSplBssPad(self):
1304 """Test that we can pad SPL's BSS with zeros"""
Simon Glass6b187df2017-11-12 21:52:27 -07001305 # ELF file with a '__bss_size' symbol
Simon Glass11ae93e2018-10-01 21:12:47 -06001306 self._SetupSplElf()
Simon Glass741f2d62018-10-01 12:22:30 -06001307 data = self._DoReadFile('047_spl_bss_pad.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -06001308 self.assertEqual(U_BOOT_SPL_DATA + tools.GetBytes(0, 10) + U_BOOT_DATA,
1309 data)
Simon Glass56509842017-11-12 21:52:25 -07001310
Simon Glass86af5112018-10-01 21:12:42 -06001311 def testSplBssPadMissing(self):
1312 """Test that a missing symbol is detected"""
Simon Glass11ae93e2018-10-01 21:12:47 -06001313 self._SetupSplElf('u_boot_ucode_ptr')
Simon Glassb50e5612017-11-13 18:54:54 -07001314 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06001315 self._DoReadFile('047_spl_bss_pad.dts')
Simon Glassb50e5612017-11-13 18:54:54 -07001316 self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
1317 str(e.exception))
1318
Simon Glass87722132017-11-12 21:52:26 -07001319 def testPackStart16Spl(self):
Simon Glass35b384c2018-09-14 04:57:10 -06001320 """Test that an image with an x86 start16 SPL region can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001321 data = self._DoReadFile('048_x86_start16_spl.dts')
Simon Glass87722132017-11-12 21:52:26 -07001322 self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
1323
Simon Glass736bb0a2018-07-06 10:27:17 -06001324 def _PackUbootSplMicrocode(self, dts, ucode_second=False):
1325 """Helper function for microcode tests
Simon Glass6b187df2017-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 Glass736bb0a2018-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 Glass6b187df2017-11-12 21:52:27 -07001337 """
Simon Glass11ae93e2018-10-01 21:12:47 -06001338 self._SetupSplElf('u_boot_ucode_ptr')
Simon Glass736bb0a2018-07-06 10:27:17 -06001339 first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
1340 ucode_second=ucode_second)
Simon Glassc6c10e72019-05-17 22:00:46 -06001341 self.assertEqual(b'splnodtb with microc' + pos_and_size +
1342 b'ter somewhere in here', first)
Simon Glass6b187df2017-11-12 21:52:27 -07001343
Simon Glass736bb0a2018-07-06 10:27:17 -06001344 def testPackUbootSplMicrocode(self):
1345 """Test that x86 microcode can be handled correctly in SPL"""
Simon Glass741f2d62018-10-01 12:22:30 -06001346 self._PackUbootSplMicrocode('049_x86_ucode_spl.dts')
Simon Glass736bb0a2018-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 Glass741f2d62018-10-01 12:22:30 -06001355 self._PackUbootSplMicrocode('058_x86_ucode_spl_needs_retry.dts',
Simon Glass736bb0a2018-07-06 10:27:17 -06001356 ucode_second=True)
1357
Simon Glassca4f4ff2017-11-12 21:52:28 -07001358 def testPackMrc(self):
1359 """Test that an image with an MRC binary can be created"""
Simon Glass741f2d62018-10-01 12:22:30 -06001360 data = self._DoReadFile('050_intel_mrc.dts')
Simon Glassca4f4ff2017-11-12 21:52:28 -07001361 self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
1362
Simon Glass47419ea2017-11-13 18:54:55 -07001363 def testSplDtb(self):
1364 """Test that an image with spl/u-boot-spl.dtb can be created"""
Simon Glass741f2d62018-10-01 12:22:30 -06001365 data = self._DoReadFile('051_u_boot_spl_dtb.dts')
Simon Glass47419ea2017-11-13 18:54:55 -07001366 self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
1367
Simon Glass4e6fdbe2017-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 Glass0fe44dc2021-04-25 08:39:32 +12001370 self._SetupSplElf()
Simon Glass741f2d62018-10-01 12:22:30 -06001371 data = self._DoReadFile('052_u_boot_spl_nodtb.dts')
Simon Glass4e6fdbe2017-11-13 18:54:56 -07001372 self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
1373
Simon Glass3d433382021-03-21 18:24:30 +13001374 def checkSymbols(self, dts, base_data, u_boot_offset, entry_args=None,
1375 use_expanded=False):
Simon Glassf5898822021-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 Glass3d433382021-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 Glassf5898822021-03-18 20:24:56 +13001387 """
Simon Glass1542c8b2019-08-24 07:22:56 -06001388 elf_fname = self.ElfTestFile('u_boot_binman_syms')
Simon Glass19790632017-11-13 18:55:01 -07001389 syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
1390 addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
Simon Glassf5898822021-03-18 20:24:56 +13001391 self.assertEqual(syms['_binman_u_boot_spl_any_prop_offset'].address,
1392 addr)
Simon Glass19790632017-11-13 18:55:01 -07001393
Simon Glass11ae93e2018-10-01 21:12:47 -06001394 self._SetupSplElf('u_boot_binman_syms')
Simon Glass3d433382021-03-21 18:24:30 +13001395 data = self._DoReadFileDtb(dts, entry_args=entry_args,
1396 use_expanded=use_expanded)[0]
Simon Glassf5898822021-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 Glasse6d85ff2019-05-14 15:53:47 -06001404 tools.GetBytes(0xff, 1) + U_BOOT_DATA + sym_values +
Simon Glassf5898822021-03-18 20:24:56 +13001405 base_data[20:])
Simon Glass19790632017-11-13 18:55:01 -07001406 self.assertEqual(expected, data)
1407
Simon Glassf5898822021-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 Glasse9e0db82021-03-21 18:24:29 +13001414 self.checkSymbols('196_symbols_nodtb.dts',
Simon Glassf5898822021-03-18 20:24:56 +13001415 U_BOOT_SPL_NODTB_DATA + U_BOOT_SPL_DTB_DATA,
1416 0x38)
1417
Simon Glassdd57c132018-06-01 09:38:11 -06001418 def testPackUnitAddress(self):
1419 """Test that we support multiple binaries with the same name"""
Simon Glass741f2d62018-10-01 12:22:30 -06001420 data = self._DoReadFile('054_unit_address.dts')
Simon Glassdd57c132018-06-01 09:38:11 -06001421 self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
1422
Simon Glass18546952018-06-01 09:38:16 -06001423 def testSections(self):
1424 """Basic test of sections"""
Simon Glass741f2d62018-10-01 12:22:30 -06001425 data = self._DoReadFile('055_sections.dts')
Simon Glassc6c10e72019-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 Glass18546952018-06-01 09:38:16 -06001429 self.assertEqual(expected, data)
Simon Glass9fc60b42017-11-12 21:52:22 -07001430
Simon Glass3b0c38212018-06-01 09:38:20 -06001431 def testMap(self):
1432 """Tests outputting a map of the images"""
Simon Glass741f2d62018-10-01 12:22:30 -06001433 _, _, map_data, _ = self._DoReadFileDtb('055_sections.dts', map=True)
Simon Glass1be70d22018-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 Glass3b0c38212018-06-01 09:38:20 -06001442''', map_data)
1443
Simon Glassc8d48ef2018-06-01 09:38:21 -06001444 def testNamePrefix(self):
1445 """Tests that name prefixes are used"""
Simon Glass741f2d62018-10-01 12:22:30 -06001446 _, _, map_data, _ = self._DoReadFileDtb('056_name_prefix.dts', map=True)
Simon Glass1be70d22018-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 Glassc8d48ef2018-06-01 09:38:21 -06001453''', map_data)
1454
Simon Glass736bb0a2018-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 Glass741f2d62018-10-01 12:22:30 -06001458 self._DoReadFile('057_unknown_contents.dts', True)
Simon Glass8beb11e2019-07-08 14:25:47 -06001459 self.assertIn("Image '/binman': Internal error: Could not complete "
Simon Glass16287932020-04-17 18:09:03 -06001460 "processing of contents: remaining ["
1461 "<binman.etype._testing.Entry__testing ", str(e.exception))
Simon Glass736bb0a2018-07-06 10:27:17 -06001462
Simon Glass5c890232018-07-06 10:27:19 -06001463 def testBadChangeSize(self):
1464 """Test that trying to change the size of an entry fails"""
Simon Glassc52c9e72019-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 Glass79d3c582019-07-20 12:23:57 -06001469 self.assertIn("Node '/binman/_testing': Cannot update entry size from 2 to 3",
Simon Glassc52c9e72019-07-08 14:25:37 -06001470 str(e.exception))
1471 finally:
1472 state.SetAllowEntryExpansion(True)
Simon Glass5c890232018-07-06 10:27:19 -06001473
Simon Glass16b8d6b2018-07-06 10:27:42 -06001474 def testUpdateFdt(self):
Simon Glass3ab95982018-08-01 15:22:37 -06001475 """Test that we can update the device tree with offset/size info"""
Simon Glass741f2d62018-10-01 12:22:30 -06001476 _, _, _, out_dtb_fname = self._DoReadFileDtb('060_fdt_update.dts',
Simon Glass16b8d6b2018-07-06 10:27:42 -06001477 update_dtb=True)
Simon Glasscee02e62018-07-17 13:25:52 -06001478 dtb = fdt.Fdt(out_dtb_fname)
1479 dtb.Scan()
Simon Glass12bb1a92019-07-20 12:23:51 -06001480 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS)
Simon Glass16b8d6b2018-07-06 10:27:42 -06001481 self.assertEqual({
Simon Glassdbf6be92018-08-01 15:22:42 -06001482 'image-pos': 0,
Simon Glass8122f392018-07-17 13:25:28 -06001483 'offset': 0,
Simon Glass3ab95982018-08-01 15:22:37 -06001484 '_testing:offset': 32,
Simon Glass79d3c582019-07-20 12:23:57 -06001485 '_testing:size': 2,
Simon Glassdbf6be92018-08-01 15:22:42 -06001486 '_testing:image-pos': 32,
Simon Glass3ab95982018-08-01 15:22:37 -06001487 'section@0/u-boot:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001488 'section@0/u-boot:size': len(U_BOOT_DATA),
Simon Glassdbf6be92018-08-01 15:22:42 -06001489 'section@0/u-boot:image-pos': 0,
Simon Glass3ab95982018-08-01 15:22:37 -06001490 'section@0:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001491 'section@0:size': 16,
Simon Glassdbf6be92018-08-01 15:22:42 -06001492 'section@0:image-pos': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001493
Simon Glass3ab95982018-08-01 15:22:37 -06001494 'section@1/u-boot:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001495 'section@1/u-boot:size': len(U_BOOT_DATA),
Simon Glassdbf6be92018-08-01 15:22:42 -06001496 'section@1/u-boot:image-pos': 16,
Simon Glass3ab95982018-08-01 15:22:37 -06001497 'section@1:offset': 16,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001498 'section@1:size': 16,
Simon Glassdbf6be92018-08-01 15:22:42 -06001499 'section@1:image-pos': 16,
Simon Glass16b8d6b2018-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 Glass741f2d62018-10-01 12:22:30 -06001506 self._DoReadFileDtb('061_fdt_update_bad.dts', update_dtb=True)
Simon Glass16b8d6b2018-07-06 10:27:42 -06001507 self.assertIn('Could not complete processing of Fdt: remaining '
Simon Glass16287932020-04-17 18:09:03 -06001508 '[<binman.etype._testing.Entry__testing',
1509 str(e.exception))
Simon Glass5c890232018-07-06 10:27:19 -06001510
Simon Glass53af22a2018-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 Glass741f2d62018-10-01 12:22:30 -06001517 self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
Simon Glass53af22a2018-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 Glass741f2d62018-10-01 12:22:30 -06001530 self._DoReadFileDtb('063_entry_args_missing.dts', entry_args=entry_args)
Simon Glass53af22a2018-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 Glass741f2d62018-10-01 12:22:30 -06001543 self._DoReadFileDtb('064_entry_args_required.dts')
Simon Glass3decfa32020-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 Glass53af22a2018-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 Glass53cd5d92019-07-08 14:25:29 -06001551 args = ['build', '-d', self.TestFile('064_entry_args_required.dts'),
1552 '-ano-value']
Simon Glass53af22a2018-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 Glass741f2d62018-10-01 12:22:30 -06001563 self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
Simon Glass53af22a2018-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 Glass741f2d62018-10-01 12:22:30 -06001579 self._DoReadFileDtb('065_entry_args_unknown_datatype.dts',
Simon Glass53af22a2018-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 Glassbb748372018-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 Glass741f2d62018-10-01 12:22:30 -06001591 data, _, _, _ = self._DoReadFileDtb('066_text.dts',
Simon Glassbb748372018-07-17 13:25:33 -06001592 entry_args=entry_args)
Simon Glassc6c10e72019-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 Glassaa88b502019-07-08 13:18:40 -06001596 b'some text' + b'more text')
Simon Glassbb748372018-07-17 13:25:33 -06001597 self.assertEqual(expected, data)
1598
Simon Glassfd8d1f72018-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 Glass87d43322020-08-05 13:27:46 -06001602 control.WriteEntryDocs(control.GetEntryModules())
Simon Glassfd8d1f72018-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 Glass87d43322020-08-05 13:27:46 -06001609 control.WriteEntryDocs(control.GetEntryModules(), 'u_boot')
Simon Glassfd8d1f72018-07-17 13:25:36 -06001610 self.assertIn('Documentation is missing for modules: u_boot',
1611 str(e.exception))
1612
Simon Glass11e36cc2018-07-17 13:25:38 -06001613 def testFmap(self):
1614 """Basic test of generation of a flashrom fmap"""
Simon Glass741f2d62018-10-01 12:22:30 -06001615 data = self._DoReadFile('067_fmap.dts')
Simon Glass11e36cc2018-07-17 13:25:38 -06001616 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
Simon Glassc6c10e72019-05-17 22:00:46 -06001617 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
1618 U_BOOT_DATA + tools.GetBytes(ord('a'), 12))
Simon Glass11e36cc2018-07-17 13:25:38 -06001619 self.assertEqual(expected, data[:32])
Simon Glassc6c10e72019-05-17 22:00:46 -06001620 self.assertEqual(b'__FMAP__', fhdr.signature)
Simon Glass11e36cc2018-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 Glass17365752021-04-03 11:05:10 +13001624 expect_size = fmap_util.FMAP_HEADER_LEN + fmap_util.FMAP_AREA_LEN * 5
Simon Glassc7722e82021-04-03 11:05:09 +13001625 self.assertEqual(16 + 16 + expect_size, fhdr.image_size)
Simon Glassc6c10e72019-05-17 22:00:46 -06001626 self.assertEqual(b'FMAP', fhdr.name)
Simon Glass17365752021-04-03 11:05:10 +13001627 self.assertEqual(5, fhdr.nareas)
Simon Glassc7722e82021-04-03 11:05:09 +13001628 fiter = iter(fentries)
Simon Glass11e36cc2018-07-17 13:25:38 -06001629
Simon Glassc7722e82021-04-03 11:05:09 +13001630 fentry = next(fiter)
Simon Glass17365752021-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 Glassc7722e82021-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 Glass11e36cc2018-07-17 13:25:38 -06001641
Simon Glassc7722e82021-04-03 11:05:09 +13001642 fentry = next(fiter)
Simon Glass17365752021-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 Glassc7722e82021-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 Glass11e36cc2018-07-17 13:25:38 -06001653
Simon Glassc7722e82021-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 Glass11e36cc2018-07-17 13:25:38 -06001659
Simon Glassec127af2018-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 Glass3decfa32020-09-01 05:13:54 -06001665 self._DoReadFileDtb('068_blob_named_by_arg.dts', entry_args=entry_args)
Simon Glassec127af2018-07-17 13:25:39 -06001666
Simon Glass3af8e492018-07-17 13:25:40 -06001667 def testFill(self):
1668 """Test for an fill entry type"""
Simon Glass741f2d62018-10-01 12:22:30 -06001669 data = self._DoReadFile('069_fill.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -06001670 expected = tools.GetBytes(0xff, 8) + tools.GetBytes(0, 8)
Simon Glass3af8e492018-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 Glass741f2d62018-10-01 12:22:30 -06001676 self._DoReadFile('070_fill_no_size.dts')
Simon Glass3af8e492018-07-17 13:25:40 -06001677 self.assertIn("'fill' entry must have a size property",
1678 str(e.exception))
1679
Simon Glass0ef87aa2018-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 Glass1d0ebf72019-05-14 15:53:42 -06001686 with open(fname, 'ab') as fd:
Simon Glass0ef87aa2018-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 Glass741f2d62018-10-01 12:22:30 -06001697 data, _, _, _ = self._DoReadFileDtb('071_gbb.dts', entry_args=entry_args)
Simon Glass0ef87aa2018-07-17 13:25:44 -06001698
1699 # Since futility
Simon Glasse6d85ff2019-05-14 15:53:47 -06001700 expected = (GBB_DATA + GBB_DATA + tools.GetBytes(0, 8) +
1701 tools.GetBytes(0, 0x2180 - 16))
Simon Glass0ef87aa2018-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 Glass741f2d62018-10-01 12:22:30 -06001707 self._DoReadFileDtb('072_gbb_too_small.dts')
Simon Glass0ef87aa2018-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 Glass741f2d62018-10-01 12:22:30 -06001714 self._DoReadFileDtb('073_gbb_no_size.dts')
Simon Glass0ef87aa2018-07-17 13:25:44 -06001715 self.assertIn("Node '/binman/gbb': GBB must have a fixed size",
1716 str(e.exception))
1717
Simon Glass24d0d3c2018-07-17 13:25:47 -06001718 def _HandleVblockCommand(self, pipe_list):
Simon Glass5af9ebc2021-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 Glass24d0d3c2018-07-17 13:25:47 -06001733 if pipe_list[0][0] == 'futility':
1734 fname = pipe_list[0][3]
Simon Glassa326b492018-09-14 04:57:11 -06001735 with open(fname, 'wb') as fd:
Simon Glass5af9ebc2021-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 Glass24d0d3c2018-07-17 13:25:47 -06001745 return command.CommandResult()
1746
1747 def testVblock(self):
1748 """Test for the Chromium OS Verified Boot Block"""
Simon Glass5af9ebc2021-01-06 21:35:17 -07001749 self._hash_data = False
Simon Glass24d0d3c2018-07-17 13:25:47 -06001750 command.test_result = self._HandleVblockCommand
1751 entry_args = {
1752 'keydir': 'devkeys',
1753 }
Simon Glass741f2d62018-10-01 12:22:30 -06001754 data, _, _, _ = self._DoReadFileDtb('074_vblock.dts',
Simon Glass24d0d3c2018-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 Glass741f2d62018-10-01 12:22:30 -06001762 self._DoReadFile('075_vblock_no_content.dts')
Simon Glass189f2912021-03-21 18:24:31 +13001763 self.assertIn("Node '/binman/vblock': Collection must have a 'content' "
Simon Glass24d0d3c2018-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 Glass741f2d62018-10-01 12:22:30 -06001769 self._DoReadFile('076_vblock_bad_phandle.dts')
Simon Glass24d0d3c2018-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 Glass741f2d62018-10-01 12:22:30 -06001776 self._DoReadFile('077_vblock_bad_entry.dts')
Simon Glass24d0d3c2018-07-17 13:25:47 -06001777 self.assertIn("Node '/binman/vblock': Cannot find entry for node "
1778 "'other'", str(e.exception))
1779
Simon Glass5af9ebc2021-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 Glassb8ef5b62018-07-17 13:25:48 -06001803 def testTpl(self):
Simon Glass2090f1e2019-08-24 07:23:00 -06001804 """Test that an image with TPL and its device tree can be created"""
Simon Glassb8ef5b62018-07-17 13:25:48 -06001805 # ELF file with a '__bss_size' symbol
Simon Glass2090f1e2019-08-24 07:23:00 -06001806 self._SetupTplElf()
Simon Glass741f2d62018-10-01 12:22:30 -06001807 data = self._DoReadFile('078_u_boot_tpl.dts')
Simon Glassb8ef5b62018-07-17 13:25:48 -06001808 self.assertEqual(U_BOOT_TPL_DATA + U_BOOT_TPL_DTB_DATA, data)
1809
Simon Glass15a587c2018-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 Glass741f2d62018-10-01 12:22:30 -06001813 data = self._DoReadFile('079_uses_pos.dts')
Simon Glass15a587c2018-07-17 13:25:51 -06001814 self.assertIn("Node '/binman/u-boot': Please use 'offset' instead of "
1815 "'pos'", str(e.exception))
1816
Simon Glassd178eab2018-09-14 04:57:08 -06001817 def testFillZero(self):
1818 """Test for an fill entry type with a size of 0"""
Simon Glass741f2d62018-10-01 12:22:30 -06001819 data = self._DoReadFile('080_fill_empty.dts')
Simon Glasse6d85ff2019-05-14 15:53:47 -06001820 self.assertEqual(tools.GetBytes(0, 16), data)
Simon Glassd178eab2018-09-14 04:57:08 -06001821
Simon Glass0b489362018-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 Glass741f2d62018-10-01 12:22:30 -06001825 self._DoReadFileDtb('066_text.dts',)
Simon Glass0b489362018-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 Glass35b384c2018-09-14 04:57:10 -06001829 def testPackStart16Tpl(self):
1830 """Test that an image with an x86 start16 TPL region can be created"""
Simon Glass9255f3c2019-08-24 07:23:01 -06001831 data = self._DoReadFile('081_x86_start16_tpl.dts')
Simon Glass35b384c2018-09-14 04:57:10 -06001832 self.assertEqual(X86_START16_TPL_DATA, data[:len(X86_START16_TPL_DATA)])
1833
Simon Glass0bfa7b02018-09-14 04:57:12 -06001834 def testSelectImage(self):
1835 """Test that we can select which images to build"""
Simon Glasseb833d82019-04-25 21:58:34 -06001836 expected = 'Skipping images: image1'
Simon Glass0bfa7b02018-09-14 04:57:12 -06001837
Simon Glasseb833d82019-04-25 21:58:34 -06001838 # We should only get the expected message in verbose mode
Simon Glassee0c9a72019-07-08 13:18:48 -06001839 for verbosity in (0, 2):
Simon Glasseb833d82019-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())
1849
1850 self.assertFalse(os.path.exists(tools.GetOutputFilename('image1.bin')))
1851 self.assertTrue(os.path.exists(tools.GetOutputFilename('image2.bin')))
Simon Glassf86a7362019-07-20 12:24:10 -06001852 self._CleanupOutputDir()
Simon Glass0bfa7b02018-09-14 04:57:12 -06001853
Simon Glass6ed45ba2018-09-14 04:57:24 -06001854 def testUpdateFdtAll(self):
1855 """Test that all device trees are updated with offset/size info"""
Simon Glass3c081312019-07-08 14:25:26 -06001856 data = self._DoReadFileRealDtb('082_fdt_update_all.dts')
Simon Glass6ed45ba2018-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 Glass12bb1a92019-07-20 12:23:51 -06001884 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS +
1885 ['spl', 'tpl'])
Simon Glass6ed45ba2018-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 Glass741f2d62018-10-01 12:22:30 -06001895 data, dtb_data, _, _ = self._DoReadFileDtb('082_fdt_update_all.dts',
Simon Glass6ed45ba2018-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 Glass741f2d62018-10-01 12:22:30 -06001900 # source file (e.g. test/075_fdt_update_all.dts) thus does not enter
Simon Glass6ed45ba2018-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 Glass6ed45ba2018-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 Glass83d73c22018-09-14 04:57:26 -06001925 def _decompress(self, data):
Simon Glassff5c7e32019-07-08 13:18:42 -06001926 return tools.Decompress(data, 'lz4')
Simon Glass83d73c22018-09-14 04:57:26 -06001927
1928 def testCompress(self):
1929 """Test compression of blobs"""
Simon Glassac62fba2019-07-08 13:18:53 -06001930 self._CheckLz4()
Simon Glass741f2d62018-10-01 12:22:30 -06001931 data, _, _, out_dtb_fname = self._DoReadFileDtb('083_compress.dts',
Simon Glass83d73c22018-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 Glass97c3e9a2020-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 Glass63e7ba62020-10-26 17:40:16 -06001950 self.assertEqual(image.data, entry.data)
1951
Simon Glass83d73c22018-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 Glass0a98b282018-09-14 04:57:28 -06001959 def testFiles(self):
1960 """Test bringing in multiple files"""
Simon Glass741f2d62018-10-01 12:22:30 -06001961 data = self._DoReadFile('084_files.dts')
Simon Glass0a98b282018-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 Glassac62fba2019-07-08 13:18:53 -06001966 self._CheckLz4()
Simon Glass741f2d62018-10-01 12:22:30 -06001967 data = self._DoReadFile('085_files_compress.dts')
Simon Glass0a98b282018-09-14 04:57:28 -06001968
1969 image = control.images['image']
1970 entries = image.GetEntries()
1971 files = entries['files']
Simon Glass8beb11e2019-07-08 14:25:47 -06001972 entries = files._entries
Simon Glass0a98b282018-09-14 04:57:28 -06001973
Simon Glassc6c10e72019-05-17 22:00:46 -06001974 orig = b''
Simon Glass0a98b282018-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 Glass741f2d62018-10-01 12:22:30 -06001987 data = self._DoReadFile('086_files_none.dts')
Simon Glass0a98b282018-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 Glass741f2d62018-10-01 12:22:30 -06001994 data = self._DoReadFile('087_files_no_pattern.dts')
Simon Glass0a98b282018-09-14 04:57:28 -06001995 self.assertIn("Node '/binman/files': Missing 'pattern' property",
1996 str(e.exception))
1997
Simon Glassba64a0b2018-09-14 04:57:29 -06001998 def testExpandSize(self):
1999 """Test an expanding entry"""
Simon Glass741f2d62018-10-01 12:22:30 -06002000 data, _, map_data, _ = self._DoReadFileDtb('088_expand_size.dts',
Simon Glassba64a0b2018-09-14 04:57:29 -06002001 map=True)
Simon Glassc6c10e72019-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 Glassba64a0b2018-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 Glass163ed6c2018-09-14 04:57:36 -06002022 with test_util.capture_sys_output() as (stdout, stderr):
2023 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06002024 self._DoReadFileDtb('089_expand_size_bad.dts', map=True)
Simon Glassba64a0b2018-09-14 04:57:29 -06002025 self.assertIn("Node '/binman/_testing': Cannot obtain contents when "
2026 'expanding entry', str(e.exception))
2027
Simon Glasse0e5df92018-09-14 04:57:31 -06002028 def testHash(self):
2029 """Test hashing of the contents of an entry"""
Simon Glass741f2d62018-10-01 12:22:30 -06002030 _, _, _, out_dtb_fname = self._DoReadFileDtb('090_hash.dts',
Simon Glasse0e5df92018-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 Glassc6c10e72019-05-17 22:00:46 -06002037 self.assertEqual(m.digest(), b''.join(hash_node.value))
Simon Glasse0e5df92018-09-14 04:57:31 -06002038
2039 def testHashNoAlgo(self):
2040 with self.assertRaises(ValueError) as e:
Simon Glass741f2d62018-10-01 12:22:30 -06002041 self._DoReadFileDtb('091_hash_no_algo.dts', update_dtb=True)
Simon Glasse0e5df92018-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 Glass741f2d62018-10-01 12:22:30 -06002047 self._DoReadFileDtb('092_hash_bad_algo.dts', update_dtb=True)
Simon Glasse0e5df92018-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 Glass741f2d62018-10-01 12:22:30 -06002053 _, _, _, out_dtb_fname = self._DoReadFileDtb('099_hash_section.dts',
Simon Glasse0e5df92018-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 Glassc6c10e72019-05-17 22:00:46 -06002060 m.update(tools.GetBytes(ord('a'), 16))
2061 self.assertEqual(m.digest(), b''.join(hash_node.value))
Simon Glasse0e5df92018-09-14 04:57:31 -06002062
Simon Glassf0253632018-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 Glass2090f1e2019-08-24 07:23:00 -06002072 self._SetupTplElf('u_boot_ucode_ptr')
Simon Glass741f2d62018-10-01 12:22:30 -06002073 first, pos_and_size = self._RunMicrocodeTest('093_x86_tpl_ucode.dts',
Simon Glassf0253632018-09-14 04:57:32 -06002074 U_BOOT_TPL_NODTB_DATA)
Simon Glassc6c10e72019-05-17 22:00:46 -06002075 self.assertEqual(b'tplnodtb with microc' + pos_and_size +
2076 b'ter somewhere in here', first)
Simon Glassf0253632018-09-14 04:57:32 -06002077
Simon Glassf8f8df62018-09-14 04:57:34 -06002078 def testFmapX86(self):
2079 """Basic test of generation of a flashrom fmap"""
Simon Glass741f2d62018-10-01 12:22:30 -06002080 data = self._DoReadFile('094_fmap_x86.dts')
Simon Glassf8f8df62018-09-14 04:57:34 -06002081 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
Simon Glassc6c10e72019-05-17 22:00:46 -06002082 expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('a'), 32 - 7)
Simon Glassf8f8df62018-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 Glassc6c10e72019-05-17 22:00:46 -06002090 self.assertEqual(b'U_BOOT', fentries[0].name)
Simon Glassf8f8df62018-09-14 04:57:34 -06002091
2092 self.assertEqual(4, fentries[1].offset)
2093 self.assertEqual(3, fentries[1].size)
Simon Glassc6c10e72019-05-17 22:00:46 -06002094 self.assertEqual(b'INTEL_MRC', fentries[1].name)
Simon Glassf8f8df62018-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 Glassc6c10e72019-05-17 22:00:46 -06002099 self.assertEqual(b'FMAP', fentries[2].name)
Simon Glassf8f8df62018-09-14 04:57:34 -06002100
2101 def testFmapX86Section(self):
2102 """Basic test of generation of a flashrom fmap"""
Simon Glass741f2d62018-10-01 12:22:30 -06002103 data = self._DoReadFile('095_fmap_x86_section.dts')
Simon Glassc6c10e72019-05-17 22:00:46 -06002104 expected = U_BOOT_DATA + MRC_DATA + tools.GetBytes(ord('b'), 32 - 7)
Simon Glassf8f8df62018-09-14 04:57:34 -06002105 self.assertEqual(expected, data[:32])
2106 fhdr, fentries = fmap_util.DecodeFmap(data[36:])
2107
Simon Glass17365752021-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 Glassc7722e82021-04-03 11:05:09 +13002110 fiter = iter(fentries)
Simon Glassf8f8df62018-09-14 04:57:34 -06002111
Simon Glassc7722e82021-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 Glassf8f8df62018-09-14 04:57:34 -06002116
Simon Glassc7722e82021-04-03 11:05:09 +13002117 fentry = next(fiter)
Simon Glass17365752021-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 Glassc7722e82021-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 Glassf8f8df62018-09-14 04:57:34 -06002126
Simon Glassc7722e82021-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 Glassf8f8df62018-09-14 04:57:34 -06002131
Simon Glassfe1ae3e2018-09-14 04:57:35 -06002132 def testElf(self):
2133 """Basic test of ELF entries"""
Simon Glass11ae93e2018-10-01 21:12:47 -06002134 self._SetupSplElf()
Simon Glass2090f1e2019-08-24 07:23:00 -06002135 self._SetupTplElf()
Simon Glass53e22bf2019-08-24 07:22:53 -06002136 with open(self.ElfTestFile('bss_data'), 'rb') as fd:
Simon Glassfe1ae3e2018-09-14 04:57:35 -06002137 TestFunctional._MakeInputFile('-boot', fd.read())
Simon Glass741f2d62018-10-01 12:22:30 -06002138 data = self._DoReadFile('096_elf.dts')
Simon Glassfe1ae3e2018-09-14 04:57:35 -06002139
Simon Glass093d1682019-07-08 13:18:25 -06002140 def testElfStrip(self):
Simon Glassfe1ae3e2018-09-14 04:57:35 -06002141 """Basic test of ELF entries"""
Simon Glass11ae93e2018-10-01 21:12:47 -06002142 self._SetupSplElf()
Simon Glass53e22bf2019-08-24 07:22:53 -06002143 with open(self.ElfTestFile('bss_data'), 'rb') as fd:
Simon Glassfe1ae3e2018-09-14 04:57:35 -06002144 TestFunctional._MakeInputFile('-boot', fd.read())
Simon Glass741f2d62018-10-01 12:22:30 -06002145 data = self._DoReadFile('097_elf_strip.dts')
Simon Glassfe1ae3e2018-09-14 04:57:35 -06002146
Simon Glass163ed6c2018-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 Glass741f2d62018-10-01 12:22:30 -06002151 self._DoTestFile('014_pack_overlap.dts', map=True)
Simon Glass163ed6c2018-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 Glasseb546ac2019-05-17 22:00:51 -06002159 map_data = tools.ReadFile(map_fname, binary=False)
Simon Glass163ed6c2018-09-14 04:57:36 -06002160 self.assertEqual('''ImagePos Offset Size Name
Simon Glass0ff83da2020-10-26 17:40:24 -06002161<none> 00000000 00000008 main-section
Simon Glass163ed6c2018-09-14 04:57:36 -06002162<none> 00000000 00000004 u-boot
2163<none> 00000003 00000004 u-boot-align
2164''', map_data)
2165
Simon Glass093d1682019-07-08 13:18:25 -06002166 def testPackRefCode(self):
Simon Glass3ae192c2018-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 Glass9481c802019-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 Glasse6d85ff2019-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 Glass9481c802019-04-25 21:58:39 -06002191
Simon Glassac62fba2019-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 Glasse2f04742021-11-23 11:03:54 -07002260 def testCbfsNoContents(self):
Simon Glassac62fba2019-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 Glassc5ac1382019-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 Glass2090f1e2019-08-24 07:23:00 -06002294 self._SetupTplElf()
Simon Glassc5ac1382019-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 Glasse95be632019-08-24 07:22:51 -06002318 self.assertEqual(U_BOOT_TPL_DATA, tpl_data[:len(U_BOOT_TPL_DATA)])
Simon Glassc5ac1382019-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 Glass9255f3c2019-08-24 07:23:01 -06002323 data = self._DoReadFile('111_x86_rom_ifwi.dts')
Simon Glassc5ac1382019-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 Glass9255f3c2019-08-24 07:23:01 -06002329 data = self._DoReadFile('112_x86_rom_ifwi_nodesc.dts')
Simon Glassc5ac1382019-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 Glass9255f3c2019-08-24 07:23:01 -06002336 data = self._DoReadFile('113_x86_rom_ifwi_nodata.dts')
Simon Glassc5ac1382019-07-08 13:18:54 -06002337 self.assertIn('Could not complete processing of contents',
2338 str(e.exception))
Simon Glass53af22a2018-07-17 13:25:32 -06002339
Simon Glasse073d4e2019-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 Glass086cec92019-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 Glassb6ee0cf2019-10-31 07:43:03 -06002367 self.assertEqual(b'_FDTMAP_', magic)
Simon Glass086cec92019-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 Glass6ccbfcd2019-07-20 12:23:47 -06002373 props = self._GetPropTree(dtb, BASE_DTB_PROPS, prefix='/')
Simon Glass086cec92019-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 Glasscf228942019-07-08 14:25:28 -06002393 image._node.path += '-suffix'
Simon Glass086cec92019-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 Glasscf228942019-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 Glassb6ee0cf2019-10-31 07:43:03 -06002410 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscf228942019-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 Glassb6ee0cf2019-10-31 07:43:03 -06002419 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscf228942019-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 Glassb6ee0cf2019-10-31 07:43:03 -06002428 self.assertEqual(b'BinM', hdr_data[:4])
Simon Glasscf228942019-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 Glassc52c9e72019-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 Glass79d3c582019-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 Glassc52c9e72019-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 Glass61ec04f2019-07-20 12:23:58 -06002457 self.assertIn("Image '/binman': Entries changed size after packing",
Simon Glassc52c9e72019-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 Glass79d3c582019-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 Glassc52c9e72019-07-08 14:25:37 -06002466
Simon Glass6c223fd2019-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 Glass69f7cb32019-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 Glass6ccbfcd2019-07-20 12:23:47 -06002492 props = self._GetPropTree(dtb, BASE_DTB_PROPS + ['uncomp-size'])
Simon Glass69f7cb32019-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 Glass8a1ad062019-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 Glass41b8ba02019-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 Glass8beb11e2019-07-08 14:25:47 -06002530 self.assertEqual(0, ent.offset)
Simon Glass41b8ba02019-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 Glass8beb11e2019-07-08 14:25:47 -06002548 self.assertEqual(0x100, ent.offset)
Simon Glass41b8ba02019-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 Glasse1925fa2019-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 Glass2d260032019-07-08 14:25:45 -06002605 def testFindImageHeader(self):
2606 """Test locating a image header"""
2607 self._CheckLz4()
Simon Glassffded752019-07-08 14:25:46 -06002608 data = self.data = self._DoReadFileRealDtb('128_decode_image.dts')
Simon Glass2d260032019-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 Glassffded752019-07-08 14:25:46 -06002617 data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts')
Simon Glass2d260032019-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 Glassffded752019-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 Glass10f9d002019-07-20 12:23:50 -06002652 self.assertEqual('image', image.image_name[-5:])
Simon Glassffded752019-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 Glasse073d4e2019-07-08 13:18:56 -06002661
Simon Glass61f564d2019-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 Glassf86a7362019-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 Glass61f564d2019-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 Glassb6ee0cf2019-10-31 07:43:03 -06002689' u-boot-dtb 180 105 u-boot-dtb 80 3c9',
Simon Glass61f564d2019-07-08 14:25:48 -06002690' u-boot-dtb 500 %x u-boot-dtb 400 3c9' % fdt_size,
Simon Glassb6ee0cf2019-10-31 07:43:03 -06002691' fdtmap %x 3bd fdtmap %x' %
Simon Glass61f564d2019-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 Glassf86a7362019-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 Glass61f564d2019-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 Glassf667e452019-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 Glass71ce0ba2019-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 Glassb6ee0cf2019-10-31 07:43:03 -06002776 self.assertEqual(['u-boot', 'u-boot-dtb', ''], list(cbfs.files.keys()))
Simon Glass71ce0ba2019-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 Glasseb0f4a42019-07-20 12:24:06 -06002805 dtb = tools.Decompress(data, 'lzma', with_header=False)
Simon Glass71ce0ba2019-07-08 14:25:52 -06002806 self.assertEqual(EXTRACT_DTB_SIZE, len(dtb))
2807
Simon Glassf667e452019-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 Glass71ce0ba2019-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 Glass71ce0ba2019-07-08 14:25:52 -06002831 fname = os.path.join(self._indir, 'output.extact')
Simon Glassf86a7362019-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 Glass71ce0ba2019-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 Glassbb5edc12019-07-20 12:24:14 -06002970 self.assertIn('Must specify an entry path to write with -f',
Simon Glass71ce0ba2019-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 Glassbb5edc12019-07-20 12:24:14 -06002980 self.assertIn('Must specify exactly one entry path to write with -f',
Simon Glass71ce0ba2019-07-08 14:25:52 -06002981 str(e.exception))
2982
Simon Glasse2705fa2019-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 Glass51014aa2019-07-20 12:23:56 -06003048 def _RunReplaceCmd(self, entry_name, data, decomp=True, allow_resize=True,
3049 dts='132_replace.dts'):
Simon Glass10f9d002019-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 Glass51014aa2019-07-20 12:23:56 -06003060 allow_resize: True to allow entries to change size, False to raise
3061 an exception
Simon Glass10f9d002019-07-20 12:23:50 -06003062
3063 Returns:
3064 Tuple:
3065 data from entry
3066 data from fdtmap (excluding header)
Simon Glass51014aa2019-07-20 12:23:56 -06003067 Image object that was modified
Simon Glass10f9d002019-07-20 12:23:50 -06003068 """
Simon Glass51014aa2019-07-20 12:23:56 -06003069 dtb_data = self._DoReadFileDtb(dts, use_real_dtb=True,
Simon Glass10f9d002019-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 Glass51014aa2019-07-20 12:23:56 -06003081 image = control.WriteEntry(updated_fname, entry_name, data, decomp,
3082 allow_resize)
Simon Glass10f9d002019-07-20 12:23:50 -06003083 data = control.ReadEntry(updated_fname, entry_name, decomp)
3084
Simon Glass51014aa2019-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 Glass10f9d002019-07-20 12:23:50 -06003091
Simon Glass51014aa2019-07-20 12:23:56 -06003092 return data, orig_fdtmap_data[fdtmap.FDTMAP_HDR_LEN:], image
Simon Glass10f9d002019-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 Glass51014aa2019-07-20 12:23:56 -06003097 data, expected_fdtmap, _ = self._RunReplaceCmd('u-boot', expected,
3098 allow_resize=False)
Simon Glass10f9d002019-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 Glass51014aa2019-07-20 12:23:56 -06003106 self.assertIsNotNone(path)
Simon Glass10f9d002019-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 Glass51014aa2019-07-20 12:23:56 -06003125 self._RunReplaceCmd('u-boot', expected, allow_resize=False,
3126 dts='139_replace_repack.dts')
Simon Glass10f9d002019-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 Glass51014aa2019-07-20 12:23:56 -06003138 control.WriteEntry(updated_fname, entry_name, expected,
3139 allow_resize=False)
Simon Glass10f9d002019-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 Glass51014aa2019-07-20 12:23:56 -06003151 control.WriteEntry(updated_fname, entry_name, expected,
3152 allow_resize=False)
Simon Glass10f9d002019-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 Glass8beb11e2019-07-08 14:25:47 -06003158
Simon Glass12bb1a92019-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 Glasseba1f0c2019-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 Glass51014aa2019-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 Glass61ec04f2019-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 Glass27145fd2019-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 Glasseb0f4a42019-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 Glassa6cb9952019-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 Glass38fdb4c2020-07-09 18:39:39 -06003485 stderr.getvalue())
Simon Glassa6cb9952019-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 Glass2250ee62019-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 Glass5af12072019-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 Glass7c150132019-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 Glass2090f1e2019-08-24 07:23:00 -06003561 upto1 = 4 + len(U_BOOT_SPL_DATA)
Simon Glassb87064c2019-08-24 07:23:05 -06003562 expected1 = tools.GetBytes(0xff, 4) + sym_values + U_BOOT_SPL_DATA[20:]
Simon Glass2090f1e2019-08-24 07:23:00 -06003563 self.assertEqual(expected1, data[:upto1])
3564
3565 upto2 = upto1 + 1 + len(U_BOOT_SPL_DATA)
Simon Glassb87064c2019-08-24 07:23:05 -06003566 expected2 = tools.GetBytes(0xff, 1) + sym_values + U_BOOT_SPL_DATA[20:]
Simon Glass2090f1e2019-08-24 07:23:00 -06003567 self.assertEqual(expected2, data[upto1:upto2])
3568
Simon Glasseb0086f2019-08-24 07:23:04 -06003569 upto3 = 0x34 + len(U_BOOT_DATA)
3570 expected3 = tools.GetBytes(0xff, 1) + U_BOOT_DATA
Simon Glass2090f1e2019-08-24 07:23:00 -06003571 self.assertEqual(expected3, data[upto2:upto3])
3572
Simon Glassb87064c2019-08-24 07:23:05 -06003573 expected4 = sym_values + U_BOOT_TPL_DATA[20:]
Simon Glass7c150132019-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 Glass2090f1e2019-08-24 07:23:00 -06003590
Simon Glassbf4d0e22019-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 Glassea0fff92019-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 Glassbc6a88f2019-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 Glassea0fff92019-08-24 07:23:07 -06003606
Simon Glass998d1482019-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 Glass0dc706f2020-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 Glassce867ad2020-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 Glass4f9f1052020-07-09 18:39:38 -06003631 def testExtblobMissingOk(self):
3632 """Test an image with an missing external blob that is allowed"""
Simon Glassb1cca952020-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 Glass4f9f1052020-07-09 18:39:38 -06003646
Simon Glass0ba4b3d2020-07-09 18:39:41 -06003647 def testPackX86RomMeMissingDesc(self):
3648 """Test that an missing Intel descriptor entry is allowed"""
Simon Glass0ba4b3d2020-07-09 18:39:41 -06003649 with test_util.capture_sys_output() as (stdout, stderr):
Simon Glass52b10dd2020-07-25 15:11:19 -06003650 self._DoTestFile('164_x86_rom_me_missing.dts', allow_missing=True)
Simon Glass0ba4b3d2020-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 Glassb3295fd2020-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 Glassfdc34362020-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 Glasse9d336d2020-09-01 05:13:55 -06003712 """Test an image with an FIT with external images"""
Simon Glassfdc34362020-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
3716 # The data should be outside the FIT
3717 dtb = fdt.Fdt.FromData(fit_data)
3718 dtb.Scan()
3719 fnode = dtb.GetNode('/images/kernel')
3720 self.assertNotIn('data', fnode.props)
Simon Glass12bb1a92019-07-20 12:23:51 -06003721
Alper Nebi Yasak8001d0b2020-08-31 12:58:18 +03003722 def testSectionIgnoreHashSignature(self):
3723 """Test that sections ignore hash, signature nodes for its data"""
3724 data = self._DoReadFile('165_section_ignore_hash_signature.dts')
3725 expected = (U_BOOT_DATA + U_BOOT_DATA)
3726 self.assertEqual(expected, data)
3727
Alper Nebi Yasak3fdeb142020-08-31 12:58:19 +03003728 def testPadInSections(self):
3729 """Test pad-before, pad-after for entries in sections"""
Simon Glassf90d9062020-10-26 17:40:09 -06003730 data, _, _, out_dtb_fname = self._DoReadFileDtb(
3731 '166_pad_in_sections.dts', update_dtb=True)
Alper Nebi Yasak3fdeb142020-08-31 12:58:19 +03003732 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
3733 U_BOOT_DATA + tools.GetBytes(ord('!'), 6) +
3734 U_BOOT_DATA)
3735 self.assertEqual(expected, data)
3736
Simon Glassf90d9062020-10-26 17:40:09 -06003737 dtb = fdt.Fdt(out_dtb_fname)
3738 dtb.Scan()
3739 props = self._GetPropTree(dtb, ['size', 'image-pos', 'offset'])
3740 expected = {
3741 'image-pos': 0,
3742 'offset': 0,
3743 'size': 12 + 6 + 3 * len(U_BOOT_DATA),
3744
3745 'section:image-pos': 0,
3746 'section:offset': 0,
3747 'section:size': 12 + 6 + 3 * len(U_BOOT_DATA),
3748
3749 'section/before:image-pos': 0,
3750 'section/before:offset': 0,
3751 'section/before:size': len(U_BOOT_DATA),
3752
3753 'section/u-boot:image-pos': 4,
3754 'section/u-boot:offset': 4,
3755 'section/u-boot:size': 12 + len(U_BOOT_DATA) + 6,
3756
3757 'section/after:image-pos': 26,
3758 'section/after:offset': 26,
3759 'section/after:size': len(U_BOOT_DATA),
3760 }
3761 self.assertEqual(expected, props)
3762
Alper Nebi Yasakfe057012020-08-31 12:58:20 +03003763 def testFitImageSubentryAlignment(self):
3764 """Test relative alignability of FIT image subentries"""
3765 entry_args = {
3766 'test-id': TEXT_DATA,
3767 }
3768 data, _, _, _ = self._DoReadFileDtb('167_fit_image_subentry_alignment.dts',
3769 entry_args=entry_args)
3770 dtb = fdt.Fdt.FromData(data)
3771 dtb.Scan()
3772
3773 node = dtb.GetNode('/images/kernel')
3774 data = dtb.GetProps(node)["data"].bytes
3775 align_pad = 0x10 - (len(U_BOOT_SPL_DATA) % 0x10)
3776 expected = (tools.GetBytes(0, 0x20) + U_BOOT_SPL_DATA +
3777 tools.GetBytes(0, align_pad) + U_BOOT_DATA)
3778 self.assertEqual(expected, data)
3779
3780 node = dtb.GetNode('/images/fdt-1')
3781 data = dtb.GetProps(node)["data"].bytes
3782 expected = (U_BOOT_SPL_DTB_DATA + tools.GetBytes(0, 20) +
3783 tools.ToBytes(TEXT_DATA) + tools.GetBytes(0, 30) +
3784 U_BOOT_DTB_DATA)
3785 self.assertEqual(expected, data)
3786
3787 def testFitExtblobMissingOk(self):
3788 """Test a FIT with a missing external blob that is allowed"""
3789 with test_util.capture_sys_output() as (stdout, stderr):
3790 self._DoTestFile('168_fit_missing_blob.dts',
3791 allow_missing=True)
3792 err = stderr.getvalue()
Simon Glassb2381432020-09-06 10:39:09 -06003793 self.assertRegex(err, "Image 'main-section'.*missing.*: atf-bl31")
Alper Nebi Yasakfe057012020-08-31 12:58:20 +03003794
Simon Glass3decfa32020-09-01 05:13:54 -06003795 def testBlobNamedByArgMissing(self):
3796 """Test handling of a missing entry arg"""
3797 with self.assertRaises(ValueError) as e:
3798 self._DoReadFile('068_blob_named_by_arg.dts')
3799 self.assertIn("Missing required properties/entry args: cros-ec-rw-path",
3800 str(e.exception))
3801
Simon Glassdc2f81a2020-09-01 05:13:58 -06003802 def testPackBl31(self):
3803 """Test that an image with an ATF BL31 binary can be created"""
3804 data = self._DoReadFile('169_atf_bl31.dts')
3805 self.assertEqual(ATF_BL31_DATA, data[:len(ATF_BL31_DATA)])
3806
Samuel Holland18bd4552020-10-21 21:12:15 -05003807 def testPackScp(self):
3808 """Test that an image with an SCP binary can be created"""
3809 data = self._DoReadFile('172_scp.dts')
3810 self.assertEqual(SCP_DATA, data[:len(SCP_DATA)])
3811
Simon Glass6cf99532020-09-01 05:13:59 -06003812 def testFitFdt(self):
3813 """Test an image with an FIT with multiple FDT images"""
3814 def _CheckFdt(seq, expected_data):
3815 """Check the FDT nodes
3816
3817 Args:
3818 seq: Sequence number to check (0 or 1)
3819 expected_data: Expected contents of 'data' property
3820 """
3821 name = 'fdt-%d' % seq
3822 fnode = dtb.GetNode('/images/%s' % name)
3823 self.assertIsNotNone(fnode)
3824 self.assertEqual({'description','type', 'compression', 'data'},
3825 set(fnode.props.keys()))
3826 self.assertEqual(expected_data, fnode.props['data'].bytes)
3827 self.assertEqual('fdt-test-fdt%d.dtb' % seq,
3828 fnode.props['description'].value)
3829
3830 def _CheckConfig(seq, expected_data):
3831 """Check the configuration nodes
3832
3833 Args:
3834 seq: Sequence number to check (0 or 1)
3835 expected_data: Expected contents of 'data' property
3836 """
3837 cnode = dtb.GetNode('/configurations')
3838 self.assertIn('default', cnode.props)
Simon Glassc0f1ebe2020-09-06 10:39:08 -06003839 self.assertEqual('config-2', cnode.props['default'].value)
Simon Glass6cf99532020-09-01 05:13:59 -06003840
3841 name = 'config-%d' % seq
3842 fnode = dtb.GetNode('/configurations/%s' % name)
3843 self.assertIsNotNone(fnode)
3844 self.assertEqual({'description','firmware', 'loadables', 'fdt'},
3845 set(fnode.props.keys()))
3846 self.assertEqual('conf-test-fdt%d.dtb' % seq,
3847 fnode.props['description'].value)
3848 self.assertEqual('fdt-%d' % seq, fnode.props['fdt'].value)
3849
3850 entry_args = {
3851 'of-list': 'test-fdt1 test-fdt2',
Simon Glassc0f1ebe2020-09-06 10:39:08 -06003852 'default-dt': 'test-fdt2',
Simon Glass6cf99532020-09-01 05:13:59 -06003853 }
3854 data = self._DoReadFileDtb(
Bin Mengaa75ce92021-05-10 20:23:32 +08003855 '170_fit_fdt.dts',
Simon Glass6cf99532020-09-01 05:13:59 -06003856 entry_args=entry_args,
3857 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3858 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3859 fit_data = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3860
3861 dtb = fdt.Fdt.FromData(fit_data)
3862 dtb.Scan()
3863 fnode = dtb.GetNode('/images/kernel')
3864 self.assertIn('data', fnode.props)
3865
3866 # Check all the properties in fdt-1 and fdt-2
3867 _CheckFdt(1, TEST_FDT1_DATA)
3868 _CheckFdt(2, TEST_FDT2_DATA)
3869
3870 # Check configurations
3871 _CheckConfig(1, TEST_FDT1_DATA)
3872 _CheckConfig(2, TEST_FDT2_DATA)
3873
3874 def testFitFdtMissingList(self):
3875 """Test handling of a missing 'of-list' entry arg"""
3876 with self.assertRaises(ValueError) as e:
Bin Mengaa75ce92021-05-10 20:23:32 +08003877 self._DoReadFile('170_fit_fdt.dts')
Simon Glass6cf99532020-09-01 05:13:59 -06003878 self.assertIn("Generator node requires 'of-list' entry argument",
3879 str(e.exception))
3880
3881 def testFitFdtEmptyList(self):
3882 """Test handling of an empty 'of-list' entry arg"""
3883 entry_args = {
3884 'of-list': '',
3885 }
3886 data = self._DoReadFileDtb('170_fit_fdt.dts', entry_args=entry_args)[0]
3887
3888 def testFitFdtMissingProp(self):
3889 """Test handling of a missing 'fit,fdt-list' property"""
3890 with self.assertRaises(ValueError) as e:
3891 self._DoReadFile('171_fit_fdt_missing_prop.dts')
3892 self.assertIn("Generator node requires 'fit,fdt-list' property",
3893 str(e.exception))
Simon Glassdc2f81a2020-09-01 05:13:58 -06003894
Simon Glassc0f1ebe2020-09-06 10:39:08 -06003895 def testFitFdtEmptyList(self):
3896 """Test handling of an empty 'of-list' entry arg"""
3897 entry_args = {
3898 'of-list': '',
3899 }
Bin Mengaa75ce92021-05-10 20:23:32 +08003900 data = self._DoReadFileDtb('170_fit_fdt.dts', entry_args=entry_args)[0]
Simon Glassc0f1ebe2020-09-06 10:39:08 -06003901
3902 def testFitFdtMissing(self):
3903 """Test handling of a missing 'default-dt' entry arg"""
3904 entry_args = {
3905 'of-list': 'test-fdt1 test-fdt2',
3906 }
3907 with self.assertRaises(ValueError) as e:
3908 self._DoReadFileDtb(
Bin Mengaa75ce92021-05-10 20:23:32 +08003909 '170_fit_fdt.dts',
Simon Glassc0f1ebe2020-09-06 10:39:08 -06003910 entry_args=entry_args,
3911 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3912 self.assertIn("Generated 'default' node requires default-dt entry argument",
3913 str(e.exception))
3914
3915 def testFitFdtNotInList(self):
3916 """Test handling of a default-dt that is not in the of-list"""
3917 entry_args = {
3918 'of-list': 'test-fdt1 test-fdt2',
3919 'default-dt': 'test-fdt3',
3920 }
3921 with self.assertRaises(ValueError) as e:
3922 self._DoReadFileDtb(
Bin Mengaa75ce92021-05-10 20:23:32 +08003923 '170_fit_fdt.dts',
Simon Glassc0f1ebe2020-09-06 10:39:08 -06003924 entry_args=entry_args,
3925 extra_indirs=[os.path.join(self._indir, TEST_FDT_SUBDIR)])[0]
3926 self.assertIn("default-dt entry argument 'test-fdt3' not found in fdt list: test-fdt1, test-fdt2",
3927 str(e.exception))
3928
Simon Glassb2381432020-09-06 10:39:09 -06003929 def testFitExtblobMissingHelp(self):
3930 """Test display of help messages when an external blob is missing"""
3931 control.missing_blob_help = control._ReadMissingBlobHelp()
3932 control.missing_blob_help['wibble'] = 'Wibble test'
3933 control.missing_blob_help['another'] = 'Another test'
3934 with test_util.capture_sys_output() as (stdout, stderr):
3935 self._DoTestFile('168_fit_missing_blob.dts',
3936 allow_missing=True)
3937 err = stderr.getvalue()
3938
3939 # We can get the tag from the name, the type or the missing-msg
3940 # property. Check all three.
3941 self.assertIn('You may need to build ARM Trusted', err)
3942 self.assertIn('Wibble test', err)
3943 self.assertIn('Another test', err)
3944
Simon Glass204aa782020-09-06 10:35:32 -06003945 def testMissingBlob(self):
3946 """Test handling of a blob containing a missing file"""
3947 with self.assertRaises(ValueError) as e:
3948 self._DoTestFile('173_missing_blob.dts', allow_missing=True)
3949 self.assertIn("Filename 'missing' not found in input path",
3950 str(e.exception))
3951
Simon Glassfb91d562020-09-06 10:35:33 -06003952 def testEnvironment(self):
3953 """Test adding a U-Boot environment"""
3954 data = self._DoReadFile('174_env.dts')
3955 self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)])
3956 self.assertEqual(U_BOOT_NODTB_DATA, data[-len(U_BOOT_NODTB_DATA):])
3957 env = data[len(U_BOOT_DATA):-len(U_BOOT_NODTB_DATA)]
3958 self.assertEqual(b'\x1b\x97\x22\x7c\x01var1=1\0var2="2"\0\0\xff\xff',
3959 env)
3960
3961 def testEnvironmentNoSize(self):
3962 """Test that a missing 'size' property is detected"""
3963 with self.assertRaises(ValueError) as e:
Simon Glassa4dfe3e2020-10-26 17:40:00 -06003964 self._DoTestFile('175_env_no_size.dts')
Simon Glassfb91d562020-09-06 10:35:33 -06003965 self.assertIn("'u-boot-env' entry must have a size property",
3966 str(e.exception))
3967
3968 def testEnvironmentTooSmall(self):
3969 """Test handling of an environment that does not fit"""
3970 with self.assertRaises(ValueError) as e:
Simon Glassa4dfe3e2020-10-26 17:40:00 -06003971 self._DoTestFile('176_env_too_small.dts')
Simon Glassfb91d562020-09-06 10:35:33 -06003972
3973 # checksum, start byte, environment with \0 terminator, final \0
3974 need = 4 + 1 + len(ENV_DATA) + 1 + 1
3975 short = need - 0x8
3976 self.assertIn("too small to hold data (need %#x more bytes)" % short,
3977 str(e.exception))
3978
Simon Glassf2c0dd82020-10-26 17:40:01 -06003979 def testSkipAtStart(self):
3980 """Test handling of skip-at-start section"""
3981 data = self._DoReadFile('177_skip_at_start.dts')
3982 self.assertEqual(U_BOOT_DATA, data)
3983
3984 image = control.images['image']
3985 entries = image.GetEntries()
3986 section = entries['section']
3987 self.assertEqual(0, section.offset)
3988 self.assertEqual(len(U_BOOT_DATA), section.size)
3989 self.assertEqual(U_BOOT_DATA, section.GetData())
3990
3991 entry = section.GetEntries()['u-boot']
3992 self.assertEqual(16, entry.offset)
3993 self.assertEqual(len(U_BOOT_DATA), entry.size)
3994 self.assertEqual(U_BOOT_DATA, entry.data)
3995
3996 def testSkipAtStartPad(self):
3997 """Test handling of skip-at-start section with padded entry"""
3998 data = self._DoReadFile('178_skip_at_start_pad.dts')
3999 before = tools.GetBytes(0, 8)
4000 after = tools.GetBytes(0, 4)
4001 all = before + U_BOOT_DATA + after
4002 self.assertEqual(all, data)
4003
4004 image = control.images['image']
4005 entries = image.GetEntries()
4006 section = entries['section']
4007 self.assertEqual(0, section.offset)
4008 self.assertEqual(len(all), section.size)
4009 self.assertEqual(all, section.GetData())
4010
4011 entry = section.GetEntries()['u-boot']
4012 self.assertEqual(16, entry.offset)
4013 self.assertEqual(len(all), entry.size)
4014 self.assertEqual(U_BOOT_DATA, entry.data)
4015
4016 def testSkipAtStartSectionPad(self):
4017 """Test handling of skip-at-start section with padding"""
4018 data = self._DoReadFile('179_skip_at_start_section_pad.dts')
4019 before = tools.GetBytes(0, 8)
4020 after = tools.GetBytes(0, 4)
4021 all = before + U_BOOT_DATA + after
Simon Glassd1d3ad72020-10-26 17:40:13 -06004022 self.assertEqual(all, data)
Simon Glassf2c0dd82020-10-26 17:40:01 -06004023
4024 image = control.images['image']
4025 entries = image.GetEntries()
4026 section = entries['section']
4027 self.assertEqual(0, section.offset)
4028 self.assertEqual(len(all), section.size)
Simon Glass63e7ba62020-10-26 17:40:16 -06004029 self.assertEqual(U_BOOT_DATA, section.data)
Simon Glassd1d3ad72020-10-26 17:40:13 -06004030 self.assertEqual(all, section.GetPaddedData())
Simon Glassf2c0dd82020-10-26 17:40:01 -06004031
4032 entry = section.GetEntries()['u-boot']
4033 self.assertEqual(16, entry.offset)
4034 self.assertEqual(len(U_BOOT_DATA), entry.size)
4035 self.assertEqual(U_BOOT_DATA, entry.data)
Simon Glassfb91d562020-09-06 10:35:33 -06004036
Simon Glass7d398bb2020-10-26 17:40:14 -06004037 def testSectionPad(self):
4038 """Testing padding with sections"""
4039 data = self._DoReadFile('180_section_pad.dts')
4040 expected = (tools.GetBytes(ord('&'), 3) +
4041 tools.GetBytes(ord('!'), 5) +
4042 U_BOOT_DATA +
4043 tools.GetBytes(ord('!'), 1) +
4044 tools.GetBytes(ord('&'), 2))
4045 self.assertEqual(expected, data)
4046
4047 def testSectionAlign(self):
4048 """Testing alignment with sections"""
4049 data = self._DoReadFileDtb('181_section_align.dts', map=True)[0]
4050 expected = (b'\0' + # fill section
4051 tools.GetBytes(ord('&'), 1) + # padding to section align
4052 b'\0' + # fill section
4053 tools.GetBytes(ord('!'), 3) + # padding to u-boot align
4054 U_BOOT_DATA +
4055 tools.GetBytes(ord('!'), 4) + # padding to u-boot size
4056 tools.GetBytes(ord('!'), 4)) # padding to section size
4057 self.assertEqual(expected, data)
4058
Simon Glass8f5ef892020-10-26 17:40:25 -06004059 def testCompressImage(self):
4060 """Test compression of the entire image"""
4061 self._CheckLz4()
4062 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4063 '182_compress_image.dts', use_real_dtb=True, update_dtb=True)
4064 dtb = fdt.Fdt(out_dtb_fname)
4065 dtb.Scan()
4066 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4067 'uncomp-size'])
4068 orig = self._decompress(data)
4069 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4070
4071 # Do a sanity check on various fields
4072 image = control.images['image']
4073 entries = image.GetEntries()
4074 self.assertEqual(2, len(entries))
4075
4076 entry = entries['blob']
4077 self.assertEqual(COMPRESS_DATA, entry.data)
4078 self.assertEqual(len(COMPRESS_DATA), entry.size)
4079
4080 entry = entries['u-boot']
4081 self.assertEqual(U_BOOT_DATA, entry.data)
4082 self.assertEqual(len(U_BOOT_DATA), entry.size)
4083
4084 self.assertEqual(len(data), image.size)
4085 self.assertEqual(COMPRESS_DATA + U_BOOT_DATA, image.uncomp_data)
4086 self.assertEqual(len(COMPRESS_DATA + U_BOOT_DATA), image.uncomp_size)
4087 orig = self._decompress(image.data)
4088 self.assertEqual(orig, image.uncomp_data)
4089
4090 expected = {
4091 'blob:offset': 0,
4092 'blob:size': len(COMPRESS_DATA),
4093 'u-boot:offset': len(COMPRESS_DATA),
4094 'u-boot:size': len(U_BOOT_DATA),
4095 'uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4096 'offset': 0,
4097 'image-pos': 0,
4098 'size': len(data),
4099 }
4100 self.assertEqual(expected, props)
4101
4102 def testCompressImageLess(self):
4103 """Test compression where compression reduces the image size"""
4104 self._CheckLz4()
4105 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4106 '183_compress_image_less.dts', use_real_dtb=True, update_dtb=True)
4107 dtb = fdt.Fdt(out_dtb_fname)
4108 dtb.Scan()
4109 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4110 'uncomp-size'])
4111 orig = self._decompress(data)
4112
4113 self.assertEquals(COMPRESS_DATA + COMPRESS_DATA + U_BOOT_DATA, orig)
4114
4115 # Do a sanity check on various fields
4116 image = control.images['image']
4117 entries = image.GetEntries()
4118 self.assertEqual(2, len(entries))
4119
4120 entry = entries['blob']
4121 self.assertEqual(COMPRESS_DATA_BIG, entry.data)
4122 self.assertEqual(len(COMPRESS_DATA_BIG), entry.size)
4123
4124 entry = entries['u-boot']
4125 self.assertEqual(U_BOOT_DATA, entry.data)
4126 self.assertEqual(len(U_BOOT_DATA), entry.size)
4127
4128 self.assertEqual(len(data), image.size)
4129 self.assertEqual(COMPRESS_DATA_BIG + U_BOOT_DATA, image.uncomp_data)
4130 self.assertEqual(len(COMPRESS_DATA_BIG + U_BOOT_DATA),
4131 image.uncomp_size)
4132 orig = self._decompress(image.data)
4133 self.assertEqual(orig, image.uncomp_data)
4134
4135 expected = {
4136 'blob:offset': 0,
4137 'blob:size': len(COMPRESS_DATA_BIG),
4138 'u-boot:offset': len(COMPRESS_DATA_BIG),
4139 'u-boot:size': len(U_BOOT_DATA),
4140 'uncomp-size': len(COMPRESS_DATA_BIG + U_BOOT_DATA),
4141 'offset': 0,
4142 'image-pos': 0,
4143 'size': len(data),
4144 }
4145 self.assertEqual(expected, props)
4146
4147 def testCompressSectionSize(self):
4148 """Test compression of a section with a fixed size"""
4149 self._CheckLz4()
4150 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4151 '184_compress_section_size.dts', use_real_dtb=True, update_dtb=True)
4152 dtb = fdt.Fdt(out_dtb_fname)
4153 dtb.Scan()
4154 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4155 'uncomp-size'])
4156 orig = self._decompress(data)
4157 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4158 expected = {
4159 'section/blob:offset': 0,
4160 'section/blob:size': len(COMPRESS_DATA),
4161 'section/u-boot:offset': len(COMPRESS_DATA),
4162 'section/u-boot:size': len(U_BOOT_DATA),
4163 'section:offset': 0,
4164 'section:image-pos': 0,
4165 'section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4166 'section:size': 0x30,
4167 'offset': 0,
4168 'image-pos': 0,
4169 'size': 0x30,
4170 }
4171 self.assertEqual(expected, props)
4172
4173 def testCompressSection(self):
4174 """Test compression of a section with no fixed size"""
4175 self._CheckLz4()
4176 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4177 '185_compress_section.dts', use_real_dtb=True, update_dtb=True)
4178 dtb = fdt.Fdt(out_dtb_fname)
4179 dtb.Scan()
4180 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4181 'uncomp-size'])
4182 orig = self._decompress(data)
4183 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, orig)
4184 expected = {
4185 'section/blob:offset': 0,
4186 'section/blob:size': len(COMPRESS_DATA),
4187 'section/u-boot:offset': len(COMPRESS_DATA),
4188 'section/u-boot:size': len(U_BOOT_DATA),
4189 'section:offset': 0,
4190 'section:image-pos': 0,
4191 'section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4192 'section:size': len(data),
4193 'offset': 0,
4194 'image-pos': 0,
4195 'size': len(data),
4196 }
4197 self.assertEqual(expected, props)
4198
4199 def testCompressExtra(self):
4200 """Test compression of a section with no fixed size"""
4201 self._CheckLz4()
4202 data, _, _, out_dtb_fname = self._DoReadFileDtb(
4203 '186_compress_extra.dts', use_real_dtb=True, update_dtb=True)
4204 dtb = fdt.Fdt(out_dtb_fname)
4205 dtb.Scan()
4206 props = self._GetPropTree(dtb, ['offset', 'image-pos', 'size',
4207 'uncomp-size'])
4208
4209 base = data[len(U_BOOT_DATA):]
4210 self.assertEquals(U_BOOT_DATA, base[:len(U_BOOT_DATA)])
4211 rest = base[len(U_BOOT_DATA):]
4212
4213 # Check compressed data
4214 section1 = self._decompress(rest)
4215 expect1 = tools.Compress(COMPRESS_DATA + U_BOOT_DATA, 'lz4')
4216 self.assertEquals(expect1, rest[:len(expect1)])
4217 self.assertEquals(COMPRESS_DATA + U_BOOT_DATA, section1)
4218 rest1 = rest[len(expect1):]
4219
4220 section2 = self._decompress(rest1)
4221 expect2 = tools.Compress(COMPRESS_DATA + COMPRESS_DATA, 'lz4')
4222 self.assertEquals(expect2, rest1[:len(expect2)])
4223 self.assertEquals(COMPRESS_DATA + COMPRESS_DATA, section2)
4224 rest2 = rest1[len(expect2):]
4225
4226 expect_size = (len(U_BOOT_DATA) + len(U_BOOT_DATA) + len(expect1) +
4227 len(expect2) + len(U_BOOT_DATA))
4228 #self.assertEquals(expect_size, len(data))
4229
4230 #self.assertEquals(U_BOOT_DATA, rest2)
4231
4232 self.maxDiff = None
4233 expected = {
4234 'u-boot:offset': 0,
4235 'u-boot:image-pos': 0,
4236 'u-boot:size': len(U_BOOT_DATA),
4237
4238 'base:offset': len(U_BOOT_DATA),
4239 'base:image-pos': len(U_BOOT_DATA),
4240 'base:size': len(data) - len(U_BOOT_DATA),
4241 'base/u-boot:offset': 0,
4242 'base/u-boot:image-pos': len(U_BOOT_DATA),
4243 'base/u-boot:size': len(U_BOOT_DATA),
4244 'base/u-boot2:offset': len(U_BOOT_DATA) + len(expect1) +
4245 len(expect2),
4246 'base/u-boot2:image-pos': len(U_BOOT_DATA) * 2 + len(expect1) +
4247 len(expect2),
4248 'base/u-boot2:size': len(U_BOOT_DATA),
4249
4250 'base/section:offset': len(U_BOOT_DATA),
4251 'base/section:image-pos': len(U_BOOT_DATA) * 2,
4252 'base/section:size': len(expect1),
4253 'base/section:uncomp-size': len(COMPRESS_DATA + U_BOOT_DATA),
4254 'base/section/blob:offset': 0,
4255 'base/section/blob:size': len(COMPRESS_DATA),
4256 'base/section/u-boot:offset': len(COMPRESS_DATA),
4257 'base/section/u-boot:size': len(U_BOOT_DATA),
4258
4259 'base/section2:offset': len(U_BOOT_DATA) + len(expect1),
4260 'base/section2:image-pos': len(U_BOOT_DATA) * 2 + len(expect1),
4261 'base/section2:size': len(expect2),
4262 'base/section2:uncomp-size': len(COMPRESS_DATA + COMPRESS_DATA),
4263 'base/section2/blob:offset': 0,
4264 'base/section2/blob:size': len(COMPRESS_DATA),
4265 'base/section2/blob2:offset': len(COMPRESS_DATA),
4266 'base/section2/blob2:size': len(COMPRESS_DATA),
4267
4268 'offset': 0,
4269 'image-pos': 0,
4270 'size': len(data),
4271 }
4272 self.assertEqual(expected, props)
4273
Simon Glass870a9ea2021-01-06 21:35:15 -07004274 def testSymbolsSubsection(self):
4275 """Test binman can assign symbols from a subsection"""
Simon Glassf5898822021-03-18 20:24:56 +13004276 self.checkSymbols('187_symbols_sub.dts', U_BOOT_SPL_DATA, 0x18)
Simon Glass870a9ea2021-01-06 21:35:15 -07004277
Simon Glass939d1062021-01-06 21:35:16 -07004278 def testReadImageEntryArg(self):
4279 """Test reading an image that would need an entry arg to generate"""
4280 entry_args = {
4281 'cros-ec-rw-path': 'ecrw.bin',
4282 }
4283 data = self.data = self._DoReadFileDtb(
4284 '188_image_entryarg.dts',use_real_dtb=True, update_dtb=True,
4285 entry_args=entry_args)
4286
4287 image_fname = tools.GetOutputFilename('image.bin')
4288 orig_image = control.images['image']
4289
4290 # This should not generate an error about the missing 'cros-ec-rw-path'
4291 # since we are reading the image from a file. Compare with
4292 # testEntryArgsRequired()
4293 image = Image.FromFile(image_fname)
4294 self.assertEqual(orig_image.GetEntries().keys(),
4295 image.GetEntries().keys())
4296
Simon Glass6eb99322021-01-06 21:35:18 -07004297 def testFilesAlign(self):
4298 """Test alignment with files"""
4299 data = self._DoReadFile('190_files_align.dts')
4300
4301 # The first string is 15 bytes so will align to 16
4302 expect = FILES_DATA[:15] + b'\0' + FILES_DATA[15:]
4303 self.assertEqual(expect, data)
4304
Simon Glass5c6ba712021-01-06 21:35:19 -07004305 def testReadImageSkip(self):
4306 """Test reading an image and accessing its FDT map"""
4307 data = self.data = self._DoReadFileRealDtb('191_read_image_skip.dts')
4308 image_fname = tools.GetOutputFilename('image.bin')
4309 orig_image = control.images['image']
4310 image = Image.FromFile(image_fname)
4311 self.assertEqual(orig_image.GetEntries().keys(),
4312 image.GetEntries().keys())
4313
4314 orig_entry = orig_image.GetEntries()['fdtmap']
4315 entry = image.GetEntries()['fdtmap']
4316 self.assertEqual(orig_entry.offset, entry.offset)
4317 self.assertEqual(orig_entry.size, entry.size)
4318 self.assertEqual(16, entry.image_pos)
4319
4320 u_boot = image.GetEntries()['section'].GetEntries()['u-boot']
4321
4322 self.assertEquals(U_BOOT_DATA, u_boot.ReadData())
4323
Simon Glass77a64e02021-03-18 20:24:57 +13004324 def testTplNoDtb(self):
4325 """Test that an image with tpl/u-boot-tpl-nodtb.bin can be created"""
Simon Glass0fe44dc2021-04-25 08:39:32 +12004326 self._SetupTplElf()
Simon Glass77a64e02021-03-18 20:24:57 +13004327 data = self._DoReadFile('192_u_boot_tpl_nodtb.dts')
4328 self.assertEqual(U_BOOT_TPL_NODTB_DATA,
4329 data[:len(U_BOOT_TPL_NODTB_DATA)])
4330
Simon Glassd26efc82021-03-18 20:24:58 +13004331 def testTplBssPad(self):
4332 """Test that we can pad TPL's BSS with zeros"""
4333 # ELF file with a '__bss_size' symbol
4334 self._SetupTplElf()
4335 data = self._DoReadFile('193_tpl_bss_pad.dts')
4336 self.assertEqual(U_BOOT_TPL_DATA + tools.GetBytes(0, 10) + U_BOOT_DATA,
4337 data)
4338
4339 def testTplBssPadMissing(self):
4340 """Test that a missing symbol is detected"""
4341 self._SetupTplElf('u_boot_ucode_ptr')
4342 with self.assertRaises(ValueError) as e:
4343 self._DoReadFile('193_tpl_bss_pad.dts')
4344 self.assertIn('Expected __bss_size symbol in tpl/u-boot-tpl',
4345 str(e.exception))
4346
Simon Glass06684922021-03-18 20:25:07 +13004347 def checkDtbSizes(self, data, pad_len, start):
4348 """Check the size arguments in a dtb embedded in an image
4349
4350 Args:
4351 data: The image data
4352 pad_len: Length of the pad section in the image, in bytes
4353 start: Start offset of the devicetree to examine, within the image
4354
4355 Returns:
4356 Size of the devicetree in bytes
4357 """
4358 dtb_data = data[start:]
4359 dtb = fdt.Fdt.FromData(dtb_data)
4360 fdt_size = dtb.GetFdtObj().totalsize()
4361 dtb.Scan()
4362 props = self._GetPropTree(dtb, 'size')
4363 self.assertEqual({
4364 'size': len(data),
4365 'u-boot-spl/u-boot-spl-bss-pad:size': pad_len,
4366 'u-boot-spl/u-boot-spl-dtb:size': 801,
4367 'u-boot-spl/u-boot-spl-nodtb:size': len(U_BOOT_SPL_NODTB_DATA),
4368 'u-boot-spl:size': 860,
4369 'u-boot-tpl:size': len(U_BOOT_TPL_DATA),
4370 'u-boot/u-boot-dtb:size': 781,
4371 'u-boot/u-boot-nodtb:size': len(U_BOOT_NODTB_DATA),
4372 'u-boot:size': 827,
4373 }, props)
4374 return fdt_size
4375
4376 def testExpanded(self):
4377 """Test that an expanded entry type is selected when needed"""
4378 self._SetupSplElf()
4379 self._SetupTplElf()
4380
4381 # SPL has a devicetree, TPL does not
4382 entry_args = {
4383 'spl-dtb': '1',
4384 'spl-bss-pad': 'y',
4385 'tpl-dtb': '',
4386 }
4387 self._DoReadFileDtb('194_fdt_incl.dts', use_expanded=True,
4388 entry_args=entry_args)
4389 image = control.images['image']
4390 entries = image.GetEntries()
4391 self.assertEqual(3, len(entries))
4392
4393 # First, u-boot, which should be expanded into u-boot-nodtb and dtb
4394 self.assertIn('u-boot', entries)
4395 entry = entries['u-boot']
4396 self.assertEqual('u-boot-expanded', entry.etype)
4397 subent = entry.GetEntries()
4398 self.assertEqual(2, len(subent))
4399 self.assertIn('u-boot-nodtb', subent)
4400 self.assertIn('u-boot-dtb', subent)
4401
4402 # Second, u-boot-spl, which should be expanded into three parts
4403 self.assertIn('u-boot-spl', entries)
4404 entry = entries['u-boot-spl']
4405 self.assertEqual('u-boot-spl-expanded', entry.etype)
4406 subent = entry.GetEntries()
4407 self.assertEqual(3, len(subent))
4408 self.assertIn('u-boot-spl-nodtb', subent)
4409 self.assertIn('u-boot-spl-bss-pad', subent)
4410 self.assertIn('u-boot-spl-dtb', subent)
4411
4412 # Third, u-boot-tpl, which should be not be expanded, since TPL has no
4413 # devicetree
4414 self.assertIn('u-boot-tpl', entries)
4415 entry = entries['u-boot-tpl']
4416 self.assertEqual('u-boot-tpl', entry.etype)
4417 self.assertEqual(None, entry.GetEntries())
4418
4419 def testExpandedTpl(self):
4420 """Test that an expanded entry type is selected for TPL when needed"""
4421 self._SetupTplElf()
4422
4423 entry_args = {
4424 'tpl-bss-pad': 'y',
4425 'tpl-dtb': 'y',
4426 }
4427 self._DoReadFileDtb('195_fdt_incl_tpl.dts', use_expanded=True,
4428 entry_args=entry_args)
4429 image = control.images['image']
4430 entries = image.GetEntries()
4431 self.assertEqual(1, len(entries))
4432
4433 # We only have u-boot-tpl, which be expanded
4434 self.assertIn('u-boot-tpl', entries)
4435 entry = entries['u-boot-tpl']
4436 self.assertEqual('u-boot-tpl-expanded', entry.etype)
4437 subent = entry.GetEntries()
4438 self.assertEqual(3, len(subent))
4439 self.assertIn('u-boot-tpl-nodtb', subent)
4440 self.assertIn('u-boot-tpl-bss-pad', subent)
4441 self.assertIn('u-boot-tpl-dtb', subent)
4442
4443 def testExpandedNoPad(self):
4444 """Test an expanded entry without BSS pad enabled"""
4445 self._SetupSplElf()
4446 self._SetupTplElf()
4447
4448 # SPL has a devicetree, TPL does not
4449 entry_args = {
4450 'spl-dtb': 'something',
4451 'spl-bss-pad': 'n',
4452 'tpl-dtb': '',
4453 }
4454 self._DoReadFileDtb('194_fdt_incl.dts', use_expanded=True,
4455 entry_args=entry_args)
4456 image = control.images['image']
4457 entries = image.GetEntries()
4458
4459 # Just check u-boot-spl, which should be expanded into two parts
4460 self.assertIn('u-boot-spl', entries)
4461 entry = entries['u-boot-spl']
4462 self.assertEqual('u-boot-spl-expanded', entry.etype)
4463 subent = entry.GetEntries()
4464 self.assertEqual(2, len(subent))
4465 self.assertIn('u-boot-spl-nodtb', subent)
4466 self.assertIn('u-boot-spl-dtb', subent)
4467
4468 def testExpandedTplNoPad(self):
4469 """Test that an expanded entry type with padding disabled in TPL"""
4470 self._SetupTplElf()
4471
4472 entry_args = {
4473 'tpl-bss-pad': '',
4474 'tpl-dtb': 'y',
4475 }
4476 self._DoReadFileDtb('195_fdt_incl_tpl.dts', use_expanded=True,
4477 entry_args=entry_args)
4478 image = control.images['image']
4479 entries = image.GetEntries()
4480 self.assertEqual(1, len(entries))
4481
4482 # We only have u-boot-tpl, which be expanded
4483 self.assertIn('u-boot-tpl', entries)
4484 entry = entries['u-boot-tpl']
4485 self.assertEqual('u-boot-tpl-expanded', entry.etype)
4486 subent = entry.GetEntries()
4487 self.assertEqual(2, len(subent))
4488 self.assertIn('u-boot-tpl-nodtb', subent)
4489 self.assertIn('u-boot-tpl-dtb', subent)
4490
4491 def testFdtInclude(self):
4492 """Test that an Fdt is update within all binaries"""
4493 self._SetupSplElf()
4494 self._SetupTplElf()
4495
4496 # SPL has a devicetree, TPL does not
4497 self.maxDiff = None
4498 entry_args = {
4499 'spl-dtb': '1',
4500 'spl-bss-pad': 'y',
4501 'tpl-dtb': '',
4502 }
4503 # Build the image. It includes two separate devicetree binaries, each
4504 # with their own contents, but all contain the binman definition.
4505 data = self._DoReadFileDtb(
4506 '194_fdt_incl.dts', use_real_dtb=True, use_expanded=True,
4507 update_dtb=True, entry_args=entry_args)[0]
4508 pad_len = 10
4509
4510 # Check the U-Boot dtb
4511 start = len(U_BOOT_NODTB_DATA)
4512 fdt_size = self.checkDtbSizes(data, pad_len, start)
4513
4514 # Now check SPL
4515 start += fdt_size + len(U_BOOT_SPL_NODTB_DATA) + pad_len
4516 fdt_size = self.checkDtbSizes(data, pad_len, start)
4517
4518 # TPL has no devicetree
4519 start += fdt_size + len(U_BOOT_TPL_DATA)
4520 self.assertEqual(len(data), start)
Simon Glass7d398bb2020-10-26 17:40:14 -06004521
Simon Glass3d433382021-03-21 18:24:30 +13004522 def testSymbolsExpanded(self):
4523 """Test binman can assign symbols in expanded entries"""
4524 entry_args = {
4525 'spl-dtb': '1',
4526 }
4527 self.checkSymbols('197_symbols_expand.dts', U_BOOT_SPL_NODTB_DATA +
4528 U_BOOT_SPL_DTB_DATA, 0x38,
4529 entry_args=entry_args, use_expanded=True)
4530
Simon Glass189f2912021-03-21 18:24:31 +13004531 def testCollection(self):
4532 """Test a collection"""
4533 data = self._DoReadFile('198_collection.dts')
4534 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA +
4535 tools.GetBytes(0xff, 2) + U_BOOT_NODTB_DATA +
4536 tools.GetBytes(0xfe, 3) + U_BOOT_DTB_DATA,
4537 data)
4538
Simon Glass631f7522021-03-21 18:24:32 +13004539 def testCollectionSection(self):
4540 """Test a collection where a section must be built first"""
4541 # Sections never have their contents when GetData() is called, but when
Simon Glassd34bcdd2021-11-23 11:03:47 -07004542 # BuildSectionData() is called with required=True, a section will force
Simon Glass631f7522021-03-21 18:24:32 +13004543 # building the contents, producing an error is anything is still
4544 # missing.
4545 data = self._DoReadFile('199_collection_section.dts')
4546 section = U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA
4547 self.assertEqual(section + U_BOOT_DATA + tools.GetBytes(0xff, 2) +
4548 section + tools.GetBytes(0xfe, 3) + U_BOOT_DATA,
4549 data)
4550
Simon Glass5ff9fed2021-03-21 18:24:33 +13004551 def testAlignDefault(self):
4552 """Test that default alignment works on sections"""
4553 data = self._DoReadFile('200_align_default.dts')
4554 expected = (U_BOOT_DATA + tools.GetBytes(0, 8 - len(U_BOOT_DATA)) +
4555 U_BOOT_DATA)
4556 # Special alignment for section
4557 expected += tools.GetBytes(0, 32 - len(expected))
4558 # No alignment within the nested section
4559 expected += U_BOOT_DATA + U_BOOT_NODTB_DATA;
4560 # Now the final piece, which should be default-aligned
4561 expected += tools.GetBytes(0, 88 - len(expected)) + U_BOOT_NODTB_DATA
4562 self.assertEqual(expected, data)
Simon Glass631f7522021-03-21 18:24:32 +13004563
Bin Meng4c4d6072021-05-10 20:23:33 +08004564 def testPackOpenSBI(self):
4565 """Test that an image with an OpenSBI binary can be created"""
4566 data = self._DoReadFile('201_opensbi.dts')
4567 self.assertEqual(OPENSBI_DATA, data[:len(OPENSBI_DATA)])
4568
Simon Glassc69d19c2021-07-06 10:36:37 -06004569 def testSectionsSingleThread(self):
4570 """Test sections without multithreading"""
4571 data = self._DoReadFileDtb('055_sections.dts', threads=0)[0]
4572 expected = (U_BOOT_DATA + tools.GetBytes(ord('!'), 12) +
4573 U_BOOT_DATA + tools.GetBytes(ord('a'), 12) +
4574 U_BOOT_DATA + tools.GetBytes(ord('&'), 4))
4575 self.assertEqual(expected, data)
4576
4577 def testThreadTimeout(self):
4578 """Test handling a thread that takes too long"""
4579 with self.assertRaises(ValueError) as e:
4580 self._DoTestFile('202_section_timeout.dts',
4581 test_section_timeout=True)
Simon Glassb2dfe832021-10-18 12:13:15 -06004582 self.assertIn("Timed out obtaining contents", str(e.exception))
Simon Glassc69d19c2021-07-06 10:36:37 -06004583
Simon Glass03ebc202021-07-06 10:36:41 -06004584 def testTiming(self):
4585 """Test output of timing information"""
4586 data = self._DoReadFile('055_sections.dts')
4587 with test_util.capture_sys_output() as (stdout, stderr):
4588 state.TimingShow()
4589 self.assertIn('read:', stdout.getvalue())
4590 self.assertIn('compress:', stdout.getvalue())
4591
Simon Glass0427bed2021-11-03 21:09:18 -06004592 def testUpdateFdtInElf(self):
4593 """Test that we can update the devicetree in an ELF file"""
4594 infile = elf_fname = self.ElfTestFile('u_boot_binman_embed')
4595 outfile = os.path.join(self._indir, 'u-boot.out')
4596 begin_sym = 'dtb_embed_begin'
4597 end_sym = 'dtb_embed_end'
4598 retcode = self._DoTestFile(
4599 '060_fdt_update.dts', update_dtb=True,
4600 update_fdt_in_elf=','.join([infile,outfile,begin_sym,end_sym]))
4601 self.assertEqual(0, retcode)
4602
4603 # Check that the output file does in fact contact a dtb with the binman
4604 # definition in the correct place
4605 syms = elf.GetSymbolFileOffset(infile,
4606 ['dtb_embed_begin', 'dtb_embed_end'])
4607 data = tools.ReadFile(outfile)
4608 dtb_data = data[syms['dtb_embed_begin'].offset:
4609 syms['dtb_embed_end'].offset]
4610
4611 dtb = fdt.Fdt.FromData(dtb_data)
4612 dtb.Scan()
4613 props = self._GetPropTree(dtb, BASE_DTB_PROPS + REPACK_DTB_PROPS)
4614 self.assertEqual({
4615 'image-pos': 0,
4616 'offset': 0,
4617 '_testing:offset': 32,
4618 '_testing:size': 2,
4619 '_testing:image-pos': 32,
4620 'section@0/u-boot:offset': 0,
4621 'section@0/u-boot:size': len(U_BOOT_DATA),
4622 'section@0/u-boot:image-pos': 0,
4623 'section@0:offset': 0,
4624 'section@0:size': 16,
4625 'section@0:image-pos': 0,
4626
4627 'section@1/u-boot:offset': 0,
4628 'section@1/u-boot:size': len(U_BOOT_DATA),
4629 'section@1/u-boot:image-pos': 16,
4630 'section@1:offset': 16,
4631 'section@1:size': 16,
4632 'section@1:image-pos': 16,
4633 'size': 40
4634 }, props)
4635
4636 def testUpdateFdtInElfInvalid(self):
4637 """Test that invalid args are detected with --update-fdt-in-elf"""
4638 with self.assertRaises(ValueError) as e:
4639 self._DoTestFile('060_fdt_update.dts', update_fdt_in_elf='fred')
4640 self.assertIn("Invalid args ['fred'] to --update-fdt-in-elf",
4641 str(e.exception))
4642
4643 def testUpdateFdtInElfNoSyms(self):
4644 """Test that missing symbols are detected with --update-fdt-in-elf"""
4645 infile = elf_fname = self.ElfTestFile('u_boot_binman_embed')
4646 outfile = ''
4647 begin_sym = 'wrong_begin'
4648 end_sym = 'wrong_end'
4649 with self.assertRaises(ValueError) as e:
4650 self._DoTestFile(
4651 '060_fdt_update.dts',
4652 update_fdt_in_elf=','.join([infile,outfile,begin_sym,end_sym]))
4653 self.assertIn("Expected two symbols 'wrong_begin' and 'wrong_end': got 0:",
4654 str(e.exception))
4655
4656 def testUpdateFdtInElfTooSmall(self):
4657 """Test that an over-large dtb is detected with --update-fdt-in-elf"""
4658 infile = elf_fname = self.ElfTestFile('u_boot_binman_embed_sm')
4659 outfile = os.path.join(self._indir, 'u-boot.out')
4660 begin_sym = 'dtb_embed_begin'
4661 end_sym = 'dtb_embed_end'
4662 with self.assertRaises(ValueError) as e:
4663 self._DoTestFile(
4664 '060_fdt_update.dts', update_dtb=True,
4665 update_fdt_in_elf=','.join([infile,outfile,begin_sym,end_sym]))
4666 self.assertRegex(
4667 str(e.exception),
4668 "Not enough space in '.*u_boot_binman_embed_sm' for data length.*")
4669
Heiko Thierya89c8f22022-01-06 11:49:41 +01004670 def testFakeBlob(self):
4671 """Test handling of faking an external blob"""
4672 with test_util.capture_sys_output() as (stdout, stderr):
4673 self._DoTestFile('203_fake_blob.dts', allow_missing=True,
4674 allow_fake_blobs=True)
4675 err = stderr.getvalue()
4676 self.assertRegex(err,
4677 "Image '.*' has faked external blobs and is non-functional: .*")
4678 os.remove('binman_faking_test_blob')
4679
Simon Glassc475dec2021-11-23 11:03:42 -07004680 def testVersion(self):
4681 """Test we can get the binman version"""
4682 version = '(unreleased)'
4683 self.assertEqual(version, state.GetVersion(self._indir))
4684
4685 with self.assertRaises(SystemExit):
4686 with test_util.capture_sys_output() as (_, stderr):
4687 self._DoBinman('-V')
4688 self.assertEqual('Binman %s\n' % version, stderr.getvalue())
4689
4690 # Try running the tool too, just to be safe
4691 result = self._RunBinman('-V')
4692 self.assertEqual('Binman %s\n' % version, result.stderr)
4693
4694 # Set up a version file to make sure that works
4695 version = 'v2025.01-rc2'
4696 tools.WriteFile(os.path.join(self._indir, 'version'), version,
4697 binary=False)
4698 self.assertEqual(version, state.GetVersion(self._indir))
4699
Simon Glass943bf782021-11-23 21:09:50 -07004700 def testAltFormat(self):
4701 """Test that alternative formats can be used to extract"""
4702 self._DoReadFileRealDtb('213_fdtmap_alt_format.dts')
4703
4704 try:
4705 tmpdir, updated_fname = self._SetupImageInTmpdir()
4706 with test_util.capture_sys_output() as (stdout, _):
4707 self._DoBinman('extract', '-i', updated_fname, '-F', 'list')
4708 self.assertEqual(
4709 '''Flag (-F) Entry type Description
4710fdt fdtmap Extract the devicetree blob from the fdtmap
4711''',
4712 stdout.getvalue())
4713
4714 dtb = os.path.join(tmpdir, 'fdt.dtb')
4715 self._DoBinman('extract', '-i', updated_fname, '-F', 'fdt', '-f',
4716 dtb, 'fdtmap')
4717
4718 # Check that we can read it and it can be scanning, meaning it does
4719 # not have a 16-byte fdtmap header
4720 data = tools.ReadFile(dtb)
4721 dtb = fdt.Fdt.FromData(data)
4722 dtb.Scan()
4723
4724 # Now check u-boot which has no alt_format
4725 fname = os.path.join(tmpdir, 'fdt.dtb')
4726 self._DoBinman('extract', '-i', updated_fname, '-F', 'dummy',
4727 '-f', fname, 'u-boot')
4728 data = tools.ReadFile(fname)
4729 self.assertEqual(U_BOOT_DATA, data)
4730
4731 finally:
4732 shutil.rmtree(tmpdir)
4733
Simon Glasscc2c5002021-11-23 21:09:52 -07004734 def testExtblobList(self):
4735 """Test an image with an external blob list"""
4736 data = self._DoReadFile('215_blob_ext_list.dts')
4737 self.assertEqual(REFCODE_DATA + FSP_M_DATA, data)
4738
4739 def testExtblobListMissing(self):
4740 """Test an image with a missing external blob"""
4741 with self.assertRaises(ValueError) as e:
4742 self._DoReadFile('216_blob_ext_list_missing.dts')
4743 self.assertIn("Filename 'missing-file' not found in input path",
4744 str(e.exception))
4745
4746 def testExtblobListMissingOk(self):
4747 """Test an image with an missing external blob that is allowed"""
4748 with test_util.capture_sys_output() as (stdout, stderr):
4749 self._DoTestFile('216_blob_ext_list_missing.dts',
4750 allow_missing=True)
4751 err = stderr.getvalue()
4752 self.assertRegex(err, "Image 'main-section'.*missing.*: blob-ext")
4753
Simon Glass75989722021-11-23 21:08:59 -07004754 def testFip(self):
4755 """Basic test of generation of an ARM Firmware Image Package (FIP)"""
4756 data = self._DoReadFile('203_fip.dts')
4757 hdr, fents = fip_util.decode_fip(data)
4758 self.assertEqual(fip_util.HEADER_MAGIC, hdr.name)
4759 self.assertEqual(fip_util.HEADER_SERIAL, hdr.serial)
4760 self.assertEqual(0x123, hdr.flags)
4761
4762 self.assertEqual(2, len(fents))
4763
4764 fent = fents[0]
4765 self.assertEqual(
4766 bytes([0x47, 0xd4, 0x08, 0x6d, 0x4c, 0xfe, 0x98, 0x46,
4767 0x9b, 0x95, 0x29, 0x50, 0xcb, 0xbd, 0x5a, 0x0]), fent.uuid)
4768 self.assertEqual('soc-fw', fent.fip_type)
4769 self.assertEqual(0x88, fent.offset)
4770 self.assertEqual(len(ATF_BL31_DATA), fent.size)
4771 self.assertEqual(0x123456789abcdef, fent.flags)
4772 self.assertEqual(ATF_BL31_DATA, fent.data)
4773 self.assertEqual(True, fent.valid)
4774
4775 fent = fents[1]
4776 self.assertEqual(
4777 bytes([0x65, 0x92, 0x27, 0x03, 0x2f, 0x74, 0xe6, 0x44,
4778 0x8d, 0xff, 0x57, 0x9a, 0xc1, 0xff, 0x06, 0x10]), fent.uuid)
4779 self.assertEqual('scp-fwu-cfg', fent.fip_type)
4780 self.assertEqual(0x8c, fent.offset)
4781 self.assertEqual(len(ATF_BL31_DATA), fent.size)
4782 self.assertEqual(0, fent.flags)
4783 self.assertEqual(ATF_BL2U_DATA, fent.data)
4784 self.assertEqual(True, fent.valid)
4785
4786 def testFipOther(self):
4787 """Basic FIP with something that isn't a external blob"""
4788 data = self._DoReadFile('204_fip_other.dts')
4789 hdr, fents = fip_util.decode_fip(data)
4790
4791 self.assertEqual(2, len(fents))
4792 fent = fents[1]
4793 self.assertEqual('rot-cert', fent.fip_type)
4794 self.assertEqual(b'aa', fent.data)
4795
4796 def testFipOther(self):
4797 """Basic FIP with something that isn't a external blob"""
4798 data = self._DoReadFile('204_fip_other.dts')
4799 hdr, fents = fip_util.decode_fip(data)
4800
4801 self.assertEqual(2, len(fents))
4802 fent = fents[1]
4803 self.assertEqual('rot-cert', fent.fip_type)
4804 self.assertEqual(b'aa', fent.data)
4805
4806 def testFipNoType(self):
4807 """FIP with an entry of an unknown type"""
4808 with self.assertRaises(ValueError) as e:
4809 self._DoReadFile('205_fip_no_type.dts')
4810 self.assertIn("Must provide a fip-type (node name 'u-boot' is not a known FIP type)",
4811 str(e.exception))
4812
4813 def testFipUuid(self):
4814 """Basic FIP with a manual uuid"""
4815 data = self._DoReadFile('206_fip_uuid.dts')
4816 hdr, fents = fip_util.decode_fip(data)
4817
4818 self.assertEqual(2, len(fents))
4819 fent = fents[1]
4820 self.assertEqual(None, fent.fip_type)
4821 self.assertEqual(
4822 bytes([0xfc, 0x65, 0x13, 0x92, 0x4a, 0x5b, 0x11, 0xec,
4823 0x94, 0x35, 0xff, 0x2d, 0x1c, 0xfc, 0x79, 0x9c]),
4824 fent.uuid)
4825 self.assertEqual(U_BOOT_DATA, fent.data)
4826
4827 def testFipLs(self):
4828 """Test listing a FIP"""
4829 data = self._DoReadFileRealDtb('207_fip_ls.dts')
4830 hdr, fents = fip_util.decode_fip(data)
4831
4832 try:
4833 tmpdir, updated_fname = self._SetupImageInTmpdir()
4834 with test_util.capture_sys_output() as (stdout, stderr):
4835 self._DoBinman('ls', '-i', updated_fname)
4836 finally:
4837 shutil.rmtree(tmpdir)
4838 lines = stdout.getvalue().splitlines()
4839 expected = [
4840'Name Image-pos Size Entry-type Offset Uncomp-size',
4841'----------------------------------------------------------------',
4842'main-section 0 2d3 section 0',
4843' atf-fip 0 90 atf-fip 0',
4844' soc-fw 88 4 blob-ext 88',
4845' u-boot 8c 4 u-boot 8c',
4846' fdtmap 90 243 fdtmap 90',
4847]
4848 self.assertEqual(expected, lines)
4849
4850 image = control.images['image']
4851 entries = image.GetEntries()
4852 fdtmap = entries['fdtmap']
4853
4854 fdtmap_data = data[fdtmap.image_pos:fdtmap.image_pos + fdtmap.size]
4855 magic = fdtmap_data[:8]
4856 self.assertEqual(b'_FDTMAP_', magic)
4857 self.assertEqual(tools.GetBytes(0, 8), fdtmap_data[8:16])
4858
4859 fdt_data = fdtmap_data[16:]
4860 dtb = fdt.Fdt.FromData(fdt_data)
4861 dtb.Scan()
4862 props = self._GetPropTree(dtb, BASE_DTB_PROPS, prefix='/')
4863 self.assertEqual({
4864 'atf-fip/soc-fw:image-pos': 136,
4865 'atf-fip/soc-fw:offset': 136,
4866 'atf-fip/soc-fw:size': 4,
4867 'atf-fip/u-boot:image-pos': 140,
4868 'atf-fip/u-boot:offset': 140,
4869 'atf-fip/u-boot:size': 4,
4870 'atf-fip:image-pos': 0,
4871 'atf-fip:offset': 0,
4872 'atf-fip:size': 144,
4873 'image-pos': 0,
4874 'offset': 0,
4875 'fdtmap:image-pos': fdtmap.image_pos,
4876 'fdtmap:offset': fdtmap.offset,
4877 'fdtmap:size': len(fdtmap_data),
4878 'size': len(data),
4879 }, props)
4880
4881 def testFipExtractOneEntry(self):
4882 """Test extracting a single entry fron an FIP"""
4883 self._DoReadFileRealDtb('207_fip_ls.dts')
4884 image_fname = tools.GetOutputFilename('image.bin')
4885 fname = os.path.join(self._indir, 'output.extact')
4886 control.ExtractEntries(image_fname, fname, None, ['atf-fip/u-boot'])
4887 data = tools.ReadFile(fname)
4888 self.assertEqual(U_BOOT_DATA, data)
4889
4890 def testFipReplace(self):
4891 """Test replacing a single file in a FIP"""
4892 expected = U_BOOT_DATA + tools.GetBytes(0x78, 50)
4893 data = self._DoReadFileRealDtb('208_fip_replace.dts')
4894 updated_fname = tools.GetOutputFilename('image-updated.bin')
4895 tools.WriteFile(updated_fname, data)
4896 entry_name = 'atf-fip/u-boot'
4897 control.WriteEntry(updated_fname, entry_name, expected,
4898 allow_resize=True)
4899 actual = control.ReadEntry(updated_fname, entry_name)
4900 self.assertEqual(expected, actual)
4901
4902 new_data = tools.ReadFile(updated_fname)
4903 hdr, fents = fip_util.decode_fip(new_data)
4904
4905 self.assertEqual(2, len(fents))
4906
4907 # Check that the FIP entry is updated
4908 fent = fents[1]
4909 self.assertEqual(0x8c, fent.offset)
4910 self.assertEqual(len(expected), fent.size)
4911 self.assertEqual(0, fent.flags)
4912 self.assertEqual(expected, fent.data)
4913 self.assertEqual(True, fent.valid)
4914
4915 def testFipMissing(self):
4916 with test_util.capture_sys_output() as (stdout, stderr):
4917 self._DoTestFile('209_fip_missing.dts', allow_missing=True)
4918 err = stderr.getvalue()
4919 self.assertRegex(err, "Image 'main-section'.*missing.*: rmm-fw")
4920
4921 def testFipSize(self):
4922 """Test a FIP with a size property"""
4923 data = self._DoReadFile('210_fip_size.dts')
4924 self.assertEqual(0x100 + len(U_BOOT_DATA), len(data))
4925 hdr, fents = fip_util.decode_fip(data)
4926 self.assertEqual(fip_util.HEADER_MAGIC, hdr.name)
4927 self.assertEqual(fip_util.HEADER_SERIAL, hdr.serial)
4928
4929 self.assertEqual(1, len(fents))
4930
4931 fent = fents[0]
4932 self.assertEqual('soc-fw', fent.fip_type)
4933 self.assertEqual(0x60, fent.offset)
4934 self.assertEqual(len(ATF_BL31_DATA), fent.size)
4935 self.assertEqual(ATF_BL31_DATA, fent.data)
4936 self.assertEqual(True, fent.valid)
4937
4938 rest = data[0x60 + len(ATF_BL31_DATA):0x100]
4939 self.assertEqual(tools.GetBytes(0xff, len(rest)), rest)
4940
4941 def testFipBadAlign(self):
4942 """Test that an invalid alignment value in a FIP is detected"""
4943 with self.assertRaises(ValueError) as e:
4944 self._DoTestFile('211_fip_bad_align.dts')
4945 self.assertIn(
4946 "Node \'/binman/atf-fip\': FIP alignment 31 must be a power of two",
4947 str(e.exception))
4948
4949 def testFipCollection(self):
4950 """Test using a FIP in a collection"""
4951 data = self._DoReadFile('212_fip_collection.dts')
4952 entry1 = control.images['image'].GetEntries()['collection']
4953 data1 = data[:entry1.size]
4954 hdr1, fents2 = fip_util.decode_fip(data1)
4955
4956 entry2 = control.images['image'].GetEntries()['atf-fip']
4957 data2 = data[entry2.offset:entry2.offset + entry2.size]
4958 hdr1, fents2 = fip_util.decode_fip(data2)
4959
4960 # The 'collection' entry should have U-Boot included at the end
4961 self.assertEqual(entry1.size - len(U_BOOT_DATA), entry2.size)
4962 self.assertEqual(data1, data2 + U_BOOT_DATA)
4963 self.assertEqual(U_BOOT_DATA, data1[-4:])
4964
4965 # There should be a U-Boot after the final FIP
4966 self.assertEqual(U_BOOT_DATA, data[-4:])
Simon Glassc69d19c2021-07-06 10:36:37 -06004967
Simon Glass9fc60b42017-11-12 21:52:22 -07004968if __name__ == "__main__":
4969 unittest.main()