test-fit.py 12 KB

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