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 # The 'command' library in patman is convenient for running commands
24 base_path = os.path.dirname(sys.argv[0])
25 patman = os.path.join(base_path, '../../tools/patman')
26 sys.path.append(patman)
30 # Define a base ITS which we can adjust using % and a dictionary
35 description = "Chrome OS kernel image with one or more FDT blobs";
40 data = /incbin/("%(kernel)s");
50 data = /incbin/("u-boot.dtb");
56 algo = "sha1,rsa2048";
57 key-name-hint = "dev";
62 data = /incbin/("%(ramdisk)s");
81 # Define a base FDT - currently we don't use anything in this
86 model = "Sandbox Verified Boot Test";
87 compatible = "sandbox";
92 # This is the U-Boot script that is run for each test. First load the fit,
93 # then do the 'bootm' command, then save out memory from the places where
94 # we expect 'bootm' to write things. Then quit.
96 sb load hostfs 0 %(fit_addr)x %(fit)s
98 bootm start %(fit_addr)x
100 sb save hostfs 0 %(kernel_out)s %(kernel_addr)x %(kernel_size)x
101 sb save hostfs 0 %(fdt_out)s %(fdt_addr)x %(fdt_size)x
102 sb save hostfs 0 %(ramdisk_out)s %(ramdisk_addr)x %(ramdisk_size)x
106 def make_fname(leaf):
107 """Make a temporary filename
110 leaf: Leaf name of file to create (within temporary directory)
116 return os.path.join(base_dir, leaf)
119 """Get the size of a file
122 fname: Filename to check
124 Size of file in bytes
126 return os.stat(fname).st_size
128 def read_file(fname):
129 """Read the contents of a file
132 fname: Filename to read
134 Contents of file as a string
136 with open(fname, 'r') as fd:
140 """Make a sample .dts file and compile it to a .dtb
143 Filename of .dtb file created
145 src = make_fname('u-boot.dts')
146 dtb = make_fname('u-boot.dtb')
147 with open(src, 'w') as fd:
149 command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
152 def make_its(params):
153 """Make a sample .its file with parameters embedded
156 params: Dictionary containing parameters to embed in the %() strings
158 Filename of .its file created
160 its = make_fname('test.its')
161 with open(its, 'w') as fd:
162 print >>fd, base_its % params
165 def make_fit(mkimage, params):
166 """Make a sample .fit file ready for loading
168 This creates a .its script with the selected parameters and uses mkimage to
169 turn this into a .fit image.
172 mkimage: Filename of 'mkimage' utility
173 params: Dictionary containing parameters to embed in the %() strings
175 Filename of .fit file created
177 fit = make_fname('test.fit')
178 its = make_its(params)
179 command.Output(mkimage, '-f', its, fit)
180 with open(make_fname('u-boot.dts'), 'w') as fd:
185 """Make a sample kernel with test data
188 Filename of kernel created
190 fname = make_fname('test-kernel.bin')
193 data += 'this kernel %d is unlikely to boot\n' % i
194 with open(fname, 'w') as fd:
199 """Make a sample ramdisk with test data
202 Filename of ramdisk created
204 fname = make_fname('test-ramdisk.bin')
207 data += 'ramdisk %d was seldom used in the middle ages\n' % i
208 with open(fname, 'w') as fd:
212 def find_matching(text, match):
213 """Find a match in a line of text, and return the unmatched line portion
215 This is used to extract a part of a line from some text. The match string
216 is used to locate the line - we use the first line that contains that
219 Once we find a match, we discard the match string itself from the line,
220 and return what remains.
222 TODO: If this function becomes more generally useful, we could change it
223 to use regex and return groups.
226 text: Text to check (each line separated by \n)
227 match: String to search for
229 String containing unmatched portion of line
231 ValueError: If match is not found
233 >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
235 >>> find_matching('first line:10\\nsecond_line:20', 'second linex')
236 Traceback (most recent call last):
238 ValueError: Test aborted
239 >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
242 for line in text.splitlines():
243 pos = line.find(match)
245 return line[:pos] + line[pos + len(match):]
247 print "Expected '%s' but not found in output:"
249 raise ValueError('Test aborted')
252 """Set the name of the current test and print a message
262 def fail(msg, stdout):
263 """Raise an error with a helpful failure message
266 msg: Message to display
269 raise ValueError("Test '%s' failed: %s" % (test_name, msg))
271 def run_fit_test(mkimage, u_boot):
272 """Basic sanity check of FIT loading in U-Boot
274 TODO: Almost everything:
275 - hash algorithms - invalid hash/contents should be detected
276 - signature algorithms - invalid sig/contents should be detected
278 - checking that errors are detected like:
281 - invalid configurations
282 - incorrect os/arch/type fields
284 - images too large/small
285 - invalid FDT (e.g. putting a random binary in instead)
286 - default configuration selection
287 - bootm command line parameters should have desired effect
288 - run code coverage to make sure we are testing all the code
292 # Set up invariant files
293 control_dtb = make_dtb()
294 kernel = make_kernel()
295 ramdisk = make_ramdisk()
296 kernel_out = make_fname('kernel-out.bin')
297 fdt_out = make_fname('fdt-out.dtb')
298 ramdisk_out = make_fname('ramdisk-out.bin')
300 # Set up basic parameters with default values
305 'kernel_out' : kernel_out,
306 'kernel_addr' : 0x40000,
307 'kernel_size' : filesize(kernel),
310 'fdt_addr' : 0x80000,
311 'fdt_size' : filesize(control_dtb),
315 'ramdisk_out' : ramdisk_out,
316 'ramdisk_addr' : 0xc0000,
317 'ramdisk_size' : filesize(ramdisk),
319 'ramdisk_config' : '',
322 # Make a basic FIT and a script to load it
323 fit = make_fit(mkimage, params)
325 cmd = base_script % params
327 # First check that we can load a kernel
328 # We could perhaps reduce duplication with some loss of readability
329 set_test('Kernel load')
330 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
331 if read_file(kernel) != read_file(kernel_out):
332 fail('Kernel not loaded', stdout)
333 if read_file(control_dtb) == read_file(fdt_out):
334 fail('FDT loaded but should be ignored', stdout)
335 if read_file(ramdisk) == read_file(ramdisk_out):
336 fail('Ramdisk loaded but should not be', stdout)
338 # Find out the offset in the FIT where U-Boot has found the FDT
339 line = find_matching(stdout, 'Booting using the fdt blob at ')
340 fit_offset = int(line, 16) - params['fit_addr']
341 fdt_magic = struct.pack('>L', 0xd00dfeed)
342 data = read_file(fit)
344 # Now find where it actually is in the FIT (skip the first word)
345 real_fit_offset = data.find(fdt_magic, 4)
346 if fit_offset != real_fit_offset:
347 fail('U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
348 (fit_offset, real_fit_offset), stdout)
350 # Now a kernel and an FDT
351 set_test('Kernel + FDT load')
352 params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
353 fit = make_fit(mkimage, params)
354 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
355 if read_file(kernel) != read_file(kernel_out):
356 fail('Kernel not loaded', stdout)
357 if read_file(control_dtb) != read_file(fdt_out):
358 fail('FDT not loaded', stdout)
359 if read_file(ramdisk) == read_file(ramdisk_out):
360 fail('Ramdisk loaded but should not be', stdout)
363 set_test('Kernel + FDT + Ramdisk load')
364 params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
365 params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
366 fit = make_fit(mkimage, params)
367 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
368 if read_file(ramdisk) != read_file(ramdisk_out):
369 fail('Ramdisk not loaded', stdout)
372 """Parse options, run the FIT tests and print the result"""
373 global base_path, base_dir
375 # Work in a temporary directory
376 base_dir = tempfile.mkdtemp()
377 parser = OptionParser()
378 parser.add_option('-u', '--u-boot',
379 default=os.path.join(base_path, 'u-boot'),
380 help='Select U-Boot sandbox binary')
381 parser.add_option('-k', '--keep', action='store_true',
382 help="Don't delete temporary directory even when tests pass")
383 parser.add_option('-t', '--selftest', action='store_true',
384 help='Run internal self tests')
385 (options, args) = parser.parse_args()
387 # Find the path to U-Boot, and assume mkimage is in its tools/mkimage dir
388 base_path = os.path.dirname(options.u_boot)
389 mkimage = os.path.join(base_path, 'tools/mkimage')
391 # There are a few doctests - handle these here
397 print title, '\n', '=' * len(title)
399 run_fit_test(mkimage, options.u_boot)
401 print '\nTests passed'
402 print 'Caveat: this is only a sanity check - test coverage is poor'
404 # Remove the tempoerary directory unless we are asked to keep it
406 print "Output files are in '%s'" % base_dir
408 shutil.rmtree(base_dir)