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";
114 # This is the U-Boot script that is run for each test. First load the fit,
115 # then do the 'bootm' command, then save out memory from the places where
116 # we expect 'bootm' to write things. Then quit.
118 sb load hostfs 0 %(fit_addr)x %(fit)s
119 fdt addr %(fit_addr)x
120 bootm start %(fit_addr)x
122 sb save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
123 sb save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
124 sb save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
125 sb save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
126 sb save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
130 def debug_stdout(stdout):
134 def make_fname(leaf):
135 """Make a temporary filename
138 leaf: Leaf name of file to create (within temporary directory)
144 return os.path.join(base_dir, leaf)
147 """Get the size of a file
150 fname: Filename to check
152 Size of file in bytes
154 return os.stat(fname).st_size
156 def read_file(fname):
157 """Read the contents of a file
160 fname: Filename to read
162 Contents of file as a string
164 with open(fname, 'r') as fd:
168 """Make a sample .dts file and compile it to a .dtb
171 Filename of .dtb file created
173 src = make_fname('u-boot.dts')
174 dtb = make_fname('u-boot.dtb')
175 with open(src, 'w') as fd:
177 command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
180 def make_its(params):
181 """Make a sample .its file with parameters embedded
184 params: Dictionary containing parameters to embed in the %() strings
186 Filename of .its file created
188 its = make_fname('test.its')
189 with open(its, 'w') as fd:
190 print >>fd, base_its % params
193 def make_fit(mkimage, params):
194 """Make a sample .fit file ready for loading
196 This creates a .its script with the selected parameters and uses mkimage to
197 turn this into a .fit image.
200 mkimage: Filename of 'mkimage' utility
201 params: Dictionary containing parameters to embed in the %() strings
203 Filename of .fit file created
205 fit = make_fname('test.fit')
206 its = make_its(params)
207 command.Output(mkimage, '-f', its, fit)
208 with open(make_fname('u-boot.dts'), 'w') as fd:
212 def make_kernel(filename, text):
213 """Make a sample kernel with test data
216 filename: the name of the file you want to create
218 Full path and filename of the kernel it created
220 fname = make_fname(filename)
223 data += 'this %s %d is unlikely to boot\n' % (text, i)
224 with open(fname, 'w') as fd:
228 def make_ramdisk(filename, text):
229 """Make a sample ramdisk with test data
232 Filename of ramdisk created
234 fname = make_fname(filename)
237 data += '%s %d was seldom used in the middle ages\n' % (text, i)
238 with open(fname, 'w') as fd:
242 def find_matching(text, match):
243 """Find a match in a line of text, and return the unmatched line portion
245 This is used to extract a part of a line from some text. The match string
246 is used to locate the line - we use the first line that contains that
249 Once we find a match, we discard the match string itself from the line,
250 and return what remains.
252 TODO: If this function becomes more generally useful, we could change it
253 to use regex and return groups.
256 text: Text to check (each line separated by \n)
257 match: String to search for
259 String containing unmatched portion of line
261 ValueError: If match is not found
263 >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
265 >>> find_matching('first line:10\\nsecond_line:20', 'second linex')
266 Traceback (most recent call last):
268 ValueError: Test aborted
269 >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
272 for line in text.splitlines():
273 pos = line.find(match)
275 return line[:pos] + line[pos + len(match):]
277 print "Expected '%s' but not found in output:"
279 raise ValueError('Test aborted')
282 """Set the name of the current test and print a message
292 def fail(msg, stdout):
293 """Raise an error with a helpful failure message
296 msg: Message to display
299 raise ValueError("Test '%s' failed: %s" % (test_name, msg))
301 def run_fit_test(mkimage, u_boot):
302 """Basic sanity check of FIT loading in U-Boot
304 TODO: Almost everything:
305 - hash algorithms - invalid hash/contents should be detected
306 - signature algorithms - invalid sig/contents should be detected
308 - checking that errors are detected like:
311 - invalid configurations
312 - incorrect os/arch/type fields
314 - images too large/small
315 - invalid FDT (e.g. putting a random binary in instead)
316 - default configuration selection
317 - bootm command line parameters should have desired effect
318 - run code coverage to make sure we are testing all the code
322 # Set up invariant files
323 control_dtb = make_dtb()
324 kernel = make_kernel('test-kernel.bin', 'kernel')
325 ramdisk = make_ramdisk('test-ramdisk.bin', 'ramdisk')
326 loadables1 = make_kernel('test-loadables1.bin', 'lenrek')
327 loadables2 = make_ramdisk('test-loadables2.bin', 'ksidmar')
328 kernel_out = make_fname('kernel-out.bin')
329 fdt_out = make_fname('fdt-out.dtb')
330 ramdisk_out = make_fname('ramdisk-out.bin')
331 loadables1_out = make_fname('loadables1-out.bin')
332 loadables2_out = make_fname('loadables2-out.bin')
334 # Set up basic parameters with default values
339 'kernel_out' : kernel_out,
340 'kernel_addr' : 0x40000,
341 'kernel_size' : filesize(kernel),
344 'fdt_addr' : 0x80000,
345 'fdt_size' : filesize(control_dtb),
349 'ramdisk_out' : ramdisk_out,
350 'ramdisk_addr' : 0xc0000,
351 'ramdisk_size' : filesize(ramdisk),
353 'ramdisk_config' : '',
355 'loadables1' : loadables1,
356 'loadables1_out' : loadables1_out,
357 'loadables1_addr' : 0x100000,
358 'loadables1_size' : filesize(loadables1),
359 'loadables1_load' : '',
361 'loadables2' : loadables2,
362 'loadables2_out' : loadables2_out,
363 'loadables2_addr' : 0x140000,
364 'loadables2_size' : filesize(loadables2),
365 'loadables2_load' : '',
367 'loadables_config' : '',
370 # Make a basic FIT and a script to load it
371 fit = make_fit(mkimage, params)
373 cmd = base_script % params
375 # First check that we can load a kernel
376 # We could perhaps reduce duplication with some loss of readability
377 set_test('Kernel load')
378 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
380 if read_file(kernel) != read_file(kernel_out):
381 fail('Kernel not loaded', stdout)
382 if read_file(control_dtb) == read_file(fdt_out):
383 fail('FDT loaded but should be ignored', stdout)
384 if read_file(ramdisk) == read_file(ramdisk_out):
385 fail('Ramdisk loaded but should not be', stdout)
387 # Find out the offset in the FIT where U-Boot has found the FDT
388 line = find_matching(stdout, 'Booting using the fdt blob at ')
389 fit_offset = int(line, 16) - params['fit_addr']
390 fdt_magic = struct.pack('>L', 0xd00dfeed)
391 data = read_file(fit)
393 # Now find where it actually is in the FIT (skip the first word)
394 real_fit_offset = data.find(fdt_magic, 4)
395 if fit_offset != real_fit_offset:
396 fail('U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
397 (fit_offset, real_fit_offset), stdout)
399 # Now a kernel and an FDT
400 set_test('Kernel + FDT load')
401 params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
402 fit = make_fit(mkimage, params)
403 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
405 if read_file(kernel) != read_file(kernel_out):
406 fail('Kernel not loaded', stdout)
407 if read_file(control_dtb) != read_file(fdt_out):
408 fail('FDT not loaded', stdout)
409 if read_file(ramdisk) == read_file(ramdisk_out):
410 fail('Ramdisk loaded but should not be', stdout)
413 set_test('Kernel + FDT + Ramdisk load')
414 params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
415 params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
416 fit = make_fit(mkimage, params)
417 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
419 if read_file(ramdisk) != read_file(ramdisk_out):
420 fail('Ramdisk not loaded', stdout)
422 # Configuration with some Loadables
423 set_test('Kernel + FDT + Ramdisk load + Loadables')
424 params['loadables_config'] = 'loadables = "kernel@2", "ramdisk@2";'
425 params['loadables1_load'] = 'load = <%#x>;' % params['loadables1_addr']
426 params['loadables2_load'] = 'load = <%#x>;' % params['loadables2_addr']
427 fit = make_fit(mkimage, params)
428 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
430 if read_file(loadables1) != read_file(loadables1_out):
431 fail('Loadables1 (kernel) not loaded', stdout)
432 if read_file(loadables2) != read_file(loadables2_out):
433 fail('Loadables2 (ramdisk) not loaded', stdout)
436 """Parse options, run the FIT tests and print the result"""
437 global base_path, base_dir
439 # Work in a temporary directory
440 base_dir = tempfile.mkdtemp()
441 parser = OptionParser()
442 parser.add_option('-u', '--u-boot',
443 default=os.path.join(base_path, 'u-boot'),
444 help='Select U-Boot sandbox binary')
445 parser.add_option('-k', '--keep', action='store_true',
446 help="Don't delete temporary directory even when tests pass")
447 parser.add_option('-t', '--selftest', action='store_true',
448 help='Run internal self tests')
449 (options, args) = parser.parse_args()
451 # Find the path to U-Boot, and assume mkimage is in its tools/mkimage dir
452 base_path = os.path.dirname(options.u_boot)
453 mkimage = os.path.join(base_path, 'tools/mkimage')
455 # There are a few doctests - handle these here
461 print title, '\n', '=' * len(title)
463 run_fit_test(mkimage, options.u_boot)
465 print '\nTests passed'
466 print 'Caveat: this is only a sanity check - test coverage is poor'
468 # Remove the tempoerary directory unless we are asked to keep it
470 print "Output files are in '%s'" % base_dir
472 shutil.rmtree(base_dir)