blob: 4e467145d711380928e7407d374204db19747b39 [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
Simon Glass11e36cc2018-07-17 13:25:38 -060024import fmap_util
Simon Glassfd8d1f72018-07-17 13:25:36 -060025import test_util
Simon Glass4f443042016-11-25 20:15:52 -070026import tools
27import tout
28
29# Contents of test files, corresponding to different entry types
Simon Glass6b187df2017-11-12 21:52:27 -070030U_BOOT_DATA = '1234'
31U_BOOT_IMG_DATA = 'img'
Simon Glassf6898902017-11-13 18:54:59 -070032U_BOOT_SPL_DATA = '56780123456789abcde'
Simon Glass6b187df2017-11-12 21:52:27 -070033BLOB_DATA = '89'
34ME_DATA = '0abcd'
35VGA_DATA = 'vga'
36U_BOOT_DTB_DATA = 'udtb'
Simon Glass47419ea2017-11-13 18:54:55 -070037U_BOOT_SPL_DTB_DATA = 'spldtb'
Simon Glass6b187df2017-11-12 21:52:27 -070038X86_START16_DATA = 'start16'
39X86_START16_SPL_DATA = 'start16spl'
40U_BOOT_NODTB_DATA = 'nodtb with microcode pointer somewhere in here'
41U_BOOT_SPL_NODTB_DATA = 'splnodtb with microcode pointer somewhere in here'
42FSP_DATA = 'fsp'
43CMC_DATA = 'cmc'
44VBT_DATA = 'vbt'
Simon Glassca4f4ff2017-11-12 21:52:28 -070045MRC_DATA = 'mrc'
Simon Glassbb748372018-07-17 13:25:33 -060046TEXT_DATA = 'text'
47TEXT_DATA2 = 'text2'
48TEXT_DATA3 = 'text3'
Simon Glassec127af2018-07-17 13:25:39 -060049CROS_EC_RW_DATA = 'ecrw'
50
Simon Glass4f443042016-11-25 20:15:52 -070051
52class TestFunctional(unittest.TestCase):
53 """Functional tests for binman
54
55 Most of these use a sample .dts file to build an image and then check
56 that it looks correct. The sample files are in the test/ subdirectory
57 and are numbered.
58
59 For each entry type a very small test file is created using fixed
60 string contents. This makes it easy to test that things look right, and
61 debug problems.
62
63 In some cases a 'real' file must be used - these are also supplied in
64 the test/ diurectory.
65 """
66 @classmethod
67 def setUpClass(self):
Simon Glass4d5994f2017-11-12 21:52:20 -070068 global entry
69 import entry
70
Simon Glass4f443042016-11-25 20:15:52 -070071 # Handle the case where argv[0] is 'python'
72 self._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
73 self._binman_pathname = os.path.join(self._binman_dir, 'binman')
74
75 # Create a temporary directory for input files
76 self._indir = tempfile.mkdtemp(prefix='binmant.')
77
78 # Create some test files
79 TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
80 TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
81 TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
82 TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -070083 TestFunctional._MakeInputFile('me.bin', ME_DATA)
84 TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
Simon Glass4f443042016-11-25 20:15:52 -070085 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
Simon Glass47419ea2017-11-13 18:54:55 -070086 TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -070087 TestFunctional._MakeInputFile('u-boot-x86-16bit.bin', X86_START16_DATA)
Simon Glass87722132017-11-12 21:52:26 -070088 TestFunctional._MakeInputFile('spl/u-boot-x86-16bit-spl.bin',
89 X86_START16_SPL_DATA)
Simon Glass4f443042016-11-25 20:15:52 -070090 TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
Simon Glass6b187df2017-11-12 21:52:27 -070091 TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
92 U_BOOT_SPL_NODTB_DATA)
Simon Glassda229092016-11-25 20:15:56 -070093 TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
94 TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
Bin Meng59ea8c22017-08-15 22:41:54 -070095 TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
Simon Glassca4f4ff2017-11-12 21:52:28 -070096 TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
Simon Glassec127af2018-07-17 13:25:39 -060097 TestFunctional._MakeInputFile('ecrw.bin', CROS_EC_RW_DATA)
Simon Glass4f443042016-11-25 20:15:52 -070098 self._output_setup = False
99
Simon Glasse0ff8552016-11-25 20:15:53 -0700100 # ELF file with a '_dt_ucode_base_size' symbol
101 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
102 TestFunctional._MakeInputFile('u-boot', fd.read())
103
104 # Intel flash descriptor file
105 with open(self.TestFile('descriptor.bin')) as fd:
106 TestFunctional._MakeInputFile('descriptor.bin', fd.read())
107
Simon Glass4f443042016-11-25 20:15:52 -0700108 @classmethod
109 def tearDownClass(self):
110 """Remove the temporary input directory and its contents"""
111 if self._indir:
112 shutil.rmtree(self._indir)
113 self._indir = None
114
115 def setUp(self):
116 # Enable this to turn on debugging output
117 # tout.Init(tout.DEBUG)
118 command.test_result = None
119
120 def tearDown(self):
121 """Remove the temporary output directory"""
122 tools._FinaliseForTest()
123
124 def _RunBinman(self, *args, **kwargs):
125 """Run binman using the command line
126
127 Args:
128 Arguments to pass, as a list of strings
129 kwargs: Arguments to pass to Command.RunPipe()
130 """
131 result = command.RunPipe([[self._binman_pathname] + list(args)],
132 capture=True, capture_stderr=True, raise_on_error=False)
133 if result.return_code and kwargs.get('raise_on_error', True):
134 raise Exception("Error running '%s': %s" % (' '.join(args),
135 result.stdout + result.stderr))
136 return result
137
138 def _DoBinman(self, *args):
139 """Run binman using directly (in the same process)
140
141 Args:
142 Arguments to pass, as a list of strings
143 Returns:
144 Return value (0 for success)
145 """
Simon Glass7fe91732017-11-13 18:55:00 -0700146 args = list(args)
147 if '-D' in sys.argv:
148 args = args + ['-D']
149 (options, args) = cmdline.ParseArgs(args)
Simon Glass4f443042016-11-25 20:15:52 -0700150 options.pager = 'binman-invalid-pager'
151 options.build_dir = self._indir
152
153 # For testing, you can force an increase in verbosity here
154 # options.verbosity = tout.DEBUG
155 return control.Binman(options, args)
156
Simon Glass53af22a2018-07-17 13:25:32 -0600157 def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
158 entry_args=None):
Simon Glass4f443042016-11-25 20:15:52 -0700159 """Run binman with a given test file
160
161 Args:
Simon Glass7ae5f312018-06-01 09:38:19 -0600162 fname: Device-tree source filename to use (e.g. 05_simple.dts)
163 debug: True to enable debugging output
Simon Glass3b0c3822018-06-01 09:38:20 -0600164 map: True to output map files for the images
Simon Glass3ab95982018-08-01 15:22:37 -0600165 update_dtb: Update the offset and size of each entry in the device
Simon Glass16b8d6b2018-07-06 10:27:42 -0600166 tree before packing it into the image
Simon Glass4f443042016-11-25 20:15:52 -0700167 """
Simon Glass7fe91732017-11-13 18:55:00 -0700168 args = ['-p', '-I', self._indir, '-d', self.TestFile(fname)]
169 if debug:
170 args.append('-D')
Simon Glass3b0c3822018-06-01 09:38:20 -0600171 if map:
172 args.append('-m')
Simon Glass16b8d6b2018-07-06 10:27:42 -0600173 if update_dtb:
174 args.append('-up')
Simon Glass53af22a2018-07-17 13:25:32 -0600175 if entry_args:
176 for arg, value in entry_args.iteritems():
177 args.append('-a%s=%s' % (arg, value))
Simon Glass7fe91732017-11-13 18:55:00 -0700178 return self._DoBinman(*args)
Simon Glass4f443042016-11-25 20:15:52 -0700179
180 def _SetupDtb(self, fname, outfile='u-boot.dtb'):
Simon Glasse0ff8552016-11-25 20:15:53 -0700181 """Set up a new test device-tree file
182
183 The given file is compiled and set up as the device tree to be used
184 for ths test.
185
186 Args:
187 fname: Filename of .dts file to read
Simon Glass7ae5f312018-06-01 09:38:19 -0600188 outfile: Output filename for compiled device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700189
190 Returns:
Simon Glass7ae5f312018-06-01 09:38:19 -0600191 Contents of device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700192 """
Simon Glass4f443042016-11-25 20:15:52 -0700193 if not self._output_setup:
194 tools.PrepareOutputDir(self._indir, True)
195 self._output_setup = True
196 dtb = fdt_util.EnsureCompiled(self.TestFile(fname))
197 with open(dtb) as fd:
198 data = fd.read()
199 TestFunctional._MakeInputFile(outfile, data)
Simon Glasse0ff8552016-11-25 20:15:53 -0700200 return data
Simon Glass4f443042016-11-25 20:15:52 -0700201
Simon Glass16b8d6b2018-07-06 10:27:42 -0600202 def _DoReadFileDtb(self, fname, use_real_dtb=False, map=False,
Simon Glass53af22a2018-07-17 13:25:32 -0600203 update_dtb=False, entry_args=None):
Simon Glass4f443042016-11-25 20:15:52 -0700204 """Run binman and return the resulting image
205
206 This runs binman with a given test file and then reads the resulting
207 output file. It is a shortcut function since most tests need to do
208 these steps.
209
210 Raises an assertion failure if binman returns a non-zero exit code.
211
212 Args:
Simon Glass7ae5f312018-06-01 09:38:19 -0600213 fname: Device-tree source filename to use (e.g. 05_simple.dts)
Simon Glass4f443042016-11-25 20:15:52 -0700214 use_real_dtb: True to use the test file as the contents of
215 the u-boot-dtb entry. Normally this is not needed and the
216 test contents (the U_BOOT_DTB_DATA string) can be used.
217 But in some test we need the real contents.
Simon Glass3b0c3822018-06-01 09:38:20 -0600218 map: True to output map files for the images
Simon Glass3ab95982018-08-01 15:22:37 -0600219 update_dtb: Update the offset and size of each entry in the device
Simon Glass16b8d6b2018-07-06 10:27:42 -0600220 tree before packing it into the image
Simon Glasse0ff8552016-11-25 20:15:53 -0700221
222 Returns:
223 Tuple:
224 Resulting image contents
225 Device tree contents
Simon Glass3b0c3822018-06-01 09:38:20 -0600226 Map data showing contents of image (or None if none)
Simon Glassea6922e2018-07-17 13:25:27 -0600227 Output device tree binary filename ('u-boot.dtb' path)
Simon Glass4f443042016-11-25 20:15:52 -0700228 """
Simon Glasse0ff8552016-11-25 20:15:53 -0700229 dtb_data = None
Simon Glass4f443042016-11-25 20:15:52 -0700230 # Use the compiled test file as the u-boot-dtb input
231 if use_real_dtb:
Simon Glasse0ff8552016-11-25 20:15:53 -0700232 dtb_data = self._SetupDtb(fname)
Simon Glass4f443042016-11-25 20:15:52 -0700233
234 try:
Simon Glass53af22a2018-07-17 13:25:32 -0600235 retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
236 entry_args=entry_args)
Simon Glass4f443042016-11-25 20:15:52 -0700237 self.assertEqual(0, retcode)
Simon Glass16b8d6b2018-07-06 10:27:42 -0600238 out_dtb_fname = control.GetFdtPath('u-boot.dtb')
Simon Glass4f443042016-11-25 20:15:52 -0700239
240 # Find the (only) image, read it and return its contents
241 image = control.images['image']
Simon Glass16b8d6b2018-07-06 10:27:42 -0600242 image_fname = tools.GetOutputFilename('image.bin')
243 self.assertTrue(os.path.exists(image_fname))
Simon Glass3b0c3822018-06-01 09:38:20 -0600244 if map:
245 map_fname = tools.GetOutputFilename('image.map')
246 with open(map_fname) as fd:
247 map_data = fd.read()
248 else:
249 map_data = None
Simon Glass16b8d6b2018-07-06 10:27:42 -0600250 with open(image_fname) as fd:
251 return fd.read(), dtb_data, map_data, out_dtb_fname
Simon Glass4f443042016-11-25 20:15:52 -0700252 finally:
253 # Put the test file back
254 if use_real_dtb:
255 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
256
Simon Glasse0ff8552016-11-25 20:15:53 -0700257 def _DoReadFile(self, fname, use_real_dtb=False):
Simon Glass7ae5f312018-06-01 09:38:19 -0600258 """Helper function which discards the device-tree binary
259
260 Args:
261 fname: Device-tree source filename to use (e.g. 05_simple.dts)
262 use_real_dtb: True to use the test file as the contents of
263 the u-boot-dtb entry. Normally this is not needed and the
264 test contents (the U_BOOT_DTB_DATA string) can be used.
265 But in some test we need the real contents.
Simon Glassea6922e2018-07-17 13:25:27 -0600266
267 Returns:
268 Resulting image contents
Simon Glass7ae5f312018-06-01 09:38:19 -0600269 """
Simon Glasse0ff8552016-11-25 20:15:53 -0700270 return self._DoReadFileDtb(fname, use_real_dtb)[0]
271
Simon Glass4f443042016-11-25 20:15:52 -0700272 @classmethod
273 def _MakeInputFile(self, fname, contents):
274 """Create a new test input file, creating directories as needed
275
276 Args:
Simon Glass3ab95982018-08-01 15:22:37 -0600277 fname: Filename to create
Simon Glass4f443042016-11-25 20:15:52 -0700278 contents: File contents to write in to the file
279 Returns:
280 Full pathname of file created
281 """
282 pathname = os.path.join(self._indir, fname)
283 dirname = os.path.dirname(pathname)
284 if dirname and not os.path.exists(dirname):
285 os.makedirs(dirname)
286 with open(pathname, 'wb') as fd:
287 fd.write(contents)
288 return pathname
289
290 @classmethod
291 def TestFile(self, fname):
292 return os.path.join(self._binman_dir, 'test', fname)
293
294 def AssertInList(self, grep_list, target):
295 """Assert that at least one of a list of things is in a target
296
297 Args:
298 grep_list: List of strings to check
299 target: Target string
300 """
301 for grep in grep_list:
302 if grep in target:
303 return
304 self.fail("Error: '%' not found in '%s'" % (grep_list, target))
305
306 def CheckNoGaps(self, entries):
307 """Check that all entries fit together without gaps
308
309 Args:
310 entries: List of entries to check
311 """
Simon Glass3ab95982018-08-01 15:22:37 -0600312 offset = 0
Simon Glass4f443042016-11-25 20:15:52 -0700313 for entry in entries.values():
Simon Glass3ab95982018-08-01 15:22:37 -0600314 self.assertEqual(offset, entry.offset)
315 offset += entry.size
Simon Glass4f443042016-11-25 20:15:52 -0700316
Simon Glasse0ff8552016-11-25 20:15:53 -0700317 def GetFdtLen(self, dtb):
Simon Glass7ae5f312018-06-01 09:38:19 -0600318 """Get the totalsize field from a device-tree binary
Simon Glasse0ff8552016-11-25 20:15:53 -0700319
320 Args:
Simon Glass7ae5f312018-06-01 09:38:19 -0600321 dtb: Device-tree binary contents
Simon Glasse0ff8552016-11-25 20:15:53 -0700322
323 Returns:
Simon Glass7ae5f312018-06-01 09:38:19 -0600324 Total size of device-tree binary, from the header
Simon Glasse0ff8552016-11-25 20:15:53 -0700325 """
326 return struct.unpack('>L', dtb[4:8])[0]
327
Simon Glass16b8d6b2018-07-06 10:27:42 -0600328 def _GetPropTree(self, dtb_data, node_names):
329 def AddNode(node, path):
330 if node.name != '/':
331 path += '/' + node.name
Simon Glass16b8d6b2018-07-06 10:27:42 -0600332 for subnode in node.subnodes:
333 for prop in subnode.props.values():
334 if prop.name in node_names:
335 prop_path = path + '/' + subnode.name + ':' + prop.name
336 tree[prop_path[len('/binman/'):]] = fdt_util.fdt32_to_cpu(
337 prop.value)
Simon Glass16b8d6b2018-07-06 10:27:42 -0600338 AddNode(subnode, path)
339
340 tree = {}
341 dtb = fdt.Fdt(dtb_data)
342 dtb.Scan()
343 AddNode(dtb.GetRoot(), '')
344 return tree
345
Simon Glass4f443042016-11-25 20:15:52 -0700346 def testRun(self):
347 """Test a basic run with valid args"""
348 result = self._RunBinman('-h')
349
350 def testFullHelp(self):
351 """Test that the full help is displayed with -H"""
352 result = self._RunBinman('-H')
353 help_file = os.path.join(self._binman_dir, 'README')
Tom Rini3759df02018-01-16 15:29:50 -0500354 # Remove possible extraneous strings
355 extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
356 gothelp = result.stdout.replace(extra, '')
357 self.assertEqual(len(gothelp), os.path.getsize(help_file))
Simon Glass4f443042016-11-25 20:15:52 -0700358 self.assertEqual(0, len(result.stderr))
359 self.assertEqual(0, result.return_code)
360
361 def testFullHelpInternal(self):
362 """Test that the full help is displayed with -H"""
363 try:
364 command.test_result = command.CommandResult()
365 result = self._DoBinman('-H')
366 help_file = os.path.join(self._binman_dir, 'README')
367 finally:
368 command.test_result = None
369
370 def testHelp(self):
371 """Test that the basic help is displayed with -h"""
372 result = self._RunBinman('-h')
373 self.assertTrue(len(result.stdout) > 200)
374 self.assertEqual(0, len(result.stderr))
375 self.assertEqual(0, result.return_code)
376
Simon Glass4f443042016-11-25 20:15:52 -0700377 def testBoard(self):
378 """Test that we can run it with a specific board"""
379 self._SetupDtb('05_simple.dts', 'sandbox/u-boot.dtb')
380 TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
381 result = self._DoBinman('-b', 'sandbox')
382 self.assertEqual(0, result)
383
384 def testNeedBoard(self):
385 """Test that we get an error when no board ius supplied"""
386 with self.assertRaises(ValueError) as e:
387 result = self._DoBinman()
388 self.assertIn("Must provide a board to process (use -b <board>)",
389 str(e.exception))
390
391 def testMissingDt(self):
Simon Glass7ae5f312018-06-01 09:38:19 -0600392 """Test that an invalid device-tree file generates an error"""
Simon Glass4f443042016-11-25 20:15:52 -0700393 with self.assertRaises(Exception) as e:
394 self._RunBinman('-d', 'missing_file')
395 # We get one error from libfdt, and a different one from fdtget.
396 self.AssertInList(["Couldn't open blob from 'missing_file'",
397 'No such file or directory'], str(e.exception))
398
399 def testBrokenDt(self):
Simon Glass7ae5f312018-06-01 09:38:19 -0600400 """Test that an invalid device-tree source file generates an error
Simon Glass4f443042016-11-25 20:15:52 -0700401
402 Since this is a source file it should be compiled and the error
403 will come from the device-tree compiler (dtc).
404 """
405 with self.assertRaises(Exception) as e:
406 self._RunBinman('-d', self.TestFile('01_invalid.dts'))
407 self.assertIn("FATAL ERROR: Unable to parse input tree",
408 str(e.exception))
409
410 def testMissingNode(self):
411 """Test that a device tree without a 'binman' node generates an error"""
412 with self.assertRaises(Exception) as e:
413 self._DoBinman('-d', self.TestFile('02_missing_node.dts'))
414 self.assertIn("does not have a 'binman' node", str(e.exception))
415
416 def testEmpty(self):
417 """Test that an empty binman node works OK (i.e. does nothing)"""
418 result = self._RunBinman('-d', self.TestFile('03_empty.dts'))
419 self.assertEqual(0, len(result.stderr))
420 self.assertEqual(0, result.return_code)
421
422 def testInvalidEntry(self):
423 """Test that an invalid entry is flagged"""
424 with self.assertRaises(Exception) as e:
425 result = self._RunBinman('-d',
426 self.TestFile('04_invalid_entry.dts'))
Simon Glass4f443042016-11-25 20:15:52 -0700427 self.assertIn("Unknown entry type 'not-a-valid-type' in node "
428 "'/binman/not-a-valid-type'", str(e.exception))
429
430 def testSimple(self):
431 """Test a simple binman with a single file"""
432 data = self._DoReadFile('05_simple.dts')
433 self.assertEqual(U_BOOT_DATA, data)
434
Simon Glass7fe91732017-11-13 18:55:00 -0700435 def testSimpleDebug(self):
436 """Test a simple binman run with debugging enabled"""
437 data = self._DoTestFile('05_simple.dts', debug=True)
438
Simon Glass4f443042016-11-25 20:15:52 -0700439 def testDual(self):
440 """Test that we can handle creating two images
441
442 This also tests image padding.
443 """
444 retcode = self._DoTestFile('06_dual_image.dts')
445 self.assertEqual(0, retcode)
446
447 image = control.images['image1']
448 self.assertEqual(len(U_BOOT_DATA), image._size)
449 fname = tools.GetOutputFilename('image1.bin')
450 self.assertTrue(os.path.exists(fname))
451 with open(fname) as fd:
452 data = fd.read()
453 self.assertEqual(U_BOOT_DATA, data)
454
455 image = control.images['image2']
456 self.assertEqual(3 + len(U_BOOT_DATA) + 5, image._size)
457 fname = tools.GetOutputFilename('image2.bin')
458 self.assertTrue(os.path.exists(fname))
459 with open(fname) as fd:
460 data = fd.read()
461 self.assertEqual(U_BOOT_DATA, data[3:7])
462 self.assertEqual(chr(0) * 3, data[:3])
463 self.assertEqual(chr(0) * 5, data[7:])
464
465 def testBadAlign(self):
466 """Test that an invalid alignment value is detected"""
467 with self.assertRaises(ValueError) as e:
468 self._DoTestFile('07_bad_align.dts')
469 self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
470 "of two", str(e.exception))
471
472 def testPackSimple(self):
473 """Test that packing works as expected"""
474 retcode = self._DoTestFile('08_pack.dts')
475 self.assertEqual(0, retcode)
476 self.assertIn('image', control.images)
477 image = control.images['image']
Simon Glass8f1da502018-06-01 09:38:12 -0600478 entries = image.GetEntries()
Simon Glass4f443042016-11-25 20:15:52 -0700479 self.assertEqual(5, len(entries))
480
481 # First u-boot
482 self.assertIn('u-boot', entries)
483 entry = entries['u-boot']
Simon Glass3ab95982018-08-01 15:22:37 -0600484 self.assertEqual(0, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700485 self.assertEqual(len(U_BOOT_DATA), entry.size)
486
487 # Second u-boot, aligned to 16-byte boundary
488 self.assertIn('u-boot-align', entries)
489 entry = entries['u-boot-align']
Simon Glass3ab95982018-08-01 15:22:37 -0600490 self.assertEqual(16, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700491 self.assertEqual(len(U_BOOT_DATA), entry.size)
492
493 # Third u-boot, size 23 bytes
494 self.assertIn('u-boot-size', entries)
495 entry = entries['u-boot-size']
Simon Glass3ab95982018-08-01 15:22:37 -0600496 self.assertEqual(20, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700497 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
498 self.assertEqual(23, entry.size)
499
500 # Fourth u-boot, placed immediate after the above
501 self.assertIn('u-boot-next', entries)
502 entry = entries['u-boot-next']
Simon Glass3ab95982018-08-01 15:22:37 -0600503 self.assertEqual(43, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700504 self.assertEqual(len(U_BOOT_DATA), entry.size)
505
Simon Glass3ab95982018-08-01 15:22:37 -0600506 # Fifth u-boot, placed at a fixed offset
Simon Glass4f443042016-11-25 20:15:52 -0700507 self.assertIn('u-boot-fixed', entries)
508 entry = entries['u-boot-fixed']
Simon Glass3ab95982018-08-01 15:22:37 -0600509 self.assertEqual(61, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700510 self.assertEqual(len(U_BOOT_DATA), entry.size)
511
512 self.assertEqual(65, image._size)
513
514 def testPackExtra(self):
515 """Test that extra packing feature works as expected"""
516 retcode = self._DoTestFile('09_pack_extra.dts')
517
518 self.assertEqual(0, retcode)
519 self.assertIn('image', control.images)
520 image = control.images['image']
Simon Glass8f1da502018-06-01 09:38:12 -0600521 entries = image.GetEntries()
Simon Glass4f443042016-11-25 20:15:52 -0700522 self.assertEqual(5, len(entries))
523
524 # First u-boot with padding before and after
525 self.assertIn('u-boot', entries)
526 entry = entries['u-boot']
Simon Glass3ab95982018-08-01 15:22:37 -0600527 self.assertEqual(0, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700528 self.assertEqual(3, entry.pad_before)
529 self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
530
531 # Second u-boot has an aligned size, but it has no effect
532 self.assertIn('u-boot-align-size-nop', entries)
533 entry = entries['u-boot-align-size-nop']
Simon Glass3ab95982018-08-01 15:22:37 -0600534 self.assertEqual(12, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700535 self.assertEqual(4, entry.size)
536
537 # Third u-boot has an aligned size too
538 self.assertIn('u-boot-align-size', entries)
539 entry = entries['u-boot-align-size']
Simon Glass3ab95982018-08-01 15:22:37 -0600540 self.assertEqual(16, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700541 self.assertEqual(32, entry.size)
542
543 # Fourth u-boot has an aligned end
544 self.assertIn('u-boot-align-end', entries)
545 entry = entries['u-boot-align-end']
Simon Glass3ab95982018-08-01 15:22:37 -0600546 self.assertEqual(48, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700547 self.assertEqual(16, entry.size)
548
549 # Fifth u-boot immediately afterwards
550 self.assertIn('u-boot-align-both', entries)
551 entry = entries['u-boot-align-both']
Simon Glass3ab95982018-08-01 15:22:37 -0600552 self.assertEqual(64, entry.offset)
Simon Glass4f443042016-11-25 20:15:52 -0700553 self.assertEqual(64, entry.size)
554
555 self.CheckNoGaps(entries)
556 self.assertEqual(128, image._size)
557
558 def testPackAlignPowerOf2(self):
559 """Test that invalid entry alignment is detected"""
560 with self.assertRaises(ValueError) as e:
561 self._DoTestFile('10_pack_align_power2.dts')
562 self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
563 "of two", str(e.exception))
564
565 def testPackAlignSizePowerOf2(self):
566 """Test that invalid entry size alignment is detected"""
567 with self.assertRaises(ValueError) as e:
568 self._DoTestFile('11_pack_align_size_power2.dts')
569 self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
570 "power of two", str(e.exception))
571
572 def testPackInvalidAlign(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600573 """Test detection of an offset that does not match its alignment"""
Simon Glass4f443042016-11-25 20:15:52 -0700574 with self.assertRaises(ValueError) as e:
575 self._DoTestFile('12_pack_inv_align.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600576 self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
Simon Glass4f443042016-11-25 20:15:52 -0700577 "align 0x4 (4)", str(e.exception))
578
579 def testPackInvalidSizeAlign(self):
580 """Test that invalid entry size alignment is detected"""
581 with self.assertRaises(ValueError) as e:
582 self._DoTestFile('13_pack_inv_size_align.dts')
583 self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
584 "align-size 0x4 (4)", str(e.exception))
585
586 def testPackOverlap(self):
587 """Test that overlapping regions are detected"""
588 with self.assertRaises(ValueError) as e:
589 self._DoTestFile('14_pack_overlap.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600590 self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
Simon Glass4f443042016-11-25 20:15:52 -0700591 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
592 str(e.exception))
593
594 def testPackEntryOverflow(self):
595 """Test that entries that overflow their size are detected"""
596 with self.assertRaises(ValueError) as e:
597 self._DoTestFile('15_pack_overflow.dts')
598 self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
599 "but entry size is 0x3 (3)", str(e.exception))
600
601 def testPackImageOverflow(self):
602 """Test that entries which overflow the image size are detected"""
603 with self.assertRaises(ValueError) as e:
604 self._DoTestFile('16_pack_image_overflow.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600605 self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
Simon Glass4f443042016-11-25 20:15:52 -0700606 "size 0x3 (3)", str(e.exception))
607
608 def testPackImageSize(self):
609 """Test that the image size can be set"""
610 retcode = self._DoTestFile('17_pack_image_size.dts')
611 self.assertEqual(0, retcode)
612 self.assertIn('image', control.images)
613 image = control.images['image']
614 self.assertEqual(7, image._size)
615
616 def testPackImageSizeAlign(self):
617 """Test that image size alignemnt works as expected"""
618 retcode = self._DoTestFile('18_pack_image_align.dts')
619 self.assertEqual(0, retcode)
620 self.assertIn('image', control.images)
621 image = control.images['image']
622 self.assertEqual(16, image._size)
623
624 def testPackInvalidImageAlign(self):
625 """Test that invalid image alignment is detected"""
626 with self.assertRaises(ValueError) as e:
627 self._DoTestFile('19_pack_inv_image_align.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600628 self.assertIn("Section '/binman': Size 0x7 (7) does not match "
Simon Glass4f443042016-11-25 20:15:52 -0700629 "align-size 0x8 (8)", str(e.exception))
630
631 def testPackAlignPowerOf2(self):
632 """Test that invalid image alignment is detected"""
633 with self.assertRaises(ValueError) as e:
634 self._DoTestFile('20_pack_inv_image_align_power2.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600635 self.assertIn("Section '/binman': Alignment size 131 must be a power of "
Simon Glass4f443042016-11-25 20:15:52 -0700636 "two", str(e.exception))
637
638 def testImagePadByte(self):
639 """Test that the image pad byte can be specified"""
Simon Glass19790632017-11-13 18:55:01 -0700640 with open(self.TestFile('bss_data')) as fd:
641 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
Simon Glass4f443042016-11-25 20:15:52 -0700642 data = self._DoReadFile('21_image_pad.dts')
Simon Glassf6898902017-11-13 18:54:59 -0700643 self.assertEqual(U_BOOT_SPL_DATA + (chr(0xff) * 1) + U_BOOT_DATA, data)
Simon Glass4f443042016-11-25 20:15:52 -0700644
645 def testImageName(self):
646 """Test that image files can be named"""
647 retcode = self._DoTestFile('22_image_name.dts')
648 self.assertEqual(0, retcode)
649 image = control.images['image1']
650 fname = tools.GetOutputFilename('test-name')
651 self.assertTrue(os.path.exists(fname))
652
653 image = control.images['image2']
654 fname = tools.GetOutputFilename('test-name.xx')
655 self.assertTrue(os.path.exists(fname))
656
657 def testBlobFilename(self):
658 """Test that generic blobs can be provided by filename"""
659 data = self._DoReadFile('23_blob.dts')
660 self.assertEqual(BLOB_DATA, data)
661
662 def testPackSorted(self):
663 """Test that entries can be sorted"""
664 data = self._DoReadFile('24_sorted.dts')
Simon Glassf6898902017-11-13 18:54:59 -0700665 self.assertEqual(chr(0) * 1 + U_BOOT_SPL_DATA + chr(0) * 2 +
Simon Glass4f443042016-11-25 20:15:52 -0700666 U_BOOT_DATA, data)
667
Simon Glass3ab95982018-08-01 15:22:37 -0600668 def testPackZeroOffset(self):
669 """Test that an entry at offset 0 is not given a new offset"""
Simon Glass4f443042016-11-25 20:15:52 -0700670 with self.assertRaises(ValueError) as e:
671 self._DoTestFile('25_pack_zero_size.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600672 self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
Simon Glass4f443042016-11-25 20:15:52 -0700673 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
674 str(e.exception))
675
676 def testPackUbootDtb(self):
677 """Test that a device tree can be added to U-Boot"""
678 data = self._DoReadFile('26_pack_u_boot_dtb.dts')
679 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
Simon Glasse0ff8552016-11-25 20:15:53 -0700680
681 def testPackX86RomNoSize(self):
682 """Test that the end-at-4gb property requires a size property"""
683 with self.assertRaises(ValueError) as e:
684 self._DoTestFile('27_pack_4gb_no_size.dts')
Simon Glass8f1da502018-06-01 09:38:12 -0600685 self.assertIn("Section '/binman': Section size must be provided when "
Simon Glasse0ff8552016-11-25 20:15:53 -0700686 "using end-at-4gb", str(e.exception))
687
688 def testPackX86RomOutside(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600689 """Test that the end-at-4gb property checks for offset boundaries"""
Simon Glasse0ff8552016-11-25 20:15:53 -0700690 with self.assertRaises(ValueError) as e:
691 self._DoTestFile('28_pack_4gb_outside.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600692 self.assertIn("Node '/binman/u-boot': Offset 0x0 (0) is outside "
Simon Glass8f1da502018-06-01 09:38:12 -0600693 "the section starting at 0xffffffe0 (4294967264)",
Simon Glasse0ff8552016-11-25 20:15:53 -0700694 str(e.exception))
695
696 def testPackX86Rom(self):
697 """Test that a basic x86 ROM can be created"""
698 data = self._DoReadFile('29_x86-rom.dts')
Simon Glassf6898902017-11-13 18:54:59 -0700699 self.assertEqual(U_BOOT_DATA + chr(0) * 7 + U_BOOT_SPL_DATA +
700 chr(0) * 2, data)
Simon Glasse0ff8552016-11-25 20:15:53 -0700701
702 def testPackX86RomMeNoDesc(self):
703 """Test that an invalid Intel descriptor entry is detected"""
704 TestFunctional._MakeInputFile('descriptor.bin', '')
705 with self.assertRaises(ValueError) as e:
706 self._DoTestFile('31_x86-rom-me.dts')
707 self.assertIn("Node '/binman/intel-descriptor': Cannot find FD "
708 "signature", str(e.exception))
709
710 def testPackX86RomBadDesc(self):
711 """Test that the Intel requires a descriptor entry"""
712 with self.assertRaises(ValueError) as e:
713 self._DoTestFile('30_x86-rom-me-no-desc.dts')
Simon Glass3ab95982018-08-01 15:22:37 -0600714 self.assertIn("Node '/binman/intel-me': No offset set with "
715 "offset-unset: should another entry provide this correct "
716 "offset?", str(e.exception))
Simon Glasse0ff8552016-11-25 20:15:53 -0700717
718 def testPackX86RomMe(self):
719 """Test that an x86 ROM with an ME region can be created"""
720 data = self._DoReadFile('31_x86-rom-me.dts')
721 self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
722
723 def testPackVga(self):
724 """Test that an image with a VGA binary can be created"""
725 data = self._DoReadFile('32_intel-vga.dts')
726 self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
727
728 def testPackStart16(self):
729 """Test that an image with an x86 start16 region can be created"""
730 data = self._DoReadFile('33_x86-start16.dts')
731 self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
732
Simon Glass736bb0a2018-07-06 10:27:17 -0600733 def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
Simon Glassadc57012018-07-06 10:27:16 -0600734 """Handle running a test for insertion of microcode
735
736 Args:
737 dts_fname: Name of test .dts file
738 nodtb_data: Data that we expect in the first section
Simon Glass736bb0a2018-07-06 10:27:17 -0600739 ucode_second: True if the microsecond entry is second instead of
740 third
Simon Glassadc57012018-07-06 10:27:16 -0600741
742 Returns:
743 Tuple:
744 Contents of first region (U-Boot or SPL)
Simon Glass3ab95982018-08-01 15:22:37 -0600745 Offset and size components of microcode pointer, as inserted
Simon Glassadc57012018-07-06 10:27:16 -0600746 in the above (two 4-byte words)
747 """
Simon Glass6b187df2017-11-12 21:52:27 -0700748 data = self._DoReadFile(dts_fname, True)
Simon Glasse0ff8552016-11-25 20:15:53 -0700749
750 # Now check the device tree has no microcode
Simon Glass736bb0a2018-07-06 10:27:17 -0600751 if ucode_second:
752 ucode_content = data[len(nodtb_data):]
753 ucode_pos = len(nodtb_data)
754 dtb_with_ucode = ucode_content[16:]
755 fdt_len = self.GetFdtLen(dtb_with_ucode)
756 else:
757 dtb_with_ucode = data[len(nodtb_data):]
758 fdt_len = self.GetFdtLen(dtb_with_ucode)
759 ucode_content = dtb_with_ucode[fdt_len:]
760 ucode_pos = len(nodtb_data) + fdt_len
Simon Glasse0ff8552016-11-25 20:15:53 -0700761 fname = tools.GetOutputFilename('test.dtb')
762 with open(fname, 'wb') as fd:
Simon Glassadc57012018-07-06 10:27:16 -0600763 fd.write(dtb_with_ucode)
Simon Glassec3f3782017-05-27 07:38:29 -0600764 dtb = fdt.FdtScan(fname)
765 ucode = dtb.GetNode('/microcode')
Simon Glasse0ff8552016-11-25 20:15:53 -0700766 self.assertTrue(ucode)
767 for node in ucode.subnodes:
768 self.assertFalse(node.props.get('data'))
769
Simon Glasse0ff8552016-11-25 20:15:53 -0700770 # Check that the microcode appears immediately after the Fdt
771 # This matches the concatenation of the data properties in
Simon Glass87722132017-11-12 21:52:26 -0700772 # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
Simon Glasse0ff8552016-11-25 20:15:53 -0700773 ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
774 0x78235609)
Simon Glassadc57012018-07-06 10:27:16 -0600775 self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
Simon Glasse0ff8552016-11-25 20:15:53 -0700776
777 # Check that the microcode pointer was inserted. It should match the
Simon Glass3ab95982018-08-01 15:22:37 -0600778 # expected offset and size
Simon Glasse0ff8552016-11-25 20:15:53 -0700779 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
780 len(ucode_data))
Simon Glass736bb0a2018-07-06 10:27:17 -0600781 u_boot = data[:len(nodtb_data)]
782 return u_boot, pos_and_size
Simon Glass6b187df2017-11-12 21:52:27 -0700783
784 def testPackUbootMicrocode(self):
785 """Test that x86 microcode can be handled correctly
786
787 We expect to see the following in the image, in order:
788 u-boot-nodtb.bin with a microcode pointer inserted at the correct
789 place
790 u-boot.dtb with the microcode removed
791 the microcode
792 """
793 first, pos_and_size = self._RunMicrocodeTest('34_x86_ucode.dts',
794 U_BOOT_NODTB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -0700795 self.assertEqual('nodtb with microcode' + pos_and_size +
796 ' somewhere in here', first)
797
Simon Glass160a7662017-05-27 07:38:26 -0600798 def _RunPackUbootSingleMicrocode(self):
Simon Glasse0ff8552016-11-25 20:15:53 -0700799 """Test that x86 microcode can be handled correctly
800
801 We expect to see the following in the image, in order:
802 u-boot-nodtb.bin with a microcode pointer inserted at the correct
803 place
804 u-boot.dtb with the microcode
805 an empty microcode region
806 """
807 # We need the libfdt library to run this test since only that allows
808 # finding the offset of a property. This is required by
809 # Entry_u_boot_dtb_with_ucode.ObtainContents().
Simon Glasse0ff8552016-11-25 20:15:53 -0700810 data = self._DoReadFile('35_x86_single_ucode.dts', True)
811
812 second = data[len(U_BOOT_NODTB_DATA):]
813
814 fdt_len = self.GetFdtLen(second)
815 third = second[fdt_len:]
816 second = second[:fdt_len]
817
Simon Glass160a7662017-05-27 07:38:26 -0600818 ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
819 self.assertIn(ucode_data, second)
820 ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
Simon Glasse0ff8552016-11-25 20:15:53 -0700821
Simon Glass160a7662017-05-27 07:38:26 -0600822 # Check that the microcode pointer was inserted. It should match the
Simon Glass3ab95982018-08-01 15:22:37 -0600823 # expected offset and size
Simon Glass160a7662017-05-27 07:38:26 -0600824 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
825 len(ucode_data))
826 first = data[:len(U_BOOT_NODTB_DATA)]
827 self.assertEqual('nodtb with microcode' + pos_and_size +
828 ' somewhere in here', first)
Simon Glassc49deb82016-11-25 20:15:54 -0700829
Simon Glass75db0862016-11-25 20:15:55 -0700830 def testPackUbootSingleMicrocode(self):
831 """Test that x86 microcode can be handled correctly with fdt_normal.
832 """
Simon Glass160a7662017-05-27 07:38:26 -0600833 self._RunPackUbootSingleMicrocode()
Simon Glass75db0862016-11-25 20:15:55 -0700834
Simon Glassc49deb82016-11-25 20:15:54 -0700835 def testUBootImg(self):
836 """Test that u-boot.img can be put in a file"""
837 data = self._DoReadFile('36_u_boot_img.dts')
838 self.assertEqual(U_BOOT_IMG_DATA, data)
Simon Glass75db0862016-11-25 20:15:55 -0700839
840 def testNoMicrocode(self):
841 """Test that a missing microcode region is detected"""
842 with self.assertRaises(ValueError) as e:
843 self._DoReadFile('37_x86_no_ucode.dts', True)
844 self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
845 "node found in ", str(e.exception))
846
847 def testMicrocodeWithoutNode(self):
848 """Test that a missing u-boot-dtb-with-ucode node is detected"""
849 with self.assertRaises(ValueError) as e:
850 self._DoReadFile('38_x86_ucode_missing_node.dts', True)
851 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
852 "microcode region u-boot-dtb-with-ucode", str(e.exception))
853
854 def testMicrocodeWithoutNode2(self):
855 """Test that a missing u-boot-ucode node is detected"""
856 with self.assertRaises(ValueError) as e:
857 self._DoReadFile('39_x86_ucode_missing_node2.dts', True)
858 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
859 "microcode region u-boot-ucode", str(e.exception))
860
861 def testMicrocodeWithoutPtrInElf(self):
862 """Test that a U-Boot binary without the microcode symbol is detected"""
863 # ELF file without a '_dt_ucode_base_size' symbol
Simon Glass75db0862016-11-25 20:15:55 -0700864 try:
865 with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
866 TestFunctional._MakeInputFile('u-boot', fd.read())
867
868 with self.assertRaises(ValueError) as e:
Simon Glass160a7662017-05-27 07:38:26 -0600869 self._RunPackUbootSingleMicrocode()
Simon Glass75db0862016-11-25 20:15:55 -0700870 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
871 "_dt_ucode_base_size symbol in u-boot", str(e.exception))
872
873 finally:
874 # Put the original file back
875 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
876 TestFunctional._MakeInputFile('u-boot', fd.read())
877
878 def testMicrocodeNotInImage(self):
879 """Test that microcode must be placed within the image"""
880 with self.assertRaises(ValueError) as e:
881 self._DoReadFile('40_x86_ucode_not_in_image.dts', True)
882 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
883 "pointer _dt_ucode_base_size at fffffe14 is outside the "
Simon Glass25ac0e62018-06-01 09:38:14 -0600884 "section ranging from 00000000 to 0000002e", str(e.exception))
Simon Glass75db0862016-11-25 20:15:55 -0700885
886 def testWithoutMicrocode(self):
887 """Test that we can cope with an image without microcode (e.g. qemu)"""
888 with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
889 TestFunctional._MakeInputFile('u-boot', fd.read())
Simon Glass16b8d6b2018-07-06 10:27:42 -0600890 data, dtb, _, _ = self._DoReadFileDtb('44_x86_optional_ucode.dts', True)
Simon Glass75db0862016-11-25 20:15:55 -0700891
892 # Now check the device tree has no microcode
893 self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
894 second = data[len(U_BOOT_NODTB_DATA):]
895
896 fdt_len = self.GetFdtLen(second)
897 self.assertEqual(dtb, second[:fdt_len])
898
899 used_len = len(U_BOOT_NODTB_DATA) + fdt_len
900 third = data[used_len:]
901 self.assertEqual(chr(0) * (0x200 - used_len), third)
902
903 def testUnknownPosSize(self):
904 """Test that microcode must be placed within the image"""
905 with self.assertRaises(ValueError) as e:
906 self._DoReadFile('41_unknown_pos_size.dts', True)
Simon Glass3ab95982018-08-01 15:22:37 -0600907 self.assertIn("Section '/binman': Unable to set offset/size for unknown "
Simon Glass75db0862016-11-25 20:15:55 -0700908 "entry 'invalid-entry'", str(e.exception))
Simon Glassda229092016-11-25 20:15:56 -0700909
910 def testPackFsp(self):
911 """Test that an image with a FSP binary can be created"""
912 data = self._DoReadFile('42_intel-fsp.dts')
913 self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
914
915 def testPackCmc(self):
Bin Meng59ea8c22017-08-15 22:41:54 -0700916 """Test that an image with a CMC binary can be created"""
Simon Glassda229092016-11-25 20:15:56 -0700917 data = self._DoReadFile('43_intel-cmc.dts')
918 self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
Bin Meng59ea8c22017-08-15 22:41:54 -0700919
920 def testPackVbt(self):
921 """Test that an image with a VBT binary can be created"""
922 data = self._DoReadFile('46_intel-vbt.dts')
923 self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
Simon Glass9fc60b42017-11-12 21:52:22 -0700924
Simon Glass56509842017-11-12 21:52:25 -0700925 def testSplBssPad(self):
926 """Test that we can pad SPL's BSS with zeros"""
Simon Glass6b187df2017-11-12 21:52:27 -0700927 # ELF file with a '__bss_size' symbol
928 with open(self.TestFile('bss_data')) as fd:
929 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
Simon Glass56509842017-11-12 21:52:25 -0700930 data = self._DoReadFile('47_spl_bss_pad.dts')
931 self.assertEqual(U_BOOT_SPL_DATA + (chr(0) * 10) + U_BOOT_DATA, data)
932
Simon Glassb50e5612017-11-13 18:54:54 -0700933 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
934 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
935 with self.assertRaises(ValueError) as e:
936 data = self._DoReadFile('47_spl_bss_pad.dts')
937 self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
938 str(e.exception))
939
Simon Glass87722132017-11-12 21:52:26 -0700940 def testPackStart16Spl(self):
941 """Test that an image with an x86 start16 region can be created"""
942 data = self._DoReadFile('48_x86-start16-spl.dts')
943 self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
944
Simon Glass736bb0a2018-07-06 10:27:17 -0600945 def _PackUbootSplMicrocode(self, dts, ucode_second=False):
946 """Helper function for microcode tests
Simon Glass6b187df2017-11-12 21:52:27 -0700947
948 We expect to see the following in the image, in order:
949 u-boot-spl-nodtb.bin with a microcode pointer inserted at the
950 correct place
951 u-boot.dtb with the microcode removed
952 the microcode
Simon Glass736bb0a2018-07-06 10:27:17 -0600953
954 Args:
955 dts: Device tree file to use for test
956 ucode_second: True if the microsecond entry is second instead of
957 third
Simon Glass6b187df2017-11-12 21:52:27 -0700958 """
959 # ELF file with a '_dt_ucode_base_size' symbol
960 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
961 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
Simon Glass736bb0a2018-07-06 10:27:17 -0600962 first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
963 ucode_second=ucode_second)
Simon Glass6b187df2017-11-12 21:52:27 -0700964 self.assertEqual('splnodtb with microc' + pos_and_size +
965 'ter somewhere in here', first)
966
Simon Glass736bb0a2018-07-06 10:27:17 -0600967 def testPackUbootSplMicrocode(self):
968 """Test that x86 microcode can be handled correctly in SPL"""
969 self._PackUbootSplMicrocode('49_x86_ucode_spl.dts')
970
971 def testPackUbootSplMicrocodeReorder(self):
972 """Test that order doesn't matter for microcode entries
973
974 This is the same as testPackUbootSplMicrocode but when we process the
975 u-boot-ucode entry we have not yet seen the u-boot-dtb-with-ucode
976 entry, so we reply on binman to try later.
977 """
978 self._PackUbootSplMicrocode('58_x86_ucode_spl_needs_retry.dts',
979 ucode_second=True)
980
Simon Glassca4f4ff2017-11-12 21:52:28 -0700981 def testPackMrc(self):
982 """Test that an image with an MRC binary can be created"""
983 data = self._DoReadFile('50_intel_mrc.dts')
984 self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
985
Simon Glass47419ea2017-11-13 18:54:55 -0700986 def testSplDtb(self):
987 """Test that an image with spl/u-boot-spl.dtb can be created"""
988 data = self._DoReadFile('51_u_boot_spl_dtb.dts')
989 self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
990
Simon Glass4e6fdbe2017-11-13 18:54:56 -0700991 def testSplNoDtb(self):
992 """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
993 data = self._DoReadFile('52_u_boot_spl_nodtb.dts')
994 self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
995
Simon Glass19790632017-11-13 18:55:01 -0700996 def testSymbols(self):
997 """Test binman can assign symbols embedded in U-Boot"""
998 elf_fname = self.TestFile('u_boot_binman_syms')
999 syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
1000 addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
Simon Glass3ab95982018-08-01 15:22:37 -06001001 self.assertEqual(syms['_binman_u_boot_spl_prop_offset'].address, addr)
Simon Glass19790632017-11-13 18:55:01 -07001002
1003 with open(self.TestFile('u_boot_binman_syms')) as fd:
1004 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
1005 data = self._DoReadFile('53_symbols.dts')
1006 sym_values = struct.pack('<LQL', 0x24 + 0, 0x24 + 24, 0x24 + 20)
1007 expected = (sym_values + U_BOOT_SPL_DATA[16:] + chr(0xff) +
1008 U_BOOT_DATA +
1009 sym_values + U_BOOT_SPL_DATA[16:])
1010 self.assertEqual(expected, data)
1011
Simon Glassdd57c132018-06-01 09:38:11 -06001012 def testPackUnitAddress(self):
1013 """Test that we support multiple binaries with the same name"""
1014 data = self._DoReadFile('54_unit_address.dts')
1015 self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
1016
Simon Glass18546952018-06-01 09:38:16 -06001017 def testSections(self):
1018 """Basic test of sections"""
1019 data = self._DoReadFile('55_sections.dts')
Simon Glass8122f392018-07-17 13:25:28 -06001020 expected = (U_BOOT_DATA + '!' * 12 + U_BOOT_DATA + 'a' * 12 +
1021 U_BOOT_DATA + '&' * 4)
Simon Glass18546952018-06-01 09:38:16 -06001022 self.assertEqual(expected, data)
Simon Glass9fc60b42017-11-12 21:52:22 -07001023
Simon Glass3b0c3822018-06-01 09:38:20 -06001024 def testMap(self):
1025 """Tests outputting a map of the images"""
Simon Glass16b8d6b2018-07-06 10:27:42 -06001026 _, _, map_data, _ = self._DoReadFileDtb('55_sections.dts', map=True)
Simon Glass3ab95982018-08-01 15:22:37 -06001027 self.assertEqual(''' Offset Size Name
Simon Glass8122f392018-07-17 13:25:28 -0600102800000000 00000028 main-section
1029 00000000 00000010 section@0
1030 00000000 00000004 u-boot
1031 00000010 00000010 section@1
1032 00000000 00000004 u-boot
1033 00000020 00000004 section@2
1034 00000000 00000004 u-boot
Simon Glass3b0c3822018-06-01 09:38:20 -06001035''', map_data)
1036
Simon Glassc8d48ef2018-06-01 09:38:21 -06001037 def testNamePrefix(self):
1038 """Tests that name prefixes are used"""
Simon Glass16b8d6b2018-07-06 10:27:42 -06001039 _, _, map_data, _ = self._DoReadFileDtb('56_name_prefix.dts', map=True)
Simon Glass3ab95982018-08-01 15:22:37 -06001040 self.assertEqual(''' Offset Size Name
Simon Glass8122f392018-07-17 13:25:28 -0600104100000000 00000028 main-section
1042 00000000 00000010 section@0
1043 00000000 00000004 ro-u-boot
1044 00000010 00000010 section@1
1045 00000000 00000004 rw-u-boot
Simon Glassc8d48ef2018-06-01 09:38:21 -06001046''', map_data)
1047
Simon Glass736bb0a2018-07-06 10:27:17 -06001048 def testUnknownContents(self):
1049 """Test that obtaining the contents works as expected"""
1050 with self.assertRaises(ValueError) as e:
1051 self._DoReadFile('57_unknown_contents.dts', True)
1052 self.assertIn("Section '/binman': Internal error: Could not complete "
1053 "processing of contents: remaining [<_testing.Entry__testing ",
1054 str(e.exception))
1055
Simon Glass5c890232018-07-06 10:27:19 -06001056 def testBadChangeSize(self):
1057 """Test that trying to change the size of an entry fails"""
1058 with self.assertRaises(ValueError) as e:
1059 self._DoReadFile('59_change_size.dts', True)
1060 self.assertIn("Node '/binman/_testing': Cannot update entry size from "
1061 '2 to 1', str(e.exception))
1062
Simon Glass16b8d6b2018-07-06 10:27:42 -06001063 def testUpdateFdt(self):
Simon Glass3ab95982018-08-01 15:22:37 -06001064 """Test that we can update the device tree with offset/size info"""
Simon Glass16b8d6b2018-07-06 10:27:42 -06001065 _, _, _, out_dtb_fname = self._DoReadFileDtb('60_fdt_update.dts',
1066 update_dtb=True)
Simon Glassdbf6be92018-08-01 15:22:42 -06001067 props = self._GetPropTree(out_dtb_fname, ['offset', 'size',
1068 'image-pos'])
Simon Glass16b8d6b2018-07-06 10:27:42 -06001069 with open('/tmp/x.dtb', 'wb') as outf:
1070 with open(out_dtb_fname) as inf:
1071 outf.write(inf.read())
1072 self.assertEqual({
Simon Glassdbf6be92018-08-01 15:22:42 -06001073 'image-pos': 0,
Simon Glass8122f392018-07-17 13:25:28 -06001074 'offset': 0,
Simon Glass3ab95982018-08-01 15:22:37 -06001075 '_testing:offset': 32,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001076 '_testing:size': 1,
Simon Glassdbf6be92018-08-01 15:22:42 -06001077 '_testing:image-pos': 32,
Simon Glass3ab95982018-08-01 15:22:37 -06001078 'section@0/u-boot:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001079 'section@0/u-boot:size': len(U_BOOT_DATA),
Simon Glassdbf6be92018-08-01 15:22:42 -06001080 'section@0/u-boot:image-pos': 0,
Simon Glass3ab95982018-08-01 15:22:37 -06001081 'section@0:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001082 'section@0:size': 16,
Simon Glassdbf6be92018-08-01 15:22:42 -06001083 'section@0:image-pos': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001084
Simon Glass3ab95982018-08-01 15:22:37 -06001085 'section@1/u-boot:offset': 0,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001086 'section@1/u-boot:size': len(U_BOOT_DATA),
Simon Glassdbf6be92018-08-01 15:22:42 -06001087 'section@1/u-boot:image-pos': 16,
Simon Glass3ab95982018-08-01 15:22:37 -06001088 'section@1:offset': 16,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001089 'section@1:size': 16,
Simon Glassdbf6be92018-08-01 15:22:42 -06001090 'section@1:image-pos': 16,
Simon Glass16b8d6b2018-07-06 10:27:42 -06001091 'size': 40
1092 }, props)
1093
1094 def testUpdateFdtBad(self):
1095 """Test that we detect when ProcessFdt never completes"""
1096 with self.assertRaises(ValueError) as e:
1097 self._DoReadFileDtb('61_fdt_update_bad.dts', update_dtb=True)
1098 self.assertIn('Could not complete processing of Fdt: remaining '
1099 '[<_testing.Entry__testing', str(e.exception))
Simon Glass5c890232018-07-06 10:27:19 -06001100
Simon Glass53af22a2018-07-17 13:25:32 -06001101 def testEntryArgs(self):
1102 """Test passing arguments to entries from the command line"""
1103 entry_args = {
1104 'test-str-arg': 'test1',
1105 'test-int-arg': '456',
1106 }
1107 self._DoReadFileDtb('62_entry_args.dts', entry_args=entry_args)
1108 self.assertIn('image', control.images)
1109 entry = control.images['image'].GetEntries()['_testing']
1110 self.assertEqual('test0', entry.test_str_fdt)
1111 self.assertEqual('test1', entry.test_str_arg)
1112 self.assertEqual(123, entry.test_int_fdt)
1113 self.assertEqual(456, entry.test_int_arg)
1114
1115 def testEntryArgsMissing(self):
1116 """Test missing arguments and properties"""
1117 entry_args = {
1118 'test-int-arg': '456',
1119 }
1120 self._DoReadFileDtb('63_entry_args_missing.dts', entry_args=entry_args)
1121 entry = control.images['image'].GetEntries()['_testing']
1122 self.assertEqual('test0', entry.test_str_fdt)
1123 self.assertEqual(None, entry.test_str_arg)
1124 self.assertEqual(None, entry.test_int_fdt)
1125 self.assertEqual(456, entry.test_int_arg)
1126
1127 def testEntryArgsRequired(self):
1128 """Test missing arguments and properties"""
1129 entry_args = {
1130 'test-int-arg': '456',
1131 }
1132 with self.assertRaises(ValueError) as e:
1133 self._DoReadFileDtb('64_entry_args_required.dts')
1134 self.assertIn("Node '/binman/_testing': Missing required "
1135 'properties/entry args: test-str-arg, test-int-fdt, test-int-arg',
1136 str(e.exception))
1137
1138 def testEntryArgsInvalidFormat(self):
1139 """Test that an invalid entry-argument format is detected"""
1140 args = ['-d', self.TestFile('64_entry_args_required.dts'), '-ano-value']
1141 with self.assertRaises(ValueError) as e:
1142 self._DoBinman(*args)
1143 self.assertIn("Invalid entry arguemnt 'no-value'", str(e.exception))
1144
1145 def testEntryArgsInvalidInteger(self):
1146 """Test that an invalid entry-argument integer is detected"""
1147 entry_args = {
1148 'test-int-arg': 'abc',
1149 }
1150 with self.assertRaises(ValueError) as e:
1151 self._DoReadFileDtb('62_entry_args.dts', entry_args=entry_args)
1152 self.assertIn("Node '/binman/_testing': Cannot convert entry arg "
1153 "'test-int-arg' (value 'abc') to integer",
1154 str(e.exception))
1155
1156 def testEntryArgsInvalidDatatype(self):
1157 """Test that an invalid entry-argument datatype is detected
1158
1159 This test could be written in entry_test.py except that it needs
1160 access to control.entry_args, which seems more than that module should
1161 be able to see.
1162 """
1163 entry_args = {
1164 'test-bad-datatype-arg': '12',
1165 }
1166 with self.assertRaises(ValueError) as e:
1167 self._DoReadFileDtb('65_entry_args_unknown_datatype.dts',
1168 entry_args=entry_args)
1169 self.assertIn('GetArg() internal error: Unknown data type ',
1170 str(e.exception))
1171
Simon Glassbb748372018-07-17 13:25:33 -06001172 def testText(self):
1173 """Test for a text entry type"""
1174 entry_args = {
1175 'test-id': TEXT_DATA,
1176 'test-id2': TEXT_DATA2,
1177 'test-id3': TEXT_DATA3,
1178 }
1179 data, _, _, _ = self._DoReadFileDtb('66_text.dts',
1180 entry_args=entry_args)
1181 expected = (TEXT_DATA + chr(0) * (8 - len(TEXT_DATA)) + TEXT_DATA2 +
1182 TEXT_DATA3 + 'some text')
1183 self.assertEqual(expected, data)
1184
Simon Glassfd8d1f72018-07-17 13:25:36 -06001185 def testEntryDocs(self):
1186 """Test for creation of entry documentation"""
1187 with test_util.capture_sys_output() as (stdout, stderr):
1188 control.WriteEntryDocs(binman.GetEntryModules())
1189 self.assertTrue(len(stdout.getvalue()) > 0)
1190
1191 def testEntryDocsMissing(self):
1192 """Test handling of missing entry documentation"""
1193 with self.assertRaises(ValueError) as e:
1194 with test_util.capture_sys_output() as (stdout, stderr):
1195 control.WriteEntryDocs(binman.GetEntryModules(), 'u_boot')
1196 self.assertIn('Documentation is missing for modules: u_boot',
1197 str(e.exception))
1198
Simon Glass11e36cc2018-07-17 13:25:38 -06001199 def testFmap(self):
1200 """Basic test of generation of a flashrom fmap"""
1201 data = self._DoReadFile('67_fmap.dts')
1202 fhdr, fentries = fmap_util.DecodeFmap(data[32:])
1203 expected = U_BOOT_DATA + '!' * 12 + U_BOOT_DATA + 'a' * 12
1204 self.assertEqual(expected, data[:32])
1205 self.assertEqual('__FMAP__', fhdr.signature)
1206 self.assertEqual(1, fhdr.ver_major)
1207 self.assertEqual(0, fhdr.ver_minor)
1208 self.assertEqual(0, fhdr.base)
1209 self.assertEqual(16 + 16 +
1210 fmap_util.FMAP_HEADER_LEN +
1211 fmap_util.FMAP_AREA_LEN * 3, fhdr.image_size)
1212 self.assertEqual('FMAP', fhdr.name)
1213 self.assertEqual(3, fhdr.nareas)
1214 for fentry in fentries:
1215 self.assertEqual(0, fentry.flags)
1216
1217 self.assertEqual(0, fentries[0].offset)
1218 self.assertEqual(4, fentries[0].size)
1219 self.assertEqual('RO_U_BOOT', fentries[0].name)
1220
1221 self.assertEqual(16, fentries[1].offset)
1222 self.assertEqual(4, fentries[1].size)
1223 self.assertEqual('RW_U_BOOT', fentries[1].name)
1224
1225 self.assertEqual(32, fentries[2].offset)
1226 self.assertEqual(fmap_util.FMAP_HEADER_LEN +
1227 fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
1228 self.assertEqual('FMAP', fentries[2].name)
1229
Simon Glassec127af2018-07-17 13:25:39 -06001230 def testBlobNamedByArg(self):
1231 """Test we can add a blob with the filename coming from an entry arg"""
1232 entry_args = {
1233 'cros-ec-rw-path': 'ecrw.bin',
1234 }
1235 data, _, _, _ = self._DoReadFileDtb('68_blob_named_by_arg.dts',
1236 entry_args=entry_args)
1237
Simon Glass3af8e492018-07-17 13:25:40 -06001238 def testFill(self):
1239 """Test for an fill entry type"""
1240 data = self._DoReadFile('69_fill.dts')
1241 expected = 8 * chr(0xff) + 8 * chr(0)
1242 self.assertEqual(expected, data)
1243
1244 def testFillNoSize(self):
1245 """Test for an fill entry type with no size"""
1246 with self.assertRaises(ValueError) as e:
1247 self._DoReadFile('70_fill_no_size.dts')
1248 self.assertIn("'fill' entry must have a size property",
1249 str(e.exception))
1250
Simon Glass53af22a2018-07-17 13:25:32 -06001251
Simon Glass9fc60b42017-11-12 21:52:22 -07001252if __name__ == "__main__":
1253 unittest.main()