test_fit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2013, Google Inc.
  3. #
  4. # Sanity check of the FIT handling in U-Boot
  5. from __future__ import print_function
  6. import os
  7. import pytest
  8. import struct
  9. import u_boot_utils as util
  10. # Define a base ITS which we can adjust using % and a dictionary
  11. base_its = '''
  12. /dts-v1/;
  13. / {
  14. description = "Chrome OS kernel image with one or more FDT blobs";
  15. #address-cells = <1>;
  16. images {
  17. kernel@1 {
  18. data = /incbin/("%(kernel)s");
  19. type = "kernel";
  20. arch = "sandbox";
  21. os = "linux";
  22. compression = "none";
  23. load = <0x40000>;
  24. entry = <0x8>;
  25. };
  26. kernel@2 {
  27. data = /incbin/("%(loadables1)s");
  28. type = "kernel";
  29. arch = "sandbox";
  30. os = "linux";
  31. compression = "none";
  32. %(loadables1_load)s
  33. entry = <0x0>;
  34. };
  35. fdt@1 {
  36. description = "snow";
  37. data = /incbin/("u-boot.dtb");
  38. type = "flat_dt";
  39. arch = "sandbox";
  40. %(fdt_load)s
  41. compression = "none";
  42. signature@1 {
  43. algo = "sha1,rsa2048";
  44. key-name-hint = "dev";
  45. };
  46. };
  47. ramdisk@1 {
  48. description = "snow";
  49. data = /incbin/("%(ramdisk)s");
  50. type = "ramdisk";
  51. arch = "sandbox";
  52. os = "linux";
  53. %(ramdisk_load)s
  54. compression = "none";
  55. };
  56. ramdisk@2 {
  57. description = "snow";
  58. data = /incbin/("%(loadables2)s");
  59. type = "ramdisk";
  60. arch = "sandbox";
  61. os = "linux";
  62. %(loadables2_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. %(loadables_config)s
  73. };
  74. };
  75. };
  76. '''
  77. # Define a base FDT - currently we don't use anything in this
  78. base_fdt = '''
  79. /dts-v1/;
  80. / {
  81. model = "Sandbox Verified Boot Test";
  82. compatible = "sandbox";
  83. reset@0 {
  84. compatible = "sandbox,reset";
  85. };
  86. };
  87. '''
  88. # This is the U-Boot script that is run for each test. First load the FIT,
  89. # then run the 'bootm' command, then save out memory from the places where
  90. # we expect 'bootm' to write things. Then quit.
  91. base_script = '''
  92. host load hostfs 0 %(fit_addr)x %(fit)s
  93. fdt addr %(fit_addr)x
  94. bootm start %(fit_addr)x
  95. bootm loados
  96. host save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
  97. host save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
  98. host save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
  99. host save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
  100. host save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
  101. '''
  102. @pytest.mark.boardspec('sandbox')
  103. @pytest.mark.buildconfigspec('fit_signature')
  104. @pytest.mark.requiredtool('dtc')
  105. def test_fit(u_boot_console):
  106. def make_fname(leaf):
  107. """Make a temporary filename
  108. Args:
  109. leaf: Leaf name of file to create (within temporary directory)
  110. Return:
  111. Temporary filename
  112. """
  113. return os.path.join(cons.config.build_dir, leaf)
  114. def filesize(fname):
  115. """Get the size of a file
  116. Args:
  117. fname: Filename to check
  118. Return:
  119. Size of file in bytes
  120. """
  121. return os.stat(fname).st_size
  122. def read_file(fname):
  123. """Read the contents of a file
  124. Args:
  125. fname: Filename to read
  126. Returns:
  127. Contents of file as a string
  128. """
  129. with open(fname, 'rb') as fd:
  130. return fd.read()
  131. def make_dtb():
  132. """Make a sample .dts file and compile it to a .dtb
  133. Returns:
  134. Filename of .dtb file created
  135. """
  136. src = make_fname('u-boot.dts')
  137. dtb = make_fname('u-boot.dtb')
  138. with open(src, 'w') as fd:
  139. print(base_fdt, file=fd)
  140. util.run_and_log(cons, ['dtc', src, '-O', 'dtb', '-o', dtb])
  141. return dtb
  142. def make_its(params):
  143. """Make a sample .its file with parameters embedded
  144. Args:
  145. params: Dictionary containing parameters to embed in the %() strings
  146. Returns:
  147. Filename of .its file created
  148. """
  149. its = make_fname('test.its')
  150. with open(its, 'w') as fd:
  151. print(base_its % params, file=fd)
  152. return its
  153. def make_fit(mkimage, params):
  154. """Make a sample .fit file ready for loading
  155. This creates a .its script with the selected parameters and uses mkimage to
  156. turn this into a .fit image.
  157. Args:
  158. mkimage: Filename of 'mkimage' utility
  159. params: Dictionary containing parameters to embed in the %() strings
  160. Return:
  161. Filename of .fit file created
  162. """
  163. fit = make_fname('test.fit')
  164. its = make_its(params)
  165. util.run_and_log(cons, [mkimage, '-f', its, fit])
  166. with open(make_fname('u-boot.dts'), 'w') as fd:
  167. print(base_fdt, file=fd)
  168. return fit
  169. def make_kernel(filename, text):
  170. """Make a sample kernel with test data
  171. Args:
  172. filename: the name of the file you want to create
  173. Returns:
  174. Full path and filename of the kernel it created
  175. """
  176. fname = make_fname(filename)
  177. data = ''
  178. for i in range(100):
  179. data += 'this %s %d is unlikely to boot\n' % (text, i)
  180. with open(fname, 'w') as fd:
  181. print(data, file=fd)
  182. return fname
  183. def make_ramdisk(filename, text):
  184. """Make a sample ramdisk with test data
  185. Returns:
  186. Filename of ramdisk created
  187. """
  188. fname = make_fname(filename)
  189. data = ''
  190. for i in range(100):
  191. data += '%s %d was seldom used in the middle ages\n' % (text, i)
  192. with open(fname, 'w') as fd:
  193. print(data, file=fd)
  194. return fname
  195. def find_matching(text, match):
  196. """Find a match in a line of text, and return the unmatched line portion
  197. This is used to extract a part of a line from some text. The match string
  198. is used to locate the line - we use the first line that contains that
  199. match text.
  200. Once we find a match, we discard the match string itself from the line,
  201. and return what remains.
  202. TODO: If this function becomes more generally useful, we could change it
  203. to use regex and return groups.
  204. Args:
  205. text: Text to check (list of strings, one for each command issued)
  206. match: String to search for
  207. Return:
  208. String containing unmatched portion of line
  209. Exceptions:
  210. ValueError: If match is not found
  211. >>> find_matching(['first line:10', 'second_line:20'], 'first line:')
  212. '10'
  213. >>> find_matching(['first line:10', 'second_line:20'], 'second line')
  214. Traceback (most recent call last):
  215. ...
  216. ValueError: Test aborted
  217. >>> find_matching('first line:10\', 'second_line:20'], 'second_line:')
  218. '20'
  219. >>> find_matching('first line:10\', 'second_line:20\nthird_line:30'],
  220. 'third_line:')
  221. '30'
  222. """
  223. __tracebackhide__ = True
  224. for line in '\n'.join(text).splitlines():
  225. pos = line.find(match)
  226. if pos != -1:
  227. return line[:pos] + line[pos + len(match):]
  228. pytest.fail("Expected '%s' but not found in output")
  229. def check_equal(expected_fname, actual_fname, failure_msg):
  230. """Check that a file matches its expected contents
  231. Args:
  232. expected_fname: Filename containing expected contents
  233. actual_fname: Filename containing actual contents
  234. failure_msg: Message to print on failure
  235. """
  236. expected_data = read_file(expected_fname)
  237. actual_data = read_file(actual_fname)
  238. assert expected_data == actual_data, failure_msg
  239. def check_not_equal(expected_fname, actual_fname, failure_msg):
  240. """Check that a file does not match its expected contents
  241. Args:
  242. expected_fname: Filename containing expected contents
  243. actual_fname: Filename containing actual contents
  244. failure_msg: Message to print on failure
  245. """
  246. expected_data = read_file(expected_fname)
  247. actual_data = read_file(actual_fname)
  248. assert expected_data != actual_data, failure_msg
  249. def run_fit_test(mkimage):
  250. """Basic sanity check of FIT loading in U-Boot
  251. TODO: Almost everything:
  252. - hash algorithms - invalid hash/contents should be detected
  253. - signature algorithms - invalid sig/contents should be detected
  254. - compression
  255. - checking that errors are detected like:
  256. - image overwriting
  257. - missing images
  258. - invalid configurations
  259. - incorrect os/arch/type fields
  260. - empty data
  261. - images too large/small
  262. - invalid FDT (e.g. putting a random binary in instead)
  263. - default configuration selection
  264. - bootm command line parameters should have desired effect
  265. - run code coverage to make sure we are testing all the code
  266. """
  267. # Set up invariant files
  268. control_dtb = make_dtb()
  269. kernel = make_kernel('test-kernel.bin', 'kernel')
  270. ramdisk = make_ramdisk('test-ramdisk.bin', 'ramdisk')
  271. loadables1 = make_kernel('test-loadables1.bin', 'lenrek')
  272. loadables2 = make_ramdisk('test-loadables2.bin', 'ksidmar')
  273. kernel_out = make_fname('kernel-out.bin')
  274. fdt_out = make_fname('fdt-out.dtb')
  275. ramdisk_out = make_fname('ramdisk-out.bin')
  276. loadables1_out = make_fname('loadables1-out.bin')
  277. loadables2_out = make_fname('loadables2-out.bin')
  278. # Set up basic parameters with default values
  279. params = {
  280. 'fit_addr' : 0x1000,
  281. 'kernel' : kernel,
  282. 'kernel_out' : kernel_out,
  283. 'kernel_addr' : 0x40000,
  284. 'kernel_size' : filesize(kernel),
  285. 'fdt_out' : fdt_out,
  286. 'fdt_addr' : 0x80000,
  287. 'fdt_size' : filesize(control_dtb),
  288. 'fdt_load' : '',
  289. 'ramdisk' : ramdisk,
  290. 'ramdisk_out' : ramdisk_out,
  291. 'ramdisk_addr' : 0xc0000,
  292. 'ramdisk_size' : filesize(ramdisk),
  293. 'ramdisk_load' : '',
  294. 'ramdisk_config' : '',
  295. 'loadables1' : loadables1,
  296. 'loadables1_out' : loadables1_out,
  297. 'loadables1_addr' : 0x100000,
  298. 'loadables1_size' : filesize(loadables1),
  299. 'loadables1_load' : '',
  300. 'loadables2' : loadables2,
  301. 'loadables2_out' : loadables2_out,
  302. 'loadables2_addr' : 0x140000,
  303. 'loadables2_size' : filesize(loadables2),
  304. 'loadables2_load' : '',
  305. 'loadables_config' : '',
  306. }
  307. # Make a basic FIT and a script to load it
  308. fit = make_fit(mkimage, params)
  309. params['fit'] = fit
  310. cmd = base_script % params
  311. # First check that we can load a kernel
  312. # We could perhaps reduce duplication with some loss of readability
  313. cons.config.dtb = control_dtb
  314. cons.restart_uboot()
  315. with cons.log.section('Kernel load'):
  316. output = cons.run_command_list(cmd.splitlines())
  317. check_equal(kernel, kernel_out, 'Kernel not loaded')
  318. check_not_equal(control_dtb, fdt_out,
  319. 'FDT loaded but should be ignored')
  320. check_not_equal(ramdisk, ramdisk_out,
  321. 'Ramdisk loaded but should not be')
  322. # Find out the offset in the FIT where U-Boot has found the FDT
  323. line = find_matching(output, 'Booting using the fdt blob at ')
  324. fit_offset = int(line, 16) - params['fit_addr']
  325. fdt_magic = struct.pack('>L', 0xd00dfeed)
  326. data = read_file(fit)
  327. # Now find where it actually is in the FIT (skip the first word)
  328. real_fit_offset = data.find(fdt_magic, 4)
  329. assert fit_offset == real_fit_offset, (
  330. 'U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
  331. (fit_offset, real_fit_offset))
  332. # Now a kernel and an FDT
  333. with cons.log.section('Kernel + FDT load'):
  334. params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
  335. fit = make_fit(mkimage, params)
  336. cons.restart_uboot()
  337. output = cons.run_command_list(cmd.splitlines())
  338. check_equal(kernel, kernel_out, 'Kernel not loaded')
  339. check_equal(control_dtb, fdt_out, 'FDT not loaded')
  340. check_not_equal(ramdisk, ramdisk_out,
  341. 'Ramdisk loaded but should not be')
  342. # Try a ramdisk
  343. with cons.log.section('Kernel + FDT + Ramdisk load'):
  344. params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
  345. params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
  346. fit = make_fit(mkimage, params)
  347. cons.restart_uboot()
  348. output = cons.run_command_list(cmd.splitlines())
  349. check_equal(ramdisk, ramdisk_out, 'Ramdisk not loaded')
  350. # Configuration with some Loadables
  351. with cons.log.section('Kernel + FDT + Ramdisk load + Loadables'):
  352. params['loadables_config'] = 'loadables = "kernel@2", "ramdisk@2";'
  353. params['loadables1_load'] = ('load = <%#x>;' %
  354. params['loadables1_addr'])
  355. params['loadables2_load'] = ('load = <%#x>;' %
  356. params['loadables2_addr'])
  357. fit = make_fit(mkimage, params)
  358. cons.restart_uboot()
  359. output = cons.run_command_list(cmd.splitlines())
  360. check_equal(loadables1, loadables1_out,
  361. 'Loadables1 (kernel) not loaded')
  362. check_equal(loadables2, loadables2_out,
  363. 'Loadables2 (ramdisk) not loaded')
  364. cons = u_boot_console
  365. try:
  366. # We need to use our own device tree file. Remember to restore it
  367. # afterwards.
  368. old_dtb = cons.config.dtb
  369. mkimage = cons.config.build_dir + '/tools/mkimage'
  370. run_fit_test(mkimage)
  371. finally:
  372. # Go back to the original U-Boot with the correct dtb.
  373. cons.config.dtb = old_dtb
  374. cons.restart_uboot()