ftest.py 32 KB

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