ftest.py 33 KB

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