ftest.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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. import hashlib
  9. from optparse import OptionParser
  10. import os
  11. import shutil
  12. import struct
  13. import sys
  14. import tempfile
  15. import unittest
  16. import binman
  17. import cmdline
  18. import command
  19. import control
  20. import elf
  21. import fdt
  22. import fdt_util
  23. import fmap_util
  24. import test_util
  25. import state
  26. import tools
  27. import tout
  28. # Contents of test files, corresponding to different entry types
  29. U_BOOT_DATA = '1234'
  30. U_BOOT_IMG_DATA = 'img'
  31. U_BOOT_SPL_DATA = '56780123456789abcde'
  32. U_BOOT_TPL_DATA = 'tpl'
  33. BLOB_DATA = '89'
  34. ME_DATA = '0abcd'
  35. VGA_DATA = 'vga'
  36. U_BOOT_DTB_DATA = 'udtb'
  37. U_BOOT_SPL_DTB_DATA = 'spldtb'
  38. U_BOOT_TPL_DTB_DATA = 'tpldtb'
  39. X86_START16_DATA = 'start16'
  40. X86_START16_SPL_DATA = 'start16spl'
  41. X86_START16_TPL_DATA = 'start16tpl'
  42. PPC_MPC85XX_BR_DATA = 'ppcmpc85xxbr'
  43. U_BOOT_NODTB_DATA = 'nodtb with microcode pointer somewhere in here'
  44. U_BOOT_SPL_NODTB_DATA = 'splnodtb with microcode pointer somewhere in here'
  45. U_BOOT_TPL_NODTB_DATA = 'tplnodtb with microcode pointer somewhere in here'
  46. FSP_DATA = 'fsp'
  47. CMC_DATA = 'cmc'
  48. VBT_DATA = 'vbt'
  49. MRC_DATA = 'mrc'
  50. TEXT_DATA = 'text'
  51. TEXT_DATA2 = 'text2'
  52. TEXT_DATA3 = 'text3'
  53. CROS_EC_RW_DATA = 'ecrw'
  54. GBB_DATA = 'gbbd'
  55. BMPBLK_DATA = 'bmp'
  56. VBLOCK_DATA = 'vblk'
  57. FILES_DATA = ("sorry I'm late\nOh, don't bother apologising, I'm " +
  58. "sorry you're alive\n")
  59. COMPRESS_DATA = 'data to compress'
  60. REFCODE_DATA = 'refcode'
  61. class TestFunctional(unittest.TestCase):
  62. """Functional tests for binman
  63. Most of these use a sample .dts file to build an image and then check
  64. that it looks correct. The sample files are in the test/ subdirectory
  65. and are numbered.
  66. For each entry type a very small test file is created using fixed
  67. string contents. This makes it easy to test that things look right, and
  68. debug problems.
  69. In some cases a 'real' file must be used - these are also supplied in
  70. the test/ diurectory.
  71. """
  72. @classmethod
  73. def setUpClass(self):
  74. global entry
  75. import entry
  76. # Handle the case where argv[0] is 'python'
  77. self._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  78. self._binman_pathname = os.path.join(self._binman_dir, 'binman')
  79. # Create a temporary directory for input files
  80. self._indir = tempfile.mkdtemp(prefix='binmant.')
  81. # Create some test files
  82. TestFunctional._MakeInputFile('u-boot.bin', U_BOOT_DATA)
  83. TestFunctional._MakeInputFile('u-boot.img', U_BOOT_IMG_DATA)
  84. TestFunctional._MakeInputFile('spl/u-boot-spl.bin', U_BOOT_SPL_DATA)
  85. TestFunctional._MakeInputFile('tpl/u-boot-tpl.bin', U_BOOT_TPL_DATA)
  86. TestFunctional._MakeInputFile('blobfile', BLOB_DATA)
  87. TestFunctional._MakeInputFile('me.bin', ME_DATA)
  88. TestFunctional._MakeInputFile('vga.bin', VGA_DATA)
  89. self._ResetDtbs()
  90. TestFunctional._MakeInputFile('u-boot-x86-16bit.bin', X86_START16_DATA)
  91. TestFunctional._MakeInputFile('u-boot-br.bin', PPC_MPC85XX_BR_DATA)
  92. TestFunctional._MakeInputFile('spl/u-boot-x86-16bit-spl.bin',
  93. X86_START16_SPL_DATA)
  94. TestFunctional._MakeInputFile('tpl/u-boot-x86-16bit-tpl.bin',
  95. X86_START16_TPL_DATA)
  96. TestFunctional._MakeInputFile('u-boot-nodtb.bin', U_BOOT_NODTB_DATA)
  97. TestFunctional._MakeInputFile('spl/u-boot-spl-nodtb.bin',
  98. U_BOOT_SPL_NODTB_DATA)
  99. TestFunctional._MakeInputFile('tpl/u-boot-tpl-nodtb.bin',
  100. U_BOOT_TPL_NODTB_DATA)
  101. TestFunctional._MakeInputFile('fsp.bin', FSP_DATA)
  102. TestFunctional._MakeInputFile('cmc.bin', CMC_DATA)
  103. TestFunctional._MakeInputFile('vbt.bin', VBT_DATA)
  104. TestFunctional._MakeInputFile('mrc.bin', MRC_DATA)
  105. TestFunctional._MakeInputFile('ecrw.bin', CROS_EC_RW_DATA)
  106. TestFunctional._MakeInputDir('devkeys')
  107. TestFunctional._MakeInputFile('bmpblk.bin', BMPBLK_DATA)
  108. TestFunctional._MakeInputFile('refcode.bin', REFCODE_DATA)
  109. # ELF file with a '_dt_ucode_base_size' symbol
  110. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  111. TestFunctional._MakeInputFile('u-boot', fd.read())
  112. # Intel flash descriptor file
  113. with open(self.TestFile('descriptor.bin')) as fd:
  114. TestFunctional._MakeInputFile('descriptor.bin', fd.read())
  115. shutil.copytree(self.TestFile('files'),
  116. os.path.join(self._indir, 'files'))
  117. TestFunctional._MakeInputFile('compress', COMPRESS_DATA)
  118. @classmethod
  119. def tearDownClass(self):
  120. """Remove the temporary input directory and its contents"""
  121. if self._indir:
  122. shutil.rmtree(self._indir)
  123. self._indir = None
  124. def setUp(self):
  125. # Enable this to turn on debugging output
  126. # tout.Init(tout.DEBUG)
  127. command.test_result = None
  128. def tearDown(self):
  129. """Remove the temporary output directory"""
  130. tools._FinaliseForTest()
  131. @classmethod
  132. def _ResetDtbs(self):
  133. TestFunctional._MakeInputFile('u-boot.dtb', U_BOOT_DTB_DATA)
  134. TestFunctional._MakeInputFile('spl/u-boot-spl.dtb', U_BOOT_SPL_DTB_DATA)
  135. TestFunctional._MakeInputFile('tpl/u-boot-tpl.dtb', U_BOOT_TPL_DTB_DATA)
  136. def _RunBinman(self, *args, **kwargs):
  137. """Run binman using the command line
  138. Args:
  139. Arguments to pass, as a list of strings
  140. kwargs: Arguments to pass to Command.RunPipe()
  141. """
  142. result = command.RunPipe([[self._binman_pathname] + list(args)],
  143. capture=True, capture_stderr=True, raise_on_error=False)
  144. if result.return_code and kwargs.get('raise_on_error', True):
  145. raise Exception("Error running '%s': %s" % (' '.join(args),
  146. result.stdout + result.stderr))
  147. return result
  148. def _DoBinman(self, *args):
  149. """Run binman using directly (in the same process)
  150. Args:
  151. Arguments to pass, as a list of strings
  152. Returns:
  153. Return value (0 for success)
  154. """
  155. args = list(args)
  156. if '-D' in sys.argv:
  157. args = args + ['-D']
  158. (options, args) = cmdline.ParseArgs(args)
  159. options.pager = 'binman-invalid-pager'
  160. options.build_dir = self._indir
  161. # For testing, you can force an increase in verbosity here
  162. # options.verbosity = tout.DEBUG
  163. return control.Binman(options, args)
  164. def _DoTestFile(self, fname, debug=False, map=False, update_dtb=False,
  165. entry_args=None, images=None, use_real_dtb=False):
  166. """Run binman with a given test file
  167. Args:
  168. fname: Device-tree source filename to use (e.g. 005_simple.dts)
  169. debug: True to enable debugging output
  170. map: True to output map files for the images
  171. update_dtb: Update the offset and size of each entry in the device
  172. tree before packing it into the image
  173. entry_args: Dict of entry args to supply to binman
  174. key: arg name
  175. value: value of that arg
  176. images: List of image names to build
  177. """
  178. args = ['-p', '-I', self._indir, '-d', self.TestFile(fname)]
  179. if debug:
  180. args.append('-D')
  181. if map:
  182. args.append('-m')
  183. if update_dtb:
  184. args.append('-up')
  185. if not use_real_dtb:
  186. args.append('--fake-dtb')
  187. if entry_args:
  188. for arg, value in entry_args.iteritems():
  189. args.append('-a%s=%s' % (arg, value))
  190. if images:
  191. for image in images:
  192. args += ['-i', image]
  193. return self._DoBinman(*args)
  194. def _SetupDtb(self, fname, outfile='u-boot.dtb'):
  195. """Set up a new test device-tree file
  196. The given file is compiled and set up as the device tree to be used
  197. for ths test.
  198. Args:
  199. fname: Filename of .dts file to read
  200. outfile: Output filename for compiled device-tree binary
  201. Returns:
  202. Contents of device-tree binary
  203. """
  204. tools.PrepareOutputDir(None)
  205. dtb = fdt_util.EnsureCompiled(self.TestFile(fname))
  206. with open(dtb) as fd:
  207. data = fd.read()
  208. TestFunctional._MakeInputFile(outfile, data)
  209. tools.FinaliseOutputDir()
  210. return data
  211. def _GetDtbContentsForSplTpl(self, dtb_data, name):
  212. """Create a version of the main DTB for SPL or SPL
  213. For testing we don't actually have different versions of the DTB. With
  214. U-Boot we normally run fdtgrep to remove unwanted nodes, but for tests
  215. we don't normally have any unwanted nodes.
  216. We still want the DTBs for SPL and TPL to be different though, since
  217. otherwise it is confusing to know which one we are looking at. So add
  218. an 'spl' or 'tpl' property to the top-level node.
  219. """
  220. dtb = fdt.Fdt.FromData(dtb_data)
  221. dtb.Scan()
  222. dtb.GetNode('/binman').AddZeroProp(name)
  223. dtb.Sync(auto_resize=True)
  224. dtb.Pack()
  225. return dtb.GetContents()
  226. def _DoReadFileDtb(self, fname, use_real_dtb=False, map=False,
  227. update_dtb=False, entry_args=None, reset_dtbs=True):
  228. """Run binman and return the resulting image
  229. This runs binman with a given test file and then reads the resulting
  230. output file. It is a shortcut function since most tests need to do
  231. these steps.
  232. Raises an assertion failure if binman returns a non-zero exit code.
  233. Args:
  234. fname: Device-tree source filename to use (e.g. 005_simple.dts)
  235. use_real_dtb: True to use the test file as the contents of
  236. the u-boot-dtb entry. Normally this is not needed and the
  237. test contents (the U_BOOT_DTB_DATA string) can be used.
  238. But in some test we need the real contents.
  239. map: True to output map files for the images
  240. update_dtb: Update the offset and size of each entry in the device
  241. tree before packing it into the image
  242. Returns:
  243. Tuple:
  244. Resulting image contents
  245. Device tree contents
  246. Map data showing contents of image (or None if none)
  247. Output device tree binary filename ('u-boot.dtb' path)
  248. """
  249. dtb_data = None
  250. # Use the compiled test file as the u-boot-dtb input
  251. if use_real_dtb:
  252. dtb_data = self._SetupDtb(fname)
  253. infile = os.path.join(self._indir, 'u-boot.dtb')
  254. # For testing purposes, make a copy of the DT for SPL and TPL. Add
  255. # a node indicating which it is, so aid verification.
  256. for name in ['spl', 'tpl']:
  257. dtb_fname = '%s/u-boot-%s.dtb' % (name, name)
  258. outfile = os.path.join(self._indir, dtb_fname)
  259. TestFunctional._MakeInputFile(dtb_fname,
  260. self._GetDtbContentsForSplTpl(dtb_data, name))
  261. try:
  262. retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb,
  263. entry_args=entry_args, use_real_dtb=use_real_dtb)
  264. self.assertEqual(0, retcode)
  265. out_dtb_fname = tools.GetOutputFilename('u-boot.dtb.out')
  266. # Find the (only) image, read it and return its contents
  267. image = control.images['image']
  268. image_fname = tools.GetOutputFilename('image.bin')
  269. self.assertTrue(os.path.exists(image_fname))
  270. if map:
  271. map_fname = tools.GetOutputFilename('image.map')
  272. with open(map_fname) as fd:
  273. map_data = fd.read()
  274. else:
  275. map_data = None
  276. with open(image_fname) as fd:
  277. return fd.read(), dtb_data, map_data, out_dtb_fname
  278. finally:
  279. # Put the test file back
  280. if reset_dtbs and use_real_dtb:
  281. self._ResetDtbs()
  282. def _DoReadFile(self, fname, use_real_dtb=False):
  283. """Helper function which discards the device-tree binary
  284. Args:
  285. fname: Device-tree source filename to use (e.g. 005_simple.dts)
  286. use_real_dtb: True to use the test file as the contents of
  287. the u-boot-dtb entry. Normally this is not needed and the
  288. test contents (the U_BOOT_DTB_DATA string) can be used.
  289. But in some test we need the real contents.
  290. Returns:
  291. Resulting image contents
  292. """
  293. return self._DoReadFileDtb(fname, use_real_dtb)[0]
  294. @classmethod
  295. def _MakeInputFile(self, fname, contents):
  296. """Create a new test input file, creating directories as needed
  297. Args:
  298. fname: Filename to create
  299. contents: File contents to write in to the file
  300. Returns:
  301. Full pathname of file created
  302. """
  303. pathname = os.path.join(self._indir, fname)
  304. dirname = os.path.dirname(pathname)
  305. if dirname and not os.path.exists(dirname):
  306. os.makedirs(dirname)
  307. with open(pathname, 'wb') as fd:
  308. fd.write(contents)
  309. return pathname
  310. @classmethod
  311. def _MakeInputDir(self, dirname):
  312. """Create a new test input directory, creating directories as needed
  313. Args:
  314. dirname: Directory name to create
  315. Returns:
  316. Full pathname of directory created
  317. """
  318. pathname = os.path.join(self._indir, dirname)
  319. if not os.path.exists(pathname):
  320. os.makedirs(pathname)
  321. return pathname
  322. @classmethod
  323. def _SetupSplElf(self, src_fname='bss_data'):
  324. """Set up an ELF file with a '_dt_ucode_base_size' symbol
  325. Args:
  326. Filename of ELF file to use as SPL
  327. """
  328. with open(self.TestFile(src_fname)) as fd:
  329. TestFunctional._MakeInputFile('spl/u-boot-spl', fd.read())
  330. @classmethod
  331. def TestFile(self, fname):
  332. return os.path.join(self._binman_dir, 'test', fname)
  333. def AssertInList(self, grep_list, target):
  334. """Assert that at least one of a list of things is in a target
  335. Args:
  336. grep_list: List of strings to check
  337. target: Target string
  338. """
  339. for grep in grep_list:
  340. if grep in target:
  341. return
  342. self.fail("Error: '%' not found in '%s'" % (grep_list, target))
  343. def CheckNoGaps(self, entries):
  344. """Check that all entries fit together without gaps
  345. Args:
  346. entries: List of entries to check
  347. """
  348. offset = 0
  349. for entry in entries.values():
  350. self.assertEqual(offset, entry.offset)
  351. offset += entry.size
  352. def GetFdtLen(self, dtb):
  353. """Get the totalsize field from a device-tree binary
  354. Args:
  355. dtb: Device-tree binary contents
  356. Returns:
  357. Total size of device-tree binary, from the header
  358. """
  359. return struct.unpack('>L', dtb[4:8])[0]
  360. def _GetPropTree(self, dtb, prop_names):
  361. def AddNode(node, path):
  362. if node.name != '/':
  363. path += '/' + node.name
  364. for subnode in node.subnodes:
  365. for prop in subnode.props.values():
  366. if prop.name in prop_names:
  367. prop_path = path + '/' + subnode.name + ':' + prop.name
  368. tree[prop_path[len('/binman/'):]] = fdt_util.fdt32_to_cpu(
  369. prop.value)
  370. AddNode(subnode, path)
  371. tree = {}
  372. AddNode(dtb.GetRoot(), '')
  373. return tree
  374. def testRun(self):
  375. """Test a basic run with valid args"""
  376. result = self._RunBinman('-h')
  377. def testFullHelp(self):
  378. """Test that the full help is displayed with -H"""
  379. result = self._RunBinman('-H')
  380. help_file = os.path.join(self._binman_dir, 'README')
  381. # Remove possible extraneous strings
  382. extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
  383. gothelp = result.stdout.replace(extra, '')
  384. self.assertEqual(len(gothelp), os.path.getsize(help_file))
  385. self.assertEqual(0, len(result.stderr))
  386. self.assertEqual(0, result.return_code)
  387. def testFullHelpInternal(self):
  388. """Test that the full help is displayed with -H"""
  389. try:
  390. command.test_result = command.CommandResult()
  391. result = self._DoBinman('-H')
  392. help_file = os.path.join(self._binman_dir, 'README')
  393. finally:
  394. command.test_result = None
  395. def testHelp(self):
  396. """Test that the basic help is displayed with -h"""
  397. result = self._RunBinman('-h')
  398. self.assertTrue(len(result.stdout) > 200)
  399. self.assertEqual(0, len(result.stderr))
  400. self.assertEqual(0, result.return_code)
  401. def testBoard(self):
  402. """Test that we can run it with a specific board"""
  403. self._SetupDtb('005_simple.dts', 'sandbox/u-boot.dtb')
  404. TestFunctional._MakeInputFile('sandbox/u-boot.bin', U_BOOT_DATA)
  405. result = self._DoBinman('-b', 'sandbox')
  406. self.assertEqual(0, result)
  407. def testNeedBoard(self):
  408. """Test that we get an error when no board ius supplied"""
  409. with self.assertRaises(ValueError) as e:
  410. result = self._DoBinman()
  411. self.assertIn("Must provide a board to process (use -b <board>)",
  412. str(e.exception))
  413. def testMissingDt(self):
  414. """Test that an invalid device-tree file generates an error"""
  415. with self.assertRaises(Exception) as e:
  416. self._RunBinman('-d', 'missing_file')
  417. # We get one error from libfdt, and a different one from fdtget.
  418. self.AssertInList(["Couldn't open blob from 'missing_file'",
  419. 'No such file or directory'], str(e.exception))
  420. def testBrokenDt(self):
  421. """Test that an invalid device-tree source file generates an error
  422. Since this is a source file it should be compiled and the error
  423. will come from the device-tree compiler (dtc).
  424. """
  425. with self.assertRaises(Exception) as e:
  426. self._RunBinman('-d', self.TestFile('001_invalid.dts'))
  427. self.assertIn("FATAL ERROR: Unable to parse input tree",
  428. str(e.exception))
  429. def testMissingNode(self):
  430. """Test that a device tree without a 'binman' node generates an error"""
  431. with self.assertRaises(Exception) as e:
  432. self._DoBinman('-d', self.TestFile('002_missing_node.dts'))
  433. self.assertIn("does not have a 'binman' node", str(e.exception))
  434. def testEmpty(self):
  435. """Test that an empty binman node works OK (i.e. does nothing)"""
  436. result = self._RunBinman('-d', self.TestFile('003_empty.dts'))
  437. self.assertEqual(0, len(result.stderr))
  438. self.assertEqual(0, result.return_code)
  439. def testInvalidEntry(self):
  440. """Test that an invalid entry is flagged"""
  441. with self.assertRaises(Exception) as e:
  442. result = self._RunBinman('-d',
  443. self.TestFile('004_invalid_entry.dts'))
  444. self.assertIn("Unknown entry type 'not-a-valid-type' in node "
  445. "'/binman/not-a-valid-type'", str(e.exception))
  446. def testSimple(self):
  447. """Test a simple binman with a single file"""
  448. data = self._DoReadFile('005_simple.dts')
  449. self.assertEqual(U_BOOT_DATA, data)
  450. def testSimpleDebug(self):
  451. """Test a simple binman run with debugging enabled"""
  452. data = self._DoTestFile('005_simple.dts', debug=True)
  453. def testDual(self):
  454. """Test that we can handle creating two images
  455. This also tests image padding.
  456. """
  457. retcode = self._DoTestFile('006_dual_image.dts')
  458. self.assertEqual(0, retcode)
  459. image = control.images['image1']
  460. self.assertEqual(len(U_BOOT_DATA), image._size)
  461. fname = tools.GetOutputFilename('image1.bin')
  462. self.assertTrue(os.path.exists(fname))
  463. with open(fname) as fd:
  464. data = fd.read()
  465. self.assertEqual(U_BOOT_DATA, data)
  466. image = control.images['image2']
  467. self.assertEqual(3 + len(U_BOOT_DATA) + 5, image._size)
  468. fname = tools.GetOutputFilename('image2.bin')
  469. self.assertTrue(os.path.exists(fname))
  470. with open(fname) as fd:
  471. data = fd.read()
  472. self.assertEqual(U_BOOT_DATA, data[3:7])
  473. self.assertEqual(chr(0) * 3, data[:3])
  474. self.assertEqual(chr(0) * 5, data[7:])
  475. def testBadAlign(self):
  476. """Test that an invalid alignment value is detected"""
  477. with self.assertRaises(ValueError) as e:
  478. self._DoTestFile('007_bad_align.dts')
  479. self.assertIn("Node '/binman/u-boot': Alignment 23 must be a power "
  480. "of two", str(e.exception))
  481. def testPackSimple(self):
  482. """Test that packing works as expected"""
  483. retcode = self._DoTestFile('008_pack.dts')
  484. self.assertEqual(0, retcode)
  485. self.assertIn('image', control.images)
  486. image = control.images['image']
  487. entries = image.GetEntries()
  488. self.assertEqual(5, len(entries))
  489. # First u-boot
  490. self.assertIn('u-boot', entries)
  491. entry = entries['u-boot']
  492. self.assertEqual(0, entry.offset)
  493. self.assertEqual(len(U_BOOT_DATA), entry.size)
  494. # Second u-boot, aligned to 16-byte boundary
  495. self.assertIn('u-boot-align', entries)
  496. entry = entries['u-boot-align']
  497. self.assertEqual(16, entry.offset)
  498. self.assertEqual(len(U_BOOT_DATA), entry.size)
  499. # Third u-boot, size 23 bytes
  500. self.assertIn('u-boot-size', entries)
  501. entry = entries['u-boot-size']
  502. self.assertEqual(20, entry.offset)
  503. self.assertEqual(len(U_BOOT_DATA), entry.contents_size)
  504. self.assertEqual(23, entry.size)
  505. # Fourth u-boot, placed immediate after the above
  506. self.assertIn('u-boot-next', entries)
  507. entry = entries['u-boot-next']
  508. self.assertEqual(43, entry.offset)
  509. self.assertEqual(len(U_BOOT_DATA), entry.size)
  510. # Fifth u-boot, placed at a fixed offset
  511. self.assertIn('u-boot-fixed', entries)
  512. entry = entries['u-boot-fixed']
  513. self.assertEqual(61, entry.offset)
  514. self.assertEqual(len(U_BOOT_DATA), entry.size)
  515. self.assertEqual(65, image._size)
  516. def testPackExtra(self):
  517. """Test that extra packing feature works as expected"""
  518. retcode = self._DoTestFile('009_pack_extra.dts')
  519. self.assertEqual(0, retcode)
  520. self.assertIn('image', control.images)
  521. image = control.images['image']
  522. entries = image.GetEntries()
  523. self.assertEqual(5, len(entries))
  524. # First u-boot with padding before and after
  525. self.assertIn('u-boot', entries)
  526. entry = entries['u-boot']
  527. self.assertEqual(0, entry.offset)
  528. self.assertEqual(3, entry.pad_before)
  529. self.assertEqual(3 + 5 + len(U_BOOT_DATA), entry.size)
  530. # Second u-boot has an aligned size, but it has no effect
  531. self.assertIn('u-boot-align-size-nop', entries)
  532. entry = entries['u-boot-align-size-nop']
  533. self.assertEqual(12, entry.offset)
  534. self.assertEqual(4, entry.size)
  535. # Third u-boot has an aligned size too
  536. self.assertIn('u-boot-align-size', entries)
  537. entry = entries['u-boot-align-size']
  538. self.assertEqual(16, entry.offset)
  539. self.assertEqual(32, entry.size)
  540. # Fourth u-boot has an aligned end
  541. self.assertIn('u-boot-align-end', entries)
  542. entry = entries['u-boot-align-end']
  543. self.assertEqual(48, entry.offset)
  544. self.assertEqual(16, entry.size)
  545. # Fifth u-boot immediately afterwards
  546. self.assertIn('u-boot-align-both', entries)
  547. entry = entries['u-boot-align-both']
  548. self.assertEqual(64, entry.offset)
  549. self.assertEqual(64, entry.size)
  550. self.CheckNoGaps(entries)
  551. self.assertEqual(128, image._size)
  552. def testPackAlignPowerOf2(self):
  553. """Test that invalid entry alignment is detected"""
  554. with self.assertRaises(ValueError) as e:
  555. self._DoTestFile('010_pack_align_power2.dts')
  556. self.assertIn("Node '/binman/u-boot': Alignment 5 must be a power "
  557. "of two", str(e.exception))
  558. def testPackAlignSizePowerOf2(self):
  559. """Test that invalid entry size alignment is detected"""
  560. with self.assertRaises(ValueError) as e:
  561. self._DoTestFile('011_pack_align_size_power2.dts')
  562. self.assertIn("Node '/binman/u-boot': Alignment size 55 must be a "
  563. "power of two", str(e.exception))
  564. def testPackInvalidAlign(self):
  565. """Test detection of an offset that does not match its alignment"""
  566. with self.assertRaises(ValueError) as e:
  567. self._DoTestFile('012_pack_inv_align.dts')
  568. self.assertIn("Node '/binman/u-boot': Offset 0x5 (5) does not match "
  569. "align 0x4 (4)", str(e.exception))
  570. def testPackInvalidSizeAlign(self):
  571. """Test that invalid entry size alignment is detected"""
  572. with self.assertRaises(ValueError) as e:
  573. self._DoTestFile('013_pack_inv_size_align.dts')
  574. self.assertIn("Node '/binman/u-boot': Size 0x5 (5) does not match "
  575. "align-size 0x4 (4)", str(e.exception))
  576. def testPackOverlap(self):
  577. """Test that overlapping regions are detected"""
  578. with self.assertRaises(ValueError) as e:
  579. self._DoTestFile('014_pack_overlap.dts')
  580. self.assertIn("Node '/binman/u-boot-align': Offset 0x3 (3) overlaps "
  581. "with previous entry '/binman/u-boot' ending at 0x4 (4)",
  582. str(e.exception))
  583. def testPackEntryOverflow(self):
  584. """Test that entries that overflow their size are detected"""
  585. with self.assertRaises(ValueError) as e:
  586. self._DoTestFile('015_pack_overflow.dts')
  587. self.assertIn("Node '/binman/u-boot': Entry contents size is 0x4 (4) "
  588. "but entry size is 0x3 (3)", str(e.exception))
  589. def testPackImageOverflow(self):
  590. """Test that entries which overflow the image size are detected"""
  591. with self.assertRaises(ValueError) as e:
  592. self._DoTestFile('016_pack_image_overflow.dts')
  593. self.assertIn("Section '/binman': contents size 0x4 (4) exceeds section "
  594. "size 0x3 (3)", str(e.exception))
  595. def testPackImageSize(self):
  596. """Test that the image size can be set"""
  597. retcode = self._DoTestFile('017_pack_image_size.dts')
  598. self.assertEqual(0, retcode)
  599. self.assertIn('image', control.images)
  600. image = control.images['image']
  601. self.assertEqual(7, image._size)
  602. def testPackImageSizeAlign(self):
  603. """Test that image size alignemnt works as expected"""
  604. retcode = self._DoTestFile('018_pack_image_align.dts')
  605. self.assertEqual(0, retcode)
  606. self.assertIn('image', control.images)
  607. image = control.images['image']
  608. self.assertEqual(16, image._size)
  609. def testPackInvalidImageAlign(self):
  610. """Test that invalid image alignment is detected"""
  611. with self.assertRaises(ValueError) as e:
  612. self._DoTestFile('019_pack_inv_image_align.dts')
  613. self.assertIn("Section '/binman': Size 0x7 (7) does not match "
  614. "align-size 0x8 (8)", str(e.exception))
  615. def testPackAlignPowerOf2(self):
  616. """Test that invalid image alignment is detected"""
  617. with self.assertRaises(ValueError) as e:
  618. self._DoTestFile('020_pack_inv_image_align_power2.dts')
  619. self.assertIn("Section '/binman': Alignment size 131 must be a power of "
  620. "two", str(e.exception))
  621. def testImagePadByte(self):
  622. """Test that the image pad byte can be specified"""
  623. self._SetupSplElf()
  624. data = self._DoReadFile('021_image_pad.dts')
  625. self.assertEqual(U_BOOT_SPL_DATA + (chr(0xff) * 1) + U_BOOT_DATA, data)
  626. def testImageName(self):
  627. """Test that image files can be named"""
  628. retcode = self._DoTestFile('022_image_name.dts')
  629. self.assertEqual(0, retcode)
  630. image = control.images['image1']
  631. fname = tools.GetOutputFilename('test-name')
  632. self.assertTrue(os.path.exists(fname))
  633. image = control.images['image2']
  634. fname = tools.GetOutputFilename('test-name.xx')
  635. self.assertTrue(os.path.exists(fname))
  636. def testBlobFilename(self):
  637. """Test that generic blobs can be provided by filename"""
  638. data = self._DoReadFile('023_blob.dts')
  639. self.assertEqual(BLOB_DATA, data)
  640. def testPackSorted(self):
  641. """Test that entries can be sorted"""
  642. self._SetupSplElf()
  643. data = self._DoReadFile('024_sorted.dts')
  644. self.assertEqual(chr(0) * 1 + U_BOOT_SPL_DATA + chr(0) * 2 +
  645. U_BOOT_DATA, data)
  646. def testPackZeroOffset(self):
  647. """Test that an entry at offset 0 is not given a new offset"""
  648. with self.assertRaises(ValueError) as e:
  649. self._DoTestFile('025_pack_zero_size.dts')
  650. self.assertIn("Node '/binman/u-boot-spl': Offset 0x0 (0) overlaps "
  651. "with previous entry '/binman/u-boot' ending at 0x4 (4)",
  652. str(e.exception))
  653. def testPackUbootDtb(self):
  654. """Test that a device tree can be added to U-Boot"""
  655. data = self._DoReadFile('026_pack_u_boot_dtb.dts')
  656. self.assertEqual(U_BOOT_NODTB_DATA + U_BOOT_DTB_DATA, data)
  657. def testPackX86RomNoSize(self):
  658. """Test that the end-at-4gb property requires a size property"""
  659. with self.assertRaises(ValueError) as e:
  660. self._DoTestFile('027_pack_4gb_no_size.dts')
  661. self.assertIn("Section '/binman': Section size must be provided when "
  662. "using end-at-4gb", str(e.exception))
  663. def test4gbAndSkipAtStartTogether(self):
  664. """Test that the end-at-4gb and skip-at-size property can't be used
  665. together"""
  666. with self.assertRaises(ValueError) as e:
  667. self._DoTestFile('80_4gb_and_skip_at_start_together.dts')
  668. self.assertIn("Section '/binman': Provide either 'end-at-4gb' or "
  669. "'skip-at-start'", str(e.exception))
  670. def testPackX86RomOutside(self):
  671. """Test that the end-at-4gb property checks for offset boundaries"""
  672. with self.assertRaises(ValueError) as e:
  673. self._DoTestFile('028_pack_4gb_outside.dts')
  674. self.assertIn("Node '/binman/u-boot': Offset 0x0 (0) is outside "
  675. "the section starting at 0xffffffe0 (4294967264)",
  676. str(e.exception))
  677. def testPackX86Rom(self):
  678. """Test that a basic x86 ROM can be created"""
  679. self._SetupSplElf()
  680. data = self._DoReadFile('029_x86-rom.dts')
  681. self.assertEqual(U_BOOT_DATA + chr(0) * 7 + U_BOOT_SPL_DATA +
  682. chr(0) * 2, data)
  683. def testPackX86RomMeNoDesc(self):
  684. """Test that an invalid Intel descriptor entry is detected"""
  685. TestFunctional._MakeInputFile('descriptor.bin', '')
  686. with self.assertRaises(ValueError) as e:
  687. self._DoTestFile('031_x86-rom-me.dts')
  688. self.assertIn("Node '/binman/intel-descriptor': Cannot find FD "
  689. "signature", str(e.exception))
  690. def testPackX86RomBadDesc(self):
  691. """Test that the Intel requires a descriptor entry"""
  692. with self.assertRaises(ValueError) as e:
  693. self._DoTestFile('030_x86-rom-me-no-desc.dts')
  694. self.assertIn("Node '/binman/intel-me': No offset set with "
  695. "offset-unset: should another entry provide this correct "
  696. "offset?", str(e.exception))
  697. def testPackX86RomMe(self):
  698. """Test that an x86 ROM with an ME region can be created"""
  699. data = self._DoReadFile('031_x86-rom-me.dts')
  700. self.assertEqual(ME_DATA, data[0x1000:0x1000 + len(ME_DATA)])
  701. def testPackVga(self):
  702. """Test that an image with a VGA binary can be created"""
  703. data = self._DoReadFile('032_intel-vga.dts')
  704. self.assertEqual(VGA_DATA, data[:len(VGA_DATA)])
  705. def testPackStart16(self):
  706. """Test that an image with an x86 start16 region can be created"""
  707. data = self._DoReadFile('033_x86-start16.dts')
  708. self.assertEqual(X86_START16_DATA, data[:len(X86_START16_DATA)])
  709. def testPackPowerpcMpc85xxBootpgResetvec(self):
  710. """Test that an image with powerpc-mpc85xx-bootpg-resetvec can be
  711. created"""
  712. data = self._DoReadFile('81_powerpc_mpc85xx_bootpg_resetvec.dts')
  713. self.assertEqual(PPC_MPC85XX_BR_DATA, data[:len(PPC_MPC85XX_BR_DATA)])
  714. def _RunMicrocodeTest(self, dts_fname, nodtb_data, ucode_second=False):
  715. """Handle running a test for insertion of microcode
  716. Args:
  717. dts_fname: Name of test .dts file
  718. nodtb_data: Data that we expect in the first section
  719. ucode_second: True if the microsecond entry is second instead of
  720. third
  721. Returns:
  722. Tuple:
  723. Contents of first region (U-Boot or SPL)
  724. Offset and size components of microcode pointer, as inserted
  725. in the above (two 4-byte words)
  726. """
  727. data = self._DoReadFile(dts_fname, True)
  728. # Now check the device tree has no microcode
  729. if ucode_second:
  730. ucode_content = data[len(nodtb_data):]
  731. ucode_pos = len(nodtb_data)
  732. dtb_with_ucode = ucode_content[16:]
  733. fdt_len = self.GetFdtLen(dtb_with_ucode)
  734. else:
  735. dtb_with_ucode = data[len(nodtb_data):]
  736. fdt_len = self.GetFdtLen(dtb_with_ucode)
  737. ucode_content = dtb_with_ucode[fdt_len:]
  738. ucode_pos = len(nodtb_data) + fdt_len
  739. fname = tools.GetOutputFilename('test.dtb')
  740. with open(fname, 'wb') as fd:
  741. fd.write(dtb_with_ucode)
  742. dtb = fdt.FdtScan(fname)
  743. ucode = dtb.GetNode('/microcode')
  744. self.assertTrue(ucode)
  745. for node in ucode.subnodes:
  746. self.assertFalse(node.props.get('data'))
  747. # Check that the microcode appears immediately after the Fdt
  748. # This matches the concatenation of the data properties in
  749. # the /microcode/update@xxx nodes in 34_x86_ucode.dts.
  750. ucode_data = struct.pack('>4L', 0x12345678, 0x12345679, 0xabcd0000,
  751. 0x78235609)
  752. self.assertEqual(ucode_data, ucode_content[:len(ucode_data)])
  753. # Check that the microcode pointer was inserted. It should match the
  754. # expected offset and size
  755. pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
  756. len(ucode_data))
  757. u_boot = data[:len(nodtb_data)]
  758. return u_boot, pos_and_size
  759. def testPackUbootMicrocode(self):
  760. """Test that x86 microcode can be handled correctly
  761. We expect to see the following in the image, in order:
  762. u-boot-nodtb.bin with a microcode pointer inserted at the correct
  763. place
  764. u-boot.dtb with the microcode removed
  765. the microcode
  766. """
  767. first, pos_and_size = self._RunMicrocodeTest('034_x86_ucode.dts',
  768. U_BOOT_NODTB_DATA)
  769. self.assertEqual('nodtb with microcode' + pos_and_size +
  770. ' somewhere in here', first)
  771. def _RunPackUbootSingleMicrocode(self):
  772. """Test that x86 microcode can be handled correctly
  773. We expect to see the following in the image, in order:
  774. u-boot-nodtb.bin with a microcode pointer inserted at the correct
  775. place
  776. u-boot.dtb with the microcode
  777. an empty microcode region
  778. """
  779. # We need the libfdt library to run this test since only that allows
  780. # finding the offset of a property. This is required by
  781. # Entry_u_boot_dtb_with_ucode.ObtainContents().
  782. data = self._DoReadFile('035_x86_single_ucode.dts', True)
  783. second = data[len(U_BOOT_NODTB_DATA):]
  784. fdt_len = self.GetFdtLen(second)
  785. third = second[fdt_len:]
  786. second = second[:fdt_len]
  787. ucode_data = struct.pack('>2L', 0x12345678, 0x12345679)
  788. self.assertIn(ucode_data, second)
  789. ucode_pos = second.find(ucode_data) + len(U_BOOT_NODTB_DATA)
  790. # Check that the microcode pointer was inserted. It should match the
  791. # expected offset and size
  792. pos_and_size = struct.pack('<2L', 0xfffffe00 + ucode_pos,
  793. len(ucode_data))
  794. first = data[:len(U_BOOT_NODTB_DATA)]
  795. self.assertEqual('nodtb with microcode' + pos_and_size +
  796. ' somewhere in here', first)
  797. def testPackUbootSingleMicrocode(self):
  798. """Test that x86 microcode can be handled correctly with fdt_normal.
  799. """
  800. self._RunPackUbootSingleMicrocode()
  801. def testUBootImg(self):
  802. """Test that u-boot.img can be put in a file"""
  803. data = self._DoReadFile('036_u_boot_img.dts')
  804. self.assertEqual(U_BOOT_IMG_DATA, data)
  805. def testNoMicrocode(self):
  806. """Test that a missing microcode region is detected"""
  807. with self.assertRaises(ValueError) as e:
  808. self._DoReadFile('037_x86_no_ucode.dts', True)
  809. self.assertIn("Node '/binman/u-boot-dtb-with-ucode': No /microcode "
  810. "node found in ", str(e.exception))
  811. def testMicrocodeWithoutNode(self):
  812. """Test that a missing u-boot-dtb-with-ucode node is detected"""
  813. with self.assertRaises(ValueError) as e:
  814. self._DoReadFile('038_x86_ucode_missing_node.dts', True)
  815. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
  816. "microcode region u-boot-dtb-with-ucode", str(e.exception))
  817. def testMicrocodeWithoutNode2(self):
  818. """Test that a missing u-boot-ucode node is detected"""
  819. with self.assertRaises(ValueError) as e:
  820. self._DoReadFile('039_x86_ucode_missing_node2.dts', True)
  821. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot find "
  822. "microcode region u-boot-ucode", str(e.exception))
  823. def testMicrocodeWithoutPtrInElf(self):
  824. """Test that a U-Boot binary without the microcode symbol is detected"""
  825. # ELF file without a '_dt_ucode_base_size' symbol
  826. try:
  827. with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
  828. TestFunctional._MakeInputFile('u-boot', fd.read())
  829. with self.assertRaises(ValueError) as e:
  830. self._RunPackUbootSingleMicrocode()
  831. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Cannot locate "
  832. "_dt_ucode_base_size symbol in u-boot", str(e.exception))
  833. finally:
  834. # Put the original file back
  835. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  836. TestFunctional._MakeInputFile('u-boot', fd.read())
  837. def testMicrocodeNotInImage(self):
  838. """Test that microcode must be placed within the image"""
  839. with self.assertRaises(ValueError) as e:
  840. self._DoReadFile('040_x86_ucode_not_in_image.dts', True)
  841. self.assertIn("Node '/binman/u-boot-with-ucode-ptr': Microcode "
  842. "pointer _dt_ucode_base_size at fffffe14 is outside the "
  843. "section ranging from 00000000 to 0000002e", str(e.exception))
  844. def testWithoutMicrocode(self):
  845. """Test that we can cope with an image without microcode (e.g. qemu)"""
  846. with open(self.TestFile('u_boot_no_ucode_ptr')) as fd:
  847. TestFunctional._MakeInputFile('u-boot', fd.read())
  848. data, dtb, _, _ = self._DoReadFileDtb('044_x86_optional_ucode.dts', True)
  849. # Now check the device tree has no microcode
  850. self.assertEqual(U_BOOT_NODTB_DATA, data[:len(U_BOOT_NODTB_DATA)])
  851. second = data[len(U_BOOT_NODTB_DATA):]
  852. fdt_len = self.GetFdtLen(second)
  853. self.assertEqual(dtb, second[:fdt_len])
  854. used_len = len(U_BOOT_NODTB_DATA) + fdt_len
  855. third = data[used_len:]
  856. self.assertEqual(chr(0) * (0x200 - used_len), third)
  857. def testUnknownPosSize(self):
  858. """Test that microcode must be placed within the image"""
  859. with self.assertRaises(ValueError) as e:
  860. self._DoReadFile('041_unknown_pos_size.dts', True)
  861. self.assertIn("Section '/binman': Unable to set offset/size for unknown "
  862. "entry 'invalid-entry'", str(e.exception))
  863. def testPackFsp(self):
  864. """Test that an image with a FSP binary can be created"""
  865. data = self._DoReadFile('042_intel-fsp.dts')
  866. self.assertEqual(FSP_DATA, data[:len(FSP_DATA)])
  867. def testPackCmc(self):
  868. """Test that an image with a CMC binary can be created"""
  869. data = self._DoReadFile('043_intel-cmc.dts')
  870. self.assertEqual(CMC_DATA, data[:len(CMC_DATA)])
  871. def testPackVbt(self):
  872. """Test that an image with a VBT binary can be created"""
  873. data = self._DoReadFile('046_intel-vbt.dts')
  874. self.assertEqual(VBT_DATA, data[:len(VBT_DATA)])
  875. def testSplBssPad(self):
  876. """Test that we can pad SPL's BSS with zeros"""
  877. # ELF file with a '__bss_size' symbol
  878. self._SetupSplElf()
  879. data = self._DoReadFile('047_spl_bss_pad.dts')
  880. self.assertEqual(U_BOOT_SPL_DATA + (chr(0) * 10) + U_BOOT_DATA, data)
  881. def testSplBssPadMissing(self):
  882. """Test that a missing symbol is detected"""
  883. self._SetupSplElf('u_boot_ucode_ptr')
  884. with self.assertRaises(ValueError) as e:
  885. self._DoReadFile('047_spl_bss_pad.dts')
  886. self.assertIn('Expected __bss_size symbol in spl/u-boot-spl',
  887. str(e.exception))
  888. def testPackStart16Spl(self):
  889. """Test that an image with an x86 start16 SPL region can be created"""
  890. data = self._DoReadFile('048_x86-start16-spl.dts')
  891. self.assertEqual(X86_START16_SPL_DATA, data[:len(X86_START16_SPL_DATA)])
  892. def _PackUbootSplMicrocode(self, dts, ucode_second=False):
  893. """Helper function for microcode tests
  894. We expect to see the following in the image, in order:
  895. u-boot-spl-nodtb.bin with a microcode pointer inserted at the
  896. correct place
  897. u-boot.dtb with the microcode removed
  898. the microcode
  899. Args:
  900. dts: Device tree file to use for test
  901. ucode_second: True if the microsecond entry is second instead of
  902. third
  903. """
  904. self._SetupSplElf('u_boot_ucode_ptr')
  905. first, pos_and_size = self._RunMicrocodeTest(dts, U_BOOT_SPL_NODTB_DATA,
  906. ucode_second=ucode_second)
  907. self.assertEqual('splnodtb with microc' + pos_and_size +
  908. 'ter somewhere in here', first)
  909. def testPackUbootSplMicrocode(self):
  910. """Test that x86 microcode can be handled correctly in SPL"""
  911. self._PackUbootSplMicrocode('049_x86_ucode_spl.dts')
  912. def testPackUbootSplMicrocodeReorder(self):
  913. """Test that order doesn't matter for microcode entries
  914. This is the same as testPackUbootSplMicrocode but when we process the
  915. u-boot-ucode entry we have not yet seen the u-boot-dtb-with-ucode
  916. entry, so we reply on binman to try later.
  917. """
  918. self._PackUbootSplMicrocode('058_x86_ucode_spl_needs_retry.dts',
  919. ucode_second=True)
  920. def testPackMrc(self):
  921. """Test that an image with an MRC binary can be created"""
  922. data = self._DoReadFile('050_intel_mrc.dts')
  923. self.assertEqual(MRC_DATA, data[:len(MRC_DATA)])
  924. def testSplDtb(self):
  925. """Test that an image with spl/u-boot-spl.dtb can be created"""
  926. data = self._DoReadFile('051_u_boot_spl_dtb.dts')
  927. self.assertEqual(U_BOOT_SPL_DTB_DATA, data[:len(U_BOOT_SPL_DTB_DATA)])
  928. def testSplNoDtb(self):
  929. """Test that an image with spl/u-boot-spl-nodtb.bin can be created"""
  930. data = self._DoReadFile('052_u_boot_spl_nodtb.dts')
  931. self.assertEqual(U_BOOT_SPL_NODTB_DATA, data[:len(U_BOOT_SPL_NODTB_DATA)])
  932. def testSymbols(self):
  933. """Test binman can assign symbols embedded in U-Boot"""
  934. elf_fname = self.TestFile('u_boot_binman_syms')
  935. syms = elf.GetSymbols(elf_fname, ['binman', 'image'])
  936. addr = elf.GetSymbolAddress(elf_fname, '__image_copy_start')
  937. self.assertEqual(syms['_binman_u_boot_spl_prop_offset'].address, addr)
  938. self._SetupSplElf('u_boot_binman_syms')
  939. data = self._DoReadFile('053_symbols.dts')
  940. sym_values = struct.pack('<LQL', 0x24 + 0, 0x24 + 24, 0x24 + 20)
  941. expected = (sym_values + U_BOOT_SPL_DATA[16:] + chr(0xff) +
  942. U_BOOT_DATA +
  943. sym_values + U_BOOT_SPL_DATA[16:])
  944. self.assertEqual(expected, data)
  945. def testPackUnitAddress(self):
  946. """Test that we support multiple binaries with the same name"""
  947. data = self._DoReadFile('054_unit_address.dts')
  948. self.assertEqual(U_BOOT_DATA + U_BOOT_DATA, data)
  949. def testSections(self):
  950. """Basic test of sections"""
  951. data = self._DoReadFile('055_sections.dts')
  952. expected = (U_BOOT_DATA + '!' * 12 + U_BOOT_DATA + 'a' * 12 +
  953. U_BOOT_DATA + '&' * 4)
  954. self.assertEqual(expected, data)
  955. def testMap(self):
  956. """Tests outputting a map of the images"""
  957. _, _, map_data, _ = self._DoReadFileDtb('055_sections.dts', map=True)
  958. self.assertEqual('''ImagePos Offset Size Name
  959. 00000000 00000000 00000028 main-section
  960. 00000000 00000000 00000010 section@0
  961. 00000000 00000000 00000004 u-boot
  962. 00000010 00000010 00000010 section@1
  963. 00000010 00000000 00000004 u-boot
  964. 00000020 00000020 00000004 section@2
  965. 00000020 00000000 00000004 u-boot
  966. ''', map_data)
  967. def testNamePrefix(self):
  968. """Tests that name prefixes are used"""
  969. _, _, map_data, _ = self._DoReadFileDtb('056_name_prefix.dts', map=True)
  970. self.assertEqual('''ImagePos Offset Size Name
  971. 00000000 00000000 00000028 main-section
  972. 00000000 00000000 00000010 section@0
  973. 00000000 00000000 00000004 ro-u-boot
  974. 00000010 00000010 00000010 section@1
  975. 00000010 00000000 00000004 rw-u-boot
  976. ''', map_data)
  977. def testUnknownContents(self):
  978. """Test that obtaining the contents works as expected"""
  979. with self.assertRaises(ValueError) as e:
  980. self._DoReadFile('057_unknown_contents.dts', True)
  981. self.assertIn("Section '/binman': Internal error: Could not complete "
  982. "processing of contents: remaining [<_testing.Entry__testing ",
  983. str(e.exception))
  984. def testBadChangeSize(self):
  985. """Test that trying to change the size of an entry fails"""
  986. with self.assertRaises(ValueError) as e:
  987. self._DoReadFile('059_change_size.dts', True)
  988. self.assertIn("Node '/binman/_testing': Cannot update entry size from "
  989. '2 to 1', str(e.exception))
  990. def testUpdateFdt(self):
  991. """Test that we can update the device tree with offset/size info"""
  992. _, _, _, out_dtb_fname = self._DoReadFileDtb('060_fdt_update.dts',
  993. update_dtb=True)
  994. dtb = fdt.Fdt(out_dtb_fname)
  995. dtb.Scan()
  996. props = self._GetPropTree(dtb, ['offset', 'size', 'image-pos'])
  997. self.assertEqual({
  998. 'image-pos': 0,
  999. 'offset': 0,
  1000. '_testing:offset': 32,
  1001. '_testing:size': 1,
  1002. '_testing:image-pos': 32,
  1003. 'section@0/u-boot:offset': 0,
  1004. 'section@0/u-boot:size': len(U_BOOT_DATA),
  1005. 'section@0/u-boot:image-pos': 0,
  1006. 'section@0:offset': 0,
  1007. 'section@0:size': 16,
  1008. 'section@0:image-pos': 0,
  1009. 'section@1/u-boot:offset': 0,
  1010. 'section@1/u-boot:size': len(U_BOOT_DATA),
  1011. 'section@1/u-boot:image-pos': 16,
  1012. 'section@1:offset': 16,
  1013. 'section@1:size': 16,
  1014. 'section@1:image-pos': 16,
  1015. 'size': 40
  1016. }, props)
  1017. def testUpdateFdtBad(self):
  1018. """Test that we detect when ProcessFdt never completes"""
  1019. with self.assertRaises(ValueError) as e:
  1020. self._DoReadFileDtb('061_fdt_update_bad.dts', update_dtb=True)
  1021. self.assertIn('Could not complete processing of Fdt: remaining '
  1022. '[<_testing.Entry__testing', str(e.exception))
  1023. def testEntryArgs(self):
  1024. """Test passing arguments to entries from the command line"""
  1025. entry_args = {
  1026. 'test-str-arg': 'test1',
  1027. 'test-int-arg': '456',
  1028. }
  1029. self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
  1030. self.assertIn('image', control.images)
  1031. entry = control.images['image'].GetEntries()['_testing']
  1032. self.assertEqual('test0', entry.test_str_fdt)
  1033. self.assertEqual('test1', entry.test_str_arg)
  1034. self.assertEqual(123, entry.test_int_fdt)
  1035. self.assertEqual(456, entry.test_int_arg)
  1036. def testEntryArgsMissing(self):
  1037. """Test missing arguments and properties"""
  1038. entry_args = {
  1039. 'test-int-arg': '456',
  1040. }
  1041. self._DoReadFileDtb('063_entry_args_missing.dts', entry_args=entry_args)
  1042. entry = control.images['image'].GetEntries()['_testing']
  1043. self.assertEqual('test0', entry.test_str_fdt)
  1044. self.assertEqual(None, entry.test_str_arg)
  1045. self.assertEqual(None, entry.test_int_fdt)
  1046. self.assertEqual(456, entry.test_int_arg)
  1047. def testEntryArgsRequired(self):
  1048. """Test missing arguments and properties"""
  1049. entry_args = {
  1050. 'test-int-arg': '456',
  1051. }
  1052. with self.assertRaises(ValueError) as e:
  1053. self._DoReadFileDtb('064_entry_args_required.dts')
  1054. self.assertIn("Node '/binman/_testing': Missing required "
  1055. 'properties/entry args: test-str-arg, test-int-fdt, test-int-arg',
  1056. str(e.exception))
  1057. def testEntryArgsInvalidFormat(self):
  1058. """Test that an invalid entry-argument format is detected"""
  1059. args = ['-d', self.TestFile('064_entry_args_required.dts'), '-ano-value']
  1060. with self.assertRaises(ValueError) as e:
  1061. self._DoBinman(*args)
  1062. self.assertIn("Invalid entry arguemnt 'no-value'", str(e.exception))
  1063. def testEntryArgsInvalidInteger(self):
  1064. """Test that an invalid entry-argument integer is detected"""
  1065. entry_args = {
  1066. 'test-int-arg': 'abc',
  1067. }
  1068. with self.assertRaises(ValueError) as e:
  1069. self._DoReadFileDtb('062_entry_args.dts', entry_args=entry_args)
  1070. self.assertIn("Node '/binman/_testing': Cannot convert entry arg "
  1071. "'test-int-arg' (value 'abc') to integer",
  1072. str(e.exception))
  1073. def testEntryArgsInvalidDatatype(self):
  1074. """Test that an invalid entry-argument datatype is detected
  1075. This test could be written in entry_test.py except that it needs
  1076. access to control.entry_args, which seems more than that module should
  1077. be able to see.
  1078. """
  1079. entry_args = {
  1080. 'test-bad-datatype-arg': '12',
  1081. }
  1082. with self.assertRaises(ValueError) as e:
  1083. self._DoReadFileDtb('065_entry_args_unknown_datatype.dts',
  1084. entry_args=entry_args)
  1085. self.assertIn('GetArg() internal error: Unknown data type ',
  1086. str(e.exception))
  1087. def testText(self):
  1088. """Test for a text entry type"""
  1089. entry_args = {
  1090. 'test-id': TEXT_DATA,
  1091. 'test-id2': TEXT_DATA2,
  1092. 'test-id3': TEXT_DATA3,
  1093. }
  1094. data, _, _, _ = self._DoReadFileDtb('066_text.dts',
  1095. entry_args=entry_args)
  1096. expected = (TEXT_DATA + chr(0) * (8 - len(TEXT_DATA)) + TEXT_DATA2 +
  1097. TEXT_DATA3 + 'some text')
  1098. self.assertEqual(expected, data)
  1099. def testEntryDocs(self):
  1100. """Test for creation of entry documentation"""
  1101. with test_util.capture_sys_output() as (stdout, stderr):
  1102. control.WriteEntryDocs(binman.GetEntryModules())
  1103. self.assertTrue(len(stdout.getvalue()) > 0)
  1104. def testEntryDocsMissing(self):
  1105. """Test handling of missing entry documentation"""
  1106. with self.assertRaises(ValueError) as e:
  1107. with test_util.capture_sys_output() as (stdout, stderr):
  1108. control.WriteEntryDocs(binman.GetEntryModules(), 'u_boot')
  1109. self.assertIn('Documentation is missing for modules: u_boot',
  1110. str(e.exception))
  1111. def testFmap(self):
  1112. """Basic test of generation of a flashrom fmap"""
  1113. data = self._DoReadFile('067_fmap.dts')
  1114. fhdr, fentries = fmap_util.DecodeFmap(data[32:])
  1115. expected = U_BOOT_DATA + '!' * 12 + U_BOOT_DATA + 'a' * 12
  1116. self.assertEqual(expected, data[:32])
  1117. self.assertEqual('__FMAP__', fhdr.signature)
  1118. self.assertEqual(1, fhdr.ver_major)
  1119. self.assertEqual(0, fhdr.ver_minor)
  1120. self.assertEqual(0, fhdr.base)
  1121. self.assertEqual(16 + 16 +
  1122. fmap_util.FMAP_HEADER_LEN +
  1123. fmap_util.FMAP_AREA_LEN * 3, fhdr.image_size)
  1124. self.assertEqual('FMAP', fhdr.name)
  1125. self.assertEqual(3, fhdr.nareas)
  1126. for fentry in fentries:
  1127. self.assertEqual(0, fentry.flags)
  1128. self.assertEqual(0, fentries[0].offset)
  1129. self.assertEqual(4, fentries[0].size)
  1130. self.assertEqual('RO_U_BOOT', fentries[0].name)
  1131. self.assertEqual(16, fentries[1].offset)
  1132. self.assertEqual(4, fentries[1].size)
  1133. self.assertEqual('RW_U_BOOT', fentries[1].name)
  1134. self.assertEqual(32, fentries[2].offset)
  1135. self.assertEqual(fmap_util.FMAP_HEADER_LEN +
  1136. fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
  1137. self.assertEqual('FMAP', fentries[2].name)
  1138. def testBlobNamedByArg(self):
  1139. """Test we can add a blob with the filename coming from an entry arg"""
  1140. entry_args = {
  1141. 'cros-ec-rw-path': 'ecrw.bin',
  1142. }
  1143. data, _, _, _ = self._DoReadFileDtb('068_blob_named_by_arg.dts',
  1144. entry_args=entry_args)
  1145. def testFill(self):
  1146. """Test for an fill entry type"""
  1147. data = self._DoReadFile('069_fill.dts')
  1148. expected = 8 * chr(0xff) + 8 * chr(0)
  1149. self.assertEqual(expected, data)
  1150. def testFillNoSize(self):
  1151. """Test for an fill entry type with no size"""
  1152. with self.assertRaises(ValueError) as e:
  1153. self._DoReadFile('070_fill_no_size.dts')
  1154. self.assertIn("'fill' entry must have a size property",
  1155. str(e.exception))
  1156. def _HandleGbbCommand(self, pipe_list):
  1157. """Fake calls to the futility utility"""
  1158. if pipe_list[0][0] == 'futility':
  1159. fname = pipe_list[0][-1]
  1160. # Append our GBB data to the file, which will happen every time the
  1161. # futility command is called.
  1162. with open(fname, 'a') as fd:
  1163. fd.write(GBB_DATA)
  1164. return command.CommandResult()
  1165. def testGbb(self):
  1166. """Test for the Chromium OS Google Binary Block"""
  1167. command.test_result = self._HandleGbbCommand
  1168. entry_args = {
  1169. 'keydir': 'devkeys',
  1170. 'bmpblk': 'bmpblk.bin',
  1171. }
  1172. data, _, _, _ = self._DoReadFileDtb('071_gbb.dts', entry_args=entry_args)
  1173. # Since futility
  1174. expected = GBB_DATA + GBB_DATA + 8 * chr(0) + (0x2180 - 16) * chr(0)
  1175. self.assertEqual(expected, data)
  1176. def testGbbTooSmall(self):
  1177. """Test for the Chromium OS Google Binary Block being large enough"""
  1178. with self.assertRaises(ValueError) as e:
  1179. self._DoReadFileDtb('072_gbb_too_small.dts')
  1180. self.assertIn("Node '/binman/gbb': GBB is too small",
  1181. str(e.exception))
  1182. def testGbbNoSize(self):
  1183. """Test for the Chromium OS Google Binary Block having a size"""
  1184. with self.assertRaises(ValueError) as e:
  1185. self._DoReadFileDtb('073_gbb_no_size.dts')
  1186. self.assertIn("Node '/binman/gbb': GBB must have a fixed size",
  1187. str(e.exception))
  1188. def _HandleVblockCommand(self, pipe_list):
  1189. """Fake calls to the futility utility"""
  1190. if pipe_list[0][0] == 'futility':
  1191. fname = pipe_list[0][3]
  1192. with open(fname, 'wb') as fd:
  1193. fd.write(VBLOCK_DATA)
  1194. return command.CommandResult()
  1195. def testVblock(self):
  1196. """Test for the Chromium OS Verified Boot Block"""
  1197. command.test_result = self._HandleVblockCommand
  1198. entry_args = {
  1199. 'keydir': 'devkeys',
  1200. }
  1201. data, _, _, _ = self._DoReadFileDtb('074_vblock.dts',
  1202. entry_args=entry_args)
  1203. expected = U_BOOT_DATA + VBLOCK_DATA + U_BOOT_DTB_DATA
  1204. self.assertEqual(expected, data)
  1205. def testVblockNoContent(self):
  1206. """Test we detect a vblock which has no content to sign"""
  1207. with self.assertRaises(ValueError) as e:
  1208. self._DoReadFile('075_vblock_no_content.dts')
  1209. self.assertIn("Node '/binman/vblock': Vblock must have a 'content' "
  1210. 'property', str(e.exception))
  1211. def testVblockBadPhandle(self):
  1212. """Test that we detect a vblock with an invalid phandle in contents"""
  1213. with self.assertRaises(ValueError) as e:
  1214. self._DoReadFile('076_vblock_bad_phandle.dts')
  1215. self.assertIn("Node '/binman/vblock': Cannot find node for phandle "
  1216. '1000', str(e.exception))
  1217. def testVblockBadEntry(self):
  1218. """Test that we detect an entry that points to a non-entry"""
  1219. with self.assertRaises(ValueError) as e:
  1220. self._DoReadFile('077_vblock_bad_entry.dts')
  1221. self.assertIn("Node '/binman/vblock': Cannot find entry for node "
  1222. "'other'", str(e.exception))
  1223. def testTpl(self):
  1224. """Test that an image with TPL and ots device tree can be created"""
  1225. # ELF file with a '__bss_size' symbol
  1226. with open(self.TestFile('bss_data')) as fd:
  1227. TestFunctional._MakeInputFile('tpl/u-boot-tpl', fd.read())
  1228. data = self._DoReadFile('078_u_boot_tpl.dts')
  1229. self.assertEqual(U_BOOT_TPL_DATA + U_BOOT_TPL_DTB_DATA, data)
  1230. def testUsesPos(self):
  1231. """Test that the 'pos' property cannot be used anymore"""
  1232. with self.assertRaises(ValueError) as e:
  1233. data = self._DoReadFile('079_uses_pos.dts')
  1234. self.assertIn("Node '/binman/u-boot': Please use 'offset' instead of "
  1235. "'pos'", str(e.exception))
  1236. def testFillZero(self):
  1237. """Test for an fill entry type with a size of 0"""
  1238. data = self._DoReadFile('080_fill_empty.dts')
  1239. self.assertEqual(chr(0) * 16, data)
  1240. def testTextMissing(self):
  1241. """Test for a text entry type where there is no text"""
  1242. with self.assertRaises(ValueError) as e:
  1243. self._DoReadFileDtb('066_text.dts',)
  1244. self.assertIn("Node '/binman/text': No value provided for text label "
  1245. "'test-id'", str(e.exception))
  1246. def testPackStart16Tpl(self):
  1247. """Test that an image with an x86 start16 TPL region can be created"""
  1248. data = self._DoReadFile('081_x86-start16-tpl.dts')
  1249. self.assertEqual(X86_START16_TPL_DATA, data[:len(X86_START16_TPL_DATA)])
  1250. def testSelectImage(self):
  1251. """Test that we can select which images to build"""
  1252. with test_util.capture_sys_output() as (stdout, stderr):
  1253. retcode = self._DoTestFile('006_dual_image.dts', images=['image2'])
  1254. self.assertEqual(0, retcode)
  1255. self.assertIn('Skipping images: image1', stdout.getvalue())
  1256. self.assertFalse(os.path.exists(tools.GetOutputFilename('image1.bin')))
  1257. self.assertTrue(os.path.exists(tools.GetOutputFilename('image2.bin')))
  1258. def testUpdateFdtAll(self):
  1259. """Test that all device trees are updated with offset/size info"""
  1260. data, _, _, _ = self._DoReadFileDtb('082_fdt_update_all.dts',
  1261. use_real_dtb=True, update_dtb=True)
  1262. base_expected = {
  1263. 'section:image-pos': 0,
  1264. 'u-boot-tpl-dtb:size': 513,
  1265. 'u-boot-spl-dtb:size': 513,
  1266. 'u-boot-spl-dtb:offset': 493,
  1267. 'image-pos': 0,
  1268. 'section/u-boot-dtb:image-pos': 0,
  1269. 'u-boot-spl-dtb:image-pos': 493,
  1270. 'section/u-boot-dtb:size': 493,
  1271. 'u-boot-tpl-dtb:image-pos': 1006,
  1272. 'section/u-boot-dtb:offset': 0,
  1273. 'section:size': 493,
  1274. 'offset': 0,
  1275. 'section:offset': 0,
  1276. 'u-boot-tpl-dtb:offset': 1006,
  1277. 'size': 1519
  1278. }
  1279. # We expect three device-tree files in the output, one after the other.
  1280. # Read them in sequence. We look for an 'spl' property in the SPL tree,
  1281. # and 'tpl' in the TPL tree, to make sure they are distinct from the
  1282. # main U-Boot tree. All three should have the same postions and offset.
  1283. start = 0
  1284. for item in ['', 'spl', 'tpl']:
  1285. dtb = fdt.Fdt.FromData(data[start:])
  1286. dtb.Scan()
  1287. props = self._GetPropTree(dtb, ['offset', 'size', 'image-pos',
  1288. 'spl', 'tpl'])
  1289. expected = dict(base_expected)
  1290. if item:
  1291. expected[item] = 0
  1292. self.assertEqual(expected, props)
  1293. start += dtb._fdt_obj.totalsize()
  1294. def testUpdateFdtOutput(self):
  1295. """Test that output DTB files are updated"""
  1296. try:
  1297. data, dtb_data, _, _ = self._DoReadFileDtb('082_fdt_update_all.dts',
  1298. use_real_dtb=True, update_dtb=True, reset_dtbs=False)
  1299. # Unfortunately, compiling a source file always results in a file
  1300. # called source.dtb (see fdt_util.EnsureCompiled()). The test
  1301. # source file (e.g. test/075_fdt_update_all.dts) thus does not enter
  1302. # binman as a file called u-boot.dtb. To fix this, copy the file
  1303. # over to the expected place.
  1304. #tools.WriteFile(os.path.join(self._indir, 'u-boot.dtb'),
  1305. #tools.ReadFile(tools.GetOutputFilename('source.dtb')))
  1306. start = 0
  1307. for fname in ['u-boot.dtb.out', 'spl/u-boot-spl.dtb.out',
  1308. 'tpl/u-boot-tpl.dtb.out']:
  1309. dtb = fdt.Fdt.FromData(data[start:])
  1310. size = dtb._fdt_obj.totalsize()
  1311. pathname = tools.GetOutputFilename(os.path.split(fname)[1])
  1312. outdata = tools.ReadFile(pathname)
  1313. name = os.path.split(fname)[0]
  1314. if name:
  1315. orig_indata = self._GetDtbContentsForSplTpl(dtb_data, name)
  1316. else:
  1317. orig_indata = dtb_data
  1318. self.assertNotEqual(outdata, orig_indata,
  1319. "Expected output file '%s' be updated" % pathname)
  1320. self.assertEqual(outdata, data[start:start + size],
  1321. "Expected output file '%s' to match output image" %
  1322. pathname)
  1323. start += size
  1324. finally:
  1325. self._ResetDtbs()
  1326. def _decompress(self, data):
  1327. out = os.path.join(self._indir, 'lz4.tmp')
  1328. with open(out, 'wb') as fd:
  1329. fd.write(data)
  1330. return tools.Run('lz4', '-dc', out)
  1331. '''
  1332. try:
  1333. orig = lz4.frame.decompress(data)
  1334. except AttributeError:
  1335. orig = lz4.decompress(data)
  1336. '''
  1337. def testCompress(self):
  1338. """Test compression of blobs"""
  1339. data, _, _, out_dtb_fname = self._DoReadFileDtb('083_compress.dts',
  1340. use_real_dtb=True, update_dtb=True)
  1341. dtb = fdt.Fdt(out_dtb_fname)
  1342. dtb.Scan()
  1343. props = self._GetPropTree(dtb, ['size', 'uncomp-size'])
  1344. orig = self._decompress(data)
  1345. self.assertEquals(COMPRESS_DATA, orig)
  1346. expected = {
  1347. 'blob:uncomp-size': len(COMPRESS_DATA),
  1348. 'blob:size': len(data),
  1349. 'size': len(data),
  1350. }
  1351. self.assertEqual(expected, props)
  1352. def testFiles(self):
  1353. """Test bringing in multiple files"""
  1354. data = self._DoReadFile('084_files.dts')
  1355. self.assertEqual(FILES_DATA, data)
  1356. def testFilesCompress(self):
  1357. """Test bringing in multiple files and compressing them"""
  1358. data = self._DoReadFile('085_files_compress.dts')
  1359. image = control.images['image']
  1360. entries = image.GetEntries()
  1361. files = entries['files']
  1362. entries = files._section._entries
  1363. orig = ''
  1364. for i in range(1, 3):
  1365. key = '%d.dat' % i
  1366. start = entries[key].image_pos
  1367. len = entries[key].size
  1368. chunk = data[start:start + len]
  1369. orig += self._decompress(chunk)
  1370. self.assertEqual(FILES_DATA, orig)
  1371. def testFilesMissing(self):
  1372. """Test missing files"""
  1373. with self.assertRaises(ValueError) as e:
  1374. data = self._DoReadFile('086_files_none.dts')
  1375. self.assertIn("Node '/binman/files': Pattern \'files/*.none\' matched "
  1376. 'no files', str(e.exception))
  1377. def testFilesNoPattern(self):
  1378. """Test missing files"""
  1379. with self.assertRaises(ValueError) as e:
  1380. data = self._DoReadFile('087_files_no_pattern.dts')
  1381. self.assertIn("Node '/binman/files': Missing 'pattern' property",
  1382. str(e.exception))
  1383. def testExpandSize(self):
  1384. """Test an expanding entry"""
  1385. data, _, map_data, _ = self._DoReadFileDtb('088_expand_size.dts',
  1386. map=True)
  1387. expect = ('a' * 8 + U_BOOT_DATA +
  1388. MRC_DATA + 'b' * 1 + U_BOOT_DATA +
  1389. 'c' * 8 + U_BOOT_DATA +
  1390. 'd' * 8)
  1391. self.assertEqual(expect, data)
  1392. self.assertEqual('''ImagePos Offset Size Name
  1393. 00000000 00000000 00000028 main-section
  1394. 00000000 00000000 00000008 fill
  1395. 00000008 00000008 00000004 u-boot
  1396. 0000000c 0000000c 00000004 section
  1397. 0000000c 00000000 00000003 intel-mrc
  1398. 00000010 00000010 00000004 u-boot2
  1399. 00000014 00000014 0000000c section2
  1400. 00000014 00000000 00000008 fill
  1401. 0000001c 00000008 00000004 u-boot
  1402. 00000020 00000020 00000008 fill2
  1403. ''', map_data)
  1404. def testExpandSizeBad(self):
  1405. """Test an expanding entry which fails to provide contents"""
  1406. with test_util.capture_sys_output() as (stdout, stderr):
  1407. with self.assertRaises(ValueError) as e:
  1408. self._DoReadFileDtb('089_expand_size_bad.dts', map=True)
  1409. self.assertIn("Node '/binman/_testing': Cannot obtain contents when "
  1410. 'expanding entry', str(e.exception))
  1411. def testHash(self):
  1412. """Test hashing of the contents of an entry"""
  1413. _, _, _, out_dtb_fname = self._DoReadFileDtb('090_hash.dts',
  1414. use_real_dtb=True, update_dtb=True)
  1415. dtb = fdt.Fdt(out_dtb_fname)
  1416. dtb.Scan()
  1417. hash_node = dtb.GetNode('/binman/u-boot/hash').props['value']
  1418. m = hashlib.sha256()
  1419. m.update(U_BOOT_DATA)
  1420. self.assertEqual(m.digest(), ''.join(hash_node.value))
  1421. def testHashNoAlgo(self):
  1422. with self.assertRaises(ValueError) as e:
  1423. self._DoReadFileDtb('091_hash_no_algo.dts', update_dtb=True)
  1424. self.assertIn("Node \'/binman/u-boot\': Missing \'algo\' property for "
  1425. 'hash node', str(e.exception))
  1426. def testHashBadAlgo(self):
  1427. with self.assertRaises(ValueError) as e:
  1428. self._DoReadFileDtb('092_hash_bad_algo.dts', update_dtb=True)
  1429. self.assertIn("Node '/binman/u-boot': Unknown hash algorithm",
  1430. str(e.exception))
  1431. def testHashSection(self):
  1432. """Test hashing of the contents of an entry"""
  1433. _, _, _, out_dtb_fname = self._DoReadFileDtb('099_hash_section.dts',
  1434. use_real_dtb=True, update_dtb=True)
  1435. dtb = fdt.Fdt(out_dtb_fname)
  1436. dtb.Scan()
  1437. hash_node = dtb.GetNode('/binman/section/hash').props['value']
  1438. m = hashlib.sha256()
  1439. m.update(U_BOOT_DATA)
  1440. m.update(16 * 'a')
  1441. self.assertEqual(m.digest(), ''.join(hash_node.value))
  1442. def testPackUBootTplMicrocode(self):
  1443. """Test that x86 microcode can be handled correctly in TPL
  1444. We expect to see the following in the image, in order:
  1445. u-boot-tpl-nodtb.bin with a microcode pointer inserted at the correct
  1446. place
  1447. u-boot-tpl.dtb with the microcode removed
  1448. the microcode
  1449. """
  1450. with open(self.TestFile('u_boot_ucode_ptr')) as fd:
  1451. TestFunctional._MakeInputFile('tpl/u-boot-tpl', fd.read())
  1452. first, pos_and_size = self._RunMicrocodeTest('093_x86_tpl_ucode.dts',
  1453. U_BOOT_TPL_NODTB_DATA)
  1454. self.assertEqual('tplnodtb with microc' + pos_and_size +
  1455. 'ter somewhere in here', first)
  1456. def testFmapX86(self):
  1457. """Basic test of generation of a flashrom fmap"""
  1458. data = self._DoReadFile('094_fmap_x86.dts')
  1459. fhdr, fentries = fmap_util.DecodeFmap(data[32:])
  1460. expected = U_BOOT_DATA + MRC_DATA + 'a' * (32 - 7)
  1461. self.assertEqual(expected, data[:32])
  1462. fhdr, fentries = fmap_util.DecodeFmap(data[32:])
  1463. self.assertEqual(0x100, fhdr.image_size)
  1464. self.assertEqual(0, fentries[0].offset)
  1465. self.assertEqual(4, fentries[0].size)
  1466. self.assertEqual('U_BOOT', fentries[0].name)
  1467. self.assertEqual(4, fentries[1].offset)
  1468. self.assertEqual(3, fentries[1].size)
  1469. self.assertEqual('INTEL_MRC', fentries[1].name)
  1470. self.assertEqual(32, fentries[2].offset)
  1471. self.assertEqual(fmap_util.FMAP_HEADER_LEN +
  1472. fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
  1473. self.assertEqual('FMAP', fentries[2].name)
  1474. def testFmapX86Section(self):
  1475. """Basic test of generation of a flashrom fmap"""
  1476. data = self._DoReadFile('095_fmap_x86_section.dts')
  1477. expected = U_BOOT_DATA + MRC_DATA + 'b' * (32 - 7)
  1478. self.assertEqual(expected, data[:32])
  1479. fhdr, fentries = fmap_util.DecodeFmap(data[36:])
  1480. self.assertEqual(0x100, fhdr.image_size)
  1481. self.assertEqual(0, fentries[0].offset)
  1482. self.assertEqual(4, fentries[0].size)
  1483. self.assertEqual('U_BOOT', fentries[0].name)
  1484. self.assertEqual(4, fentries[1].offset)
  1485. self.assertEqual(3, fentries[1].size)
  1486. self.assertEqual('INTEL_MRC', fentries[1].name)
  1487. self.assertEqual(36, fentries[2].offset)
  1488. self.assertEqual(fmap_util.FMAP_HEADER_LEN +
  1489. fmap_util.FMAP_AREA_LEN * 3, fentries[2].size)
  1490. self.assertEqual('FMAP', fentries[2].name)
  1491. def testElf(self):
  1492. """Basic test of ELF entries"""
  1493. self._SetupSplElf()
  1494. with open(self.TestFile('bss_data')) as fd:
  1495. TestFunctional._MakeInputFile('-boot', fd.read())
  1496. data = self._DoReadFile('096_elf.dts')
  1497. def testElfStripg(self):
  1498. """Basic test of ELF entries"""
  1499. self._SetupSplElf()
  1500. with open(self.TestFile('bss_data')) as fd:
  1501. TestFunctional._MakeInputFile('-boot', fd.read())
  1502. data = self._DoReadFile('097_elf_strip.dts')
  1503. def testPackOverlapMap(self):
  1504. """Test that overlapping regions are detected"""
  1505. with test_util.capture_sys_output() as (stdout, stderr):
  1506. with self.assertRaises(ValueError) as e:
  1507. self._DoTestFile('014_pack_overlap.dts', map=True)
  1508. map_fname = tools.GetOutputFilename('image.map')
  1509. self.assertEqual("Wrote map file '%s' to show errors\n" % map_fname,
  1510. stdout.getvalue())
  1511. # We should not get an inmage, but there should be a map file
  1512. self.assertFalse(os.path.exists(tools.GetOutputFilename('image.bin')))
  1513. self.assertTrue(os.path.exists(map_fname))
  1514. map_data = tools.ReadFile(map_fname)
  1515. self.assertEqual('''ImagePos Offset Size Name
  1516. <none> 00000000 00000007 main-section
  1517. <none> 00000000 00000004 u-boot
  1518. <none> 00000003 00000004 u-boot-align
  1519. ''', map_data)
  1520. def testPacRefCode(self):
  1521. """Test that an image with an Intel Reference code binary works"""
  1522. data = self._DoReadFile('100_intel_refcode.dts')
  1523. self.assertEqual(REFCODE_DATA, data[:len(REFCODE_DATA)])
  1524. if __name__ == "__main__":
  1525. unittest.main()