ftest.py 37 KB

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