func_test.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. #
  2. # Copyright (c) 2016 Google, Inc
  3. # Written by Simon Glass <sjg@chromium.org>
  4. #
  5. # SPDX-License-Identifier: GPL-2.0+
  6. #
  7. # To run a single test, change to this directory, and:
  8. #
  9. # python -m unittest func_test.TestFunctional.testHelp
  10. from optparse import OptionParser
  11. import os
  12. import shutil
  13. import struct
  14. import sys
  15. import tempfile
  16. import unittest
  17. import binman
  18. import cmdline
  19. import command
  20. import control
  21. import entry
  22. import fdt_select
  23. import fdt_util
  24. import tools
  25. import tout
  26. # Contents of test files, corresponding to different entry types
  27. U_BOOT_DATA = '1234'
  28. U_BOOT_IMG_DATA = 'img'
  29. U_BOOT_SPL_DATA = '567'
  30. BLOB_DATA = '89'
  31. ME_DATA = '0abcd'
  32. VGA_DATA = 'vga'
  33. U_BOOT_DTB_DATA = 'udtb'
  34. X86_START16_DATA = 'start16'
  35. U_BOOT_NODTB_DATA = 'nodtb with microcode pointer somewhere in here'
  36. FSP_DATA = 'fsp'
  37. CMC_DATA = 'cmc'
  38. class TestFunctional(unittest.TestCase):
  39. """Functional tests for binman
  40. Most of these use a sample .dts file to build an image and then check
  41. that it looks correct. The sample files are in the test/ subdirectory
  42. and are numbered.
  43. For each entry type a very small test file is created using fixed
  44. string contents. This makes it easy to test that things look right, and
  45. debug problems.
  46. In some cases a 'real' file must be used - these are also supplied in
  47. the test/ diurectory.
  48. """
  49. @classmethod
  50. def setUpClass(self):
  51. # Handle the case where argv[0] is 'python'
  52. self._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  53. self._binman_pathname = os.path.join(self._binman_dir, 'binman')
  54. # Create a temporary directory for input files
  55. self._indir = tempfile.mkdtemp(prefix='binmant.')
  56. # Create some test files
  57. TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
  58. TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
  59. TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
  60. TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
  61. TestFunctional._MakeInputFile('me.bin', ME_DATA)
  62. TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
  63. TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
  64. TestFunctional._MakeInputFile('u-boot-x86-16bit.bin', X86_START16_DATA)
  65. TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
  66. TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
  67. TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
  68. self._output_setup = False
  69. # ELF file with a '_dt_ucode_base_size' symbol
  70. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  71. TestFunctional._MakeInputFile('u-boot', fd.read())
  72. # Intel flash descriptor file
  73. with open(self.TestFile('descriptor.bin')) as fd:
  74. TestFunctional._MakeInputFile('descriptor.bin', fd.read())
  75. @classmethod
  76. def tearDownClass(self):
  77. """Remove the temporary input directory and its contents"""
  78. if self._indir:
  79. shutil.rmtree(self._indir)
  80. self._indir = None
  81. def setUp(self):
  82. # Enable this to turn on debugging output
  83. # tout.Init(tout.DEBUG)
  84. command.test_result = None
  85. def tearDown(self):
  86. """Remove the temporary output directory"""
  87. tools._FinaliseForTest()
  88. def _RunBinman(self, *args, **kwargs):
  89. """Run binman using the command line
  90. Args:
  91. Arguments to pass, as a list of strings
  92. kwargs: Arguments to pass to Command.RunPipe()
  93. """
  94. result = command.RunPipe([[self._binman_pathname] + list(args)],
  95. capture=True, capture_stderr=True, raise_on_error=False)
  96. if result.return_code and kwargs.get('raise_on_error', True):
  97. raise Exception("Error running '%s': %s" % (' '.join(args),
  98. result.stdout + result.stderr))
  99. return result
  100. def _DoBinman(self, *args):
  101. """Run binman using directly (in the same process)
  102. Args:
  103. Arguments to pass, as a list of strings
  104. Returns:
  105. Return value (0 for success)
  106. """
  107. (options, args) = cmdline.ParseArgs(list(args))
  108. options.pager = 'binman-invalid-pager'
  109. options.build_dir = self._indir
  110. # For testing, you can force an increase in verbosity here
  111. # options.verbosity = tout.DEBUG
  112. return control.Binman(options, args)
  113. def _DoTestFile(self, fname):
  114. """Run binman with a given test file
  115. Args:
  116. fname: Device tree source filename to use (e.g. 05_simple.dts)
  117. """
  118. return self._DoBinman('-p', '-I', self._indir,
  119. '-d', self.TestFile(fname))
  120. def _SetupDtb(self, fname, outfile='u-boot.dtb'):
  121. """Set up a new test device-tree file
  122. The given file is compiled and set up as the device tree to be used
  123. for ths test.
  124. Args:
  125. fname: Filename of .dts file to read
  126. outfile: Output filename for compiled device tree binary
  127. Returns:
  128. Contents of device tree binary
  129. """
  130. if not self._output_setup:
  131. tools.PrepareOutputDir(self._indir, True)
  132. self._output_setup = True
  133. dtb = fdt_util.EnsureCompiled(self.TestFile(fname))
  134. with open(dtb) as fd:
  135. data = fd.read()
  136. TestFunctional._MakeInputFile(outfile, data)
  137. return data
  138. def _DoReadFileDtb(self, fname, use_real_dtb=False):
  139. """Run binman and return the resulting image
  140. This runs binman with a given test file and then reads the resulting
  141. output file. It is a shortcut function since most tests need to do
  142. these steps.
  143. Raises an assertion failure if binman returns a non-zero exit code.
  144. Args:
  145. fname: Device tree source filename to use (e.g. 05_simple.dts)
  146. use_real_dtb: True to use the test file as the contents of
  147. the u-boot-dtb entry. Normally this is not needed and the
  148. test contents (the U_BOOT_DTB_DATA string) can be used.
  149. But in some test we need the real contents.
  150. Returns:
  151. Tuple:
  152. Resulting image contents
  153. Device tree contents
  154. """
  155. dtb_data = None
  156. # Use the compiled test file as the u-boot-dtb input
  157. if use_real_dtb:
  158. dtb_data = self._SetupDtb(fname)
  159. try:
  160. retcode = self._DoTestFile(fname)
  161. self.assertEqual(0, retcode)
  162. # Find the (only) image, read it and return its contents
  163. image = control.images['image']
  164. fname = tools.GetOutputFilename('image.bin')
  165. self.assertTrue(os.path.exists(fname))
  166. with open(fname) as fd:
  167. return fd.read(), dtb_data
  168. finally:
  169. # Put the test file back
  170. if use_real_dtb:
  171. TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
  172. def _DoReadFile(self, fname, use_real_dtb=False):
  173. """Helper function which discards the device-tree binary"""
  174. return self._DoReadFileDtb(fname, use_real_dtb)[0]
  175. @classmethod
  176. def _MakeInputFile(self, fname, contents):
  177. """Create a new test input file, creating directories as needed
  178. Args:
  179. fname: Filenaem to create
  180. contents: File contents to write in to the file
  181. Returns:
  182. Full pathname of file created
  183. """
  184. pathname = os.path.join(self._indir, fname)
  185. dirname = os.path.dirname(pathname)
  186. if dirname and not os.path.exists(dirname):
  187. os.makedirs(dirname)
  188. with open(pathname, 'wb') as fd:
  189. fd.write(contents)
  190. return pathname
  191. @classmethod
  192. def TestFile(self, fname):
  193. return os.path.join(self._binman_dir, 'test', fname)
  194. def AssertInList(self, grep_list, target):
  195. """Assert that at least one of a list of things is in a target
  196. Args:
  197. grep_list: List of strings to check
  198. target: Target string
  199. """
  200. for grep in grep_list:
  201. if grep in target:
  202. return
  203. self.fail("Error: '%' not found in '%s'" % (grep_list, target))
  204. def CheckNoGaps(self, entries):
  205. """Check that all entries fit together without gaps
  206. Args:
  207. entries: List of entries to check
  208. """
  209. pos = 0
  210. for entry in entries.values():
  211. self.assertEqual(pos, entry.pos)
  212. pos += entry.size
  213. def GetFdtLen(self, dtb):
  214. """Get the totalsize field from a device tree binary
  215. Args:
  216. dtb: Device tree binary contents
  217. Returns:
  218. Total size of device tree binary, from the header
  219. """
  220. return struct.unpack('>L', dtb[4:8])[0]
  221. def testRun(self):
  222. """Test a basic run with valid args"""
  223. result = self._RunBinman('-h')
  224. def testFullHelp(self):
  225. """Test that the full help is displayed with -H"""
  226. result = self._RunBinman('-H')
  227. help_file = os.path.join(self._binman_dir, 'README')
  228. self.assertEqual(len(result.stdout), os.path.getsize(help_file))
  229. self.assertEqual(0, len(result.stderr))
  230. self.assertEqual(0, result.return_code)
  231. def testFullHelpInternal(self):
  232. """Test that the full help is displayed with -H"""
  233. try:
  234. command.test_result = command.CommandResult()
  235. result = self._DoBinman('-H')
  236. help_file = os.path.join(self._binman_dir, 'README')
  237. finally:
  238. command.test_result = None
  239. def testHelp(self):
  240. """Test that the basic help is displayed with -h"""
  241. result = self._RunBinman('-h')
  242. self.assertTrue(len(result.stdout) > 200)
  243. self.assertEqual(0, len(result.stderr))
  244. self.assertEqual(0, result.return_code)
  245. # Not yet available.
  246. def testBoard(self):
  247. """Test that we can run it with a specific board"""
  248. self._SetupDtb('05_simple.dts', 'sandbox/u-boot.dtb')
  249. TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
  250. result = self._DoBinman('-b', 'sandbox')
  251. self.assertEqual(0, result)
  252. def testNeedBoard(self):
  253. """Test that we get an error when no board ius supplied"""
  254. with self.assertRaises(ValueError) as e:
  255. result = self._DoBinman()
  256. self.assertIn("Must provide a board to process (use -b <board>)",
  257. str(e.exception))
  258. def testMissingDt(self):
  259. """Test that an invalid device tree file generates an error"""
  260. with self.assertRaises(Exception) as e:
  261. self._RunBinman('-d', 'missing_file')
  262. # We get one error from libfdt, and a different one from fdtget.
  263. self.AssertInList(["Couldn't open blob from 'missing_file'",
  264. 'No such file or directory'], str(e.exception))
  265. def testBrokenDt(self):
  266. """Test that an invalid device tree source file generates an error
  267. Since this is a source file it should be compiled and the error
  268. will come from the device-tree compiler (dtc).
  269. """
  270. with self.assertRaises(Exception) as e:
  271. self._RunBinman('-d', self.TestFile('01_invalid.dts'))
  272. self.assertIn("FATAL ERROR: Unable to parse input tree",
  273. str(e.exception))
  274. def testMissingNode(self):
  275. """Test that a device tree without a 'binman' node generates an error"""
  276. with self.assertRaises(Exception) as e:
  277. self._DoBinman('-d', self.TestFile('02_missing_node.dts'))
  278. self.assertIn("does not have a 'binman' node", str(e.exception))
  279. def testEmpty(self):
  280. """Test that an empty binman node works OK (i.e. does nothing)"""
  281. result = self._RunBinman('-d', self.TestFile('03_empty.dts'))
  282. self.assertEqual(0, len(result.stderr))
  283. self.assertEqual(0, result.return_code)
  284. def testInvalidEntry(self):
  285. """Test that an invalid entry is flagged"""
  286. with self.assertRaises(Exception) as e:
  287. result = self._RunBinman('-d',
  288. self.TestFile('04_invalid_entry.dts'))
  289. #print e.exception
  290. self.assertIn("Unknown entry type 'not-a-valid-type' in node "
  291. "'/binman/not-a-valid-type'", str(e.exception))
  292. def testSimple(self):
  293. """Test a simple binman with a single file"""
  294. data = self._DoReadFile('05_simple.dts')
  295. self.assertEqual(U_BOOT_DATA, data)
  296. def testDual(self):
  297. """Test that we can handle creating two images
  298. This also tests image padding.
  299. """
  300. retcode = self._DoTestFile('06_dual_image.dts')
  301. self.assertEqual(0, retcode)
  302. image = control.images['image1']
  303. self.assertEqual(len(U_BOOT_DATA), image._size)
  304. fname = tools.GetOutputFilename('image1.bin')
  305. self.assertTrue(os.path.exists(fname))
  306. with open(fname) as fd:
  307. data = fd.read()
  308. self.assertEqual(U_BOOT_DATA, data)
  309. image = control.images['image2']
  310. self.assertEqual(3 + len(U_BOOT_DATA) + 5, image._size)
  311. fname = tools.GetOutputFilename('image2.bin')
  312. self.assertTrue(os.path.exists(fname))
  313. with open(fname) as fd:
  314. data = fd.read()
  315. self.assertEqual(U_BOOT_DATA, data[3:7])
  316. self.assertEqual(chr(0) * 3, data[:3])
  317. self.assertEqual(chr(0) * 5, data[7:])
  318. def testBadAlign(self):
  319. """Test that an invalid alignment value is detected"""
  320. with self.assertRaises(ValueError) as e:
  321. self._DoTestFile('07_bad_align.dts')
  322. self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
  323. "of two", str(e.exception))
  324. def testPackSimple(self):
  325. """Test that packing works as expected"""
  326. retcode = self._DoTestFile('08_pack.dts')
  327. self.assertEqual(0, retcode)
  328. self.assertIn('image', control.images)
  329. image = control.images['image']
  330. entries = image._entries
  331. self.assertEqual(5, len(entries))
  332. # First u-boot
  333. self.assertIn('u-boot', entries)
  334. entry = entries['u-boot']
  335. self.assertEqual(0, entry.pos)
  336. self.assertEqual(len(U_BOOT_DATA), entry.size)
  337. # Second u-boot, aligned to 16-byte boundary
  338. self.assertIn('u-boot-align', entries)
  339. entry = entries['u-boot-align']
  340. self.assertEqual(16, entry.pos)
  341. self.assertEqual(len(U_BOOT_DATA), entry.size)
  342. # Third u-boot, size 23 bytes
  343. self.assertIn('u-boot-size', entries)
  344. entry = entries['u-boot-size']
  345. self.assertEqual(20, entry.pos)
  346. self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
  347. self.assertEqual(23, entry.size)
  348. # Fourth u-boot, placed immediate after the above
  349. self.assertIn('u-boot-next', entries)
  350. entry = entries['u-boot-next']
  351. self.assertEqual(43, entry.pos)
  352. self.assertEqual(len(U_BOOT_DATA), entry.size)
  353. # Fifth u-boot, placed at a fixed position
  354. self.assertIn('u-boot-fixed', entries)
  355. entry = entries['u-boot-fixed']
  356. self.assertEqual(61, entry.pos)
  357. self.assertEqual(len(U_BOOT_DATA), entry.size)
  358. self.assertEqual(65, image._size)
  359. def testPackExtra(self):
  360. """Test that extra packing feature works as expected"""
  361. retcode = self._DoTestFile('09_pack_extra.dts')
  362. self.assertEqual(0, retcode)
  363. self.assertIn('image', control.images)
  364. image = control.images['image']
  365. entries = image._entries
  366. self.assertEqual(5, len(entries))
  367. # First u-boot with padding before and after
  368. self.assertIn('u-boot', entries)
  369. entry = entries['u-boot']
  370. self.assertEqual(0, entry.pos)
  371. self.assertEqual(3, entry.pad_before)
  372. self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
  373. # Second u-boot has an aligned size, but it has no effect
  374. self.assertIn('u-boot-align-size-nop', entries)
  375. entry = entries['u-boot-align-size-nop']
  376. self.assertEqual(12, entry.pos)
  377. self.assertEqual(4, entry.size)
  378. # Third u-boot has an aligned size too
  379. self.assertIn('u-boot-align-size', entries)
  380. entry = entries['u-boot-align-size']
  381. self.assertEqual(16, entry.pos)
  382. self.assertEqual(32, entry.size)
  383. # Fourth u-boot has an aligned end
  384. self.assertIn('u-boot-align-end', entries)
  385. entry = entries['u-boot-align-end']
  386. self.assertEqual(48, entry.pos)
  387. self.assertEqual(16, entry.size)
  388. # Fifth u-boot immediately afterwards
  389. self.assertIn('u-boot-align-both', entries)
  390. entry = entries['u-boot-align-both']
  391. self.assertEqual(64, entry.pos)
  392. self.assertEqual(64, entry.size)
  393. self.CheckNoGaps(entries)
  394. self.assertEqual(128, image._size)
  395. def testPackAlignPowerOf2(self):
  396. """Test that invalid entry alignment is detected"""
  397. with self.assertRaises(ValueError) as e:
  398. self._DoTestFile('10_pack_align_power2.dts')
  399. self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
  400. "of two", str(e.exception))
  401. def testPackAlignSizePowerOf2(self):
  402. """Test that invalid entry size alignment is detected"""
  403. with self.assertRaises(ValueError) as e:
  404. self._DoTestFile('11_pack_align_size_power2.dts')
  405. self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
  406. "power of two", str(e.exception))
  407. def testPackInvalidAlign(self):
  408. """Test detection of an position that does not match its alignment"""
  409. with self.assertRaises(ValueError) as e:
  410. self._DoTestFile('12_pack_inv_align.dts')
  411. self.assertIn("Node '/binman/u-boot': Position 0x5 (5) does not match "
  412. "align 0x4 (4)", str(e.exception))
  413. def testPackInvalidSizeAlign(self):
  414. """Test that invalid entry size alignment is detected"""
  415. with self.assertRaises(ValueError) as e:
  416. self._DoTestFile('13_pack_inv_size_align.dts')
  417. self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
  418. "align-size 0x4 (4)", str(e.exception))
  419. def testPackOverlap(self):
  420. """Test that overlapping regions are detected"""
  421. with self.assertRaises(ValueError) as e:
  422. self._DoTestFile('14_pack_overlap.dts')
  423. self.assertIn("Node '/binman/u-boot-align': Position 0x3 (3) overlaps "
  424. "with previous entry '/binman/u-boot' ending at 0x4 (4)",
  425. str(e.exception))
  426. def testPackEntryOverflow(self):
  427. """Test that entries that overflow their size are detected"""
  428. with self.assertRaises(ValueError) as e:
  429. self._DoTestFile('15_pack_overflow.dts')
  430. self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
  431. "but entry size is 0x3 (3)", str(e.exception))
  432. def testPackImageOverflow(self):
  433. """Test that entries which overflow the image size are detected"""
  434. with self.assertRaises(ValueError) as e:
  435. self._DoTestFile('16_pack_image_overflow.dts')
  436. self.assertIn("Image '/binman': contents size 0x4 (4) exceeds image "
  437. "size 0x3 (3)", str(e.exception))
  438. def testPackImageSize(self):
  439. """Test that the image size can be set"""
  440. retcode = self._DoTestFile('17_pack_image_size.dts')
  441. self.assertEqual(0, retcode)
  442. self.assertIn('image', control.images)
  443. image = control.images['image']
  444. self.assertEqual(7, image._size)
  445. def testPackImageSizeAlign(self):
  446. """Test that image size alignemnt works as expected"""
  447. retcode = self._DoTestFile('18_pack_image_align.dts')
  448. self.assertEqual(0, retcode)
  449. self.assertIn('image', control.images)
  450. image = control.images['image']
  451. self.assertEqual(16, image._size)
  452. def testPackInvalidImageAlign(self):
  453. """Test that invalid image alignment is detected"""
  454. with self.assertRaises(ValueError) as e:
  455. self._DoTestFile('19_pack_inv_image_align.dts')
  456. self.assertIn("Image '/binman': Size 0x7 (7) does not match "
  457. "align-size 0x8 (8)", str(e.exception))
  458. def testPackAlignPowerOf2(self):
  459. """Test that invalid image alignment is detected"""
  460. with self.assertRaises(ValueError) as e:
  461. self._DoTestFile('20_pack_inv_image_align_power2.dts')
  462. self.assertIn("Image '/binman': Alignment size 131 must be a power of "
  463. "two", str(e.exception))
  464. def testImagePadByte(self):
  465. """Test that the image pad byte can be specified"""
  466. data = self._DoReadFile('21_image_pad.dts')
  467. self.assertEqual(U_BOOT_SPL_DATA + (chr(0xff) * 9) + U_BOOT_DATA, data)
  468. def testImageName(self):
  469. """Test that image files can be named"""
  470. retcode = self._DoTestFile('22_image_name.dts')
  471. self.assertEqual(0, retcode)
  472. image = control.images['image1']
  473. fname = tools.GetOutputFilename('test-name')
  474. self.assertTrue(os.path.exists(fname))
  475. image = control.images['image2']
  476. fname = tools.GetOutputFilename('test-name.xx')
  477. self.assertTrue(os.path.exists(fname))
  478. def testBlobFilename(self):
  479. """Test that generic blobs can be provided by filename"""
  480. data = self._DoReadFile('23_blob.dts')
  481. self.assertEqual(BLOB_DATA, data)
  482. def testPackSorted(self):
  483. """Test that entries can be sorted"""
  484. data = self._DoReadFile('24_sorted.dts')
  485. self.assertEqual(chr(0) * 5 + U_BOOT_SPL_DATA + chr(0) * 2 +
  486. U_BOOT_DATA, data)
  487. def testPackZeroPosition(self):
  488. """Test that an entry at position 0 is not given a new position"""
  489. with self.assertRaises(ValueError) as e:
  490. self._DoTestFile('25_pack_zero_size.dts')
  491. self.assertIn("Node '/binman/u-boot-spl': Position 0x0 (0) overlaps "
  492. "with previous entry '/binman/u-boot' ending at 0x4 (4)",
  493. str(e.exception))
  494. def testPackUbootDtb(self):
  495. """Test that a device tree can be added to U-Boot"""
  496. data = self._DoReadFile('26_pack_u_boot_dtb.dts')
  497. self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
  498. def testPackX86RomNoSize(self):
  499. """Test that the end-at-4gb property requires a size property"""
  500. with self.assertRaises(ValueError) as e:
  501. self._DoTestFile('27_pack_4gb_no_size.dts')
  502. self.assertIn("Image '/binman': Image size must be provided when "
  503. "using end-at-4gb", str(e.exception))
  504. def testPackX86RomOutside(self):
  505. """Test that the end-at-4gb property checks for position boundaries"""
  506. with self.assertRaises(ValueError) as e:
  507. self._DoTestFile('28_pack_4gb_outside.dts')
  508. self.assertIn("Node '/binman/u-boot': Position 0x0 (0) is outside "
  509. "the image starting at 0xfffffff0 (4294967280)",
  510. str(e.exception))
  511. def testPackX86Rom(self):
  512. """Test that a basic x86 ROM can be created"""
  513. data = self._DoReadFile('29_x86-rom.dts')
  514. self.assertEqual(U_BOOT_DATA + chr(0) * 3 + U_BOOT_SPL_DATA +
  515. chr(0) * 6, data)
  516. def testPackX86RomMeNoDesc(self):
  517. """Test that an invalid Intel descriptor entry is detected"""
  518. TestFunctional._MakeInputFile('descriptor.bin', '')
  519. with self.assertRaises(ValueError) as e:
  520. self._DoTestFile('31_x86-rom-me.dts')
  521. self.assertIn("Node '/binman/intel-descriptor': Cannot find FD "
  522. "signature", str(e.exception))
  523. def testPackX86RomBadDesc(self):
  524. """Test that the Intel requires a descriptor entry"""
  525. with self.assertRaises(ValueError) as e:
  526. self._DoTestFile('30_x86-rom-me-no-desc.dts')
  527. self.assertIn("Node '/binman/intel-me': No position set with "
  528. "pos-unset: should another entry provide this correct "
  529. "position?", str(e.exception))
  530. def testPackX86RomMe(self):
  531. """Test that an x86 ROM with an ME region can be created"""
  532. data = self._DoReadFile('31_x86-rom-me.dts')
  533. self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
  534. def testPackVga(self):
  535. """Test that an image with a VGA binary can be created"""
  536. data = self._DoReadFile('32_intel-vga.dts')
  537. self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
  538. def testPackStart16(self):
  539. """Test that an image with an x86 start16 region can be created"""
  540. data = self._DoReadFile('33_x86-start16.dts')
  541. self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
  542. def testPackUbootMicrocode(self):
  543. """Test that x86 microcode can be handled correctly
  544. We expect to see the following in the image, in order:
  545. u-boot-nodtb.bin with a microcode pointer inserted at the correct
  546. place
  547. u-boot.dtb with the microcode removed
  548. the microcode
  549. """
  550. data = self._DoReadFile('34_x86_ucode.dts', True)
  551. # Now check the device tree has no microcode
  552. second = data[len(U_BOOT_NODTB_DATA):]
  553. fname = tools.GetOutputFilename('test.dtb')
  554. with open(fname, 'wb') as fd:
  555. fd.write(second)
  556. fdt = fdt_select.FdtScan(fname)
  557. ucode = fdt.GetNode('/microcode')
  558. self.assertTrue(ucode)
  559. for node in ucode.subnodes:
  560. self.assertFalse(node.props.get('data'))
  561. fdt_len = self.GetFdtLen(second)
  562. third = second[fdt_len:]
  563. # Check that the microcode appears immediately after the Fdt
  564. # This matches the concatenation of the data properties in
  565. # the /microcode/update@xxx nodes in x86_ucode.dts.
  566. ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
  567. 0x78235609)
  568. self.assertEqual(ucode_data, third[:len(ucode_data)])
  569. ucode_pos = len(U_BOOT_NODTB_DATA) + fdt_len
  570. # Check that the microcode pointer was inserted. It should match the
  571. # expected position and size
  572. pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
  573. len(ucode_data))
  574. first = data[:len(U_BOOT_NODTB_DATA)]
  575. self.assertEqual('nodtb with microcode' + pos_and_size +
  576. ' somewhere in here', first)
  577. def _RunPackUbootSingleMicrocode(self, collate):
  578. """Test that x86 microcode can be handled correctly
  579. We expect to see the following in the image, in order:
  580. u-boot-nodtb.bin with a microcode pointer inserted at the correct
  581. place
  582. u-boot.dtb with the microcode
  583. an empty microcode region
  584. """
  585. # We need the libfdt library to run this test since only that allows
  586. # finding the offset of a property. This is required by
  587. # Entry_u_boot_dtb_with_ucode.ObtainContents().
  588. if not fdt_select.have_libfdt:
  589. return
  590. data = self._DoReadFile('35_x86_single_ucode.dts', True)
  591. second = data[len(U_BOOT_NODTB_DATA):]
  592. fdt_len = self.GetFdtLen(second)
  593. third = second[fdt_len:]
  594. second = second[:fdt_len]
  595. if not collate:
  596. ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
  597. self.assertIn(ucode_data, second)
  598. ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
  599. # Check that the microcode pointer was inserted. It should match the
  600. # expected position and size
  601. pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
  602. len(ucode_data))
  603. first = data[:len(U_BOOT_NODTB_DATA)]
  604. self.assertEqual('nodtb with microcode' + pos_and_size +
  605. ' somewhere in here', first)
  606. def testPackUbootSingleMicrocode(self):
  607. """Test that x86 microcode can be handled correctly with fdt_normal.
  608. """
  609. self._RunPackUbootSingleMicrocode(False)
  610. def testPackUbootSingleMicrocodeFallback(self):
  611. """Test that x86 microcode can be handled correctly with fdt_fallback.
  612. This only supports collating the microcode.
  613. """
  614. try:
  615. old_val = fdt_select.UseFallback(True)
  616. self._RunPackUbootSingleMicrocode(True)
  617. finally:
  618. fdt_select.UseFallback(old_val)
  619. def testUBootImg(self):
  620. """Test that u-boot.img can be put in a file"""
  621. data = self._DoReadFile('36_u_boot_img.dts')
  622. self.assertEqual(U_BOOT_IMG_DATA, data)
  623. def testNoMicrocode(self):
  624. """Test that a missing microcode region is detected"""
  625. with self.assertRaises(ValueError) as e:
  626. self._DoReadFile('37_x86_no_ucode.dts', True)
  627. self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
  628. "node found in ", str(e.exception))
  629. def testMicrocodeWithoutNode(self):
  630. """Test that a missing u-boot-dtb-with-ucode node is detected"""
  631. with self.assertRaises(ValueError) as e:
  632. self._DoReadFile('38_x86_ucode_missing_node.dts', True)
  633. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
  634. "microcode region u-boot-dtb-with-ucode", str(e.exception))
  635. def testMicrocodeWithoutNode2(self):
  636. """Test that a missing u-boot-ucode node is detected"""
  637. with self.assertRaises(ValueError) as e:
  638. self._DoReadFile('39_x86_ucode_missing_node2.dts', True)
  639. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
  640. "microcode region u-boot-ucode", str(e.exception))
  641. def testMicrocodeWithoutPtrInElf(self):
  642. """Test that a U-Boot binary without the microcode symbol is detected"""
  643. # ELF file without a '_dt_ucode_base_size' symbol
  644. if not fdt_select.have_libfdt:
  645. return
  646. try:
  647. with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
  648. TestFunctional._MakeInputFile('u-boot', fd.read())
  649. with self.assertRaises(ValueError) as e:
  650. self._RunPackUbootSingleMicrocode(False)
  651. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
  652. "_dt_ucode_base_size symbol in u-boot", str(e.exception))
  653. finally:
  654. # Put the original file back
  655. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  656. TestFunctional._MakeInputFile('u-boot', fd.read())
  657. def testMicrocodeNotInImage(self):
  658. """Test that microcode must be placed within the image"""
  659. with self.assertRaises(ValueError) as e:
  660. self._DoReadFile('40_x86_ucode_not_in_image.dts', True)
  661. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
  662. "pointer _dt_ucode_base_size at fffffe14 is outside the "
  663. "image ranging from 00000000 to 0000002e", str(e.exception))
  664. def testWithoutMicrocode(self):
  665. """Test that we can cope with an image without microcode (e.g. qemu)"""
  666. with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
  667. TestFunctional._MakeInputFile('u-boot', fd.read())
  668. data, dtb = self._DoReadFileDtb('44_x86_optional_ucode.dts', True)
  669. # Now check the device tree has no microcode
  670. self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
  671. second = data[len(U_BOOT_NODTB_DATA):]
  672. fdt_len = self.GetFdtLen(second)
  673. self.assertEqual(dtb, second[:fdt_len])
  674. used_len = len(U_BOOT_NODTB_DATA) + fdt_len
  675. third = data[used_len:]
  676. self.assertEqual(chr(0) * (0x200 - used_len), third)
  677. def testUnknownPosSize(self):
  678. """Test that microcode must be placed within the image"""
  679. with self.assertRaises(ValueError) as e:
  680. self._DoReadFile('41_unknown_pos_size.dts', True)
  681. self.assertIn("Image '/binman': Unable to set pos/size for unknown "
  682. "entry 'invalid-entry'", str(e.exception))
  683. def testPackFsp(self):
  684. """Test that an image with a FSP binary can be created"""
  685. data = self._DoReadFile('42_intel-fsp.dts')
  686. self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
  687. def testPackCmc(self):
  688. """Test that an image with a FSP binary can be created"""
  689. data = self._DoReadFile('43_intel-cmc.dts')
  690. self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])