ftest.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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 fmap_util
  23. import test_util
  24. import tools
  25. import tout
  26. # Contents of test files, corresponding to different entry types
  27. U_BOOT_DATA = '1234'
  28. U_BOOT_IMG_DATA = 'img'
  29. U_BOOT_SPL_DATA = '56780123456789abcde'
  30. U_BOOT_TPL_DATA = 'tpl'
  31. BLOB_DATA = '89'
  32. ME_DATA = '0abcd'
  33. VGA_DATA = 'vga'
  34. U_BOOT_DTB_DATA = 'udtb'
  35. U_BOOT_SPL_DTB_DATA = 'spldtb'
  36. U_BOOT_TPL_DTB_DATA = 'tpldtb'
  37. X86_START16_DATA = 'start16'
  38. X86_START16_SPL_DATA = 'start16spl'
  39. U_BOOT_NODTB_DATA = 'nodtb with microcode pointer somewhere in here'
  40. U_BOOT_SPL_NODTB_DATA = 'splnodtb with microcode pointer somewhere in here'
  41. FSP_DATA = 'fsp'
  42. CMC_DATA = 'cmc'
  43. VBT_DATA = 'vbt'
  44. MRC_DATA = 'mrc'
  45. TEXT_DATA = 'text'
  46. TEXT_DATA2 = 'text2'
  47. TEXT_DATA3 = 'text3'
  48. CROS_EC_RW_DATA = 'ecrw'
  49. GBB_DATA = 'gbbd'
  50. BMPBLK_DATA = 'bmp'
  51. VBLOCK_DATA = 'vblk'
  52. class TestFunctional(unittest.TestCase):
  53. """Functional tests for binman
  54. Most of these use a sample .dts file to build an image and then check
  55. that it looks correct. The sample files are in the test/ subdirectory
  56. and are numbered.
  57. For each entry type a very small test file is created using fixed
  58. string contents. This makes it easy to test that things look right, and
  59. debug problems.
  60. In some cases a 'real' file must be used - these are also supplied in
  61. the test/ diurectory.
  62. """
  63. @classmethod
  64. def setUpClass(self):
  65. global entry
  66. import entry
  67. # Handle the case where argv[0] is 'python'
  68. self._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  69. self._binman_pathname = os.path.join(self._binman_dir, 'binman')
  70. # Create a temporary directory for input files
  71. self._indir = tempfile.mkdtemp(prefix='binmant.')
  72. # Create some test files
  73. TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
  74. TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
  75. TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
  76. TestFunctional._MakeInputFile('tpl/u-boot-tpl.bin', U_BOOT_TPL_DATA)
  77. TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
  78. TestFunctional._MakeInputFile('me.bin', ME_DATA)
  79. TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
  80. self._ResetDtbs()
  81. TestFunctional._MakeInputFile('u-boot-x86-16bit.bin', X86_START16_DATA)
  82. TestFunctional._MakeInputFile('spl/u-boot-x86-16bit-spl.bin',
  83. X86_START16_SPL_DATA)
  84. TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
  85. TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
  86. U_BOOT_SPL_NODTB_DATA)
  87. TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
  88. TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
  89. TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
  90. TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
  91. TestFunctional._MakeInputFile('ecrw.bin', CROS_EC_RW_DATA)
  92. TestFunctional._MakeInputDir('devkeys')
  93. TestFunctional._MakeInputFile('bmpblk.bin', BMPBLK_DATA)
  94. self._output_setup = False
  95. # ELF file with a '_dt_ucode_base_size' symbol
  96. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  97. TestFunctional._MakeInputFile('u-boot', fd.read())
  98. # Intel flash descriptor file
  99. with open(self.TestFile('descriptor.bin')) as fd:
  100. TestFunctional._MakeInputFile('descriptor.bin', fd.read())
  101. @classmethod
  102. def tearDownClass(self):
  103. """Remove the temporary input directory and its contents"""
  104. if self._indir:
  105. shutil.rmtree(self._indir)
  106. self._indir = None
  107. def setUp(self):
  108. # Enable this to turn on debugging output
  109. # tout.Init(tout.DEBUG)
  110. command.test_result = None
  111. def tearDown(self):
  112. """Remove the temporary output directory"""
  113. tools._FinaliseForTest()
  114. @classmethod
  115. def _ResetDtbs(self):
  116. TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
  117. TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
  118. TestFunctional._MakeInputFile('tpl/u-boot-tpl.dtb', U_BOOT_TPL_DTB_DATA)
  119. def _RunBinman(self, *args, **kwargs):
  120. """Run binman using the command line
  121. Args:
  122. Arguments to pass, as a list of strings
  123. kwargs: Arguments to pass to Command.RunPipe()
  124. """
  125. result = command.RunPipe([[self._binman_pathname] + list(args)],
  126. capture=True, capture_stderr=True, raise_on_error=False)
  127. if result.return_code and kwargs.get('raise_on_error', True):
  128. raise Exception("Error running '%s': %s" % (' '.join(args),
  129. result.stdout + result.stderr))
  130. return result
  131. def _DoBinman(self, *args):
  132. """Run binman using directly (in the same process)
  133. Args:
  134. Arguments to pass, as a list of strings
  135. Returns:
  136. Return value (0 for success)
  137. """
  138. args = list(args)
  139. if '-D' in sys.argv:
  140. args = args + ['-D']
  141. (options, args) = cmdline.ParseArgs(args)
  142. options.pager = 'binman-invalid-pager'
  143. options.build_dir = self._indir
  144. # For testing, you can force an increase in verbosity here
  145. # options.verbosity = tout.DEBUG
  146. return control.Binman(options, args)
  147. def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
  148. entry_args=None):
  149. """Run binman with a given test file
  150. Args:
  151. fname: Device-tree source filename to use (e.g. 05_simple.dts)
  152. debug: True to enable debugging output
  153. map: True to output map files for the images
  154. update_dtb: Update the offset and size of each entry in the device
  155. tree before packing it into the image
  156. """
  157. args = ['-p', '-I', self._indir, '-d', self.TestFile(fname)]
  158. if debug:
  159. args.append('-D')
  160. if map:
  161. args.append('-m')
  162. if update_dtb:
  163. args.append('-up')
  164. if entry_args:
  165. for arg, value in entry_args.iteritems():
  166. args.append('-a%s=%s' % (arg, value))
  167. return self._DoBinman(*args)
  168. def _SetupDtb(self, fname, outfile='u-boot.dtb'):
  169. """Set up a new test device-tree file
  170. The given file is compiled and set up as the device tree to be used
  171. for ths test.
  172. Args:
  173. fname: Filename of .dts file to read
  174. outfile: Output filename for compiled device-tree binary
  175. Returns:
  176. Contents of device-tree binary
  177. """
  178. if not self._output_setup:
  179. tools.PrepareOutputDir(self._indir, True)
  180. self._output_setup = True
  181. dtb = fdt_util.EnsureCompiled(self.TestFile(fname))
  182. with open(dtb) as fd:
  183. data = fd.read()
  184. TestFunctional._MakeInputFile(outfile, data)
  185. return data
  186. def _DoReadFileDtb(self, fname, use_real_dtb=False, map=False,
  187. update_dtb=False, entry_args=None):
  188. """Run binman and return the resulting image
  189. This runs binman with a given test file and then reads the resulting
  190. output file. It is a shortcut function since most tests need to do
  191. these steps.
  192. Raises an assertion failure if binman returns a non-zero exit code.
  193. Args:
  194. fname: Device-tree source filename to use (e.g. 05_simple.dts)
  195. use_real_dtb: True to use the test file as the contents of
  196. the u-boot-dtb entry. Normally this is not needed and the
  197. test contents (the U_BOOT_DTB_DATA string) can be used.
  198. But in some test we need the real contents.
  199. map: True to output map files for the images
  200. update_dtb: Update the offset and size of each entry in the device
  201. tree before packing it into the image
  202. Returns:
  203. Tuple:
  204. Resulting image contents
  205. Device tree contents
  206. Map data showing contents of image (or None if none)
  207. Output device tree binary filename ('u-boot.dtb' path)
  208. """
  209. dtb_data = None
  210. # Use the compiled test file as the u-boot-dtb input
  211. if use_real_dtb:
  212. dtb_data = self._SetupDtb(fname)
  213. try:
  214. retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
  215. entry_args=entry_args)
  216. self.assertEqual(0, retcode)
  217. out_dtb_fname = control.GetFdtPath('u-boot.dtb')
  218. # Find the (only) image, read it and return its contents
  219. image = control.images['image']
  220. image_fname = tools.GetOutputFilename('image.bin')
  221. self.assertTrue(os.path.exists(image_fname))
  222. if map:
  223. map_fname = tools.GetOutputFilename('image.map')
  224. with open(map_fname) as fd:
  225. map_data = fd.read()
  226. else:
  227. map_data = None
  228. with open(image_fname) as fd:
  229. return fd.read(), dtb_data, map_data, out_dtb_fname
  230. finally:
  231. # Put the test file back
  232. if use_real_dtb:
  233. self._ResetDtbs()
  234. def _DoReadFile(self, fname, use_real_dtb=False):
  235. """Helper function which discards the device-tree binary
  236. Args:
  237. fname: Device-tree source filename to use (e.g. 05_simple.dts)
  238. use_real_dtb: True to use the test file as the contents of
  239. the u-boot-dtb entry. Normally this is not needed and the
  240. test contents (the U_BOOT_DTB_DATA string) can be used.
  241. But in some test we need the real contents.
  242. Returns:
  243. Resulting image contents
  244. """
  245. return self._DoReadFileDtb(fname, use_real_dtb)[0]
  246. @classmethod
  247. def _MakeInputFile(self, fname, contents):
  248. """Create a new test input file, creating directories as needed
  249. Args:
  250. fname: Filename to create
  251. contents: File contents to write in to the file
  252. Returns:
  253. Full pathname of file created
  254. """
  255. pathname = os.path.join(self._indir, fname)
  256. dirname = os.path.dirname(pathname)
  257. if dirname and not os.path.exists(dirname):
  258. os.makedirs(dirname)
  259. with open(pathname, 'wb') as fd:
  260. fd.write(contents)
  261. return pathname
  262. @classmethod
  263. def _MakeInputDir(self, dirname):
  264. """Create a new test input directory, creating directories as needed
  265. Args:
  266. dirname: Directory name to create
  267. Returns:
  268. Full pathname of directory created
  269. """
  270. pathname = os.path.join(self._indir, dirname)
  271. if not os.path.exists(pathname):
  272. os.makedirs(pathname)
  273. return pathname
  274. @classmethod
  275. def TestFile(self, fname):
  276. return os.path.join(self._binman_dir, 'test', fname)
  277. def AssertInList(self, grep_list, target):
  278. """Assert that at least one of a list of things is in a target
  279. Args:
  280. grep_list: List of strings to check
  281. target: Target string
  282. """
  283. for grep in grep_list:
  284. if grep in target:
  285. return
  286. self.fail("Error: '%' not found in '%s'" % (grep_list, target))
  287. def CheckNoGaps(self, entries):
  288. """Check that all entries fit together without gaps
  289. Args:
  290. entries: List of entries to check
  291. """
  292. offset = 0
  293. for entry in entries.values():
  294. self.assertEqual(offset, entry.offset)
  295. offset += entry.size
  296. def GetFdtLen(self, dtb):
  297. """Get the totalsize field from a device-tree binary
  298. Args:
  299. dtb: Device-tree binary contents
  300. Returns:
  301. Total size of device-tree binary, from the header
  302. """
  303. return struct.unpack('>L', dtb[4:8])[0]
  304. def _GetPropTree(self, dtb, prop_names):
  305. def AddNode(node, path):
  306. if node.name != '/':
  307. path += '/' + node.name
  308. for subnode in node.subnodes:
  309. for prop in subnode.props.values():
  310. if prop.name in prop_names:
  311. prop_path = path + '/' + subnode.name + ':' + prop.name
  312. tree[prop_path[len('/binman/'):]] = fdt_util.fdt32_to_cpu(
  313. prop.value)
  314. AddNode(subnode, path)
  315. tree = {}
  316. AddNode(dtb.GetRoot(), '')
  317. return tree
  318. def testRun(self):
  319. """Test a basic run with valid args"""
  320. result = self._RunBinman('-h')
  321. def testFullHelp(self):
  322. """Test that the full help is displayed with -H"""
  323. result = self._RunBinman('-H')
  324. help_file = os.path.join(self._binman_dir, 'README')
  325. # Remove possible extraneous strings
  326. extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
  327. gothelp = result.stdout.replace(extra, '')
  328. self.assertEqual(len(gothelp), os.path.getsize(help_file))
  329. self.assertEqual(0, len(result.stderr))
  330. self.assertEqual(0, result.return_code)
  331. def testFullHelpInternal(self):
  332. """Test that the full help is displayed with -H"""
  333. try:
  334. command.test_result = command.CommandResult()
  335. result = self._DoBinman('-H')
  336. help_file = os.path.join(self._binman_dir, 'README')
  337. finally:
  338. command.test_result = None
  339. def testHelp(self):
  340. """Test that the basic help is displayed with -h"""
  341. result = self._RunBinman('-h')
  342. self.assertTrue(len(result.stdout) > 200)
  343. self.assertEqual(0, len(result.stderr))
  344. self.assertEqual(0, result.return_code)
  345. def testBoard(self):
  346. """Test that we can run it with a specific board"""
  347. self._SetupDtb('05_simple.dts', 'sandbox/u-boot.dtb')
  348. TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
  349. result = self._DoBinman('-b', 'sandbox')
  350. self.assertEqual(0, result)
  351. def testNeedBoard(self):
  352. """Test that we get an error when no board ius supplied"""
  353. with self.assertRaises(ValueError) as e:
  354. result = self._DoBinman()
  355. self.assertIn("Must provide a board to process (use -b <board>)",
  356. str(e.exception))
  357. def testMissingDt(self):
  358. """Test that an invalid device-tree file generates an error"""
  359. with self.assertRaises(Exception) as e:
  360. self._RunBinman('-d', 'missing_file')
  361. # We get one error from libfdt, and a different one from fdtget.
  362. self.AssertInList(["Couldn't open blob from 'missing_file'",
  363. 'No such file or directory'], str(e.exception))
  364. def testBrokenDt(self):
  365. """Test that an invalid device-tree source file generates an error
  366. Since this is a source file it should be compiled and the error
  367. will come from the device-tree compiler (dtc).
  368. """
  369. with self.assertRaises(Exception) as e:
  370. self._RunBinman('-d', self.TestFile('01_invalid.dts'))
  371. self.assertIn("FATAL ERROR: Unable to parse input tree",
  372. str(e.exception))
  373. def testMissingNode(self):
  374. """Test that a device tree without a 'binman' node generates an error"""
  375. with self.assertRaises(Exception) as e:
  376. self._DoBinman('-d', self.TestFile('02_missing_node.dts'))
  377. self.assertIn("does not have a 'binman' node", str(e.exception))
  378. def testEmpty(self):
  379. """Test that an empty binman node works OK (i.e. does nothing)"""
  380. result = self._RunBinman('-d', self.TestFile('03_empty.dts'))
  381. self.assertEqual(0, len(result.stderr))
  382. self.assertEqual(0, result.return_code)
  383. def testInvalidEntry(self):
  384. """Test that an invalid entry is flagged"""
  385. with self.assertRaises(Exception) as e:
  386. result = self._RunBinman('-d',
  387. self.TestFile('04_invalid_entry.dts'))
  388. self.assertIn("Unknown entry type 'not-a-valid-type' in node "
  389. "'/binman/not-a-valid-type'", str(e.exception))
  390. def testSimple(self):
  391. """Test a simple binman with a single file"""
  392. data = self._DoReadFile('05_simple.dts')
  393. self.assertEqual(U_BOOT_DATA, data)
  394. def testSimpleDebug(self):
  395. """Test a simple binman run with debugging enabled"""
  396. data = self._DoTestFile('05_simple.dts', debug=True)
  397. def testDual(self):
  398. """Test that we can handle creating two images
  399. This also tests image padding.
  400. """
  401. retcode = self._DoTestFile('06_dual_image.dts')
  402. self.assertEqual(0, retcode)
  403. image = control.images['image1']
  404. self.assertEqual(len(U_BOOT_DATA), image._size)
  405. fname = tools.GetOutputFilename('image1.bin')
  406. self.assertTrue(os.path.exists(fname))
  407. with open(fname) as fd:
  408. data = fd.read()
  409. self.assertEqual(U_BOOT_DATA, data)
  410. image = control.images['image2']
  411. self.assertEqual(3 + len(U_BOOT_DATA) + 5, image._size)
  412. fname = tools.GetOutputFilename('image2.bin')
  413. self.assertTrue(os.path.exists(fname))
  414. with open(fname) as fd:
  415. data = fd.read()
  416. self.assertEqual(U_BOOT_DATA, data[3:7])
  417. self.assertEqual(chr(0) * 3, data[:3])
  418. self.assertEqual(chr(0) * 5, data[7:])
  419. def testBadAlign(self):
  420. """Test that an invalid alignment value is detected"""
  421. with self.assertRaises(ValueError) as e:
  422. self._DoTestFile('07_bad_align.dts')
  423. self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
  424. "of two", str(e.exception))
  425. def testPackSimple(self):
  426. """Test that packing works as expected"""
  427. retcode = self._DoTestFile('08_pack.dts')
  428. self.assertEqual(0, retcode)
  429. self.assertIn('image', control.images)
  430. image = control.images['image']
  431. entries = image.GetEntries()
  432. self.assertEqual(5, len(entries))
  433. # First u-boot
  434. self.assertIn('u-boot', entries)
  435. entry = entries['u-boot']
  436. self.assertEqual(0, entry.offset)
  437. self.assertEqual(len(U_BOOT_DATA), entry.size)
  438. # Second u-boot, aligned to 16-byte boundary
  439. self.assertIn('u-boot-align', entries)
  440. entry = entries['u-boot-align']
  441. self.assertEqual(16, entry.offset)
  442. self.assertEqual(len(U_BOOT_DATA), entry.size)
  443. # Third u-boot, size 23 bytes
  444. self.assertIn('u-boot-size', entries)
  445. entry = entries['u-boot-size']
  446. self.assertEqual(20, entry.offset)
  447. self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
  448. self.assertEqual(23, entry.size)
  449. # Fourth u-boot, placed immediate after the above
  450. self.assertIn('u-boot-next', entries)
  451. entry = entries['u-boot-next']
  452. self.assertEqual(43, entry.offset)
  453. self.assertEqual(len(U_BOOT_DATA), entry.size)
  454. # Fifth u-boot, placed at a fixed offset
  455. self.assertIn('u-boot-fixed', entries)
  456. entry = entries['u-boot-fixed']
  457. self.assertEqual(61, entry.offset)
  458. self.assertEqual(len(U_BOOT_DATA), entry.size)
  459. self.assertEqual(65, image._size)
  460. def testPackExtra(self):
  461. """Test that extra packing feature works as expected"""
  462. retcode = self._DoTestFile('09_pack_extra.dts')
  463. self.assertEqual(0, retcode)
  464. self.assertIn('image', control.images)
  465. image = control.images['image']
  466. entries = image.GetEntries()
  467. self.assertEqual(5, len(entries))
  468. # First u-boot with padding before and after
  469. self.assertIn('u-boot', entries)
  470. entry = entries['u-boot']
  471. self.assertEqual(0, entry.offset)
  472. self.assertEqual(3, entry.pad_before)
  473. self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
  474. # Second u-boot has an aligned size, but it has no effect
  475. self.assertIn('u-boot-align-size-nop', entries)
  476. entry = entries['u-boot-align-size-nop']
  477. self.assertEqual(12, entry.offset)
  478. self.assertEqual(4, entry.size)
  479. # Third u-boot has an aligned size too
  480. self.assertIn('u-boot-align-size', entries)
  481. entry = entries['u-boot-align-size']
  482. self.assertEqual(16, entry.offset)
  483. self.assertEqual(32, entry.size)
  484. # Fourth u-boot has an aligned end
  485. self.assertIn('u-boot-align-end', entries)
  486. entry = entries['u-boot-align-end']
  487. self.assertEqual(48, entry.offset)
  488. self.assertEqual(16, entry.size)
  489. # Fifth u-boot immediately afterwards
  490. self.assertIn('u-boot-align-both', entries)
  491. entry = entries['u-boot-align-both']
  492. self.assertEqual(64, entry.offset)
  493. self.assertEqual(64, entry.size)
  494. self.CheckNoGaps(entries)
  495. self.assertEqual(128, image._size)
  496. def testPackAlignPowerOf2(self):
  497. """Test that invalid entry alignment is detected"""
  498. with self.assertRaises(ValueError) as e:
  499. self._DoTestFile('10_pack_align_power2.dts')
  500. self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
  501. "of two", str(e.exception))
  502. def testPackAlignSizePowerOf2(self):
  503. """Test that invalid entry size alignment is detected"""
  504. with self.assertRaises(ValueError) as e:
  505. self._DoTestFile('11_pack_align_size_power2.dts')
  506. self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
  507. "power of two", str(e.exception))
  508. def testPackInvalidAlign(self):
  509. """Test detection of an offset that does not match its alignment"""
  510. with self.assertRaises(ValueError) as e:
  511. self._DoTestFile('12_pack_inv_align.dts')
  512. self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
  513. "align 0x4 (4)", str(e.exception))
  514. def testPackInvalidSizeAlign(self):
  515. """Test that invalid entry size alignment is detected"""
  516. with self.assertRaises(ValueError) as e:
  517. self._DoTestFile('13_pack_inv_size_align.dts')
  518. self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
  519. "align-size 0x4 (4)", str(e.exception))
  520. def testPackOverlap(self):
  521. """Test that overlapping regions are detected"""
  522. with self.assertRaises(ValueError) as e:
  523. self._DoTestFile('14_pack_overlap.dts')
  524. self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
  525. "with previous entry '/binman/u-boot' ending at 0x4 (4)",
  526. str(e.exception))
  527. def testPackEntryOverflow(self):
  528. """Test that entries that overflow their size are detected"""
  529. with self.assertRaises(ValueError) as e:
  530. self._DoTestFile('15_pack_overflow.dts')
  531. self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
  532. "but entry size is 0x3 (3)", str(e.exception))
  533. def testPackImageOverflow(self):
  534. """Test that entries which overflow the image size are detected"""
  535. with self.assertRaises(ValueError) as e:
  536. self._DoTestFile('16_pack_image_overflow.dts')
  537. self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
  538. "size 0x3 (3)", str(e.exception))
  539. def testPackImageSize(self):
  540. """Test that the image size can be set"""
  541. retcode = self._DoTestFile('17_pack_image_size.dts')
  542. self.assertEqual(0, retcode)
  543. self.assertIn('image', control.images)
  544. image = control.images['image']
  545. self.assertEqual(7, image._size)
  546. def testPackImageSizeAlign(self):
  547. """Test that image size alignemnt works as expected"""
  548. retcode = self._DoTestFile('18_pack_image_align.dts')
  549. self.assertEqual(0, retcode)
  550. self.assertIn('image', control.images)
  551. image = control.images['image']
  552. self.assertEqual(16, image._size)
  553. def testPackInvalidImageAlign(self):
  554. """Test that invalid image alignment is detected"""
  555. with self.assertRaises(ValueError) as e:
  556. self._DoTestFile('19_pack_inv_image_align.dts')
  557. self.assertIn("Section '/binman': Size 0x7 (7) does not match "
  558. "align-size 0x8 (8)", str(e.exception))
  559. def testPackAlignPowerOf2(self):
  560. """Test that invalid image alignment is detected"""
  561. with self.assertRaises(ValueError) as e:
  562. self._DoTestFile('20_pack_inv_image_align_power2.dts')
  563. self.assertIn("Section '/binman': Alignment size 131 must be a power of "
  564. "two", str(e.exception))
  565. def testImagePadByte(self):
  566. """Test that the image pad byte can be specified"""
  567. with open(self.TestFile('bss_data')) as fd:
  568. TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
  569. data = self._DoReadFile('21_image_pad.dts')
  570. self.assertEqual(U_BOOT_SPL_DATA + (chr(0xff) * 1) + U_BOOT_DATA, data)
  571. def testImageName(self):
  572. """Test that image files can be named"""
  573. retcode = self._DoTestFile('22_image_name.dts')
  574. self.assertEqual(0, retcode)
  575. image = control.images['image1']
  576. fname = tools.GetOutputFilename('test-name')
  577. self.assertTrue(os.path.exists(fname))
  578. image = control.images['image2']
  579. fname = tools.GetOutputFilename('test-name.xx')
  580. self.assertTrue(os.path.exists(fname))
  581. def testBlobFilename(self):
  582. """Test that generic blobs can be provided by filename"""
  583. data = self._DoReadFile('23_blob.dts')
  584. self.assertEqual(BLOB_DATA, data)
  585. def testPackSorted(self):
  586. """Test that entries can be sorted"""
  587. data = self._DoReadFile('24_sorted.dts')
  588. self.assertEqual(chr(0) * 1 + U_BOOT_SPL_DATA + chr(0) * 2 +
  589. U_BOOT_DATA, data)
  590. def testPackZeroOffset(self):
  591. """Test that an entry at offset 0 is not given a new offset"""
  592. with self.assertRaises(ValueError) as e:
  593. self._DoTestFile('25_pack_zero_size.dts')
  594. self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
  595. "with previous entry '/binman/u-boot' ending at 0x4 (4)",
  596. str(e.exception))
  597. def testPackUbootDtb(self):
  598. """Test that a device tree can be added to U-Boot"""
  599. data = self._DoReadFile('26_pack_u_boot_dtb.dts')
  600. self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
  601. def testPackX86RomNoSize(self):
  602. """Test that the end-at-4gb property requires a size property"""
  603. with self.assertRaises(ValueError) as e:
  604. self._DoTestFile('27_pack_4gb_no_size.dts')
  605. self.assertIn("Section '/binman': Section size must be provided when "
  606. "using end-at-4gb", str(e.exception))
  607. def testPackX86RomOutside(self):
  608. """Test that the end-at-4gb property checks for offset boundaries"""
  609. with self.assertRaises(ValueError) as e:
  610. self._DoTestFile('28_pack_4gb_outside.dts')
  611. self.assertIn("Node '/binman/u-boot': Offset 0x0 (0) is outside "
  612. "the section starting at 0xffffffe0 (4294967264)",
  613. str(e.exception))
  614. def testPackX86Rom(self):
  615. """Test that a basic x86 ROM can be created"""
  616. data = self._DoReadFile('29_x86-rom.dts')
  617. self.assertEqual(U_BOOT_DATA + chr(0) * 7 + U_BOOT_SPL_DATA +
  618. chr(0) * 2, data)
  619. def testPackX86RomMeNoDesc(self):
  620. """Test that an invalid Intel descriptor entry is detected"""
  621. TestFunctional._MakeInputFile('descriptor.bin', '')
  622. with self.assertRaises(ValueError) as e:
  623. self._DoTestFile('31_x86-rom-me.dts')
  624. self.assertIn("Node '/binman/intel-descriptor': Cannot find FD "
  625. "signature", str(e.exception))
  626. def testPackX86RomBadDesc(self):
  627. """Test that the Intel requires a descriptor entry"""
  628. with self.assertRaises(ValueError) as e:
  629. self._DoTestFile('30_x86-rom-me-no-desc.dts')
  630. self.assertIn("Node '/binman/intel-me': No offset set with "
  631. "offset-unset: should another entry provide this correct "
  632. "offset?", str(e.exception))
  633. def testPackX86RomMe(self):
  634. """Test that an x86 ROM with an ME region can be created"""
  635. data = self._DoReadFile('31_x86-rom-me.dts')
  636. self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
  637. def testPackVga(self):
  638. """Test that an image with a VGA binary can be created"""
  639. data = self._DoReadFile('32_intel-vga.dts')
  640. self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
  641. def testPackStart16(self):
  642. """Test that an image with an x86 start16 region can be created"""
  643. data = self._DoReadFile('33_x86-start16.dts')
  644. self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
  645. def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
  646. """Handle running a test for insertion of microcode
  647. Args:
  648. dts_fname: Name of test .dts file
  649. nodtb_data: Data that we expect in the first section
  650. ucode_second: True if the microsecond entry is second instead of
  651. third
  652. Returns:
  653. Tuple:
  654. Contents of first region (U-Boot or SPL)
  655. Offset and size components of microcode pointer, as inserted
  656. in the above (two 4-byte words)
  657. """
  658. data = self._DoReadFile(dts_fname, True)
  659. # Now check the device tree has no microcode
  660. if ucode_second:
  661. ucode_content = data[len(nodtb_data):]
  662. ucode_pos = len(nodtb_data)
  663. dtb_with_ucode = ucode_content[16:]
  664. fdt_len = self.GetFdtLen(dtb_with_ucode)
  665. else:
  666. dtb_with_ucode = data[len(nodtb_data):]
  667. fdt_len = self.GetFdtLen(dtb_with_ucode)
  668. ucode_content = dtb_with_ucode[fdt_len:]
  669. ucode_pos = len(nodtb_data) + fdt_len
  670. fname = tools.GetOutputFilename('test.dtb')
  671. with open(fname, 'wb') as fd:
  672. fd.write(dtb_with_ucode)
  673. dtb = fdt.FdtScan(fname)
  674. ucode = dtb.GetNode('/microcode')
  675. self.assertTrue(ucode)
  676. for node in ucode.subnodes:
  677. self.assertFalse(node.props.get('data'))
  678. # Check that the microcode appears immediately after the Fdt
  679. # This matches the concatenation of the data properties in
  680. # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
  681. ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
  682. 0x78235609)
  683. self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
  684. # Check that the microcode pointer was inserted. It should match the
  685. # expected offset and size
  686. pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
  687. len(ucode_data))
  688. u_boot = data[:len(nodtb_data)]
  689. return u_boot, pos_and_size
  690. def testPackUbootMicrocode(self):
  691. """Test that x86 microcode can be handled correctly
  692. We expect to see the following in the image, in order:
  693. u-boot-nodtb.bin with a microcode pointer inserted at the correct
  694. place
  695. u-boot.dtb with the microcode removed
  696. the microcode
  697. """
  698. first, pos_and_size = self._RunMicrocodeTest('34_x86_ucode.dts',
  699. U_BOOT_NODTB_DATA)
  700. self.assertEqual('nodtb with microcode' + pos_and_size +
  701. ' somewhere in here', first)
  702. def _RunPackUbootSingleMicrocode(self):
  703. """Test that x86 microcode can be handled correctly
  704. We expect to see the following in the image, in order:
  705. u-boot-nodtb.bin with a microcode pointer inserted at the correct
  706. place
  707. u-boot.dtb with the microcode
  708. an empty microcode region
  709. """
  710. # We need the libfdt library to run this test since only that allows
  711. # finding the offset of a property. This is required by
  712. # Entry_u_boot_dtb_with_ucode.ObtainContents().
  713. data = self._DoReadFile('35_x86_single_ucode.dts', True)
  714. second = data[len(U_BOOT_NODTB_DATA):]
  715. fdt_len = self.GetFdtLen(second)
  716. third = second[fdt_len:]
  717. second = second[:fdt_len]
  718. ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
  719. self.assertIn(ucode_data, second)
  720. ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
  721. # Check that the microcode pointer was inserted. It should match the
  722. # expected offset and size
  723. pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
  724. len(ucode_data))
  725. first = data[:len(U_BOOT_NODTB_DATA)]
  726. self.assertEqual('nodtb with microcode' + pos_and_size +
  727. ' somewhere in here', first)
  728. def testPackUbootSingleMicrocode(self):
  729. """Test that x86 microcode can be handled correctly with fdt_normal.
  730. """
  731. self._RunPackUbootSingleMicrocode()
  732. def testUBootImg(self):
  733. """Test that u-boot.img can be put in a file"""
  734. data = self._DoReadFile('36_u_boot_img.dts')
  735. self.assertEqual(U_BOOT_IMG_DATA, data)
  736. def testNoMicrocode(self):
  737. """Test that a missing microcode region is detected"""
  738. with self.assertRaises(ValueError) as e:
  739. self._DoReadFile('37_x86_no_ucode.dts', True)
  740. self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
  741. "node found in ", str(e.exception))
  742. def testMicrocodeWithoutNode(self):
  743. """Test that a missing u-boot-dtb-with-ucode node is detected"""
  744. with self.assertRaises(ValueError) as e:
  745. self._DoReadFile('38_x86_ucode_missing_node.dts', True)
  746. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
  747. "microcode region u-boot-dtb-with-ucode", str(e.exception))
  748. def testMicrocodeWithoutNode2(self):
  749. """Test that a missing u-boot-ucode node is detected"""
  750. with self.assertRaises(ValueError) as e:
  751. self._DoReadFile('39_x86_ucode_missing_node2.dts', True)
  752. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
  753. "microcode region u-boot-ucode", str(e.exception))
  754. def testMicrocodeWithoutPtrInElf(self):
  755. """Test that a U-Boot binary without the microcode symbol is detected"""
  756. # ELF file without a '_dt_ucode_base_size' symbol
  757. try:
  758. with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
  759. TestFunctional._MakeInputFile('u-boot', fd.read())
  760. with self.assertRaises(ValueError) as e:
  761. self._RunPackUbootSingleMicrocode()
  762. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
  763. "_dt_ucode_base_size symbol in u-boot", str(e.exception))
  764. finally:
  765. # Put the original file back
  766. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  767. TestFunctional._MakeInputFile('u-boot', fd.read())
  768. def testMicrocodeNotInImage(self):
  769. """Test that microcode must be placed within the image"""
  770. with self.assertRaises(ValueError) as e:
  771. self._DoReadFile('40_x86_ucode_not_in_image.dts', True)
  772. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
  773. "pointer _dt_ucode_base_size at fffffe14 is outside the "
  774. "section ranging from 00000000 to 0000002e", str(e.exception))
  775. def testWithoutMicrocode(self):
  776. """Test that we can cope with an image without microcode (e.g. qemu)"""
  777. with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
  778. TestFunctional._MakeInputFile('u-boot', fd.read())
  779. data, dtb, _, _ = self._DoReadFileDtb('44_x86_optional_ucode.dts', True)
  780. # Now check the device tree has no microcode
  781. self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
  782. second = data[len(U_BOOT_NODTB_DATA):]
  783. fdt_len = self.GetFdtLen(second)
  784. self.assertEqual(dtb, second[:fdt_len])
  785. used_len = len(U_BOOT_NODTB_DATA) + fdt_len
  786. third = data[used_len:]
  787. self.assertEqual(chr(0) * (0x200 - used_len), third)
  788. def testUnknownPosSize(self):
  789. """Test that microcode must be placed within the image"""
  790. with self.assertRaises(ValueError) as e:
  791. self._DoReadFile('41_unknown_pos_size.dts', True)
  792. self.assertIn("Section '/binman': Unable to set offset/size for unknown "
  793. "entry 'invalid-entry'", str(e.exception))
  794. def testPackFsp(self):
  795. """Test that an image with a FSP binary can be created"""
  796. data = self._DoReadFile('42_intel-fsp.dts')
  797. self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
  798. def testPackCmc(self):
  799. """Test that an image with a CMC binary can be created"""
  800. data = self._DoReadFile('43_intel-cmc.dts')
  801. self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
  802. def testPackVbt(self):
  803. """Test that an image with a VBT binary can be created"""
  804. data = self._DoReadFile('46_intel-vbt.dts')
  805. self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
  806. def testSplBssPad(self):
  807. """Test that we can pad SPL's BSS with zeros"""
  808. # ELF file with a '__bss_size' symbol
  809. with open(self.TestFile('bss_data')) as fd:
  810. TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
  811. data = self._DoReadFile('47_spl_bss_pad.dts')
  812. self.assertEqual(U_BOOT_SPL_DATA + (chr(0) * 10) + U_BOOT_DATA, data)
  813. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  814. TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
  815. with self.assertRaises(ValueError) as e:
  816. data = self._DoReadFile('47_spl_bss_pad.dts')
  817. self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
  818. str(e.exception))
  819. def testPackStart16Spl(self):
  820. """Test that an image with an x86 start16 region can be created"""
  821. data = self._DoReadFile('48_x86-start16-spl.dts')
  822. self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
  823. def _PackUbootSplMicrocode(self, dts, ucode_second=False):
  824. """Helper function for microcode tests
  825. We expect to see the following in the image, in order:
  826. u-boot-spl-nodtb.bin with a microcode pointer inserted at the
  827. correct place
  828. u-boot.dtb with the microcode removed
  829. the microcode
  830. Args:
  831. dts: Device tree file to use for test
  832. ucode_second: True if the microsecond entry is second instead of
  833. third
  834. """
  835. # ELF file with a '_dt_ucode_base_size' symbol
  836. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  837. TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
  838. first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
  839. ucode_second=ucode_second)
  840. self.assertEqual('splnodtb with microc' + pos_and_size +
  841. 'ter somewhere in here', first)
  842. def testPackUbootSplMicrocode(self):
  843. """Test that x86 microcode can be handled correctly in SPL"""
  844. self._PackUbootSplMicrocode('49_x86_ucode_spl.dts')
  845. def testPackUbootSplMicrocodeReorder(self):
  846. """Test that order doesn't matter for microcode entries
  847. This is the same as testPackUbootSplMicrocode but when we process the
  848. u-boot-ucode entry we have not yet seen the u-boot-dtb-with-ucode
  849. entry, so we reply on binman to try later.
  850. """
  851. self._PackUbootSplMicrocode('58_x86_ucode_spl_needs_retry.dts',
  852. ucode_second=True)
  853. def testPackMrc(self):
  854. """Test that an image with an MRC binary can be created"""
  855. data = self._DoReadFile('50_intel_mrc.dts')
  856. self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
  857. def testSplDtb(self):
  858. """Test that an image with spl/u-boot-spl.dtb can be created"""
  859. data = self._DoReadFile('51_u_boot_spl_dtb.dts')
  860. self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
  861. def testSplNoDtb(self):
  862. """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
  863. data = self._DoReadFile('52_u_boot_spl_nodtb.dts')
  864. self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
  865. def testSymbols(self):
  866. """Test binman can assign symbols embedded in U-Boot"""
  867. elf_fname = self.TestFile('u_boot_binman_syms')
  868. syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
  869. addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
  870. self.assertEqual(syms['_binman_u_boot_spl_prop_offset'].address, addr)
  871. with open(self.TestFile('u_boot_binman_syms')) as fd:
  872. TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
  873. data = self._DoReadFile('53_symbols.dts')
  874. sym_values = struct.pack('<LQL', 0x24 + 0, 0x24 + 24, 0x24 + 20)
  875. expected = (sym_values + U_BOOT_SPL_DATA[16:] + chr(0xff) +
  876. U_BOOT_DATA +
  877. sym_values + U_BOOT_SPL_DATA[16:])
  878. self.assertEqual(expected, data)
  879. def testPackUnitAddress(self):
  880. """Test that we support multiple binaries with the same name"""
  881. data = self._DoReadFile('54_unit_address.dts')
  882. self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
  883. def testSections(self):
  884. """Basic test of sections"""
  885. data = self._DoReadFile('55_sections.dts')
  886. expected = (U_BOOT_DATA + '!' * 12 + U_BOOT_DATA + 'a' * 12 +
  887. U_BOOT_DATA + '&' * 4)
  888. self.assertEqual(expected, data)
  889. def testMap(self):
  890. """Tests outputting a map of the images"""
  891. _, _, map_data, _ = self._DoReadFileDtb('55_sections.dts', map=True)
  892. self.assertEqual('''ImagePos Offset Size Name
  893. 00000000 00000000 00000028 main-section
  894. 00000000 00000000 00000010 section@0
  895. 00000000 00000000 00000004 u-boot
  896. 00000010 00000010 00000010 section@1
  897. 00000010 00000000 00000004 u-boot
  898. 00000020 00000020 00000004 section@2
  899. 00000020 00000000 00000004 u-boot
  900. ''', map_data)
  901. def testNamePrefix(self):
  902. """Tests that name prefixes are used"""
  903. _, _, map_data, _ = self._DoReadFileDtb('56_name_prefix.dts', map=True)
  904. self.assertEqual('''ImagePos Offset Size Name
  905. 00000000 00000000 00000028 main-section
  906. 00000000 00000000 00000010 section@0
  907. 00000000 00000000 00000004 ro-u-boot
  908. 00000010 00000010 00000010 section@1
  909. 00000010 00000000 00000004 rw-u-boot
  910. ''', map_data)
  911. def testUnknownContents(self):
  912. """Test that obtaining the contents works as expected"""
  913. with self.assertRaises(ValueError) as e:
  914. self._DoReadFile('57_unknown_contents.dts', True)
  915. self.assertIn("Section '/binman': Internal error: Could not complete "
  916. "processing of contents: remaining [<_testing.Entry__testing ",
  917. str(e.exception))
  918. def testBadChangeSize(self):
  919. """Test that trying to change the size of an entry fails"""
  920. with self.assertRaises(ValueError) as e:
  921. self._DoReadFile('59_change_size.dts', True)
  922. self.assertIn("Node '/binman/_testing': Cannot update entry size from "
  923. '2 to 1', str(e.exception))
  924. def testUpdateFdt(self):
  925. """Test that we can update the device tree with offset/size info"""
  926. _, _, _, out_dtb_fname = self._DoReadFileDtb('60_fdt_update.dts',
  927. update_dtb=True)
  928. dtb = fdt.Fdt(out_dtb_fname)
  929. dtb.Scan()
  930. props = self._GetPropTree(dtb, ['offset', 'size', 'image-pos'])
  931. self.assertEqual({
  932. 'image-pos': 0,
  933. 'offset': 0,
  934. '_testing:offset': 32,
  935. '_testing:size': 1,
  936. '_testing:image-pos': 32,
  937. 'section@0/u-boot:offset': 0,
  938. 'section@0/u-boot:size': len(U_BOOT_DATA),
  939. 'section@0/u-boot:image-pos': 0,
  940. 'section@0:offset': 0,
  941. 'section@0:size': 16,
  942. 'section@0:image-pos': 0,
  943. 'section@1/u-boot:offset': 0,
  944. 'section@1/u-boot:size': len(U_BOOT_DATA),
  945. 'section@1/u-boot:image-pos': 16,
  946. 'section@1:offset': 16,
  947. 'section@1:size': 16,
  948. 'section@1:image-pos': 16,
  949. 'size': 40
  950. }, props)
  951. def testUpdateFdtBad(self):
  952. """Test that we detect when ProcessFdt never completes"""
  953. with self.assertRaises(ValueError) as e:
  954. self._DoReadFileDtb('61_fdt_update_bad.dts', update_dtb=True)
  955. self.assertIn('Could not complete processing of Fdt: remaining '
  956. '[<_testing.Entry__testing', str(e.exception))
  957. def testEntryArgs(self):
  958. """Test passing arguments to entries from the command line"""
  959. entry_args = {
  960. 'test-str-arg': 'test1',
  961. 'test-int-arg': '456',
  962. }
  963. self._DoReadFileDtb('62_entry_args.dts', entry_args=entry_args)
  964. self.assertIn('image', control.images)
  965. entry = control.images['image'].GetEntries()['_testing']
  966. self.assertEqual('test0', entry.test_str_fdt)
  967. self.assertEqual('test1', entry.test_str_arg)
  968. self.assertEqual(123, entry.test_int_fdt)
  969. self.assertEqual(456, entry.test_int_arg)
  970. def testEntryArgsMissing(self):
  971. """Test missing arguments and properties"""
  972. entry_args = {
  973. 'test-int-arg': '456',
  974. }
  975. self._DoReadFileDtb('63_entry_args_missing.dts', entry_args=entry_args)
  976. entry = control.images['image'].GetEntries()['_testing']
  977. self.assertEqual('test0', entry.test_str_fdt)
  978. self.assertEqual(None, entry.test_str_arg)
  979. self.assertEqual(None, entry.test_int_fdt)
  980. self.assertEqual(456, entry.test_int_arg)
  981. def testEntryArgsRequired(self):
  982. """Test missing arguments and properties"""
  983. entry_args = {
  984. 'test-int-arg': '456',
  985. }
  986. with self.assertRaises(ValueError) as e:
  987. self._DoReadFileDtb('64_entry_args_required.dts')
  988. self.assertIn("Node '/binman/_testing': Missing required "
  989. 'properties/entry args: test-str-arg, test-int-fdt, test-int-arg',
  990. str(e.exception))
  991. def testEntryArgsInvalidFormat(self):
  992. """Test that an invalid entry-argument format is detected"""
  993. args = ['-d', self.TestFile('64_entry_args_required.dts'), '-ano-value']
  994. with self.assertRaises(ValueError) as e:
  995. self._DoBinman(*args)
  996. self.assertIn("Invalid entry arguemnt 'no-value'", str(e.exception))
  997. def testEntryArgsInvalidInteger(self):
  998. """Test that an invalid entry-argument integer is detected"""
  999. entry_args = {
  1000. 'test-int-arg': 'abc',
  1001. }
  1002. with self.assertRaises(ValueError) as e:
  1003. self._DoReadFileDtb('62_entry_args.dts', entry_args=entry_args)
  1004. self.assertIn("Node '/binman/_testing': Cannot convert entry arg "
  1005. "'test-int-arg' (value 'abc') to integer",
  1006. str(e.exception))
  1007. def testEntryArgsInvalidDatatype(self):
  1008. """Test that an invalid entry-argument datatype is detected
  1009. This test could be written in entry_test.py except that it needs
  1010. access to control.entry_args, which seems more than that module should
  1011. be able to see.
  1012. """
  1013. entry_args = {
  1014. 'test-bad-datatype-arg': '12',
  1015. }
  1016. with self.assertRaises(ValueError) as e:
  1017. self._DoReadFileDtb('65_entry_args_unknown_datatype.dts',
  1018. entry_args=entry_args)
  1019. self.assertIn('GetArg() internal error: Unknown data type ',
  1020. str(e.exception))
  1021. def testText(self):
  1022. """Test for a text entry type"""
  1023. entry_args = {
  1024. 'test-id': TEXT_DATA,
  1025. 'test-id2': TEXT_DATA2,
  1026. 'test-id3': TEXT_DATA3,
  1027. }
  1028. data, _, _, _ = self._DoReadFileDtb('66_text.dts',
  1029. entry_args=entry_args)
  1030. expected = (TEXT_DATA + chr(0) * (8 - len(TEXT_DATA)) + TEXT_DATA2 +
  1031. TEXT_DATA3 + 'some text')
  1032. self.assertEqual(expected, data)
  1033. def testEntryDocs(self):
  1034. """Test for creation of entry documentation"""
  1035. with test_util.capture_sys_output() as (stdout, stderr):
  1036. control.WriteEntryDocs(binman.GetEntryModules())
  1037. self.assertTrue(len(stdout.getvalue()) > 0)
  1038. def testEntryDocsMissing(self):
  1039. """Test handling of missing entry documentation"""
  1040. with self.assertRaises(ValueError) as e:
  1041. with test_util.capture_sys_output() as (stdout, stderr):
  1042. control.WriteEntryDocs(binman.GetEntryModules(), 'u_boot')
  1043. self.assertIn('Documentation is missing for modules: u_boot',
  1044. str(e.exception))
  1045. def testFmap(self):
  1046. """Basic test of generation of a flashrom fmap"""
  1047. data = self._DoReadFile('67_fmap.dts')
  1048. fhdr, fentries = fmap_util.DecodeFmap(data[32:])
  1049. expected = U_BOOT_DATA + '!' * 12 + U_BOOT_DATA + 'a' * 12
  1050. self.assertEqual(expected, data[:32])
  1051. self.assertEqual('__FMAP__', fhdr.signature)
  1052. self.assertEqual(1, fhdr.ver_major)
  1053. self.assertEqual(0, fhdr.ver_minor)
  1054. self.assertEqual(0, fhdr.base)
  1055. self.assertEqual(16 + 16 +
  1056. fmap_util.FMAP_HEADER_LEN +
  1057. fmap_util.FMAP_AREA_LEN * 3, fhdr.image_size)
  1058. self.assertEqual('FMAP', fhdr.name)
  1059. self.assertEqual(3, fhdr.nareas)
  1060. for fentry in fentries:
  1061. self.assertEqual(0, fentry.flags)
  1062. self.assertEqual(0, fentries[0].offset)
  1063. self.assertEqual(4, fentries[0].size)
  1064. self.assertEqual('RO_U_BOOT', fentries[0].name)
  1065. self.assertEqual(16, fentries[1].offset)
  1066. self.assertEqual(4, fentries[1].size)
  1067. self.assertEqual('RW_U_BOOT', fentries[1].name)
  1068. self.assertEqual(32, fentries[2].offset)
  1069. self.assertEqual(fmap_util.FMAP_HEADER_LEN +
  1070. fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
  1071. self.assertEqual('FMAP', fentries[2].name)
  1072. def testBlobNamedByArg(self):
  1073. """Test we can add a blob with the filename coming from an entry arg"""
  1074. entry_args = {
  1075. 'cros-ec-rw-path': 'ecrw.bin',
  1076. }
  1077. data, _, _, _ = self._DoReadFileDtb('68_blob_named_by_arg.dts',
  1078. entry_args=entry_args)
  1079. def testFill(self):
  1080. """Test for an fill entry type"""
  1081. data = self._DoReadFile('69_fill.dts')
  1082. expected = 8 * chr(0xff) + 8 * chr(0)
  1083. self.assertEqual(expected, data)
  1084. def testFillNoSize(self):
  1085. """Test for an fill entry type with no size"""
  1086. with self.assertRaises(ValueError) as e:
  1087. self._DoReadFile('70_fill_no_size.dts')
  1088. self.assertIn("'fill' entry must have a size property",
  1089. str(e.exception))
  1090. def _HandleGbbCommand(self, pipe_list):
  1091. """Fake calls to the futility utility"""
  1092. if pipe_list[0][0] == 'futility':
  1093. fname = pipe_list[0][-1]
  1094. # Append our GBB data to the file, which will happen every time the
  1095. # futility command is called.
  1096. with open(fname, 'a') as fd:
  1097. fd.write(GBB_DATA)
  1098. return command.CommandResult()
  1099. def testGbb(self):
  1100. """Test for the Chromium OS Google Binary Block"""
  1101. command.test_result = self._HandleGbbCommand
  1102. entry_args = {
  1103. 'keydir': 'devkeys',
  1104. 'bmpblk': 'bmpblk.bin',
  1105. }
  1106. data, _, _, _ = self._DoReadFileDtb('71_gbb.dts', entry_args=entry_args)
  1107. # Since futility
  1108. expected = GBB_DATA + GBB_DATA + 8 * chr(0) + (0x2180 - 16) * chr(0)
  1109. self.assertEqual(expected, data)
  1110. def testGbbTooSmall(self):
  1111. """Test for the Chromium OS Google Binary Block being large enough"""
  1112. with self.assertRaises(ValueError) as e:
  1113. self._DoReadFileDtb('72_gbb_too_small.dts')
  1114. self.assertIn("Node '/binman/gbb': GBB is too small",
  1115. str(e.exception))
  1116. def testGbbNoSize(self):
  1117. """Test for the Chromium OS Google Binary Block having a size"""
  1118. with self.assertRaises(ValueError) as e:
  1119. self._DoReadFileDtb('73_gbb_no_size.dts')
  1120. self.assertIn("Node '/binman/gbb': GBB must have a fixed size",
  1121. str(e.exception))
  1122. def _HandleVblockCommand(self, pipe_list):
  1123. """Fake calls to the futility utility"""
  1124. if pipe_list[0][0] == 'futility':
  1125. fname = pipe_list[0][3]
  1126. with open(fname, 'w') as fd:
  1127. fd.write(VBLOCK_DATA)
  1128. return command.CommandResult()
  1129. def testVblock(self):
  1130. """Test for the Chromium OS Verified Boot Block"""
  1131. command.test_result = self._HandleVblockCommand
  1132. entry_args = {
  1133. 'keydir': 'devkeys',
  1134. }
  1135. data, _, _, _ = self._DoReadFileDtb('74_vblock.dts',
  1136. entry_args=entry_args)
  1137. expected = U_BOOT_DATA + VBLOCK_DATA + U_BOOT_DTB_DATA
  1138. self.assertEqual(expected, data)
  1139. def testVblockNoContent(self):
  1140. """Test we detect a vblock which has no content to sign"""
  1141. with self.assertRaises(ValueError) as e:
  1142. self._DoReadFile('75_vblock_no_content.dts')
  1143. self.assertIn("Node '/binman/vblock': Vblock must have a 'content' "
  1144. 'property', str(e.exception))
  1145. def testVblockBadPhandle(self):
  1146. """Test that we detect a vblock with an invalid phandle in contents"""
  1147. with self.assertRaises(ValueError) as e:
  1148. self._DoReadFile('76_vblock_bad_phandle.dts')
  1149. self.assertIn("Node '/binman/vblock': Cannot find node for phandle "
  1150. '1000', str(e.exception))
  1151. def testVblockBadEntry(self):
  1152. """Test that we detect an entry that points to a non-entry"""
  1153. with self.assertRaises(ValueError) as e:
  1154. self._DoReadFile('77_vblock_bad_entry.dts')
  1155. self.assertIn("Node '/binman/vblock': Cannot find entry for node "
  1156. "'other'", str(e.exception))
  1157. def testTpl(self):
  1158. """Test that an image with TPL and ots device tree can be created"""
  1159. # ELF file with a '__bss_size' symbol
  1160. with open(self.TestFile('bss_data')) as fd:
  1161. TestFunctional._MakeInputFile('tpl/u-boot-tpl', fd.read())
  1162. data = self._DoReadFile('78_u_boot_tpl.dts')
  1163. self.assertEqual(U_BOOT_TPL_DATA + U_BOOT_TPL_DTB_DATA, data)
  1164. def testUsesPos(self):
  1165. """Test that the 'pos' property cannot be used anymore"""
  1166. with self.assertRaises(ValueError) as e:
  1167. data = self._DoReadFile('79_uses_pos.dts')
  1168. self.assertIn("Node '/binman/u-boot': Please use 'offset' instead of "
  1169. "'pos'", str(e.exception))
  1170. if __name__ == "__main__":
  1171. unittest.main()