test-fit.py 12 KB

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