blob: 696889601ef66f18f3e063c4e8b799e2a3c44e8f [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
9from optparse import OptionParser
10import os
11import shutil
12import struct
13import sys
14import tempfile
15import unittest
16
17import binman
18import cmdline
19import command
20import control
Simon Glass19790632017-11-13 18:55:01 -070021import elf
Simon Glass99ed4a22017-05-27 07:38:30 -060022import fdt
Simon Glass4f443042016-11-25 20:15:52 -070023import fdt_util
24import tools
25import tout
26
27# Contents of test files, corresponding to different entry types
Simon Glass6b187df2017-11-12 21:52:27 -070028U_BOOT_DATA = '1234'
29U_BOOT_IMG_DATA = 'img'
Simon Glassf6898902017-11-13 18:54:59 -070030U_BOOT_SPL_DATA = '56780123456789abcde'
Simon Glass6b187df2017-11-12 21:52:27 -070031BLOB_DATA = '89'
32ME_DATA = '0abcd'
33VGA_DATA = 'vga'
34U_BOOT_DTB_DATA = 'udtb'
Simon Glass47419ea2017-11-13 18:54:55 -070035U_BOOT_SPL_DTB_DATA = 'spldtb'
Simon Glass6b187df2017-11-12 21:52:27 -070036X86_START16_DATA = 'start16'
37X86_START16_SPL_DATA = 'start16spl'
38U_BOOT_NODTB_DATA = 'nodtb with microcode pointer somewhere in here'
39U_BOOT_SPL_NODTB_DATA = 'splnodtb with microcode pointer somewhere in here'
40FSP_DATA = 'fsp'
41CMC_DATA = 'cmc'
42VBT_DATA = 'vbt'
Simon Glassca4f4ff2017-11-12 21:52:28 -070043MRC_DATA = 'mrc'
Simon Glassbb748372018-07-17 13:25:33 -060044TEXT_DATA = 'text'
45TEXT_DATA2 = 'text2'
46TEXT_DATA3 = 'text3'
Simon Glass4f443042016-11-25 20:15:52 -070047
48class TestFunctional(unittest.TestCase):
49 """Functional tests for binman
50
51 Most of these use a sample .dts file to build an image and then check
52 that it looks correct. The sample files are in the test/ subdirectory
53 and are numbered.
54
55 For each entry type a very small test file is created using fixed
56 string contents. This makes it easy to test that things look right, and
57 debug problems.
58
59 In some cases a 'real' file must be used - these are also supplied in
60 the test/ diurectory.
61 """
62 @classmethod
63 def setUpClass(self):
Simon Glass4d5994f2017-11-12 21:52:20 -070064 global entry
65 import entry
66
Simon Glass4f443042016-11-25 20:15:52 -070067 # Handle the case where argv[0] is 'python'
68 self._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
69 self._binman_pathname = os.path.join(self._binman_dir, 'binman')
70
71 # Create a temporary directory for input files
72 self._indir = tempfile.mkdtemp(prefix='binmant.')
73
74 # Create some test files
75 TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
76 TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
77 TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
78 TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -070079 TestFunctional._MakeInputFile('me.bin', ME_DATA)
80 TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
Simon Glass4f443042016-11-25 20:15:52 -070081 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
Simon Glass47419ea2017-11-13 18:54:55 -070082 TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -070083 TestFunctional._MakeInputFile('u-boot-x86-16bit.bin', X86_START16_DATA)
Simon Glass87722132017-11-12 21:52:26 -070084 TestFunctional._MakeInputFile('spl/u-boot-x86-16bit-spl.bin',
85 X86_START16_SPL_DATA)
Simon Glass4f443042016-11-25 20:15:52 -070086 TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
Simon Glass6b187df2017-11-12 21:52:27 -070087 TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
88 U_BOOT_SPL_NODTB_DATA)
Simon Glassda229092016-11-25 20:15:56 -070089 TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
90 TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
Bin Meng59ea8c22017-08-15 22:41:54 -070091 TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
Simon Glassca4f4ff2017-11-12 21:52:28 -070092 TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
Simon Glass4f443042016-11-25 20:15:52 -070093 self._output_setup = False
94
Simon Glasse0ff8552016-11-25 20:15:53 -070095 # ELF file with a '_dt_ucode_base_size' symbol
96 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
97 TestFunctional._MakeInputFile('u-boot', fd.read())
98
99 # Intel flash descriptor file
100 with open(self.TestFile('descriptor.bin')) as fd:
101 TestFunctional._MakeInputFile('descriptor.bin', fd.read())
102
Simon Glass4f443042016-11-25 20:15:52 -0700103 @classmethod
104 def tearDownClass(self):
105 """Remove the temporary input directory and its contents"""
106 if self._indir:
107 shutil.rmtree(self._indir)
108 self._indir = None
109
110 def setUp(self):
111 # Enable this to turn on debugging output
112 # tout.Init(tout.DEBUG)
113 command.test_result = None
114
115 def tearDown(self):
116 """Remove the temporary output directory"""
117 tools._FinaliseForTest()
118
119 def _RunBinman(self, *args, **kwargs):
120 """Run binman using the command line
121
122 Args:
123 Arguments to pass, as a list of strings
124 kwargs: Arguments to pass to Command.RunPipe()
125 """
126 result = command.RunPipe([[self._binman_pathname] + list(args)],
127 capture=True, capture_stderr=True, raise_on_error=False)
128 if result.return_code and kwargs.get('raise_on_error', True):
129 raise Exception("Error running '%s': %s" % (' '.join(args),
130 result.stdout + result.stderr))
131 return result
132
133 def _DoBinman(self, *args):
134 """Run binman using directly (in the same process)
135
136 Args:
137 Arguments to pass, as a list of strings
138 Returns:
139 Return value (0 for success)
140 """
Simon Glass7fe91732017-11-13 18:55:00 -0700141 args = list(args)
142 if '-D' in sys.argv:
143 args = args + ['-D']
144 (options, args) = cmdline.ParseArgs(args)
Simon Glass4f443042016-11-25 20:15:52 -0700145 options.pager = 'binman-invalid-pager'
146 options.build_dir = self._indir
147
148 # For testing, you can force an increase in verbosity here
149 # options.verbosity = tout.DEBUG
150 return control.Binman(options, args)
151
Simon Glass53af22a2018-07-17 13:25:32 -0600152 def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
153 entry_args=None):
Simon Glass4f443042016-11-25 20:15:52 -0700154 """Run binman with a given test file
155
156 Args:
Simon Glass7ae5f312018-06-01 09:38:19 -0600157 fname: Device-tree source filename to use (e.g. 05_simple.dts)
158 debug: True to enable debugging output
Simon Glass3b0c3822018-06-01 09:38:20 -0600159 map: True to output map files for the images
Simon Glass3ab95982018-08-01 15:22:37 -0600160 update_dtb: Update the offset and size of each entry in the device
Simon Glass16b8d6b2018-07-06 10:27:42 -0600161 tree before packing it into the image
Simon Glass4f443042016-11-25 20:15:52 -0700162 """
Simon Glass7fe91732017-11-13 18:55:00 -0700163 args = ['-p', '-I', self._indir, '-d', self.TestFile(fname)]
164 if debug:
165 args.append('-D')
Simon Glass3b0c3822018-06-01 09:38:20 -0600166 if map:
167 args.append('-m')
Simon Glass16b8d6b2018-07-06 10:27:42 -0600168 if update_dtb:
169 args.append('-up')
Simon Glass53af22a2018-07-17 13:25:32 -0600170 if entry_args:
171 for arg, value in entry_args.iteritems():
172 args.append('-a%s=%s' % (arg, value))
Simon Glass7fe91732017-11-13 18:55:00 -0700173 return self._DoBinman(*args)
Simon Glass4f443042016-11-25 20:15:52 -0700174
175 def _SetupDtb(self, fname, outfile='u-boot.dtb'):
Simon Glasse0ff8552016-11-25 20:15:53 -0700176 """Set up a new test device-tree file
177
178 The given file is compiled and set up as the device tree to be used
179 for ths test.
180
181 Args:
182 fname: Filename of .dts file to read
Simon Glass7ae5f312018-06-01 09:38:19 -0600183 outfile: Output filename for compiled device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700184
185 Returns:
Simon Glass7ae5f312018-06-01 09:38:19 -0600186 Contents of device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700187 """
Simon Glass4f443042016-11-25 20:15:52 -0700188 if not self._output_setup:
189 tools.PrepareOutputDir(self._indir, True)
190 self._output_setup = True
191 dtb = fdt_util.EnsureCompiled(self.TestFile(fname))
192 with open(dtb) as fd:
193 data = fd.read()
194 TestFunctional._MakeInputFile(outfile, data)
Simon Glasse0ff8552016-11-25 20:15:53 -0700195 return data
Simon Glass4f443042016-11-25 20:15:52 -0700196
Simon Glass16b8d6b2018-07-06 10:27:42 -0600197 def _DoReadFileDtb(self, fname, use_real_dtb=False, map=False,
Simon Glass53af22a2018-07-17 13:25:32 -0600198 update_dtb=False, entry_args=None):
Simon Glass4f443042016-11-25 20:15:52 -0700199 """Run binman and return the resulting image
200
201 This runs binman with a given test file and then reads the resulting
202 output file. It is a shortcut function since most tests need to do
203 these steps.
204
205 Raises an assertion failure if binman returns a non-zero exit code.
206
207 Args:
Simon Glass7ae5f312018-06-01 09:38:19 -0600208 fname: Device-tree source filename to use (e.g. 05_simple.dts)
Simon Glass4f443042016-11-25 20:15:52 -0700209 use_real_dtb: True to use the test file as the contents of
210 the u-boot-dtb entry. Normally this is not needed and the
211 test contents (the U_BOOT_DTB_DATA string) can be used.
212 But in some test we need the real contents.
Simon Glass3b0c3822018-06-01 09:38:20 -0600213 map: True to output map files for the images
Simon Glass3ab95982018-08-01 15:22:37 -0600214 update_dtb: Update the offset and size of each entry in the device
Simon Glass16b8d6b2018-07-06 10:27:42 -0600215 tree before packing it into the image
Simon Glasse0ff8552016-11-25 20:15:53 -0700216
217 Returns:
218 Tuple:
219 Resulting image contents
220 Device tree contents
Simon Glass3b0c3822018-06-01 09:38:20 -0600221 Map data showing contents of image (or None if none)
Simon Glassea6922e2018-07-17 13:25:27 -0600222 Output device tree binary filename ('u-boot.dtb' path)
Simon Glass4f443042016-11-25 20:15:52 -0700223 """
Simon Glasse0ff8552016-11-25 20:15:53 -0700224 dtb_data = None
Simon Glass4f443042016-11-25 20:15:52 -0700225 # Use the compiled test file as the u-boot-dtb input
226 if use_real_dtb:
Simon Glasse0ff8552016-11-25 20:15:53 -0700227 dtb_data = self._SetupDtb(fname)
Simon Glass4f443042016-11-25 20:15:52 -0700228
229 try:
Simon Glass53af22a2018-07-17 13:25:32 -0600230 retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
231 entry_args=entry_args)
Simon Glass4f443042016-11-25 20:15:52 -0700232 self.assertEqual(0, retcode)
Simon Glass16b8d6b2018-07-06 10:27:42 -0600233 out_dtb_fname = control.GetFdtPath('u-boot.dtb')
Simon Glass4f443042016-11-25 20:15:52 -0700234
235 # Find the (only) image, read it and return its contents
236 image = control.images['image']
Simon Glass16b8d6b2018-07-06 10:27:42 -0600237 image_fname = tools.GetOutputFilename('image.bin')
238 self.assertTrue(os.path.exists(image_fname))
Simon Glass3b0c3822018-06-01 09:38:20 -0600239 if map:
240 map_fname = tools.GetOutputFilename('image.map')
241 with open(map_fname) as fd:
242 map_data = fd.read()
243 else:
244 map_data = None
Simon Glass16b8d6b2018-07-06 10:27:42 -0600245 with open(image_fname) as fd:
246 return fd.read(), dtb_data, map_data, out_dtb_fname
Simon Glass4f443042016-11-25 20:15:52 -0700247 finally:
248 # Put the test file back
249 if use_real_dtb:
250 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
251
Simon Glasse0ff8552016-11-25 20:15:53 -0700252 def _DoReadFile(self, fname, use_real_dtb=False):
Simon Glass7ae5f312018-06-01 09:38:19 -0600253 """Helper function which discards the device-tree binary
254
255 Args:
256 fname: Device-tree source filename to use (e.g. 05_simple.dts)
257 use_real_dtb: True to use the test file as the contents of
258 the u-boot-dtb entry. Normally this is not needed and the
259 test contents (the U_BOOT_DTB_DATA string) can be used.
260 But in some test we need the real contents.
Simon Glassea6922e2018-07-17 13:25:27 -0600261
262 Returns:
263 Resulting image contents
Simon Glass7ae5f312018-06-01 09:38:19 -0600264 """
Simon Glasse0ff8552016-11-25 20:15:53 -0700265 return self._DoReadFileDtb(fname, use_real_dtb)[0]
266
Simon Glass4f443042016-11-25 20:15:52 -0700267 @classmethod
268 def _MakeInputFile(self, fname, contents):
269 """Create a new test input file, creating directories as needed
270
271 Args:
Simon Glass3ab95982018-08-01 15:22:37 -0600272 fname: Filename to create
Simon Glass4f443042016-11-25 20:15:52 -0700273 contents: File contents to write in to the file
274 Returns:
275 Full pathname of file created
276 """
277 pathname = os.path.join(self._indir, fname)
278 dirname = os.path.dirname(pathname)
279 if dirname and not os.path.exists(dirname):
280 os.makedirs(dirname)
281 with open(pathname, 'wb') as fd:
282 fd.write(contents)
283 return pathname
284
285 @classmethod
286 def TestFile(self, fname):
287 return os.path.join(self._binman_dir, 'test', fname)
288
289 def AssertInList(self, grep_list, target):
290 """Assert that at least one of a list of things is in a target
291
292 Args:
293 grep_list: List of strings to check
294 target: Target string
295 """
296 for grep in grep_list:
297 if grep in target:
298 return
299 self.fail("Error: '%' not found in '%s'" % (grep_list, target))
300
301 def CheckNoGaps(self, entries):
302 """Check that all entries fit together without gaps
303
304 Args:
305 entries: List of entries to check
306 """
Simon Glass3ab95982018-08-01 15:22:37 -0600307 offset = 0
Simon Glass4f443042016-11-25 20:15:52 -0700308 for entry in entries.values():
Simon Glass3ab95982018-08-01 15:22:37 -0600309 self.assertEqual(offset, entry.offset)
310 offset += entry.size
Simon Glass4f443042016-11-25 20:15:52 -0700311
Simon Glasse0ff8552016-11-25 20:15:53 -0700312 def GetFdtLen(self, dtb):
Simon Glass7ae5f312018-06-01 09:38:19 -0600313 """Get the totalsize field from a device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700314
315 Args:
Simon Glass7ae5f312018-06-01 09:38:19 -0600316 dtb: Device-tree binary contents
Simon Glasse0ff8552016-11-25 20:15:53 -0700317
318 Returns:
Simon Glass7ae5f312018-06-01 09:38:19 -0600319 Total size of device-tree binary, from the header
Simon Glasse0ff8552016-11-25 20:15:53 -0700320 """
321 return struct.unpack('>L', dtb[4:8])[0]
322
Simon Glass16b8d6b2018-07-06 10:27:42 -0600323 def _GetPropTree(self, dtb_data, node_names):
324 def AddNode(node, path):
325 if node.name != '/':
326 path += '/' + node.name
Simon Glass16b8d6b2018-07-06 10:27:42 -0600327 for subnode in node.subnodes:
328 for prop in subnode.props.values():
329 if prop.name in node_names:
330 prop_path = path + '/' + subnode.name + ':' + prop.name
331 tree[prop_path[len('/binman/'):]] = fdt_util.fdt32_to_cpu(
332 prop.value)
Simon Glass16b8d6b2018-07-06 10:27:42 -0600333 AddNode(subnode, path)
334
335 tree = {}
336 dtb = fdt.Fdt(dtb_data)
337 dtb.Scan()
338 AddNode(dtb.GetRoot(), '')
339 return tree
340
Simon Glass4f443042016-11-25 20:15:52 -0700341 def testRun(self):
342 """Test a basic run with valid args"""
343 result = self._RunBinman('-h')
344
345 def testFullHelp(self):
346 """Test that the full help is displayed with -H"""
347 result = self._RunBinman('-H')
348 help_file = os.path.join(self._binman_dir, 'README')
Tom Rini3759df02018-01-16 15:29:50 -0500349 # Remove possible extraneous strings
350 extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
351 gothelp = result.stdout.replace(extra, '')
352 self.assertEqual(len(gothelp), os.path.getsize(help_file))
Simon Glass4f443042016-11-25 20:15:52 -0700353 self.assertEqual(0, len(result.stderr))
354 self.assertEqual(0, result.return_code)
355
356 def testFullHelpInternal(self):
357 """Test that the full help is displayed with -H"""
358 try:
359 command.test_result = command.CommandResult()
360 result = self._DoBinman('-H')
361 help_file = os.path.join(self._binman_dir, 'README')
362 finally:
363 command.test_result = None
364
365 def testHelp(self):
366 """Test that the basic help is displayed with -h"""
367 result = self._RunBinman('-h')
368 self.assertTrue(len(result.stdout) > 200)
369 self.assertEqual(0, len(result.stderr))
370 self.assertEqual(0, result.return_code)
371
Simon Glass4f443042016-11-25 20:15:52 -0700372 def testBoard(self):
373 """Test that we can run it with a specific board"""
374 self._SetupDtb('05_simple.dts', 'sandbox/u-boot.dtb')
375 TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
376 result = self._DoBinman('-b', 'sandbox')
377 self.assertEqual(0, result)
378
379 def testNeedBoard(self):
380 """Test that we get an error when no board ius supplied"""
381 with self.assertRaises(ValueError) as e:
382 result = self._DoBinman()
383 self.assertIn("Must provide a board to process (use -b <board>)",
384 str(e.exception))
385
386 def testMissingDt(self):
Simon Glass7ae5f312018-06-01 09:38:19 -0600387 """Test that an invalid device-tree file generates an error"""
Simon Glass4f443042016-11-25 20:15:52 -0700388 with self.assertRaises(Exception) as e:
389 self._RunBinman('-d', 'missing_file')
390 # We get one error from libfdt, and a different one from fdtget.
391 self.AssertInList(["Couldn't open blob from 'missing_file'",
392 'No such file or directory'], str(e.exception))
393
394 def testBrokenDt(self):
Simon Glass7ae5f312018-06-01 09:38:19 -0600395 """Test that an invalid device-tree source file generates an error
Simon Glass4f443042016-11-25 20:15:52 -0700396
397 Since this is a source file it should be compiled and the error
398 will come from the device-tree compiler (dtc).
399 """
400 with self.assertRaises(Exception) as e:
401 self._RunBinman('-d', self.TestFile('01_invalid.dts'))
402 self.assertIn("FATAL ERROR: Unable to parse input tree",
403 str(e.exception))
404
405 def testMissingNode(self):
406 """Test that a device tree without a 'binman' node generates an error"""
407 with self.assertRaises(Exception) as e:
408 self._DoBinman('-d', self.TestFile('02_missing_node.dts'))
409 self.assertIn("does not have a 'binman' node", str(e.exception))
410
411 def testEmpty(self):
412 """Test that an empty binman node works OK (i.e. does nothing)"""
413 result = self._RunBinman('-d', self.TestFile('03_empty.dts'))
414 self.assertEqual(0, len(result.stderr))
415 self.assertEqual(0, result.return_code)
416
417 def testInvalidEntry(self):
418 """Test that an invalid entry is flagged"""
419 with self.assertRaises(Exception) as e:
420 result = self._RunBinman('-d',
421 self.TestFile('04_invalid_entry.dts'))
Simon Glass4f443042016-11-25 20:15:52 -0700422 self.assertIn("Unknown entry type 'not-a-valid-type' in node "
423 "'/binman/not-a-valid-type'", str(e.exception))
424
425 def testSimple(self):
426 """Test a simple binman with a single file"""
427 data = self._DoReadFile('05_simple.dts')
428 self.assertEqual(U_BOOT_DATA, data)
429
Simon Glass7fe91732017-11-13 18:55:00 -0700430 def testSimpleDebug(self):
431 """Test a simple binman run with debugging enabled"""
432 data = self._DoTestFile('05_simple.dts', debug=True)
433
Simon Glass4f443042016-11-25 20:15:52 -0700434 def testDual(self):
435 """Test that we can handle creating two images
436
437 This also tests image padding.
438 """
439 retcode = self._DoTestFile('06_dual_image.dts')
440 self.assertEqual(0, retcode)
441
442 image = control.images['image1']
443 self.assertEqual(len(U_BOOT_DATA), image._size)
444 fname = tools.GetOutputFilename('image1.bin')
445 self.assertTrue(os.path.exists(fname))
446 with open(fname) as fd:
447 data = fd.read()
448 self.assertEqual(U_BOOT_DATA, data)
449
450 image = control.images['image2']
451 self.assertEqual(3 + len(U_BOOT_DATA) + 5, image._size)
452 fname = tools.GetOutputFilename('image2.bin')
453 self.assertTrue(os.path.exists(fname))
454 with open(fname) as fd:
455 data = fd.read()
456 self.assertEqual(U_BOOT_DATA, data[3:7])
457 self.assertEqual(chr(0) * 3, data[:3])
458 self.assertEqual(chr(0) * 5, data[7:])
459
460 def testBadAlign(self):
461 """Test that an invalid alignment value is detected"""
462 with self.assertRaises(ValueError) as e:
463 self._DoTestFile('07_bad_align.dts')
464 self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
465 "of two", str(e.exception))
466
467 def testPackSimple(self):
468 """Test that packing works as expected"""
469 retcode = self._DoTestFile('08_pack.dts')
470 self.assertEqual(0, retcode)
471 self.assertIn('image', control.images)
472 image = control.images['image']
Simon Glass8f1da502018-06-01 09:38:12 -0600473 entries = image.GetEntries()
Simon Glass4f443042016-11-25 20:15:52 -0700474 self.assertEqual(5, len(entries))
475
476 # First u-boot
477 self.assertIn('u-boot', entries)
478 entry = entries['u-boot']
Simon Glass3ab95982018-08-01 15:22:37 -0600479 self.assertEqual(0, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700480 self.assertEqual(len(U_BOOT_DATA), entry.size)
481
482 # Second u-boot, aligned to 16-byte boundary
483 self.assertIn('u-boot-align', entries)
484 entry = entries['u-boot-align']
Simon Glass3ab95982018-08-01 15:22:37 -0600485 self.assertEqual(16, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700486 self.assertEqual(len(U_BOOT_DATA), entry.size)
487
488 # Third u-boot, size 23 bytes
489 self.assertIn('u-boot-size', entries)
490 entry = entries['u-boot-size']
Simon Glass3ab95982018-08-01 15:22:37 -0600491 self.assertEqual(20, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700492 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
493 self.assertEqual(23, entry.size)
494
495 # Fourth u-boot, placed immediate after the above
496 self.assertIn('u-boot-next', entries)
497 entry = entries['u-boot-next']
Simon Glass3ab95982018-08-01 15:22:37 -0600498 self.assertEqual(43, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700499 self.assertEqual(len(U_BOOT_DATA), entry.size)
500
Simon Glass3ab95982018-08-01 15:22:37 -0600501 # Fifth u-boot, placed at a fixed offset
Simon Glass4f443042016-11-25 20:15:52 -0700502 self.assertIn('u-boot-fixed', entries)
503 entry = entries['u-boot-fixed']
Simon Glass3ab95982018-08-01 15:22:37 -0600504 self.assertEqual(61, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700505 self.assertEqual(len(U_BOOT_DATA), entry.size)
506
507 self.assertEqual(65, image._size)
508
509 def testPackExtra(self):
510 """Test that extra packing feature works as expected"""
511 retcode = self._DoTestFile('09_pack_extra.dts')
512
513 self.assertEqual(0, retcode)
514 self.assertIn('image', control.images)
515 image = control.images['image']
Simon Glass8f1da502018-06-01 09:38:12 -0600516 entries = image.GetEntries()
Simon Glass4f443042016-11-25 20:15:52 -0700517 self.assertEqual(5, len(entries))
518
519 # First u-boot with padding before and after
520 self.assertIn('u-boot', entries)
521 entry = entries['u-boot']
Simon Glass3ab95982018-08-01 15:22:37 -0600522 self.assertEqual(0, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700523 self.assertEqual(3, entry.pad_before)
524 self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
525
526 # Second u-boot has an aligned size, but it has no effect
527 self.assertIn('u-boot-align-size-nop', entries)
528 entry = entries['u-boot-align-size-nop']
Simon Glass3ab95982018-08-01 15:22:37 -0600529 self.assertEqual(12, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700530 self.assertEqual(4, entry.size)
531
532 # Third u-boot has an aligned size too
533 self.assertIn('u-boot-align-size', entries)
534 entry = entries['u-boot-align-size']
Simon Glass3ab95982018-08-01 15:22:37 -0600535 self.assertEqual(16, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700536 self.assertEqual(32, entry.size)
537
538 # Fourth u-boot has an aligned end
539 self.assertIn('u-boot-align-end', entries)
540 entry = entries['u-boot-align-end']
Simon Glass3ab95982018-08-01 15:22:37 -0600541 self.assertEqual(48, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700542 self.assertEqual(16, entry.size)
543
544 # Fifth u-boot immediately afterwards
545 self.assertIn('u-boot-align-both', entries)
546 entry = entries['u-boot-align-both']
Simon Glass3ab95982018-08-01 15:22:37 -0600547 self.assertEqual(64, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700548 self.assertEqual(64, entry.size)
549
550 self.CheckNoGaps(entries)
551 self.assertEqual(128, image._size)
552
553 def testPackAlignPowerOf2(self):
554 """Test that invalid entry alignment is detected"""
555 with self.assertRaises(ValueError) as e:
556 self._DoTestFile('10_pack_align_power2.dts')
557 self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
558 "of two", str(e.exception))
559
560 def testPackAlignSizePowerOf2(self):
561 """Test that invalid entry size alignment is detected"""
562 with self.assertRaises(ValueError) as e:
563 self._DoTestFile('11_pack_align_size_power2.dts')
564 self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
565 "power of two", str(e.exception))
566
567 def testPackInvalidAlign(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600568 """Test detection of an offset that does not match its alignment"""
Simon Glass4f443042016-11-25 20:15:52 -0700569 with self.assertRaises(ValueError) as e:
570 self._DoTestFile('12_pack_inv_align.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600571 self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
Simon Glass4f443042016-11-25 20:15:52 -0700572 "align 0x4 (4)", str(e.exception))
573
574 def testPackInvalidSizeAlign(self):
575 """Test that invalid entry size alignment is detected"""
576 with self.assertRaises(ValueError) as e:
577 self._DoTestFile('13_pack_inv_size_align.dts')
578 self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
579 "align-size 0x4 (4)", str(e.exception))
580
581 def testPackOverlap(self):
582 """Test that overlapping regions are detected"""
583 with self.assertRaises(ValueError) as e:
584 self._DoTestFile('14_pack_overlap.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600585 self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
Simon Glass4f443042016-11-25 20:15:52 -0700586 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
587 str(e.exception))
588
589 def testPackEntryOverflow(self):
590 """Test that entries that overflow their size are detected"""
591 with self.assertRaises(ValueError) as e:
592 self._DoTestFile('15_pack_overflow.dts')
593 self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
594 "but entry size is 0x3 (3)", str(e.exception))
595
596 def testPackImageOverflow(self):
597 """Test that entries which overflow the image size are detected"""
598 with self.assertRaises(ValueError) as e:
599 self._DoTestFile('16_pack_image_overflow.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600600 self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
Simon Glass4f443042016-11-25 20:15:52 -0700601 "size 0x3 (3)", str(e.exception))
602
603 def testPackImageSize(self):
604 """Test that the image size can be set"""
605 retcode = self._DoTestFile('17_pack_image_size.dts')
606 self.assertEqual(0, retcode)
607 self.assertIn('image', control.images)
608 image = control.images['image']
609 self.assertEqual(7, image._size)
610
611 def testPackImageSizeAlign(self):
612 """Test that image size alignemnt works as expected"""
613 retcode = self._DoTestFile('18_pack_image_align.dts')
614 self.assertEqual(0, retcode)
615 self.assertIn('image', control.images)
616 image = control.images['image']
617 self.assertEqual(16, image._size)
618
619 def testPackInvalidImageAlign(self):
620 """Test that invalid image alignment is detected"""
621 with self.assertRaises(ValueError) as e:
622 self._DoTestFile('19_pack_inv_image_align.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600623 self.assertIn("Section '/binman': Size 0x7 (7) does not match "
Simon Glass4f443042016-11-25 20:15:52 -0700624 "align-size 0x8 (8)", str(e.exception))
625
626 def testPackAlignPowerOf2(self):
627 """Test that invalid image alignment is detected"""
628 with self.assertRaises(ValueError) as e:
629 self._DoTestFile('20_pack_inv_image_align_power2.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600630 self.assertIn("Section '/binman': Alignment size 131 must be a power of "
Simon Glass4f443042016-11-25 20:15:52 -0700631 "two", str(e.exception))
632
633 def testImagePadByte(self):
634 """Test that the image pad byte can be specified"""
Simon Glass19790632017-11-13 18:55:01 -0700635 with open(self.TestFile('bss_data')) as fd:
636 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
Simon Glass4f443042016-11-25 20:15:52 -0700637 data = self._DoReadFile('21_image_pad.dts')
Simon Glassf6898902017-11-13 18:54:59 -0700638 self.assertEqual(U_BOOT_SPL_DATA + (chr(0xff) * 1) + U_BOOT_DATA, data)
Simon Glass4f443042016-11-25 20:15:52 -0700639
640 def testImageName(self):
641 """Test that image files can be named"""
642 retcode = self._DoTestFile('22_image_name.dts')
643 self.assertEqual(0, retcode)
644 image = control.images['image1']
645 fname = tools.GetOutputFilename('test-name')
646 self.assertTrue(os.path.exists(fname))
647
648 image = control.images['image2']
649 fname = tools.GetOutputFilename('test-name.xx')
650 self.assertTrue(os.path.exists(fname))
651
652 def testBlobFilename(self):
653 """Test that generic blobs can be provided by filename"""
654 data = self._DoReadFile('23_blob.dts')
655 self.assertEqual(BLOB_DATA, data)
656
657 def testPackSorted(self):
658 """Test that entries can be sorted"""
659 data = self._DoReadFile('24_sorted.dts')
Simon Glassf6898902017-11-13 18:54:59 -0700660 self.assertEqual(chr(0) * 1 + U_BOOT_SPL_DATA + chr(0) * 2 +
Simon Glass4f443042016-11-25 20:15:52 -0700661 U_BOOT_DATA, data)
662
Simon Glass3ab95982018-08-01 15:22:37 -0600663 def testPackZeroOffset(self):
664 """Test that an entry at offset 0 is not given a new offset"""
Simon Glass4f443042016-11-25 20:15:52 -0700665 with self.assertRaises(ValueError) as e:
666 self._DoTestFile('25_pack_zero_size.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600667 self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
Simon Glass4f443042016-11-25 20:15:52 -0700668 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
669 str(e.exception))
670
671 def testPackUbootDtb(self):
672 """Test that a device tree can be added to U-Boot"""
673 data = self._DoReadFile('26_pack_u_boot_dtb.dts')
674 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
Simon Glasse0ff8552016-11-25 20:15:53 -0700675
676 def testPackX86RomNoSize(self):
677 """Test that the end-at-4gb property requires a size property"""
678 with self.assertRaises(ValueError) as e:
679 self._DoTestFile('27_pack_4gb_no_size.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600680 self.assertIn("Section '/binman': Section size must be provided when "
Simon Glasse0ff8552016-11-25 20:15:53 -0700681 "using end-at-4gb", str(e.exception))
682
683 def testPackX86RomOutside(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600684 """Test that the end-at-4gb property checks for offset boundaries"""
Simon Glasse0ff8552016-11-25 20:15:53 -0700685 with self.assertRaises(ValueError) as e:
686 self._DoTestFile('28_pack_4gb_outside.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600687 self.assertIn("Node '/binman/u-boot': Offset 0x0 (0) is outside "
Simon Glass8f1da502018-06-01 09:38:12 -0600688 "the section starting at 0xffffffe0 (4294967264)",
Simon Glasse0ff8552016-11-25 20:15:53 -0700689 str(e.exception))
690
691 def testPackX86Rom(self):
692 """Test that a basic x86 ROM can be created"""
693 data = self._DoReadFile('29_x86-rom.dts')
Simon Glassf6898902017-11-13 18:54:59 -0700694 self.assertEqual(U_BOOT_DATA + chr(0) * 7 + U_BOOT_SPL_DATA +
695 chr(0) * 2, data)
Simon Glasse0ff8552016-11-25 20:15:53 -0700696
697 def testPackX86RomMeNoDesc(self):
698 """Test that an invalid Intel descriptor entry is detected"""
699 TestFunctional._MakeInputFile('descriptor.bin', '')
700 with self.assertRaises(ValueError) as e:
701 self._DoTestFile('31_x86-rom-me.dts')
702 self.assertIn("Node '/binman/intel-descriptor': Cannot find FD "
703 "signature", str(e.exception))
704
705 def testPackX86RomBadDesc(self):
706 """Test that the Intel requires a descriptor entry"""
707 with self.assertRaises(ValueError) as e:
708 self._DoTestFile('30_x86-rom-me-no-desc.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600709 self.assertIn("Node '/binman/intel-me': No offset set with "
710 "offset-unset: should another entry provide this correct "
711 "offset?", str(e.exception))
Simon Glasse0ff8552016-11-25 20:15:53 -0700712
713 def testPackX86RomMe(self):
714 """Test that an x86 ROM with an ME region can be created"""
715 data = self._DoReadFile('31_x86-rom-me.dts')
716 self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
717
718 def testPackVga(self):
719 """Test that an image with a VGA binary can be created"""
720 data = self._DoReadFile('32_intel-vga.dts')
721 self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
722
723 def testPackStart16(self):
724 """Test that an image with an x86 start16 region can be created"""
725 data = self._DoReadFile('33_x86-start16.dts')
726 self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
727
Simon Glass736bb0a2018-07-06 10:27:17 -0600728 def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
Simon Glassadc57012018-07-06 10:27:16 -0600729 """Handle running a test for insertion of microcode
730
731 Args:
732 dts_fname: Name of test .dts file
733 nodtb_data: Data that we expect in the first section
Simon Glass736bb0a2018-07-06 10:27:17 -0600734 ucode_second: True if the microsecond entry is second instead of
735 third
Simon Glassadc57012018-07-06 10:27:16 -0600736
737 Returns:
738 Tuple:
739 Contents of first region (U-Boot or SPL)
Simon Glass3ab95982018-08-01 15:22:37 -0600740 Offset and size components of microcode pointer, as inserted
Simon Glassadc57012018-07-06 10:27:16 -0600741 in the above (two 4-byte words)
742 """
Simon Glass6b187df2017-11-12 21:52:27 -0700743 data = self._DoReadFile(dts_fname, True)
Simon Glasse0ff8552016-11-25 20:15:53 -0700744
745 # Now check the device tree has no microcode
Simon Glass736bb0a2018-07-06 10:27:17 -0600746 if ucode_second:
747 ucode_content = data[len(nodtb_data):]
748 ucode_pos = len(nodtb_data)
749 dtb_with_ucode = ucode_content[16:]
750 fdt_len = self.GetFdtLen(dtb_with_ucode)
751 else:
752 dtb_with_ucode = data[len(nodtb_data):]
753 fdt_len = self.GetFdtLen(dtb_with_ucode)
754 ucode_content = dtb_with_ucode[fdt_len:]
755 ucode_pos = len(nodtb_data) + fdt_len
Simon Glasse0ff8552016-11-25 20:15:53 -0700756 fname = tools.GetOutputFilename('test.dtb')
757 with open(fname, 'wb') as fd:
Simon Glassadc57012018-07-06 10:27:16 -0600758 fd.write(dtb_with_ucode)
Simon Glassec3f3782017-05-27 07:38:29 -0600759 dtb = fdt.FdtScan(fname)
760 ucode = dtb.GetNode('/microcode')
Simon Glasse0ff8552016-11-25 20:15:53 -0700761 self.assertTrue(ucode)
762 for node in ucode.subnodes:
763 self.assertFalse(node.props.get('data'))
764
Simon Glasse0ff8552016-11-25 20:15:53 -0700765 # Check that the microcode appears immediately after the Fdt
766 # This matches the concatenation of the data properties in
Simon Glass87722132017-11-12 21:52:26 -0700767 # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
Simon Glasse0ff8552016-11-25 20:15:53 -0700768 ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
769 0x78235609)
Simon Glassadc57012018-07-06 10:27:16 -0600770 self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
Simon Glasse0ff8552016-11-25 20:15:53 -0700771
772 # Check that the microcode pointer was inserted. It should match the
Simon Glass3ab95982018-08-01 15:22:37 -0600773 # expected offset and size
Simon Glasse0ff8552016-11-25 20:15:53 -0700774 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
775 len(ucode_data))
Simon Glass736bb0a2018-07-06 10:27:17 -0600776 u_boot = data[:len(nodtb_data)]
777 return u_boot, pos_and_size
Simon Glass6b187df2017-11-12 21:52:27 -0700778
779 def testPackUbootMicrocode(self):
780 """Test that x86 microcode can be handled correctly
781
782 We expect to see the following in the image, in order:
783 u-boot-nodtb.bin with a microcode pointer inserted at the correct
784 place
785 u-boot.dtb with the microcode removed
786 the microcode
787 """
788 first, pos_and_size = self._RunMicrocodeTest('34_x86_ucode.dts',
789 U_BOOT_NODTB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -0700790 self.assertEqual('nodtb with microcode' + pos_and_size +
791 ' somewhere in here', first)
792
Simon Glass160a7662017-05-27 07:38:26 -0600793 def _RunPackUbootSingleMicrocode(self):
Simon Glasse0ff8552016-11-25 20:15:53 -0700794 """Test that x86 microcode can be handled correctly
795
796 We expect to see the following in the image, in order:
797 u-boot-nodtb.bin with a microcode pointer inserted at the correct
798 place
799 u-boot.dtb with the microcode
800 an empty microcode region
801 """
802 # We need the libfdt library to run this test since only that allows
803 # finding the offset of a property. This is required by
804 # Entry_u_boot_dtb_with_ucode.ObtainContents().
Simon Glasse0ff8552016-11-25 20:15:53 -0700805 data = self._DoReadFile('35_x86_single_ucode.dts', True)
806
807 second = data[len(U_BOOT_NODTB_DATA):]
808
809 fdt_len = self.GetFdtLen(second)
810 third = second[fdt_len:]
811 second = second[:fdt_len]
812
Simon Glass160a7662017-05-27 07:38:26 -0600813 ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
814 self.assertIn(ucode_data, second)
815 ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -0700816
Simon Glass160a7662017-05-27 07:38:26 -0600817 # Check that the microcode pointer was inserted. It should match the
Simon Glass3ab95982018-08-01 15:22:37 -0600818 # expected offset and size
Simon Glass160a7662017-05-27 07:38:26 -0600819 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
820 len(ucode_data))
821 first = data[:len(U_BOOT_NODTB_DATA)]
822 self.assertEqual('nodtb with microcode' + pos_and_size +
823 ' somewhere in here', first)
Simon Glassc49deb82016-11-25 20:15:54 -0700824
Simon Glass75db0862016-11-25 20:15:55 -0700825 def testPackUbootSingleMicrocode(self):
826 """Test that x86 microcode can be handled correctly with fdt_normal.
827 """
Simon Glass160a7662017-05-27 07:38:26 -0600828 self._RunPackUbootSingleMicrocode()
Simon Glass75db0862016-11-25 20:15:55 -0700829
Simon Glassc49deb82016-11-25 20:15:54 -0700830 def testUBootImg(self):
831 """Test that u-boot.img can be put in a file"""
832 data = self._DoReadFile('36_u_boot_img.dts')
833 self.assertEqual(U_BOOT_IMG_DATA, data)
Simon Glass75db0862016-11-25 20:15:55 -0700834
835 def testNoMicrocode(self):
836 """Test that a missing microcode region is detected"""
837 with self.assertRaises(ValueError) as e:
838 self._DoReadFile('37_x86_no_ucode.dts', True)
839 self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
840 "node found in ", str(e.exception))
841
842 def testMicrocodeWithoutNode(self):
843 """Test that a missing u-boot-dtb-with-ucode node is detected"""
844 with self.assertRaises(ValueError) as e:
845 self._DoReadFile('38_x86_ucode_missing_node.dts', True)
846 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
847 "microcode region u-boot-dtb-with-ucode", str(e.exception))
848
849 def testMicrocodeWithoutNode2(self):
850 """Test that a missing u-boot-ucode node is detected"""
851 with self.assertRaises(ValueError) as e:
852 self._DoReadFile('39_x86_ucode_missing_node2.dts', True)
853 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
854 "microcode region u-boot-ucode", str(e.exception))
855
856 def testMicrocodeWithoutPtrInElf(self):
857 """Test that a U-Boot binary without the microcode symbol is detected"""
858 # ELF file without a '_dt_ucode_base_size' symbol
Simon Glass75db0862016-11-25 20:15:55 -0700859 try:
860 with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
861 TestFunctional._MakeInputFile('u-boot', fd.read())
862
863 with self.assertRaises(ValueError) as e:
Simon Glass160a7662017-05-27 07:38:26 -0600864 self._RunPackUbootSingleMicrocode()
Simon Glass75db0862016-11-25 20:15:55 -0700865 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
866 "_dt_ucode_base_size symbol in u-boot", str(e.exception))
867
868 finally:
869 # Put the original file back
870 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
871 TestFunctional._MakeInputFile('u-boot', fd.read())
872
873 def testMicrocodeNotInImage(self):
874 """Test that microcode must be placed within the image"""
875 with self.assertRaises(ValueError) as e:
876 self._DoReadFile('40_x86_ucode_not_in_image.dts', True)
877 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
878 "pointer _dt_ucode_base_size at fffffe14 is outside the "
Simon Glass25ac0e62018-06-01 09:38:14 -0600879 "section ranging from 00000000 to 0000002e", str(e.exception))
Simon Glass75db0862016-11-25 20:15:55 -0700880
881 def testWithoutMicrocode(self):
882 """Test that we can cope with an image without microcode (e.g. qemu)"""
883 with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
884 TestFunctional._MakeInputFile('u-boot', fd.read())
Simon Glass16b8d6b2018-07-06 10:27:42 -0600885 data, dtb, _, _ = self._DoReadFileDtb('44_x86_optional_ucode.dts', True)
Simon Glass75db0862016-11-25 20:15:55 -0700886
887 # Now check the device tree has no microcode
888 self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
889 second = data[len(U_BOOT_NODTB_DATA):]
890
891 fdt_len = self.GetFdtLen(second)
892 self.assertEqual(dtb, second[:fdt_len])
893
894 used_len = len(U_BOOT_NODTB_DATA) + fdt_len
895 third = data[used_len:]
896 self.assertEqual(chr(0) * (0x200 - used_len), third)
897
898 def testUnknownPosSize(self):
899 """Test that microcode must be placed within the image"""
900 with self.assertRaises(ValueError) as e:
901 self._DoReadFile('41_unknown_pos_size.dts', True)
Simon Glass3ab95982018-08-01 15:22:37 -0600902 self.assertIn("Section '/binman': Unable to set offset/size for unknown "
Simon Glass75db0862016-11-25 20:15:55 -0700903 "entry 'invalid-entry'", str(e.exception))
Simon Glassda229092016-11-25 20:15:56 -0700904
905 def testPackFsp(self):
906 """Test that an image with a FSP binary can be created"""
907 data = self._DoReadFile('42_intel-fsp.dts')
908 self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
909
910 def testPackCmc(self):
Bin Meng59ea8c22017-08-15 22:41:54 -0700911 """Test that an image with a CMC binary can be created"""
Simon Glassda229092016-11-25 20:15:56 -0700912 data = self._DoReadFile('43_intel-cmc.dts')
913 self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
Bin Meng59ea8c22017-08-15 22:41:54 -0700914
915 def testPackVbt(self):
916 """Test that an image with a VBT binary can be created"""
917 data = self._DoReadFile('46_intel-vbt.dts')
918 self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
Simon Glass9fc60b42017-11-12 21:52:22 -0700919
Simon Glass56509842017-11-12 21:52:25 -0700920 def testSplBssPad(self):
921 """Test that we can pad SPL's BSS with zeros"""
Simon Glass6b187df2017-11-12 21:52:27 -0700922 # ELF file with a '__bss_size' symbol
923 with open(self.TestFile('bss_data')) as fd:
924 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
Simon Glass56509842017-11-12 21:52:25 -0700925 data = self._DoReadFile('47_spl_bss_pad.dts')
926 self.assertEqual(U_BOOT_SPL_DATA + (chr(0) * 10) + U_BOOT_DATA, data)
927
Simon Glassb50e5612017-11-13 18:54:54 -0700928 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
929 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
930 with self.assertRaises(ValueError) as e:
931 data = self._DoReadFile('47_spl_bss_pad.dts')
932 self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
933 str(e.exception))
934
Simon Glass87722132017-11-12 21:52:26 -0700935 def testPackStart16Spl(self):
936 """Test that an image with an x86 start16 region can be created"""
937 data = self._DoReadFile('48_x86-start16-spl.dts')
938 self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
939
Simon Glass736bb0a2018-07-06 10:27:17 -0600940 def _PackUbootSplMicrocode(self, dts, ucode_second=False):
941 """Helper function for microcode tests
Simon Glass6b187df2017-11-12 21:52:27 -0700942
943 We expect to see the following in the image, in order:
944 u-boot-spl-nodtb.bin with a microcode pointer inserted at the
945 correct place
946 u-boot.dtb with the microcode removed
947 the microcode
Simon Glass736bb0a2018-07-06 10:27:17 -0600948
949 Args:
950 dts: Device tree file to use for test
951 ucode_second: True if the microsecond entry is second instead of
952 third
Simon Glass6b187df2017-11-12 21:52:27 -0700953 """
954 # ELF file with a '_dt_ucode_base_size' symbol
955 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
956 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
Simon Glass736bb0a2018-07-06 10:27:17 -0600957 first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
958 ucode_second=ucode_second)
Simon Glass6b187df2017-11-12 21:52:27 -0700959 self.assertEqual('splnodtb with microc' + pos_and_size +
960 'ter somewhere in here', first)
961
Simon Glass736bb0a2018-07-06 10:27:17 -0600962 def testPackUbootSplMicrocode(self):
963 """Test that x86 microcode can be handled correctly in SPL"""
964 self._PackUbootSplMicrocode('49_x86_ucode_spl.dts')
965
966 def testPackUbootSplMicrocodeReorder(self):
967 """Test that order doesn't matter for microcode entries
968
969 This is the same as testPackUbootSplMicrocode but when we process the
970 u-boot-ucode entry we have not yet seen the u-boot-dtb-with-ucode
971 entry, so we reply on binman to try later.
972 """
973 self._PackUbootSplMicrocode('58_x86_ucode_spl_needs_retry.dts',
974 ucode_second=True)
975
Simon Glassca4f4ff2017-11-12 21:52:28 -0700976 def testPackMrc(self):
977 """Test that an image with an MRC binary can be created"""
978 data = self._DoReadFile('50_intel_mrc.dts')
979 self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
980
Simon Glass47419ea2017-11-13 18:54:55 -0700981 def testSplDtb(self):
982 """Test that an image with spl/u-boot-spl.dtb can be created"""
983 data = self._DoReadFile('51_u_boot_spl_dtb.dts')
984 self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
985
Simon Glass4e6fdbe2017-11-13 18:54:56 -0700986 def testSplNoDtb(self):
987 """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
988 data = self._DoReadFile('52_u_boot_spl_nodtb.dts')
989 self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
990
Simon Glass19790632017-11-13 18:55:01 -0700991 def testSymbols(self):
992 """Test binman can assign symbols embedded in U-Boot"""
993 elf_fname = self.TestFile('u_boot_binman_syms')
994 syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
995 addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
Simon Glass3ab95982018-08-01 15:22:37 -0600996 self.assertEqual(syms['_binman_u_boot_spl_prop_offset'].address, addr)
Simon Glass19790632017-11-13 18:55:01 -0700997
998 with open(self.TestFile('u_boot_binman_syms')) as fd:
999 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
1000 data = self._DoReadFile('53_symbols.dts')
1001 sym_values = struct.pack('<LQL', 0x24 + 0, 0x24 + 24, 0x24 + 20)
1002 expected = (sym_values + U_BOOT_SPL_DATA[16:] + chr(0xff) +
1003 U_BOOT_DATA +
1004 sym_values + U_BOOT_SPL_DATA[16:])
1005 self.assertEqual(expected, data)
1006
Simon Glassdd57c132018-06-01 09:38:11 -06001007 def testPackUnitAddress(self):
1008 """Test that we support multiple binaries with the same name"""
1009 data = self._DoReadFile('54_unit_address.dts')
1010 self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
1011
Simon Glass18546952018-06-01 09:38:16 -06001012 def testSections(self):
1013 """Basic test of sections"""
1014 data = self._DoReadFile('55_sections.dts')
Simon Glass8122f392018-07-17 13:25:28 -06001015 expected = (U_BOOT_DATA + '!' * 12 + U_BOOT_DATA + 'a' * 12 +
1016 U_BOOT_DATA + '&' * 4)
Simon Glass18546952018-06-01 09:38:16 -06001017 self.assertEqual(expected, data)
Simon Glass9fc60b42017-11-12 21:52:22 -07001018
Simon Glass3b0c3822018-06-01 09:38:20 -06001019 def testMap(self):
1020 """Tests outputting a map of the images"""
Simon Glass16b8d6b2018-07-06 10:27:42 -06001021 _, _, map_data, _ = self._DoReadFileDtb('55_sections.dts', map=True)
Simon Glass3ab95982018-08-01 15:22:37 -06001022 self.assertEqual(''' Offset Size Name
Simon Glass8122f392018-07-17 13:25:28 -0600102300000000 00000028 main-section
1024 00000000 00000010 section@0
1025 00000000 00000004 u-boot
1026 00000010 00000010 section@1
1027 00000000 00000004 u-boot
1028 00000020 00000004 section@2
1029 00000000 00000004 u-boot
Simon Glass3b0c3822018-06-01 09:38:20 -06001030''', map_data)
1031
Simon Glassc8d48ef2018-06-01 09:38:21 -06001032 def testNamePrefix(self):
1033 """Tests that name prefixes are used"""
Simon Glass16b8d6b2018-07-06 10:27:42 -06001034 _, _, map_data, _ = self._DoReadFileDtb('56_name_prefix.dts', map=True)
Simon Glass3ab95982018-08-01 15:22:37 -06001035 self.assertEqual(''' Offset Size Name
Simon Glass8122f392018-07-17 13:25:28 -0600103600000000 00000028 main-section
1037 00000000 00000010 section@0
1038 00000000 00000004 ro-u-boot
1039 00000010 00000010 section@1
1040 00000000 00000004 rw-u-boot
Simon Glassc8d48ef2018-06-01 09:38:21 -06001041''', map_data)
1042
Simon Glass736bb0a2018-07-06 10:27:17 -06001043 def testUnknownContents(self):
1044 """Test that obtaining the contents works as expected"""
1045 with self.assertRaises(ValueError) as e:
1046 self._DoReadFile('57_unknown_contents.dts', True)
1047 self.assertIn("Section '/binman': Internal error: Could not complete "
1048 "processing of contents: remaining [<_testing.Entry__testing ",
1049 str(e.exception))
1050
Simon Glass5c890232018-07-06 10:27:19 -06001051 def testBadChangeSize(self):
1052 """Test that trying to change the size of an entry fails"""
1053 with self.assertRaises(ValueError) as e:
1054 self._DoReadFile('59_change_size.dts', True)
1055 self.assertIn("Node '/binman/_testing': Cannot update entry size from "
1056 '2 to 1', str(e.exception))
1057
Simon Glass16b8d6b2018-07-06 10:27:42 -06001058 def testUpdateFdt(self):
Simon Glass3ab95982018-08-01 15:22:37 -06001059 """Test that we can update the device tree with offset/size info"""
Simon Glass16b8d6b2018-07-06 10:27:42 -06001060 _, _, _, out_dtb_fname = self._DoReadFileDtb('60_fdt_update.dts',
1061 update_dtb=True)
Simon Glassdbf6be92018-08-01 15:22:42 -06001062 props = self._GetPropTree(out_dtb_fname, ['offset', 'size',
1063 'image-pos'])
Simon Glass16b8d6b2018-07-06 10:27:42 -06001064 with open('/tmp/x.dtb', 'wb') as outf:
1065 with open(out_dtb_fname) as inf:
1066 outf.write(inf.read())
1067 self.assertEqual({
Simon Glassdbf6be92018-08-01 15:22:42 -06001068 'image-pos': 0,
Simon Glass8122f392018-07-17 13:25:28 -06001069 'offset': 0,
Simon Glass3ab95982018-08-01 15:22:37 -06001070 '_testing:offset': 32,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001071 '_testing:size': 1,
Simon Glassdbf6be92018-08-01 15:22:42 -06001072 '_testing:image-pos': 32,
Simon Glass3ab95982018-08-01 15:22:37 -06001073 'section@0/u-boot:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001074 'section@0/u-boot:size': len(U_BOOT_DATA),
Simon Glassdbf6be92018-08-01 15:22:42 -06001075 'section@0/u-boot:image-pos': 0,
Simon Glass3ab95982018-08-01 15:22:37 -06001076 'section@0:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001077 'section@0:size': 16,
Simon Glassdbf6be92018-08-01 15:22:42 -06001078 'section@0:image-pos': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001079
Simon Glass3ab95982018-08-01 15:22:37 -06001080 'section@1/u-boot:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001081 'section@1/u-boot:size': len(U_BOOT_DATA),
Simon Glassdbf6be92018-08-01 15:22:42 -06001082 'section@1/u-boot:image-pos': 16,
Simon Glass3ab95982018-08-01 15:22:37 -06001083 'section@1:offset': 16,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001084 'section@1:size': 16,
Simon Glassdbf6be92018-08-01 15:22:42 -06001085 'section@1:image-pos': 16,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001086 'size': 40
1087 }, props)
1088
1089 def testUpdateFdtBad(self):
1090 """Test that we detect when ProcessFdt never completes"""
1091 with self.assertRaises(ValueError) as e:
1092 self._DoReadFileDtb('61_fdt_update_bad.dts', update_dtb=True)
1093 self.assertIn('Could not complete processing of Fdt: remaining '
1094 '[<_testing.Entry__testing', str(e.exception))
Simon Glass5c890232018-07-06 10:27:19 -06001095
Simon Glass53af22a2018-07-17 13:25:32 -06001096 def testEntryArgs(self):
1097 """Test passing arguments to entries from the command line"""
1098 entry_args = {
1099 'test-str-arg': 'test1',
1100 'test-int-arg': '456',
1101 }
1102 self._DoReadFileDtb('62_entry_args.dts', entry_args=entry_args)
1103 self.assertIn('image', control.images)
1104 entry = control.images['image'].GetEntries()['_testing']
1105 self.assertEqual('test0', entry.test_str_fdt)
1106 self.assertEqual('test1', entry.test_str_arg)
1107 self.assertEqual(123, entry.test_int_fdt)
1108 self.assertEqual(456, entry.test_int_arg)
1109
1110 def testEntryArgsMissing(self):
1111 """Test missing arguments and properties"""
1112 entry_args = {
1113 'test-int-arg': '456',
1114 }
1115 self._DoReadFileDtb('63_entry_args_missing.dts', entry_args=entry_args)
1116 entry = control.images['image'].GetEntries()['_testing']
1117 self.assertEqual('test0', entry.test_str_fdt)
1118 self.assertEqual(None, entry.test_str_arg)
1119 self.assertEqual(None, entry.test_int_fdt)
1120 self.assertEqual(456, entry.test_int_arg)
1121
1122 def testEntryArgsRequired(self):
1123 """Test missing arguments and properties"""
1124 entry_args = {
1125 'test-int-arg': '456',
1126 }
1127 with self.assertRaises(ValueError) as e:
1128 self._DoReadFileDtb('64_entry_args_required.dts')
1129 self.assertIn("Node '/binman/_testing': Missing required "
1130 'properties/entry args: test-str-arg, test-int-fdt, test-int-arg',
1131 str(e.exception))
1132
1133 def testEntryArgsInvalidFormat(self):
1134 """Test that an invalid entry-argument format is detected"""
1135 args = ['-d', self.TestFile('64_entry_args_required.dts'), '-ano-value']
1136 with self.assertRaises(ValueError) as e:
1137 self._DoBinman(*args)
1138 self.assertIn("Invalid entry arguemnt 'no-value'", str(e.exception))
1139
1140 def testEntryArgsInvalidInteger(self):
1141 """Test that an invalid entry-argument integer is detected"""
1142 entry_args = {
1143 'test-int-arg': 'abc',
1144 }
1145 with self.assertRaises(ValueError) as e:
1146 self._DoReadFileDtb('62_entry_args.dts', entry_args=entry_args)
1147 self.assertIn("Node '/binman/_testing': Cannot convert entry arg "
1148 "'test-int-arg' (value 'abc') to integer",
1149 str(e.exception))
1150
1151 def testEntryArgsInvalidDatatype(self):
1152 """Test that an invalid entry-argument datatype is detected
1153
1154 This test could be written in entry_test.py except that it needs
1155 access to control.entry_args, which seems more than that module should
1156 be able to see.
1157 """
1158 entry_args = {
1159 'test-bad-datatype-arg': '12',
1160 }
1161 with self.assertRaises(ValueError) as e:
1162 self._DoReadFileDtb('65_entry_args_unknown_datatype.dts',
1163 entry_args=entry_args)
1164 self.assertIn('GetArg() internal error: Unknown data type ',
1165 str(e.exception))
1166
Simon Glassbb748372018-07-17 13:25:33 -06001167 def testText(self):
1168 """Test for a text entry type"""
1169 entry_args = {
1170 'test-id': TEXT_DATA,
1171 'test-id2': TEXT_DATA2,
1172 'test-id3': TEXT_DATA3,
1173 }
1174 data, _, _, _ = self._DoReadFileDtb('66_text.dts',
1175 entry_args=entry_args)
1176 expected = (TEXT_DATA + chr(0) * (8 - len(TEXT_DATA)) + TEXT_DATA2 +
1177 TEXT_DATA3 + 'some text')
1178 self.assertEqual(expected, data)
1179
Simon Glass53af22a2018-07-17 13:25:32 -06001180
Simon Glass9fc60b42017-11-12 21:52:22 -07001181if __name__ == "__main__":
1182 unittest.main()