1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2016 Google, Inc
3 # Written by Simon Glass <sjg@chromium.org>
5 # To run a single test, change to this directory, and:
7 # python -m unittest func_test.TestFunctional.testHelp
9 from optparse import OptionParser
27 # Contents of test files, corresponding to different entry types
29 U_BOOT_IMG_DATA = 'img'
30 U_BOOT_SPL_DATA = '56780123456789abcde'
34 U_BOOT_DTB_DATA = 'udtb'
35 U_BOOT_SPL_DTB_DATA = 'spldtb'
36 X86_START16_DATA = 'start16'
37 X86_START16_SPL_DATA = 'start16spl'
38 U_BOOT_NODTB_DATA = 'nodtb with microcode pointer somewhere in here'
39 U_BOOT_SPL_NODTB_DATA = 'splnodtb with microcode pointer somewhere in here'
45 class TestFunctional(unittest.TestCase):
46 """Functional tests for binman
48 Most of these use a sample .dts file to build an image and then check
49 that it looks correct. The sample files are in the test/ subdirectory
52 For each entry type a very small test file is created using fixed
53 string contents. This makes it easy to test that things look right, and
56 In some cases a 'real' file must be used - these are also supplied in
64 # Handle the case where argv[0] is 'python'
65 self._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
66 self._binman_pathname = os.path.join(self._binman_dir, 'binman')
68 # Create a temporary directory for input files
69 self._indir = tempfile.mkdtemp(prefix='binmant.')
71 # Create some test files
72 TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
73 TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
74 TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
75 TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
76 TestFunctional._MakeInputFile('me.bin', ME_DATA)
77 TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
78 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
79 TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
80 TestFunctional._MakeInputFile('u-boot-x86-16bit.bin', X86_START16_DATA)
81 TestFunctional._MakeInputFile('spl/u-boot-x86-16bit-spl.bin',
83 TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
84 TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
85 U_BOOT_SPL_NODTB_DATA)
86 TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
87 TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
88 TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
89 TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
90 self._output_setup = False
92 # ELF file with a '_dt_ucode_base_size' symbol
93 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
94 TestFunctional._MakeInputFile('u-boot', fd.read())
96 # Intel flash descriptor file
97 with open(self.TestFile('descriptor.bin')) as fd:
98 TestFunctional._MakeInputFile('descriptor.bin', fd.read())
101 def tearDownClass(self):
102 """Remove the temporary input directory and its contents"""
104 shutil.rmtree(self._indir)
108 # Enable this to turn on debugging output
109 # tout.Init(tout.DEBUG)
110 command.test_result = None
113 """Remove the temporary output directory"""
114 tools._FinaliseForTest()
116 def _RunBinman(self, *args, **kwargs):
117 """Run binman using the command line
120 Arguments to pass, as a list of strings
121 kwargs: Arguments to pass to Command.RunPipe()
123 result = command.RunPipe([[self._binman_pathname] + list(args)],
124 capture=True, capture_stderr=True, raise_on_error=False)
125 if result.return_code and kwargs.get('raise_on_error', True):
126 raise Exception("Error running '%s': %s" % (' '.join(args),
127 result.stdout + result.stderr))
130 def _DoBinman(self, *args):
131 """Run binman using directly (in the same process)
134 Arguments to pass, as a list of strings
136 Return value (0 for success)
141 (options, args) = cmdline.ParseArgs(args)
142 options.pager = 'binman-invalid-pager'
143 options.build_dir = self._indir
145 # For testing, you can force an increase in verbosity here
146 # options.verbosity = tout.DEBUG
147 return control.Binman(options, args)
149 def _DoTestFile(self, fname, debug=False):
150 """Run binman with a given test file
153 fname: Device-tree source filename to use (e.g. 05_simple.dts)
154 debug: True to enable debugging output
156 args = ['-p', '-I', self._indir, '-d', self.TestFile(fname)]
159 return self._DoBinman(*args)
161 def _SetupDtb(self, fname, outfile='u-boot.dtb'):
162 """Set up a new test device-tree file
164 The given file is compiled and set up as the device tree to be used
168 fname: Filename of .dts file to read
169 outfile: Output filename for compiled device-tree binary
172 Contents of device-tree binary
174 if not self._output_setup:
175 tools.PrepareOutputDir(self._indir, True)
176 self._output_setup = True
177 dtb = fdt_util.EnsureCompiled(self.TestFile(fname))
178 with open(dtb) as fd:
180 TestFunctional._MakeInputFile(outfile, data)
183 def _DoReadFileDtb(self, fname, use_real_dtb=False):
184 """Run binman and return the resulting image
186 This runs binman with a given test file and then reads the resulting
187 output file. It is a shortcut function since most tests need to do
190 Raises an assertion failure if binman returns a non-zero exit code.
193 fname: Device-tree source filename to use (e.g. 05_simple.dts)
194 use_real_dtb: True to use the test file as the contents of
195 the u-boot-dtb entry. Normally this is not needed and the
196 test contents (the U_BOOT_DTB_DATA string) can be used.
197 But in some test we need the real contents.
201 Resulting image contents
205 # Use the compiled test file as the u-boot-dtb input
207 dtb_data = self._SetupDtb(fname)
210 retcode = self._DoTestFile(fname)
211 self.assertEqual(0, retcode)
213 # Find the (only) image, read it and return its contents
214 image = control.images['image']
215 fname = tools.GetOutputFilename('image.bin')
216 self.assertTrue(os.path.exists(fname))
217 with open(fname) as fd:
218 return fd.read(), dtb_data
220 # Put the test file back
222 TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
224 def _DoReadFile(self, fname, use_real_dtb=False):
225 """Helper function which discards the device-tree binary
228 fname: Device-tree source filename to use (e.g. 05_simple.dts)
229 use_real_dtb: True to use the test file as the contents of
230 the u-boot-dtb entry. Normally this is not needed and the
231 test contents (the U_BOOT_DTB_DATA string) can be used.
232 But in some test we need the real contents.
234 return self._DoReadFileDtb(fname, use_real_dtb)[0]
237 def _MakeInputFile(self, fname, contents):
238 """Create a new test input file, creating directories as needed
241 fname: Filenaem to create
242 contents: File contents to write in to the file
244 Full pathname of file created
246 pathname = os.path.join(self._indir, fname)
247 dirname = os.path.dirname(pathname)
248 if dirname and not os.path.exists(dirname):
250 with open(pathname, 'wb') as fd:
255 def TestFile(self, fname):
256 return os.path.join(self._binman_dir, 'test', fname)
258 def AssertInList(self, grep_list, target):
259 """Assert that at least one of a list of things is in a target
262 grep_list: List of strings to check
263 target: Target string
265 for grep in grep_list:
268 self.fail("Error: '%' not found in '%s'" % (grep_list, target))
270 def CheckNoGaps(self, entries):
271 """Check that all entries fit together without gaps
274 entries: List of entries to check
277 for entry in entries.values():
278 self.assertEqual(pos, entry.pos)
281 def GetFdtLen(self, dtb):
282 """Get the totalsize field from a device-tree binary
285 dtb: Device-tree binary contents
288 Total size of device-tree binary, from the header
290 return struct.unpack('>L', dtb[4:8])[0]
293 """Test a basic run with valid args"""
294 result = self._RunBinman('-h')
296 def testFullHelp(self):
297 """Test that the full help is displayed with -H"""
298 result = self._RunBinman('-H')
299 help_file = os.path.join(self._binman_dir, 'README')
300 # Remove possible extraneous strings
301 extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
302 gothelp = result.stdout.replace(extra, '')
303 self.assertEqual(len(gothelp), os.path.getsize(help_file))
304 self.assertEqual(0, len(result.stderr))
305 self.assertEqual(0, result.return_code)
307 def testFullHelpInternal(self):
308 """Test that the full help is displayed with -H"""
310 command.test_result = command.CommandResult()
311 result = self._DoBinman('-H')
312 help_file = os.path.join(self._binman_dir, 'README')
314 command.test_result = None
317 """Test that the basic help is displayed with -h"""
318 result = self._RunBinman('-h')
319 self.assertTrue(len(result.stdout) > 200)
320 self.assertEqual(0, len(result.stderr))
321 self.assertEqual(0, result.return_code)
324 """Test that we can run it with a specific board"""
325 self._SetupDtb('05_simple.dts', 'sandbox/u-boot.dtb')
326 TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
327 result = self._DoBinman('-b', 'sandbox')
328 self.assertEqual(0, result)
330 def testNeedBoard(self):
331 """Test that we get an error when no board ius supplied"""
332 with self.assertRaises(ValueError) as e:
333 result = self._DoBinman()
334 self.assertIn("Must provide a board to process (use -b <board>)",
337 def testMissingDt(self):
338 """Test that an invalid device-tree file generates an error"""
339 with self.assertRaises(Exception) as e:
340 self._RunBinman('-d', 'missing_file')
341 # We get one error from libfdt, and a different one from fdtget.
342 self.AssertInList(["Couldn't open blob from 'missing_file'",
343 'No such file or directory'], str(e.exception))
345 def testBrokenDt(self):
346 """Test that an invalid device-tree source file generates an error
348 Since this is a source file it should be compiled and the error
349 will come from the device-tree compiler (dtc).
351 with self.assertRaises(Exception) as e:
352 self._RunBinman('-d', self.TestFile('01_invalid.dts'))
353 self.assertIn("FATAL ERROR: Unable to parse input tree",
356 def testMissingNode(self):
357 """Test that a device tree without a 'binman' node generates an error"""
358 with self.assertRaises(Exception) as e:
359 self._DoBinman('-d', self.TestFile('02_missing_node.dts'))
360 self.assertIn("does not have a 'binman' node", str(e.exception))
363 """Test that an empty binman node works OK (i.e. does nothing)"""
364 result = self._RunBinman('-d', self.TestFile('03_empty.dts'))
365 self.assertEqual(0, len(result.stderr))
366 self.assertEqual(0, result.return_code)
368 def testInvalidEntry(self):
369 """Test that an invalid entry is flagged"""
370 with self.assertRaises(Exception) as e:
371 result = self._RunBinman('-d',
372 self.TestFile('04_invalid_entry.dts'))
374 self.assertIn("Unknown entry type 'not-a-valid-type' in node "
375 "'/binman/not-a-valid-type'", str(e.exception))
377 def testSimple(self):
378 """Test a simple binman with a single file"""
379 data = self._DoReadFile('05_simple.dts')
380 self.assertEqual(U_BOOT_DATA, data)
382 def testSimpleDebug(self):
383 """Test a simple binman run with debugging enabled"""
384 data = self._DoTestFile('05_simple.dts', debug=True)
387 """Test that we can handle creating two images
389 This also tests image padding.
391 retcode = self._DoTestFile('06_dual_image.dts')
392 self.assertEqual(0, retcode)
394 image = control.images['image1']
395 self.assertEqual(len(U_BOOT_DATA), image._size)
396 fname = tools.GetOutputFilename('image1.bin')
397 self.assertTrue(os.path.exists(fname))
398 with open(fname) as fd:
400 self.assertEqual(U_BOOT_DATA, data)
402 image = control.images['image2']
403 self.assertEqual(3 + len(U_BOOT_DATA) + 5, image._size)
404 fname = tools.GetOutputFilename('image2.bin')
405 self.assertTrue(os.path.exists(fname))
406 with open(fname) as fd:
408 self.assertEqual(U_BOOT_DATA, data[3:7])
409 self.assertEqual(chr(0) * 3, data[:3])
410 self.assertEqual(chr(0) * 5, data[7:])
412 def testBadAlign(self):
413 """Test that an invalid alignment value is detected"""
414 with self.assertRaises(ValueError) as e:
415 self._DoTestFile('07_bad_align.dts')
416 self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
417 "of two", str(e.exception))
419 def testPackSimple(self):
420 """Test that packing works as expected"""
421 retcode = self._DoTestFile('08_pack.dts')
422 self.assertEqual(0, retcode)
423 self.assertIn('image', control.images)
424 image = control.images['image']
425 entries = image.GetEntries()
426 self.assertEqual(5, len(entries))
429 self.assertIn('u-boot', entries)
430 entry = entries['u-boot']
431 self.assertEqual(0, entry.pos)
432 self.assertEqual(len(U_BOOT_DATA), entry.size)
434 # Second u-boot, aligned to 16-byte boundary
435 self.assertIn('u-boot-align', entries)
436 entry = entries['u-boot-align']
437 self.assertEqual(16, entry.pos)
438 self.assertEqual(len(U_BOOT_DATA), entry.size)
440 # Third u-boot, size 23 bytes
441 self.assertIn('u-boot-size', entries)
442 entry = entries['u-boot-size']
443 self.assertEqual(20, entry.pos)
444 self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
445 self.assertEqual(23, entry.size)
447 # Fourth u-boot, placed immediate after the above
448 self.assertIn('u-boot-next', entries)
449 entry = entries['u-boot-next']
450 self.assertEqual(43, entry.pos)
451 self.assertEqual(len(U_BOOT_DATA), entry.size)
453 # Fifth u-boot, placed at a fixed position
454 self.assertIn('u-boot-fixed', entries)
455 entry = entries['u-boot-fixed']
456 self.assertEqual(61, entry.pos)
457 self.assertEqual(len(U_BOOT_DATA), entry.size)
459 self.assertEqual(65, image._size)
461 def testPackExtra(self):
462 """Test that extra packing feature works as expected"""
463 retcode = self._DoTestFile('09_pack_extra.dts')
465 self.assertEqual(0, retcode)
466 self.assertIn('image', control.images)
467 image = control.images['image']
468 entries = image.GetEntries()
469 self.assertEqual(5, len(entries))
471 # First u-boot with padding before and after
472 self.assertIn('u-boot', entries)
473 entry = entries['u-boot']
474 self.assertEqual(0, entry.pos)
475 self.assertEqual(3, entry.pad_before)
476 self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
478 # Second u-boot has an aligned size, but it has no effect
479 self.assertIn('u-boot-align-size-nop', entries)
480 entry = entries['u-boot-align-size-nop']
481 self.assertEqual(12, entry.pos)
482 self.assertEqual(4, entry.size)
484 # Third u-boot has an aligned size too
485 self.assertIn('u-boot-align-size', entries)
486 entry = entries['u-boot-align-size']
487 self.assertEqual(16, entry.pos)
488 self.assertEqual(32, entry.size)
490 # Fourth u-boot has an aligned end
491 self.assertIn('u-boot-align-end', entries)
492 entry = entries['u-boot-align-end']
493 self.assertEqual(48, entry.pos)
494 self.assertEqual(16, entry.size)
496 # Fifth u-boot immediately afterwards
497 self.assertIn('u-boot-align-both', entries)
498 entry = entries['u-boot-align-both']
499 self.assertEqual(64, entry.pos)
500 self.assertEqual(64, entry.size)
502 self.CheckNoGaps(entries)
503 self.assertEqual(128, image._size)
505 def testPackAlignPowerOf2(self):
506 """Test that invalid entry alignment is detected"""
507 with self.assertRaises(ValueError) as e:
508 self._DoTestFile('10_pack_align_power2.dts')
509 self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
510 "of two", str(e.exception))
512 def testPackAlignSizePowerOf2(self):
513 """Test that invalid entry size alignment is detected"""
514 with self.assertRaises(ValueError) as e:
515 self._DoTestFile('11_pack_align_size_power2.dts')
516 self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
517 "power of two", str(e.exception))
519 def testPackInvalidAlign(self):
520 """Test detection of an position that does not match its alignment"""
521 with self.assertRaises(ValueError) as e:
522 self._DoTestFile('12_pack_inv_align.dts')
523 self.assertIn("Node '/binman/u-boot': Position 0x5 (5) does not match "
524 "align 0x4 (4)", str(e.exception))
526 def testPackInvalidSizeAlign(self):
527 """Test that invalid entry size alignment is detected"""
528 with self.assertRaises(ValueError) as e:
529 self._DoTestFile('13_pack_inv_size_align.dts')
530 self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
531 "align-size 0x4 (4)", str(e.exception))
533 def testPackOverlap(self):
534 """Test that overlapping regions are detected"""
535 with self.assertRaises(ValueError) as e:
536 self._DoTestFile('14_pack_overlap.dts')
537 self.assertIn("Node '/binman/u-boot-align': Position 0x3 (3) overlaps "
538 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
541 def testPackEntryOverflow(self):
542 """Test that entries that overflow their size are detected"""
543 with self.assertRaises(ValueError) as e:
544 self._DoTestFile('15_pack_overflow.dts')
545 self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
546 "but entry size is 0x3 (3)", str(e.exception))
548 def testPackImageOverflow(self):
549 """Test that entries which overflow the image size are detected"""
550 with self.assertRaises(ValueError) as e:
551 self._DoTestFile('16_pack_image_overflow.dts')
552 self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
553 "size 0x3 (3)", str(e.exception))
555 def testPackImageSize(self):
556 """Test that the image size can be set"""
557 retcode = self._DoTestFile('17_pack_image_size.dts')
558 self.assertEqual(0, retcode)
559 self.assertIn('image', control.images)
560 image = control.images['image']
561 self.assertEqual(7, image._size)
563 def testPackImageSizeAlign(self):
564 """Test that image size alignemnt works as expected"""
565 retcode = self._DoTestFile('18_pack_image_align.dts')
566 self.assertEqual(0, retcode)
567 self.assertIn('image', control.images)
568 image = control.images['image']
569 self.assertEqual(16, image._size)
571 def testPackInvalidImageAlign(self):
572 """Test that invalid image alignment is detected"""
573 with self.assertRaises(ValueError) as e:
574 self._DoTestFile('19_pack_inv_image_align.dts')
575 self.assertIn("Section '/binman': Size 0x7 (7) does not match "
576 "align-size 0x8 (8)", str(e.exception))
578 def testPackAlignPowerOf2(self):
579 """Test that invalid image alignment is detected"""
580 with self.assertRaises(ValueError) as e:
581 self._DoTestFile('20_pack_inv_image_align_power2.dts')
582 self.assertIn("Section '/binman': Alignment size 131 must be a power of "
583 "two", str(e.exception))
585 def testImagePadByte(self):
586 """Test that the image pad byte can be specified"""
587 with open(self.TestFile('bss_data')) as fd:
588 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
589 data = self._DoReadFile('21_image_pad.dts')
590 self.assertEqual(U_BOOT_SPL_DATA + (chr(0xff) * 1) + U_BOOT_DATA, data)
592 def testImageName(self):
593 """Test that image files can be named"""
594 retcode = self._DoTestFile('22_image_name.dts')
595 self.assertEqual(0, retcode)
596 image = control.images['image1']
597 fname = tools.GetOutputFilename('test-name')
598 self.assertTrue(os.path.exists(fname))
600 image = control.images['image2']
601 fname = tools.GetOutputFilename('test-name.xx')
602 self.assertTrue(os.path.exists(fname))
604 def testBlobFilename(self):
605 """Test that generic blobs can be provided by filename"""
606 data = self._DoReadFile('23_blob.dts')
607 self.assertEqual(BLOB_DATA, data)
609 def testPackSorted(self):
610 """Test that entries can be sorted"""
611 data = self._DoReadFile('24_sorted.dts')
612 self.assertEqual(chr(0) * 1 + U_BOOT_SPL_DATA + chr(0) * 2 +
615 def testPackZeroPosition(self):
616 """Test that an entry at position 0 is not given a new position"""
617 with self.assertRaises(ValueError) as e:
618 self._DoTestFile('25_pack_zero_size.dts')
619 self.assertIn("Node '/binman/u-boot-spl': Position 0x0 (0) overlaps "
620 "with previous entry '/binman/u-boot' ending at 0x4 (4)",
623 def testPackUbootDtb(self):
624 """Test that a device tree can be added to U-Boot"""
625 data = self._DoReadFile('26_pack_u_boot_dtb.dts')
626 self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
628 def testPackX86RomNoSize(self):
629 """Test that the end-at-4gb property requires a size property"""
630 with self.assertRaises(ValueError) as e:
631 self._DoTestFile('27_pack_4gb_no_size.dts')
632 self.assertIn("Section '/binman': Section size must be provided when "
633 "using end-at-4gb", str(e.exception))
635 def testPackX86RomOutside(self):
636 """Test that the end-at-4gb property checks for position boundaries"""
637 with self.assertRaises(ValueError) as e:
638 self._DoTestFile('28_pack_4gb_outside.dts')
639 self.assertIn("Node '/binman/u-boot': Position 0x0 (0) is outside "
640 "the section starting at 0xffffffe0 (4294967264)",
643 def testPackX86Rom(self):
644 """Test that a basic x86 ROM can be created"""
645 data = self._DoReadFile('29_x86-rom.dts')
646 self.assertEqual(U_BOOT_DATA + chr(0) * 7 + U_BOOT_SPL_DATA +
649 def testPackX86RomMeNoDesc(self):
650 """Test that an invalid Intel descriptor entry is detected"""
651 TestFunctional._MakeInputFile('descriptor.bin', '')
652 with self.assertRaises(ValueError) as e:
653 self._DoTestFile('31_x86-rom-me.dts')
654 self.assertIn("Node '/binman/intel-descriptor': Cannot find FD "
655 "signature", str(e.exception))
657 def testPackX86RomBadDesc(self):
658 """Test that the Intel requires a descriptor entry"""
659 with self.assertRaises(ValueError) as e:
660 self._DoTestFile('30_x86-rom-me-no-desc.dts')
661 self.assertIn("Node '/binman/intel-me': No position set with "
662 "pos-unset: should another entry provide this correct "
663 "position?", str(e.exception))
665 def testPackX86RomMe(self):
666 """Test that an x86 ROM with an ME region can be created"""
667 data = self._DoReadFile('31_x86-rom-me.dts')
668 self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
670 def testPackVga(self):
671 """Test that an image with a VGA binary can be created"""
672 data = self._DoReadFile('32_intel-vga.dts')
673 self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
675 def testPackStart16(self):
676 """Test that an image with an x86 start16 region can be created"""
677 data = self._DoReadFile('33_x86-start16.dts')
678 self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
680 def _RunMicrocodeTest(self, dts_fname, nodtb_data):
681 data = self._DoReadFile(dts_fname, True)
683 # Now check the device tree has no microcode
684 second = data[len(nodtb_data):]
685 fname = tools.GetOutputFilename('test.dtb')
686 with open(fname, 'wb') as fd:
688 dtb = fdt.FdtScan(fname)
689 ucode = dtb.GetNode('/microcode')
690 self.assertTrue(ucode)
691 for node in ucode.subnodes:
692 self.assertFalse(node.props.get('data'))
694 fdt_len = self.GetFdtLen(second)
695 third = second[fdt_len:]
697 # Check that the microcode appears immediately after the Fdt
698 # This matches the concatenation of the data properties in
699 # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
700 ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
702 self.assertEqual(ucode_data, third[:len(ucode_data)])
703 ucode_pos = len(nodtb_data) + fdt_len
705 # Check that the microcode pointer was inserted. It should match the
706 # expected position and size
707 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
709 first = data[:len(nodtb_data)]
710 return first, pos_and_size
712 def testPackUbootMicrocode(self):
713 """Test that x86 microcode can be handled correctly
715 We expect to see the following in the image, in order:
716 u-boot-nodtb.bin with a microcode pointer inserted at the correct
718 u-boot.dtb with the microcode removed
721 first, pos_and_size = self._RunMicrocodeTest('34_x86_ucode.dts',
723 self.assertEqual('nodtb with microcode' + pos_and_size +
724 ' somewhere in here', first)
726 def _RunPackUbootSingleMicrocode(self):
727 """Test that x86 microcode can be handled correctly
729 We expect to see the following in the image, in order:
730 u-boot-nodtb.bin with a microcode pointer inserted at the correct
732 u-boot.dtb with the microcode
733 an empty microcode region
735 # We need the libfdt library to run this test since only that allows
736 # finding the offset of a property. This is required by
737 # Entry_u_boot_dtb_with_ucode.ObtainContents().
738 data = self._DoReadFile('35_x86_single_ucode.dts', True)
740 second = data[len(U_BOOT_NODTB_DATA):]
742 fdt_len = self.GetFdtLen(second)
743 third = second[fdt_len:]
744 second = second[:fdt_len]
746 ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
747 self.assertIn(ucode_data, second)
748 ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
750 # Check that the microcode pointer was inserted. It should match the
751 # expected position and size
752 pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
754 first = data[:len(U_BOOT_NODTB_DATA)]
755 self.assertEqual('nodtb with microcode' + pos_and_size +
756 ' somewhere in here', first)
758 def testPackUbootSingleMicrocode(self):
759 """Test that x86 microcode can be handled correctly with fdt_normal.
761 self._RunPackUbootSingleMicrocode()
763 def testUBootImg(self):
764 """Test that u-boot.img can be put in a file"""
765 data = self._DoReadFile('36_u_boot_img.dts')
766 self.assertEqual(U_BOOT_IMG_DATA, data)
768 def testNoMicrocode(self):
769 """Test that a missing microcode region is detected"""
770 with self.assertRaises(ValueError) as e:
771 self._DoReadFile('37_x86_no_ucode.dts', True)
772 self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
773 "node found in ", str(e.exception))
775 def testMicrocodeWithoutNode(self):
776 """Test that a missing u-boot-dtb-with-ucode node is detected"""
777 with self.assertRaises(ValueError) as e:
778 self._DoReadFile('38_x86_ucode_missing_node.dts', True)
779 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
780 "microcode region u-boot-dtb-with-ucode", str(e.exception))
782 def testMicrocodeWithoutNode2(self):
783 """Test that a missing u-boot-ucode node is detected"""
784 with self.assertRaises(ValueError) as e:
785 self._DoReadFile('39_x86_ucode_missing_node2.dts', True)
786 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
787 "microcode region u-boot-ucode", str(e.exception))
789 def testMicrocodeWithoutPtrInElf(self):
790 """Test that a U-Boot binary without the microcode symbol is detected"""
791 # ELF file without a '_dt_ucode_base_size' symbol
793 with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
794 TestFunctional._MakeInputFile('u-boot', fd.read())
796 with self.assertRaises(ValueError) as e:
797 self._RunPackUbootSingleMicrocode()
798 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
799 "_dt_ucode_base_size symbol in u-boot", str(e.exception))
802 # Put the original file back
803 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
804 TestFunctional._MakeInputFile('u-boot', fd.read())
806 def testMicrocodeNotInImage(self):
807 """Test that microcode must be placed within the image"""
808 with self.assertRaises(ValueError) as e:
809 self._DoReadFile('40_x86_ucode_not_in_image.dts', True)
810 self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
811 "pointer _dt_ucode_base_size at fffffe14 is outside the "
812 "section ranging from 00000000 to 0000002e", str(e.exception))
814 def testWithoutMicrocode(self):
815 """Test that we can cope with an image without microcode (e.g. qemu)"""
816 with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
817 TestFunctional._MakeInputFile('u-boot', fd.read())
818 data, dtb = self._DoReadFileDtb('44_x86_optional_ucode.dts', True)
820 # Now check the device tree has no microcode
821 self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
822 second = data[len(U_BOOT_NODTB_DATA):]
824 fdt_len = self.GetFdtLen(second)
825 self.assertEqual(dtb, second[:fdt_len])
827 used_len = len(U_BOOT_NODTB_DATA) + fdt_len
828 third = data[used_len:]
829 self.assertEqual(chr(0) * (0x200 - used_len), third)
831 def testUnknownPosSize(self):
832 """Test that microcode must be placed within the image"""
833 with self.assertRaises(ValueError) as e:
834 self._DoReadFile('41_unknown_pos_size.dts', True)
835 self.assertIn("Section '/binman': Unable to set pos/size for unknown "
836 "entry 'invalid-entry'", str(e.exception))
838 def testPackFsp(self):
839 """Test that an image with a FSP binary can be created"""
840 data = self._DoReadFile('42_intel-fsp.dts')
841 self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
843 def testPackCmc(self):
844 """Test that an image with a CMC binary can be created"""
845 data = self._DoReadFile('43_intel-cmc.dts')
846 self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
848 def testPackVbt(self):
849 """Test that an image with a VBT binary can be created"""
850 data = self._DoReadFile('46_intel-vbt.dts')
851 self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
853 def testSplBssPad(self):
854 """Test that we can pad SPL's BSS with zeros"""
855 # ELF file with a '__bss_size' symbol
856 with open(self.TestFile('bss_data')) as fd:
857 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
858 data = self._DoReadFile('47_spl_bss_pad.dts')
859 self.assertEqual(U_BOOT_SPL_DATA + (chr(0) * 10) + U_BOOT_DATA, data)
861 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
862 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
863 with self.assertRaises(ValueError) as e:
864 data = self._DoReadFile('47_spl_bss_pad.dts')
865 self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
868 def testPackStart16Spl(self):
869 """Test that an image with an x86 start16 region can be created"""
870 data = self._DoReadFile('48_x86-start16-spl.dts')
871 self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
873 def testPackUbootSplMicrocode(self):
874 """Test that x86 microcode can be handled correctly in SPL
876 We expect to see the following in the image, in order:
877 u-boot-spl-nodtb.bin with a microcode pointer inserted at the
879 u-boot.dtb with the microcode removed
882 # ELF file with a '_dt_ucode_base_size' symbol
883 with open(self.TestFile('u_boot_ucode_ptr')) as fd:
884 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
885 first, pos_and_size = self._RunMicrocodeTest('49_x86_ucode_spl.dts',
886 U_BOOT_SPL_NODTB_DATA)
887 self.assertEqual('splnodtb with microc' + pos_and_size +
888 'ter somewhere in here', first)
890 def testPackMrc(self):
891 """Test that an image with an MRC binary can be created"""
892 data = self._DoReadFile('50_intel_mrc.dts')
893 self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
895 def testSplDtb(self):
896 """Test that an image with spl/u-boot-spl.dtb can be created"""
897 data = self._DoReadFile('51_u_boot_spl_dtb.dts')
898 self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
900 def testSplNoDtb(self):
901 """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
902 data = self._DoReadFile('52_u_boot_spl_nodtb.dts')
903 self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
905 def testSymbols(self):
906 """Test binman can assign symbols embedded in U-Boot"""
907 elf_fname = self.TestFile('u_boot_binman_syms')
908 syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
909 addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
910 self.assertEqual(syms['_binman_u_boot_spl_prop_pos'].address, addr)
912 with open(self.TestFile('u_boot_binman_syms')) as fd:
913 TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
914 data = self._DoReadFile('53_symbols.dts')
915 sym_values = struct.pack('<LQL', 0x24 + 0, 0x24 + 24, 0x24 + 20)
916 expected = (sym_values + U_BOOT_SPL_DATA[16:] + chr(0xff) +
918 sym_values + U_BOOT_SPL_DATA[16:])
919 self.assertEqual(expected, data)
921 def testPackUnitAddress(self):
922 """Test that we support multiple binaries with the same name"""
923 data = self._DoReadFile('54_unit_address.dts')
924 self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
926 def testSections(self):
927 """Basic test of sections"""
928 data = self._DoReadFile('55_sections.dts')
929 expected = U_BOOT_DATA + '!' * 12 + U_BOOT_DATA + 'a' * 12 + '&' * 8
930 self.assertEqual(expected, data)
932 if __name__ == "__main__":