test-fit.py 15 KB

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