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
15 # Note: The above testing requires the Python development package, typically
16 # called python-devel or something similar.
19 from optparse import OptionParser
26 # Enable printing of all U-Boot output
29 # The 'command' library in patman is convenient for running commands
30 base_path = os.path.dirname(sys.argv[0])
31 patman = os.path.join(base_path, '../../tools/patman')
32 sys.path.append(patman)
36 # Define a base ITS which we can adjust using % and a dictionary
41 description = "Chrome OS kernel image with one or more FDT blobs";
46 data = /incbin/("%(kernel)s");
55 data = /incbin/("%(loadables1)s");
65 data = /incbin/("u-boot.dtb");
71 algo = "sha1,rsa2048";
72 key-name-hint = "dev";
77 data = /incbin/("%(ramdisk)s");
86 data = /incbin/("%(loadables2)s");
106 # Define a base FDT - currently we don't use anything in this
111 model = "Sandbox Verified Boot Test";
112 compatible = "sandbox";
115 compatible = "sandbox,reset";
121 # This is the U-Boot script that is run for each test. First load the FIT,
122 # then run the 'bootm' command, then save out memory from the places where
123 # we expect 'bootm' to write things. Then quit.
125 sb load hostfs 0 %(fit_addr)x %(fit)s
126 fdt addr %(fit_addr)x
127 bootm start %(fit_addr)x
129 sb save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
130 sb save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
131 sb save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
132 sb save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
133 sb save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
137 def debug_stdout(stdout):
141 def make_fname(leaf):
142 """Make a temporary filename
145 leaf: Leaf name of file to create (within temporary directory)
151 return os.path.join(base_dir, leaf)
154 """Get the size of a file
157 fname: Filename to check
159 Size of file in bytes
161 return os.stat(fname).st_size
163 def read_file(fname):
164 """Read the contents of a file
167 fname: Filename to read
169 Contents of file as a string
171 with open(fname, 'r') as fd:
175 """Make a sample .dts file and compile it to a .dtb
178 Filename of .dtb file created
180 src = make_fname('u-boot.dts')
181 dtb = make_fname('u-boot.dtb')
182 with open(src, 'w') as fd:
184 command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
187 def make_its(params):
188 """Make a sample .its file with parameters embedded
191 params: Dictionary containing parameters to embed in the %() strings
193 Filename of .its file created
195 its = make_fname('test.its')
196 with open(its, 'w') as fd:
197 print >>fd, base_its % params
200 def make_fit(mkimage, params):
201 """Make a sample .fit file ready for loading
203 This creates a .its script with the selected parameters and uses mkimage to
204 turn this into a .fit image.
207 mkimage: Filename of 'mkimage' utility
208 params: Dictionary containing parameters to embed in the %() strings
210 Filename of .fit file created
212 fit = make_fname('test.fit')
213 its = make_its(params)
214 command.Output(mkimage, '-f', its, fit)
215 with open(make_fname('u-boot.dts'), 'w') as fd:
219 def make_kernel(filename, text):
220 """Make a sample kernel with test data
223 filename: the name of the file you want to create
225 Full path and filename of the kernel it created
227 fname = make_fname(filename)
230 data += 'this %s %d is unlikely to boot\n' % (text, i)
231 with open(fname, 'w') as fd:
235 def make_ramdisk(filename, text):
236 """Make a sample ramdisk with test data
239 Filename of ramdisk created
241 fname = make_fname(filename)
244 data += '%s %d was seldom used in the middle ages\n' % (text, i)
245 with open(fname, 'w') as fd:
249 def find_matching(text, match):
250 """Find a match in a line of text, and return the unmatched line portion
252 This is used to extract a part of a line from some text. The match string
253 is used to locate the line - we use the first line that contains that
256 Once we find a match, we discard the match string itself from the line,
257 and return what remains.
259 TODO: If this function becomes more generally useful, we could change it
260 to use regex and return groups.
263 text: Text to check (each line separated by \n)
264 match: String to search for
266 String containing unmatched portion of line
268 ValueError: If match is not found
270 >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
272 >>> find_matching('first line:10\\nsecond_line:20', 'second line')
273 Traceback (most recent call last):
275 ValueError: Test aborted
276 >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
279 for line in text.splitlines():
280 pos = line.find(match)
282 return line[:pos] + line[pos + len(match):]
284 print "Expected '%s' but not found in output:"
286 raise ValueError('Test aborted')
289 """Set the name of the current test and print a message
299 def fail(msg, stdout):
300 """Raise an error with a helpful failure message
303 msg: Message to display
306 raise ValueError("Test '%s' failed: %s" % (test_name, msg))
308 def run_fit_test(mkimage, u_boot):
309 """Basic sanity check of FIT loading in U-Boot
311 TODO: Almost everything:
312 - hash algorithms - invalid hash/contents should be detected
313 - signature algorithms - invalid sig/contents should be detected
315 - checking that errors are detected like:
318 - invalid configurations
319 - incorrect os/arch/type fields
321 - images too large/small
322 - invalid FDT (e.g. putting a random binary in instead)
323 - default configuration selection
324 - bootm command line parameters should have desired effect
325 - run code coverage to make sure we are testing all the code
329 # Set up invariant files
330 control_dtb = make_dtb()
331 kernel = make_kernel('test-kernel.bin', 'kernel')
332 ramdisk = make_ramdisk('test-ramdisk.bin', 'ramdisk')
333 loadables1 = make_kernel('test-loadables1.bin', 'lenrek')
334 loadables2 = make_ramdisk('test-loadables2.bin', 'ksidmar')
335 kernel_out = make_fname('kernel-out.bin')
336 fdt_out = make_fname('fdt-out.dtb')
337 ramdisk_out = make_fname('ramdisk-out.bin')
338 loadables1_out = make_fname('loadables1-out.bin')
339 loadables2_out = make_fname('loadables2-out.bin')
341 # Set up basic parameters with default values
346 'kernel_out' : kernel_out,
347 'kernel_addr' : 0x40000,
348 'kernel_size' : filesize(kernel),
351 'fdt_addr' : 0x80000,
352 'fdt_size' : filesize(control_dtb),
356 'ramdisk_out' : ramdisk_out,
357 'ramdisk_addr' : 0xc0000,
358 'ramdisk_size' : filesize(ramdisk),
360 'ramdisk_config' : '',
362 'loadables1' : loadables1,
363 'loadables1_out' : loadables1_out,
364 'loadables1_addr' : 0x100000,
365 'loadables1_size' : filesize(loadables1),
366 'loadables1_load' : '',
368 'loadables2' : loadables2,
369 'loadables2_out' : loadables2_out,
370 'loadables2_addr' : 0x140000,
371 'loadables2_size' : filesize(loadables2),
372 'loadables2_load' : '',
374 'loadables_config' : '',
377 # Make a basic FIT and a script to load it
378 fit = make_fit(mkimage, params)
380 cmd = base_script % params
382 # First check that we can load a kernel
383 # We could perhaps reduce duplication with some loss of readability
384 set_test('Kernel load')
385 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
387 if read_file(kernel) != read_file(kernel_out):
388 fail('Kernel not loaded', stdout)
389 if read_file(control_dtb) == read_file(fdt_out):
390 fail('FDT loaded but should be ignored', stdout)
391 if read_file(ramdisk) == read_file(ramdisk_out):
392 fail('Ramdisk loaded but should not be', stdout)
394 # Find out the offset in the FIT where U-Boot has found the FDT
395 line = find_matching(stdout, 'Booting using the FDT blob at ')
396 fit_offset = int(line, 16) - params['fit_addr']
397 fdt_magic = struct.pack('>L', 0xd00dfeed)
398 data = read_file(fit)
400 # Now find where it actually is in the FIT (skip the first word)
401 real_fit_offset = data.find(fdt_magic, 4)
402 if fit_offset != real_fit_offset:
403 fail('U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
404 (fit_offset, real_fit_offset), stdout)
406 # Now a kernel and an FDT
407 set_test('Kernel + FDT load')
408 params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
409 fit = make_fit(mkimage, params)
410 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
412 if read_file(kernel) != read_file(kernel_out):
413 fail('Kernel not loaded', stdout)
414 if read_file(control_dtb) != read_file(fdt_out):
415 fail('FDT not loaded', stdout)
416 if read_file(ramdisk) == read_file(ramdisk_out):
417 fail('Ramdisk loaded but should not be', stdout)
420 set_test('Kernel + FDT + Ramdisk load')
421 params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
422 params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
423 fit = make_fit(mkimage, params)
424 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
426 if read_file(ramdisk) != read_file(ramdisk_out):
427 fail('Ramdisk not loaded', stdout)
429 # Configuration with some Loadables
430 set_test('Kernel + FDT + Ramdisk load + Loadables')
431 params['loadables_config'] = 'loadables = "kernel@2", "ramdisk@2";'
432 params['loadables1_load'] = 'load = <%#x>;' % params['loadables1_addr']
433 params['loadables2_load'] = 'load = <%#x>;' % params['loadables2_addr']
434 fit = make_fit(mkimage, params)
435 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
437 if read_file(loadables1) != read_file(loadables1_out):
438 fail('Loadables1 (kernel) not loaded', stdout)
439 if read_file(loadables2) != read_file(loadables2_out):
440 fail('Loadables2 (ramdisk) not loaded', stdout)
443 """Parse options, run the FIT tests and print the result"""
444 global base_path, base_dir
446 # Work in a temporary directory
447 base_dir = tempfile.mkdtemp()
448 parser = OptionParser()
449 parser.add_option('-u', '--u-boot',
450 default=os.path.join(base_path, 'u-boot'),
451 help='Select U-Boot sandbox binary')
452 parser.add_option('-k', '--keep', action='store_true',
453 help="Don't delete temporary directory even when tests pass")
454 parser.add_option('-t', '--selftest', action='store_true',
455 help='Run internal self tests')
456 (options, args) = parser.parse_args()
458 # Find the path to U-Boot, and assume mkimage is in its tools/mkimage dir
459 base_path = os.path.dirname(options.u_boot)
460 mkimage = os.path.join(base_path, 'tools/mkimage')
462 # There are a few doctests - handle these here
468 print title, '\n', '=' * len(title)
470 run_fit_test(mkimage, options.u_boot)
472 print '\nTests passed'
473 print 'Caveat: this is only a sanity check - test coverage is poor'
475 # Remove the temporary directory unless we are asked to keep it
477 print "Output files are in '%s'" % base_dir
479 shutil.rmtree(base_dir)