ftest.py 35 KB

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