test-fit.py 15 KB

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