ftest.py 56 KB

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