test-fit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. #!/usr/bin/python
  2. #
  3. # Copyright (c) 2013, Google Inc.
  4. #
  5. # Sanity check of the FIT handling in U-Boot
  6. #
  7. # SPDX-License-Identifier: GPL-2.0+
  8. #
  9. # To run this:
  10. #
  11. # make O=sandbox sandbox_config
  12. # make O=sandbox
  13. # ./test/image/test-fit.py -u sandbox/u-boot
  14. #
  15. # Note: The above testing requires the Python development package, typically
  16. # called python-devel or something similar.
  17. import doctest
  18. from optparse import OptionParser
  19. import os
  20. import shutil
  21. import struct
  22. import sys
  23. import tempfile
  24. # Enable printing of all U-Boot output
  25. DEBUG = True
  26. # The 'command' library in patman is convenient for running commands
  27. base_path = os.path.dirname(sys.argv[0])
  28. patman = os.path.join(base_path, '../../tools/patman')
  29. sys.path.append(patman)
  30. import command
  31. # Define a base ITS which we can adjust using % and a dictionary
  32. base_its = '''
  33. /dts-v1/;
  34. / {
  35. description = "Chrome OS kernel image with one or more FDT blobs";
  36. #address-cells = <1>;
  37. images {
  38. kernel@1 {
  39. data = /incbin/("%(kernel)s");
  40. type = "kernel";
  41. arch = "sandbox";
  42. os = "linux";
  43. compression = "none";
  44. load = <0x40000>;
  45. entry = <0x8>;
  46. };
  47. kernel@2 {
  48. data = /incbin/("%(loadables1)s");
  49. type = "kernel";
  50. arch = "sandbox";
  51. os = "linux";
  52. compression = "none";
  53. %(loadables1_load)s
  54. entry = <0x0>;
  55. };
  56. fdt@1 {
  57. description = "snow";
  58. data = /incbin/("u-boot.dtb");
  59. type = "flat_dt";
  60. arch = "sandbox";
  61. %(fdt_load)s
  62. compression = "none";
  63. signature@1 {
  64. algo = "sha1,rsa2048";
  65. key-name-hint = "dev";
  66. };
  67. };
  68. ramdisk@1 {
  69. description = "snow";
  70. data = /incbin/("%(ramdisk)s");
  71. type = "ramdisk";
  72. arch = "sandbox";
  73. os = "linux";
  74. %(ramdisk_load)s
  75. compression = "none";
  76. };
  77. ramdisk@2 {
  78. description = "snow";
  79. data = /incbin/("%(loadables2)s");
  80. type = "ramdisk";
  81. arch = "sandbox";
  82. os = "linux";
  83. %(loadables2_load)s
  84. compression = "none";
  85. };
  86. };
  87. configurations {
  88. default = "conf@1";
  89. conf@1 {
  90. kernel = "kernel@1";
  91. fdt = "fdt@1";
  92. %(ramdisk_config)s
  93. %(loadables_config)s
  94. };
  95. };
  96. };
  97. '''
  98. # Define a base FDT - currently we don't use anything in this
  99. base_fdt = '''
  100. /dts-v1/;
  101. / {
  102. model = "Sandbox Verified Boot Test";
  103. compatible = "sandbox";
  104. reset@0 {
  105. compatible = "sandbox,reset";
  106. };
  107. };
  108. '''
  109. # This is the U-Boot script that is run for each test. First load the FIT,
  110. # then run the 'bootm' command, then save out memory from the places where
  111. # we expect 'bootm' to write things. Then quit.
  112. base_script = '''
  113. sb load hostfs 0 %(fit_addr)x %(fit)s
  114. fdt addr %(fit_addr)x
  115. bootm start %(fit_addr)x
  116. bootm loados
  117. sb save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
  118. sb save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
  119. sb save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
  120. sb save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
  121. sb save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
  122. reset
  123. '''
  124. def debug_stdout(stdout):
  125. if DEBUG:
  126. print stdout
  127. def make_fname(leaf):
  128. """Make a temporary filename
  129. Args:
  130. leaf: Leaf name of file to create (within temporary directory)
  131. Return:
  132. Temporary filename
  133. """
  134. global base_dir
  135. return os.path.join(base_dir, leaf)
  136. def filesize(fname):
  137. """Get the size of a file
  138. Args:
  139. fname: Filename to check
  140. Return:
  141. Size of file in bytes
  142. """
  143. return os.stat(fname).st_size
  144. def read_file(fname):
  145. """Read the contents of a file
  146. Args:
  147. fname: Filename to read
  148. Returns:
  149. Contents of file as a string
  150. """
  151. with open(fname, 'r') as fd:
  152. return fd.read()
  153. def make_dtb():
  154. """Make a sample .dts file and compile it to a .dtb
  155. Returns:
  156. Filename of .dtb file created
  157. """
  158. src = make_fname('u-boot.dts')
  159. dtb = make_fname('u-boot.dtb')
  160. with open(src, 'w') as fd:
  161. print >>fd, base_fdt
  162. command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
  163. return dtb
  164. def make_its(params):
  165. """Make a sample .its file with parameters embedded
  166. Args:
  167. params: Dictionary containing parameters to embed in the %() strings
  168. Returns:
  169. Filename of .its file created
  170. """
  171. its = make_fname('test.its')
  172. with open(its, 'w') as fd:
  173. print >>fd, base_its % params
  174. return its
  175. def make_fit(mkimage, params):
  176. """Make a sample .fit file ready for loading
  177. This creates a .its script with the selected parameters and uses mkimage to
  178. turn this into a .fit image.
  179. Args:
  180. mkimage: Filename of 'mkimage' utility
  181. params: Dictionary containing parameters to embed in the %() strings
  182. Return:
  183. Filename of .fit file created
  184. """
  185. fit = make_fname('test.fit')
  186. its = make_its(params)
  187. command.Output(mkimage, '-f', its, fit)
  188. with open(make_fname('u-boot.dts'), 'w') as fd:
  189. print >>fd, base_fdt
  190. return fit
  191. def make_kernel(filename, text):
  192. """Make a sample kernel with test data
  193. Args:
  194. filename: the name of the file you want to create
  195. Returns:
  196. Full path and filename of the kernel it created
  197. """
  198. fname = make_fname(filename)
  199. data = ''
  200. for i in range(100):
  201. data += 'this %s %d is unlikely to boot\n' % (text, i)
  202. with open(fname, 'w') as fd:
  203. print >>fd, data
  204. return fname
  205. def make_ramdisk(filename, text):
  206. """Make a sample ramdisk with test data
  207. Returns:
  208. Filename of ramdisk created
  209. """
  210. fname = make_fname(filename)
  211. data = ''
  212. for i in range(100):
  213. data += '%s %d was seldom used in the middle ages\n' % (text, i)
  214. with open(fname, 'w') as fd:
  215. print >>fd, data
  216. return fname
  217. def find_matching(text, match):
  218. """Find a match in a line of text, and return the unmatched line portion
  219. This is used to extract a part of a line from some text. The match string
  220. is used to locate the line - we use the first line that contains that
  221. match text.
  222. Once we find a match, we discard the match string itself from the line,
  223. and return what remains.
  224. TODO: If this function becomes more generally useful, we could change it
  225. to use regex and return groups.
  226. Args:
  227. text: Text to check (each line separated by \n)
  228. match: String to search for
  229. Return:
  230. String containing unmatched portion of line
  231. Exceptions:
  232. ValueError: If match is not found
  233. >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
  234. '10'
  235. >>> find_matching('first line:10\\nsecond_line:20', 'second line')
  236. Traceback (most recent call last):
  237. ...
  238. ValueError: Test aborted
  239. >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
  240. '20'
  241. """
  242. for line in text.splitlines():
  243. pos = line.find(match)
  244. if pos != -1:
  245. return line[:pos] + line[pos + len(match):]
  246. print "Expected '%s' but not found in output:"
  247. print text
  248. raise ValueError('Test aborted')
  249. def set_test(name):
  250. """Set the name of the current test and print a message
  251. Args:
  252. name: Name of test
  253. """
  254. global test_name
  255. test_name = name
  256. print name
  257. def fail(msg, stdout):
  258. """Raise an error with a helpful failure message
  259. Args:
  260. msg: Message to display
  261. """
  262. print stdout
  263. raise ValueError("Test '%s' failed: %s" % (test_name, msg))
  264. def run_fit_test(mkimage, u_boot):
  265. """Basic sanity check of FIT loading in U-Boot
  266. TODO: Almost everything:
  267. - hash algorithms - invalid hash/contents should be detected
  268. - signature algorithms - invalid sig/contents should be detected
  269. - compression
  270. - checking that errors are detected like:
  271. - image overwriting
  272. - missing images
  273. - invalid configurations
  274. - incorrect os/arch/type fields
  275. - empty data
  276. - images too large/small
  277. - invalid FDT (e.g. putting a random binary in instead)
  278. - default configuration selection
  279. - bootm command line parameters should have desired effect
  280. - run code coverage to make sure we are testing all the code
  281. """
  282. global test_name
  283. # Set up invariant files
  284. control_dtb = make_dtb()
  285. kernel = make_kernel('test-kernel.bin', 'kernel')
  286. ramdisk = make_ramdisk('test-ramdisk.bin', 'ramdisk')
  287. loadables1 = make_kernel('test-loadables1.bin', 'lenrek')
  288. loadables2 = make_ramdisk('test-loadables2.bin', 'ksidmar')
  289. kernel_out = make_fname('kernel-out.bin')
  290. fdt_out = make_fname('fdt-out.dtb')
  291. ramdisk_out = make_fname('ramdisk-out.bin')
  292. loadables1_out = make_fname('loadables1-out.bin')
  293. loadables2_out = make_fname('loadables2-out.bin')
  294. # Set up basic parameters with default values
  295. params = {
  296. 'fit_addr' : 0x1000,
  297. 'kernel' : kernel,
  298. 'kernel_out' : kernel_out,
  299. 'kernel_addr' : 0x40000,
  300. 'kernel_size' : filesize(kernel),
  301. 'fdt_out' : fdt_out,
  302. 'fdt_addr' : 0x80000,
  303. 'fdt_size' : filesize(control_dtb),
  304. 'fdt_load' : '',
  305. 'ramdisk' : ramdisk,
  306. 'ramdisk_out' : ramdisk_out,
  307. 'ramdisk_addr' : 0xc0000,
  308. 'ramdisk_size' : filesize(ramdisk),
  309. 'ramdisk_load' : '',
  310. 'ramdisk_config' : '',
  311. 'loadables1' : loadables1,
  312. 'loadables1_out' : loadables1_out,
  313. 'loadables1_addr' : 0x100000,
  314. 'loadables1_size' : filesize(loadables1),
  315. 'loadables1_load' : '',
  316. 'loadables2' : loadables2,
  317. 'loadables2_out' : loadables2_out,
  318. 'loadables2_addr' : 0x140000,
  319. 'loadables2_size' : filesize(loadables2),
  320. 'loadables2_load' : '',
  321. 'loadables_config' : '',
  322. }
  323. # Make a basic FIT and a script to load it
  324. fit = make_fit(mkimage, params)
  325. params['fit'] = fit
  326. cmd = base_script % params
  327. # First check that we can load a kernel
  328. # We could perhaps reduce duplication with some loss of readability
  329. set_test('Kernel load')
  330. stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
  331. debug_stdout(stdout)
  332. if read_file(kernel) != read_file(kernel_out):
  333. fail('Kernel not loaded', stdout)
  334. if read_file(control_dtb) == read_file(fdt_out):
  335. fail('FDT loaded but should be ignored', stdout)
  336. if read_file(ramdisk) == read_file(ramdisk_out):
  337. fail('Ramdisk loaded but should not be', stdout)
  338. # Find out the offset in the FIT where U-Boot has found the FDT
  339. line = find_matching(stdout, 'Booting using the FDT blob at ')
  340. fit_offset = int(line, 16) - params['fit_addr']
  341. fdt_magic = struct.pack('>L', 0xd00dfeed)
  342. data = read_file(fit)
  343. # Now find where it actually is in the FIT (skip the first word)
  344. real_fit_offset = data.find(fdt_magic, 4)
  345. if fit_offset != real_fit_offset:
  346. fail('U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
  347. (fit_offset, real_fit_offset), stdout)
  348. # Now a kernel and an FDT
  349. set_test('Kernel + FDT load')
  350. params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
  351. fit = make_fit(mkimage, params)
  352. stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
  353. debug_stdout(stdout)
  354. if read_file(kernel) != read_file(kernel_out):
  355. fail('Kernel not loaded', stdout)
  356. if read_file(control_dtb) != read_file(fdt_out):
  357. fail('FDT not loaded', stdout)
  358. if read_file(ramdisk) == read_file(ramdisk_out):
  359. fail('Ramdisk loaded but should not be', stdout)
  360. # Try a ramdisk
  361. set_test('Kernel + FDT + Ramdisk load')
  362. params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
  363. params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
  364. fit = make_fit(mkimage, params)
  365. stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
  366. debug_stdout(stdout)
  367. if read_file(ramdisk) != read_file(ramdisk_out):
  368. fail('Ramdisk not loaded', stdout)
  369. # Configuration with some Loadables
  370. set_test('Kernel + FDT + Ramdisk load + Loadables')
  371. params['loadables_config'] = 'loadables = "kernel@2", "ramdisk@2";'
  372. params['loadables1_load'] = 'load = <%#x>;' % params['loadables1_addr']
  373. params['loadables2_load'] = 'load = <%#x>;' % params['loadables2_addr']
  374. fit = make_fit(mkimage, params)
  375. stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
  376. debug_stdout(stdout)
  377. if read_file(loadables1) != read_file(loadables1_out):
  378. fail('Loadables1 (kernel) not loaded', stdout)
  379. if read_file(loadables2) != read_file(loadables2_out):
  380. fail('Loadables2 (ramdisk) not loaded', stdout)
  381. def run_tests():
  382. """Parse options, run the FIT tests and print the result"""
  383. global base_path, base_dir
  384. # Work in a temporary directory
  385. base_dir = tempfile.mkdtemp()
  386. parser = OptionParser()
  387. parser.add_option('-u', '--u-boot',
  388. default=os.path.join(base_path, 'u-boot'),
  389. help='Select U-Boot sandbox binary')
  390. parser.add_option('-k', '--keep', action='store_true',
  391. help="Don't delete temporary directory even when tests pass")
  392. parser.add_option('-t', '--selftest', action='store_true',
  393. help='Run internal self tests')
  394. (options, args) = parser.parse_args()
  395. # Find the path to U-Boot, and assume mkimage is in its tools/mkimage dir
  396. base_path = os.path.dirname(options.u_boot)
  397. mkimage = os.path.join(base_path, 'tools/mkimage')
  398. # There are a few doctests - handle these here
  399. if options.selftest:
  400. doctest.testmod()
  401. return
  402. title = 'FIT Tests'
  403. print title, '\n', '=' * len(title)
  404. run_fit_test(mkimage, options.u_boot)
  405. print '\nTests passed'
  406. print 'Caveat: this is only a sanity check - test coverage is poor'
  407. # Remove the temporary directory unless we are asked to keep it
  408. if options.keep:
  409. print "Output files are in '%s'" % base_dir
  410. else:
  411. shutil.rmtree(base_dir)
  412. run_tests()