test-fit.py 13 KB

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