ftest.py 37 KB

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