ftest.py 34 KB

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