ftest.py 63 KB

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