3 # Copyright (c) 2013, Google Inc.
5 # Sanity check of the FIT handling in U-Boot
7 # SPDX-License-Identifier: GPL-2.0+
11 # make O=sandbox sandbox_config
13 # ./test/image/test-fit.py -u sandbox/u-boot
16 from optparse import OptionParser
23 # Enable printing of all U-Boot output
26 # The 'command' library in patman is convenient for running commands
27 base_path = os.path.dirname(sys.argv[0])
28 patman = os.path.join(base_path, '../../tools/patman')
29 sys.path.append(patman)
33 # Define a base ITS which we can adjust using % and a dictionary
38 description = "Chrome OS kernel image with one or more FDT blobs";
43 data = /incbin/("%(kernel)s");
52 data = /incbin/("%(loadables1)s");
62 data = /incbin/("u-boot.dtb");
68 algo = "sha1,rsa2048";
69 key-name-hint = "dev";
74 data = /incbin/("%(ramdisk)s");
83 data = /incbin/("%(loadables2)s");
103 # Define a base FDT - currently we don't use anything in this
108 model = "Sandbox Verified Boot Test";
109 compatible = "sandbox";
112 compatible = "sandbox,reset";
118 # This is the U-Boot script that is run for each test. First load the fit,
119 # then do the 'bootm' command, then save out memory from the places where
120 # we expect 'bootm' to write things. Then quit.
122 sb load hostfs 0 %(fit_addr)x %(fit)s
123 fdt addr %(fit_addr)x
124 bootm start %(fit_addr)x
126 sb save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
127 sb save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
128 sb save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
129 sb save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
130 sb save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
134 def debug_stdout(stdout):
138 def make_fname(leaf):
139 """Make a temporary filename
142 leaf: Leaf name of file to create (within temporary directory)
148 return os.path.join(base_dir, leaf)
151 """Get the size of a file
154 fname: Filename to check
156 Size of file in bytes
158 return os.stat(fname).st_size
160 def read_file(fname):
161 """Read the contents of a file
164 fname: Filename to read
166 Contents of file as a string
168 with open(fname, 'r') as fd:
172 """Make a sample .dts file and compile it to a .dtb
175 Filename of .dtb file created
177 src = make_fname('u-boot.dts')
178 dtb = make_fname('u-boot.dtb')
179 with open(src, 'w') as fd:
181 command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
184 def make_its(params):
185 """Make a sample .its file with parameters embedded
188 params: Dictionary containing parameters to embed in the %() strings
190 Filename of .its file created
192 its = make_fname('test.its')
193 with open(its, 'w') as fd:
194 print >>fd, base_its % params
197 def make_fit(mkimage, params):
198 """Make a sample .fit file ready for loading
200 This creates a .its script with the selected parameters and uses mkimage to
201 turn this into a .fit image.
204 mkimage: Filename of 'mkimage' utility
205 params: Dictionary containing parameters to embed in the %() strings
207 Filename of .fit file created
209 fit = make_fname('test.fit')
210 its = make_its(params)
211 command.Output(mkimage, '-f', its, fit)
212 with open(make_fname('u-boot.dts'), 'w') as fd:
216 def make_kernel(filename, text):
217 """Make a sample kernel with test data
220 filename: the name of the file you want to create
222 Full path and filename of the kernel it created
224 fname = make_fname(filename)
227 data += 'this %s %d is unlikely to boot\n' % (text, i)
228 with open(fname, 'w') as fd:
232 def make_ramdisk(filename, text):
233 """Make a sample ramdisk with test data
236 Filename of ramdisk created
238 fname = make_fname(filename)
241 data += '%s %d was seldom used in the middle ages\n' % (text, i)
242 with open(fname, 'w') as fd:
246 def find_matching(text, match):
247 """Find a match in a line of text, and return the unmatched line portion
249 This is used to extract a part of a line from some text. The match string
250 is used to locate the line - we use the first line that contains that
253 Once we find a match, we discard the match string itself from the line,
254 and return what remains.
256 TODO: If this function becomes more generally useful, we could change it
257 to use regex and return groups.
260 text: Text to check (each line separated by \n)
261 match: String to search for
263 String containing unmatched portion of line
265 ValueError: If match is not found
267 >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
269 >>> find_matching('first line:10\\nsecond_line:20', 'second linex')
270 Traceback (most recent call last):
272 ValueError: Test aborted
273 >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
276 for line in text.splitlines():
277 pos = line.find(match)
279 return line[:pos] + line[pos + len(match):]
281 print "Expected '%s' but not found in output:"
283 raise ValueError('Test aborted')
286 """Set the name of the current test and print a message
296 def fail(msg, stdout):
297 """Raise an error with a helpful failure message
300 msg: Message to display
303 raise ValueError("Test '%s' failed: %s" % (test_name, msg))
305 def run_fit_test(mkimage, u_boot):
306 """Basic sanity check of FIT loading in U-Boot
308 TODO: Almost everything:
309 - hash algorithms - invalid hash/contents should be detected
310 - signature algorithms - invalid sig/contents should be detected
312 - checking that errors are detected like:
315 - invalid configurations
316 - incorrect os/arch/type fields
318 - images too large/small
319 - invalid FDT (e.g. putting a random binary in instead)
320 - default configuration selection
321 - bootm command line parameters should have desired effect
322 - run code coverage to make sure we are testing all the code
326 # Set up invariant files
327 control_dtb = make_dtb()
328 kernel = make_kernel('test-kernel.bin', 'kernel')
329 ramdisk = make_ramdisk('test-ramdisk.bin', 'ramdisk')
330 loadables1 = make_kernel('test-loadables1.bin', 'lenrek')
331 loadables2 = make_ramdisk('test-loadables2.bin', 'ksidmar')
332 kernel_out = make_fname('kernel-out.bin')
333 fdt_out = make_fname('fdt-out.dtb')
334 ramdisk_out = make_fname('ramdisk-out.bin')
335 loadables1_out = make_fname('loadables1-out.bin')
336 loadables2_out = make_fname('loadables2-out.bin')
338 # Set up basic parameters with default values
343 'kernel_out' : kernel_out,
344 'kernel_addr' : 0x40000,
345 'kernel_size' : filesize(kernel),
348 'fdt_addr' : 0x80000,
349 'fdt_size' : filesize(control_dtb),
353 'ramdisk_out' : ramdisk_out,
354 'ramdisk_addr' : 0xc0000,
355 'ramdisk_size' : filesize(ramdisk),
357 'ramdisk_config' : '',
359 'loadables1' : loadables1,
360 'loadables1_out' : loadables1_out,
361 'loadables1_addr' : 0x100000,
362 'loadables1_size' : filesize(loadables1),
363 'loadables1_load' : '',
365 'loadables2' : loadables2,
366 'loadables2_out' : loadables2_out,
367 'loadables2_addr' : 0x140000,
368 'loadables2_size' : filesize(loadables2),
369 'loadables2_load' : '',
371 'loadables_config' : '',
374 # Make a basic FIT and a script to load it
375 fit = make_fit(mkimage, params)
377 cmd = base_script % params
379 # First check that we can load a kernel
380 # We could perhaps reduce duplication with some loss of readability
381 set_test('Kernel load')
382 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
384 if read_file(kernel) != read_file(kernel_out):
385 fail('Kernel not loaded', stdout)
386 if read_file(control_dtb) == read_file(fdt_out):
387 fail('FDT loaded but should be ignored', stdout)
388 if read_file(ramdisk) == read_file(ramdisk_out):
389 fail('Ramdisk loaded but should not be', stdout)
391 # Find out the offset in the FIT where U-Boot has found the FDT
392 line = find_matching(stdout, 'Booting using the fdt blob at ')
393 fit_offset = int(line, 16) - params['fit_addr']
394 fdt_magic = struct.pack('>L', 0xd00dfeed)
395 data = read_file(fit)
397 # Now find where it actually is in the FIT (skip the first word)
398 real_fit_offset = data.find(fdt_magic, 4)
399 if fit_offset != real_fit_offset:
400 fail('U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
401 (fit_offset, real_fit_offset), stdout)
403 # Now a kernel and an FDT
404 set_test('Kernel + FDT load')
405 params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
406 fit = make_fit(mkimage, params)
407 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
409 if read_file(kernel) != read_file(kernel_out):
410 fail('Kernel not loaded', stdout)
411 if read_file(control_dtb) != read_file(fdt_out):
412 fail('FDT not loaded', stdout)
413 if read_file(ramdisk) == read_file(ramdisk_out):
414 fail('Ramdisk loaded but should not be', stdout)
417 set_test('Kernel + FDT + Ramdisk load')
418 params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
419 params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
420 fit = make_fit(mkimage, params)
421 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
423 if read_file(ramdisk) != read_file(ramdisk_out):
424 fail('Ramdisk not loaded', stdout)
426 # Configuration with some Loadables
427 set_test('Kernel + FDT + Ramdisk load + Loadables')
428 params['loadables_config'] = 'loadables = "kernel@2", "ramdisk@2";'
429 params['loadables1_load'] = 'load = <%#x>;' % params['loadables1_addr']
430 params['loadables2_load'] = 'load = <%#x>;' % params['loadables2_addr']
431 fit = make_fit(mkimage, params)
432 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
434 if read_file(loadables1) != read_file(loadables1_out):
435 fail('Loadables1 (kernel) not loaded', stdout)
436 if read_file(loadables2) != read_file(loadables2_out):
437 fail('Loadables2 (ramdisk) not loaded', stdout)
440 """Parse options, run the FIT tests and print the result"""
441 global base_path, base_dir
443 # Work in a temporary directory
444 base_dir = tempfile.mkdtemp()
445 parser = OptionParser()
446 parser.add_option('-u', '--u-boot',
447 default=os.path.join(base_path, 'u-boot'),
448 help='Select U-Boot sandbox binary')
449 parser.add_option('-k', '--keep', action='store_true',
450 help="Don't delete temporary directory even when tests pass")
451 parser.add_option('-t', '--selftest', action='store_true',
452 help='Run internal self tests')
453 (options, args) = parser.parse_args()
455 # Find the path to U-Boot, and assume mkimage is in its tools/mkimage dir
456 base_path = os.path.dirname(options.u_boot)
457 mkimage = os.path.join(base_path, 'tools/mkimage')
459 # There are a few doctests - handle these here
465 print title, '\n', '=' * len(title)
467 run_fit_test(mkimage, options.u_boot)
469 print '\nTests passed'
470 print 'Caveat: this is only a sanity check - test coverage is poor'
472 # Remove the tempoerary directory unless we are asked to keep it
474 print "Output files are in '%s'" % base_dir
476 shutil.rmtree(base_dir)