blob: b0d0538919770e29caf0012f74fa4cfa1ae522fb [file] [log] [blame]
Simon Glass301e8032013-05-16 13:53:28 +00001#!/usr/bin/python
2#
3# Copyright (c) 2013, Google Inc.
4#
5# Sanity check of the FIT handling in U-Boot
6#
Wolfgang Denk1a459662013-07-08 09:37:19 +02007# SPDX-License-Identifier: GPL-2.0+
Simon Glass301e8032013-05-16 13:53:28 +00008#
9# To run this:
10#
11# make O=sandbox sandbox_config
12# make O=sandbox
13# ./test/image/test-fit.py -u sandbox/u-boot
Robert P. J. Dayb28c5fc2017-03-13 06:50:55 -040014#
15# Note: The above testing requires the Python development package, typically
16# called python-devel or something similar.
Simon Glass301e8032013-05-16 13:53:28 +000017
18import doctest
19from optparse import OptionParser
20import os
21import shutil
22import struct
23import sys
24import tempfile
25
Simon Glasscc447722014-12-02 13:17:32 -070026# Enable printing of all U-Boot output
27DEBUG = True
28
Simon Glass301e8032013-05-16 13:53:28 +000029# The 'command' library in patman is convenient for running commands
30base_path = os.path.dirname(sys.argv[0])
31patman = os.path.join(base_path, '../../tools/patman')
32sys.path.append(patman)
33
34import command
35
36# Define a base ITS which we can adjust using % and a dictionary
37base_its = '''
38/dts-v1/;
39
40/ {
41 description = "Chrome OS kernel image with one or more FDT blobs";
42 #address-cells = <1>;
43
44 images {
45 kernel@1 {
46 data = /incbin/("%(kernel)s");
47 type = "kernel";
48 arch = "sandbox";
49 os = "linux";
50 compression = "none";
51 load = <0x40000>;
52 entry = <0x8>;
53 };
Karl Apsite657fd2d2015-05-21 09:52:50 -040054 kernel@2 {
55 data = /incbin/("%(loadables1)s");
56 type = "kernel";
57 arch = "sandbox";
58 os = "linux";
59 compression = "none";
60 %(loadables1_load)s
61 entry = <0x0>;
62 };
Simon Glass301e8032013-05-16 13:53:28 +000063 fdt@1 {
64 description = "snow";
65 data = /incbin/("u-boot.dtb");
66 type = "flat_dt";
67 arch = "sandbox";
68 %(fdt_load)s
69 compression = "none";
70 signature@1 {
71 algo = "sha1,rsa2048";
72 key-name-hint = "dev";
73 };
74 };
75 ramdisk@1 {
76 description = "snow";
77 data = /incbin/("%(ramdisk)s");
78 type = "ramdisk";
79 arch = "sandbox";
80 os = "linux";
81 %(ramdisk_load)s
82 compression = "none";
83 };
Karl Apsite657fd2d2015-05-21 09:52:50 -040084 ramdisk@2 {
85 description = "snow";
86 data = /incbin/("%(loadables2)s");
87 type = "ramdisk";
88 arch = "sandbox";
89 os = "linux";
90 %(loadables2_load)s
91 compression = "none";
92 };
Simon Glass301e8032013-05-16 13:53:28 +000093 };
94 configurations {
95 default = "conf@1";
96 conf@1 {
97 kernel = "kernel@1";
98 fdt = "fdt@1";
99 %(ramdisk_config)s
Karl Apsite657fd2d2015-05-21 09:52:50 -0400100 %(loadables_config)s
Simon Glass301e8032013-05-16 13:53:28 +0000101 };
102 };
103};
104'''
105
106# Define a base FDT - currently we don't use anything in this
107base_fdt = '''
108/dts-v1/;
109
110/ {
111 model = "Sandbox Verified Boot Test";
112 compatible = "sandbox";
113
Simon Glass0edd82e2016-02-24 09:14:44 -0700114 reset@0 {
115 compatible = "sandbox,reset";
116 };
117
Simon Glass301e8032013-05-16 13:53:28 +0000118};
119'''
120
Robert P. J. Dayb28c5fc2017-03-13 06:50:55 -0400121# 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
Simon Glass301e8032013-05-16 13:53:28 +0000123# we expect 'bootm' to write things. Then quit.
124base_script = '''
Simon Glassdfe6f4d2014-08-22 14:26:44 -0600125sb load hostfs 0 %(fit_addr)x %(fit)s
Simon Glass301e8032013-05-16 13:53:28 +0000126fdt addr %(fit_addr)x
127bootm start %(fit_addr)x
128bootm loados
Simon Glassb5493d12014-12-02 13:17:31 -0700129sb save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
130sb save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
131sb save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
Karl Apsite657fd2d2015-05-21 09:52:50 -0400132sb save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
133sb save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
Simon Glass301e8032013-05-16 13:53:28 +0000134reset
135'''
136
Simon Glasscc447722014-12-02 13:17:32 -0700137def debug_stdout(stdout):
138 if DEBUG:
139 print stdout
140
Simon Glass301e8032013-05-16 13:53:28 +0000141def make_fname(leaf):
142 """Make a temporary filename
143
144 Args:
145 leaf: Leaf name of file to create (within temporary directory)
146 Return:
147 Temporary filename
148 """
149 global base_dir
150
151 return os.path.join(base_dir, leaf)
152
153def filesize(fname):
154 """Get the size of a file
155
156 Args:
157 fname: Filename to check
158 Return:
159 Size of file in bytes
160 """
161 return os.stat(fname).st_size
162
163def read_file(fname):
164 """Read the contents of a file
165
166 Args:
167 fname: Filename to read
168 Returns:
169 Contents of file as a string
170 """
171 with open(fname, 'r') as fd:
172 return fd.read()
173
174def make_dtb():
175 """Make a sample .dts file and compile it to a .dtb
176
177 Returns:
178 Filename of .dtb file created
179 """
180 src = make_fname('u-boot.dts')
181 dtb = make_fname('u-boot.dtb')
182 with open(src, 'w') as fd:
183 print >>fd, base_fdt
184 command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
185 return dtb
186
187def make_its(params):
188 """Make a sample .its file with parameters embedded
189
190 Args:
191 params: Dictionary containing parameters to embed in the %() strings
192 Returns:
193 Filename of .its file created
194 """
195 its = make_fname('test.its')
196 with open(its, 'w') as fd:
197 print >>fd, base_its % params
198 return its
199
200def make_fit(mkimage, params):
201 """Make a sample .fit file ready for loading
202
203 This creates a .its script with the selected parameters and uses mkimage to
204 turn this into a .fit image.
205
206 Args:
207 mkimage: Filename of 'mkimage' utility
208 params: Dictionary containing parameters to embed in the %() strings
209 Return:
210 Filename of .fit file created
211 """
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:
216 print >>fd, base_fdt
217 return fit
218
Karl Apsite657fd2d2015-05-21 09:52:50 -0400219def make_kernel(filename, text):
Simon Glass301e8032013-05-16 13:53:28 +0000220 """Make a sample kernel with test data
221
Karl Apsite657fd2d2015-05-21 09:52:50 -0400222 Args:
223 filename: the name of the file you want to create
Simon Glass301e8032013-05-16 13:53:28 +0000224 Returns:
Karl Apsite657fd2d2015-05-21 09:52:50 -0400225 Full path and filename of the kernel it created
Simon Glass301e8032013-05-16 13:53:28 +0000226 """
Karl Apsite657fd2d2015-05-21 09:52:50 -0400227 fname = make_fname(filename)
Simon Glass301e8032013-05-16 13:53:28 +0000228 data = ''
229 for i in range(100):
Karl Apsite657fd2d2015-05-21 09:52:50 -0400230 data += 'this %s %d is unlikely to boot\n' % (text, i)
Simon Glass301e8032013-05-16 13:53:28 +0000231 with open(fname, 'w') as fd:
232 print >>fd, data
233 return fname
234
Karl Apsite657fd2d2015-05-21 09:52:50 -0400235def make_ramdisk(filename, text):
Simon Glass301e8032013-05-16 13:53:28 +0000236 """Make a sample ramdisk with test data
237
238 Returns:
239 Filename of ramdisk created
240 """
Karl Apsite657fd2d2015-05-21 09:52:50 -0400241 fname = make_fname(filename)
Simon Glass301e8032013-05-16 13:53:28 +0000242 data = ''
243 for i in range(100):
Karl Apsite657fd2d2015-05-21 09:52:50 -0400244 data += '%s %d was seldom used in the middle ages\n' % (text, i)
Simon Glass301e8032013-05-16 13:53:28 +0000245 with open(fname, 'w') as fd:
246 print >>fd, data
247 return fname
248
249def find_matching(text, match):
250 """Find a match in a line of text, and return the unmatched line portion
251
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
254 match text.
255
256 Once we find a match, we discard the match string itself from the line,
257 and return what remains.
258
259 TODO: If this function becomes more generally useful, we could change it
260 to use regex and return groups.
261
262 Args:
263 text: Text to check (each line separated by \n)
264 match: String to search for
265 Return:
266 String containing unmatched portion of line
267 Exceptions:
268 ValueError: If match is not found
269
270 >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
271 '10'
Robert P. J. Dayb28c5fc2017-03-13 06:50:55 -0400272 >>> find_matching('first line:10\\nsecond_line:20', 'second line')
Simon Glass301e8032013-05-16 13:53:28 +0000273 Traceback (most recent call last):
274 ...
275 ValueError: Test aborted
276 >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
277 '20'
278 """
279 for line in text.splitlines():
280 pos = line.find(match)
281 if pos != -1:
282 return line[:pos] + line[pos + len(match):]
283
284 print "Expected '%s' but not found in output:"
285 print text
286 raise ValueError('Test aborted')
287
288def set_test(name):
289 """Set the name of the current test and print a message
290
291 Args:
292 name: Name of test
293 """
294 global test_name
295
296 test_name = name
297 print name
298
Simon Glassaec36cf2013-06-11 11:14:36 -0700299def fail(msg, stdout):
Simon Glass301e8032013-05-16 13:53:28 +0000300 """Raise an error with a helpful failure message
301
302 Args:
303 msg: Message to display
304 """
Simon Glassaec36cf2013-06-11 11:14:36 -0700305 print stdout
Simon Glass301e8032013-05-16 13:53:28 +0000306 raise ValueError("Test '%s' failed: %s" % (test_name, msg))
307
308def run_fit_test(mkimage, u_boot):
309 """Basic sanity check of FIT loading in U-Boot
310
311 TODO: Almost everything:
312 - hash algorithms - invalid hash/contents should be detected
313 - signature algorithms - invalid sig/contents should be detected
314 - compression
315 - checking that errors are detected like:
316 - image overwriting
317 - missing images
318 - invalid configurations
319 - incorrect os/arch/type fields
320 - empty data
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
326 """
327 global test_name
328
329 # Set up invariant files
330 control_dtb = make_dtb()
Karl Apsite657fd2d2015-05-21 09:52:50 -0400331 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')
Simon Glass301e8032013-05-16 13:53:28 +0000335 kernel_out = make_fname('kernel-out.bin')
336 fdt_out = make_fname('fdt-out.dtb')
337 ramdisk_out = make_fname('ramdisk-out.bin')
Karl Apsite657fd2d2015-05-21 09:52:50 -0400338 loadables1_out = make_fname('loadables1-out.bin')
339 loadables2_out = make_fname('loadables2-out.bin')
Simon Glass301e8032013-05-16 13:53:28 +0000340
341 # Set up basic parameters with default values
342 params = {
343 'fit_addr' : 0x1000,
344
345 'kernel' : kernel,
346 'kernel_out' : kernel_out,
347 'kernel_addr' : 0x40000,
348 'kernel_size' : filesize(kernel),
349
350 'fdt_out' : fdt_out,
351 'fdt_addr' : 0x80000,
352 'fdt_size' : filesize(control_dtb),
353 'fdt_load' : '',
354
355 'ramdisk' : ramdisk,
356 'ramdisk_out' : ramdisk_out,
357 'ramdisk_addr' : 0xc0000,
358 'ramdisk_size' : filesize(ramdisk),
359 'ramdisk_load' : '',
360 'ramdisk_config' : '',
Karl Apsite657fd2d2015-05-21 09:52:50 -0400361
362 'loadables1' : loadables1,
363 'loadables1_out' : loadables1_out,
364 'loadables1_addr' : 0x100000,
365 'loadables1_size' : filesize(loadables1),
366 'loadables1_load' : '',
367
368 'loadables2' : loadables2,
369 'loadables2_out' : loadables2_out,
370 'loadables2_addr' : 0x140000,
371 'loadables2_size' : filesize(loadables2),
372 'loadables2_load' : '',
373
374 'loadables_config' : '',
Simon Glass301e8032013-05-16 13:53:28 +0000375 }
376
377 # Make a basic FIT and a script to load it
378 fit = make_fit(mkimage, params)
379 params['fit'] = fit
380 cmd = base_script % params
381
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)
Simon Glasscc447722014-12-02 13:17:32 -0700386 debug_stdout(stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000387 if read_file(kernel) != read_file(kernel_out):
Simon Glassaec36cf2013-06-11 11:14:36 -0700388 fail('Kernel not loaded', stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000389 if read_file(control_dtb) == read_file(fdt_out):
Simon Glassaec36cf2013-06-11 11:14:36 -0700390 fail('FDT loaded but should be ignored', stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000391 if read_file(ramdisk) == read_file(ramdisk_out):
Simon Glassaec36cf2013-06-11 11:14:36 -0700392 fail('Ramdisk loaded but should not be', stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000393
394 # Find out the offset in the FIT where U-Boot has found the FDT
Robert P. J. Dayb28c5fc2017-03-13 06:50:55 -0400395 line = find_matching(stdout, 'Booting using the FDT blob at ')
Simon Glass301e8032013-05-16 13:53:28 +0000396 fit_offset = int(line, 16) - params['fit_addr']
397 fdt_magic = struct.pack('>L', 0xd00dfeed)
398 data = read_file(fit)
399
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' %
Simon Glassaec36cf2013-06-11 11:14:36 -0700404 (fit_offset, real_fit_offset), stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000405
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)
Simon Glasscc447722014-12-02 13:17:32 -0700411 debug_stdout(stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000412 if read_file(kernel) != read_file(kernel_out):
Simon Glassaec36cf2013-06-11 11:14:36 -0700413 fail('Kernel not loaded', stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000414 if read_file(control_dtb) != read_file(fdt_out):
Simon Glassaec36cf2013-06-11 11:14:36 -0700415 fail('FDT not loaded', stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000416 if read_file(ramdisk) == read_file(ramdisk_out):
Simon Glassaec36cf2013-06-11 11:14:36 -0700417 fail('Ramdisk loaded but should not be', stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000418
419 # Try a ramdisk
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)
Simon Glasscc447722014-12-02 13:17:32 -0700425 debug_stdout(stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000426 if read_file(ramdisk) != read_file(ramdisk_out):
Simon Glassaec36cf2013-06-11 11:14:36 -0700427 fail('Ramdisk not loaded', stdout)
Simon Glass301e8032013-05-16 13:53:28 +0000428
Karl Apsite657fd2d2015-05-21 09:52:50 -0400429 # 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)
436 debug_stdout(stdout)
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)
441
Simon Glass301e8032013-05-16 13:53:28 +0000442def run_tests():
443 """Parse options, run the FIT tests and print the result"""
444 global base_path, base_dir
445
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()
457
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')
461
462 # There are a few doctests - handle these here
463 if options.selftest:
464 doctest.testmod()
465 return
466
467 title = 'FIT Tests'
468 print title, '\n', '=' * len(title)
469
470 run_fit_test(mkimage, options.u_boot)
471
472 print '\nTests passed'
473 print 'Caveat: this is only a sanity check - test coverage is poor'
474
Robert P. J. Dayb28c5fc2017-03-13 06:50:55 -0400475 # Remove the temporary directory unless we are asked to keep it
Simon Glass301e8032013-05-16 13:53:28 +0000476 if options.keep:
477 print "Output files are in '%s'" % base_dir
478 else:
479 shutil.rmtree(base_dir)
480
481run_tests()