ftest.py 72 KB

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