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");
53 data = /incbin/("u-boot.dtb");
59 algo = "sha1,rsa2048";
60 key-name-hint = "dev";
65 data = /incbin/("%(ramdisk)s");
84 # Define a base FDT - currently we don't use anything in this
89 model = "Sandbox Verified Boot Test";
90 compatible = "sandbox";
95 # This is the U-Boot script that is run for each test. First load the fit,
96 # then do the 'bootm' command, then save out memory from the places where
97 # we expect 'bootm' to write things. Then quit.
99 sb load hostfs 0 %(fit_addr)x %(fit)s
100 fdt addr %(fit_addr)x
101 bootm start %(fit_addr)x
103 sb save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
104 sb save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
105 sb save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
109 def debug_stdout(stdout):
113 def make_fname(leaf):
114 """Make a temporary filename
117 leaf: Leaf name of file to create (within temporary directory)
123 return os.path.join(base_dir, leaf)
126 """Get the size of a file
129 fname: Filename to check
131 Size of file in bytes
133 return os.stat(fname).st_size
135 def read_file(fname):
136 """Read the contents of a file
139 fname: Filename to read
141 Contents of file as a string
143 with open(fname, 'r') as fd:
147 """Make a sample .dts file and compile it to a .dtb
150 Filename of .dtb file created
152 src = make_fname('u-boot.dts')
153 dtb = make_fname('u-boot.dtb')
154 with open(src, 'w') as fd:
156 command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
159 def make_its(params):
160 """Make a sample .its file with parameters embedded
163 params: Dictionary containing parameters to embed in the %() strings
165 Filename of .its file created
167 its = make_fname('test.its')
168 with open(its, 'w') as fd:
169 print >>fd, base_its % params
172 def make_fit(mkimage, params):
173 """Make a sample .fit file ready for loading
175 This creates a .its script with the selected parameters and uses mkimage to
176 turn this into a .fit image.
179 mkimage: Filename of 'mkimage' utility
180 params: Dictionary containing parameters to embed in the %() strings
182 Filename of .fit file created
184 fit = make_fname('test.fit')
185 its = make_its(params)
186 command.Output(mkimage, '-f', its, fit)
187 with open(make_fname('u-boot.dts'), 'w') as fd:
192 """Make a sample kernel with test data
195 Filename of kernel created
197 fname = make_fname('test-kernel.bin')
200 data += 'this kernel %d is unlikely to boot\n' % i
201 with open(fname, 'w') as fd:
206 """Make a sample ramdisk with test data
209 Filename of ramdisk created
211 fname = make_fname('test-ramdisk.bin')
214 data += 'ramdisk %d was seldom used in the middle ages\n' % i
215 with open(fname, 'w') as fd:
219 def find_matching(text, match):
220 """Find a match in a line of text, and return the unmatched line portion
222 This is used to extract a part of a line from some text. The match string
223 is used to locate the line - we use the first line that contains that
226 Once we find a match, we discard the match string itself from the line,
227 and return what remains.
229 TODO: If this function becomes more generally useful, we could change it
230 to use regex and return groups.
233 text: Text to check (each line separated by \n)
234 match: String to search for
236 String containing unmatched portion of line
238 ValueError: If match is not found
240 >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
242 >>> find_matching('first line:10\\nsecond_line:20', 'second linex')
243 Traceback (most recent call last):
245 ValueError: Test aborted
246 >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
249 for line in text.splitlines():
250 pos = line.find(match)
252 return line[:pos] + line[pos + len(match):]
254 print "Expected '%s' but not found in output:"
256 raise ValueError('Test aborted')
259 """Set the name of the current test and print a message
269 def fail(msg, stdout):
270 """Raise an error with a helpful failure message
273 msg: Message to display
276 raise ValueError("Test '%s' failed: %s" % (test_name, msg))
278 def run_fit_test(mkimage, u_boot):
279 """Basic sanity check of FIT loading in U-Boot
281 TODO: Almost everything:
282 - hash algorithms - invalid hash/contents should be detected
283 - signature algorithms - invalid sig/contents should be detected
285 - checking that errors are detected like:
288 - invalid configurations
289 - incorrect os/arch/type fields
291 - images too large/small
292 - invalid FDT (e.g. putting a random binary in instead)
293 - default configuration selection
294 - bootm command line parameters should have desired effect
295 - run code coverage to make sure we are testing all the code
299 # Set up invariant files
300 control_dtb = make_dtb()
301 kernel = make_kernel()
302 ramdisk = make_ramdisk()
303 kernel_out = make_fname('kernel-out.bin')
304 fdt_out = make_fname('fdt-out.dtb')
305 ramdisk_out = make_fname('ramdisk-out.bin')
307 # Set up basic parameters with default values
312 'kernel_out' : kernel_out,
313 'kernel_addr' : 0x40000,
314 'kernel_size' : filesize(kernel),
317 'fdt_addr' : 0x80000,
318 'fdt_size' : filesize(control_dtb),
322 'ramdisk_out' : ramdisk_out,
323 'ramdisk_addr' : 0xc0000,
324 'ramdisk_size' : filesize(ramdisk),
326 'ramdisk_config' : '',
329 # Make a basic FIT and a script to load it
330 fit = make_fit(mkimage, params)
332 cmd = base_script % params
334 # First check that we can load a kernel
335 # We could perhaps reduce duplication with some loss of readability
336 set_test('Kernel load')
337 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
339 if read_file(kernel) != read_file(kernel_out):
340 fail('Kernel not loaded', stdout)
341 if read_file(control_dtb) == read_file(fdt_out):
342 fail('FDT loaded but should be ignored', stdout)
343 if read_file(ramdisk) == read_file(ramdisk_out):
344 fail('Ramdisk loaded but should not be', stdout)
346 # Find out the offset in the FIT where U-Boot has found the FDT
347 line = find_matching(stdout, 'Booting using the fdt blob at ')
348 fit_offset = int(line, 16) - params['fit_addr']
349 fdt_magic = struct.pack('>L', 0xd00dfeed)
350 data = read_file(fit)
352 # Now find where it actually is in the FIT (skip the first word)
353 real_fit_offset = data.find(fdt_magic, 4)
354 if fit_offset != real_fit_offset:
355 fail('U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
356 (fit_offset, real_fit_offset), stdout)
358 # Now a kernel and an FDT
359 set_test('Kernel + FDT load')
360 params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
361 fit = make_fit(mkimage, params)
362 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
364 if read_file(kernel) != read_file(kernel_out):
365 fail('Kernel not loaded', stdout)
366 if read_file(control_dtb) != read_file(fdt_out):
367 fail('FDT not loaded', stdout)
368 if read_file(ramdisk) == read_file(ramdisk_out):
369 fail('Ramdisk loaded but should not be', stdout)
372 set_test('Kernel + FDT + Ramdisk load')
373 params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
374 params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
375 fit = make_fit(mkimage, params)
376 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
378 if read_file(ramdisk) != read_file(ramdisk_out):
379 fail('Ramdisk not loaded', stdout)
382 """Parse options, run the FIT tests and print the result"""
383 global base_path, base_dir
385 # Work in a temporary directory
386 base_dir = tempfile.mkdtemp()
387 parser = OptionParser()
388 parser.add_option('-u', '--u-boot',
389 default=os.path.join(base_path, 'u-boot'),
390 help='Select U-Boot sandbox binary')
391 parser.add_option('-k', '--keep', action='store_true',
392 help="Don't delete temporary directory even when tests pass")
393 parser.add_option('-t', '--selftest', action='store_true',
394 help='Run internal self tests')
395 (options, args) = parser.parse_args()
397 # Find the path to U-Boot, and assume mkimage is in its tools/mkimage dir
398 base_path = os.path.dirname(options.u_boot)
399 mkimage = os.path.join(base_path, 'tools/mkimage')
401 # There are a few doctests - handle these here
407 print title, '\n', '=' * len(title)
409 run_fit_test(mkimage, options.u_boot)
411 print '\nTests passed'
412 print 'Caveat: this is only a sanity check - test coverage is poor'
414 # Remove the tempoerary directory unless we are asked to keep it
416 print "Output files are in '%s'" % base_dir
418 shutil.rmtree(base_dir)