ftest.py 37 KB

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