ftest.py 54 KB

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