test_fit.py 15 KB

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