3 # Copyright (c) 2013, Google Inc.
5 # Sanity check of the FIT handling in U-Boot
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License as
9 # published by the Free Software Foundation; either version 2 of
10 # the License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston,
24 # make O=sandbox sandbox_config
26 # ./test/image/test-fit.py -u sandbox/u-boot
29 from optparse import OptionParser
36 # The 'command' library in patman is convenient for running commands
37 base_path = os.path.dirname(sys.argv[0])
38 patman = os.path.join(base_path, '../../tools/patman')
39 sys.path.append(patman)
43 # Define a base ITS which we can adjust using % and a dictionary
48 description = "Chrome OS kernel image with one or more FDT blobs";
53 data = /incbin/("%(kernel)s");
63 data = /incbin/("u-boot.dtb");
69 algo = "sha1,rsa2048";
70 key-name-hint = "dev";
75 data = /incbin/("%(ramdisk)s");
94 # Define a base FDT - currently we don't use anything in this
99 model = "Sandbox Verified Boot Test";
100 compatible = "sandbox";
105 # This is the U-Boot script that is run for each test. First load the fit,
106 # then do the 'bootm' command, then save out memory from the places where
107 # we expect 'bootm' to write things. Then quit.
109 sb load host 0 %(fit_addr)x %(fit)s
110 fdt addr %(fit_addr)x
111 bootm start %(fit_addr)x
113 sb save host 0 %(kernel_out)s %(kernel_addr)x %(kernel_size)x
114 sb save host 0 %(fdt_out)s %(fdt_addr)x %(fdt_size)x
115 sb save host 0 %(ramdisk_out)s %(ramdisk_addr)x %(ramdisk_size)x
119 def make_fname(leaf):
120 """Make a temporary filename
123 leaf: Leaf name of file to create (within temporary directory)
129 return os.path.join(base_dir, leaf)
132 """Get the size of a file
135 fname: Filename to check
137 Size of file in bytes
139 return os.stat(fname).st_size
141 def read_file(fname):
142 """Read the contents of a file
145 fname: Filename to read
147 Contents of file as a string
149 with open(fname, 'r') as fd:
153 """Make a sample .dts file and compile it to a .dtb
156 Filename of .dtb file created
158 src = make_fname('u-boot.dts')
159 dtb = make_fname('u-boot.dtb')
160 with open(src, 'w') as fd:
162 command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
165 def make_its(params):
166 """Make a sample .its file with parameters embedded
169 params: Dictionary containing parameters to embed in the %() strings
171 Filename of .its file created
173 its = make_fname('test.its')
174 with open(its, 'w') as fd:
175 print >>fd, base_its % params
178 def make_fit(mkimage, params):
179 """Make a sample .fit file ready for loading
181 This creates a .its script with the selected parameters and uses mkimage to
182 turn this into a .fit image.
185 mkimage: Filename of 'mkimage' utility
186 params: Dictionary containing parameters to embed in the %() strings
188 Filename of .fit file created
190 fit = make_fname('test.fit')
191 its = make_its(params)
192 command.Output(mkimage, '-f', its, fit)
193 with open(make_fname('u-boot.dts'), 'w') as fd:
198 """Make a sample kernel with test data
201 Filename of kernel created
203 fname = make_fname('test-kernel.bin')
206 data += 'this kernel %d is unlikely to boot\n' % i
207 with open(fname, 'w') as fd:
212 """Make a sample ramdisk with test data
215 Filename of ramdisk created
217 fname = make_fname('test-ramdisk.bin')
220 data += 'ramdisk %d was seldom used in the middle ages\n' % i
221 with open(fname, 'w') as fd:
225 def find_matching(text, match):
226 """Find a match in a line of text, and return the unmatched line portion
228 This is used to extract a part of a line from some text. The match string
229 is used to locate the line - we use the first line that contains that
232 Once we find a match, we discard the match string itself from the line,
233 and return what remains.
235 TODO: If this function becomes more generally useful, we could change it
236 to use regex and return groups.
239 text: Text to check (each line separated by \n)
240 match: String to search for
242 String containing unmatched portion of line
244 ValueError: If match is not found
246 >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
248 >>> find_matching('first line:10\\nsecond_line:20', 'second linex')
249 Traceback (most recent call last):
251 ValueError: Test aborted
252 >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
255 for line in text.splitlines():
256 pos = line.find(match)
258 return line[:pos] + line[pos + len(match):]
260 print "Expected '%s' but not found in output:"
262 raise ValueError('Test aborted')
265 """Set the name of the current test and print a message
275 def fail(msg, stdout):
276 """Raise an error with a helpful failure message
279 msg: Message to display
282 raise ValueError("Test '%s' failed: %s" % (test_name, msg))
284 def run_fit_test(mkimage, u_boot):
285 """Basic sanity check of FIT loading in U-Boot
287 TODO: Almost everything:
288 - hash algorithms - invalid hash/contents should be detected
289 - signature algorithms - invalid sig/contents should be detected
291 - checking that errors are detected like:
294 - invalid configurations
295 - incorrect os/arch/type fields
297 - images too large/small
298 - invalid FDT (e.g. putting a random binary in instead)
299 - default configuration selection
300 - bootm command line parameters should have desired effect
301 - run code coverage to make sure we are testing all the code
305 # Set up invariant files
306 control_dtb = make_dtb()
307 kernel = make_kernel()
308 ramdisk = make_ramdisk()
309 kernel_out = make_fname('kernel-out.bin')
310 fdt_out = make_fname('fdt-out.dtb')
311 ramdisk_out = make_fname('ramdisk-out.bin')
313 # Set up basic parameters with default values
318 'kernel_out' : kernel_out,
319 'kernel_addr' : 0x40000,
320 'kernel_size' : filesize(kernel),
323 'fdt_addr' : 0x80000,
324 'fdt_size' : filesize(control_dtb),
328 'ramdisk_out' : ramdisk_out,
329 'ramdisk_addr' : 0xc0000,
330 'ramdisk_size' : filesize(ramdisk),
332 'ramdisk_config' : '',
335 # Make a basic FIT and a script to load it
336 fit = make_fit(mkimage, params)
338 cmd = base_script % params
340 # First check that we can load a kernel
341 # We could perhaps reduce duplication with some loss of readability
342 set_test('Kernel load')
343 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
344 if read_file(kernel) != read_file(kernel_out):
345 fail('Kernel not loaded', stdout)
346 if read_file(control_dtb) == read_file(fdt_out):
347 fail('FDT loaded but should be ignored', stdout)
348 if read_file(ramdisk) == read_file(ramdisk_out):
349 fail('Ramdisk loaded but should not be', stdout)
351 # Find out the offset in the FIT where U-Boot has found the FDT
352 line = find_matching(stdout, 'Booting using the fdt blob at ')
353 fit_offset = int(line, 16) - params['fit_addr']
354 fdt_magic = struct.pack('>L', 0xd00dfeed)
355 data = read_file(fit)
357 # Now find where it actually is in the FIT (skip the first word)
358 real_fit_offset = data.find(fdt_magic, 4)
359 if fit_offset != real_fit_offset:
360 fail('U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
361 (fit_offset, real_fit_offset), stdout)
363 # Now a kernel and an FDT
364 set_test('Kernel + FDT load')
365 params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
366 fit = make_fit(mkimage, params)
367 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
368 if read_file(kernel) != read_file(kernel_out):
369 fail('Kernel not loaded', stdout)
370 if read_file(control_dtb) != read_file(fdt_out):
371 fail('FDT not loaded', stdout)
372 if read_file(ramdisk) == read_file(ramdisk_out):
373 fail('Ramdisk loaded but should not be', stdout)
376 set_test('Kernel + FDT + Ramdisk load')
377 params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
378 params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
379 fit = make_fit(mkimage, params)
380 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
381 if read_file(ramdisk) != read_file(ramdisk_out):
382 fail('Ramdisk not loaded', stdout)
385 """Parse options, run the FIT tests and print the result"""
386 global base_path, base_dir
388 # Work in a temporary directory
389 base_dir = tempfile.mkdtemp()
390 parser = OptionParser()
391 parser.add_option('-u', '--u-boot',
392 default=os.path.join(base_path, 'u-boot'),
393 help='Select U-Boot sandbox binary')
394 parser.add_option('-k', '--keep', action='store_true',
395 help="Don't delete temporary directory even when tests pass")
396 parser.add_option('-t', '--selftest', action='store_true',
397 help='Run internal self tests')
398 (options, args) = parser.parse_args()
400 # Find the path to U-Boot, and assume mkimage is in its tools/mkimage dir
401 base_path = os.path.dirname(options.u_boot)
402 mkimage = os.path.join(base_path, 'tools/mkimage')
404 # There are a few doctests - handle these here
410 print title, '\n', '=' * len(title)
412 run_fit_test(mkimage, options.u_boot)
414 print '\nTests passed'
415 print 'Caveat: this is only a sanity check - test coverage is poor'
417 # Remove the tempoerary directory unless we are asked to keep it
419 print "Output files are in '%s'" % base_dir
421 shutil.rmtree(base_dir)