func_test.py 32 KB

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