ftest.py 39 KB

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