blob: db0649fca8d0138103a4bfc7b26246138728ba92 [file] [log] [blame]
Simon Glassdb749192013-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 Denkd79de1d2013-07-08 09:37:19 +02007# SPDX-License-Identifier: GPL-2.0+
Simon Glassdb749192013-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
14
15import doctest
16from optparse import OptionParser
17import os
18import shutil
19import struct
20import sys
21import tempfile
22
Simon Glassb5f97d52014-12-02 13:17:32 -070023# Enable printing of all U-Boot output
24DEBUG = True
25
Simon Glassdb749192013-05-16 13:53:28 +000026# The 'command' library in patman is convenient for running commands
27base_path = os.path.dirname(sys.argv[0])
28patman = os.path.join(base_path, '../../tools/patman')
29sys.path.append(patman)
30
31import command
32
33# Define a base ITS which we can adjust using % and a dictionary
34base_its = '''
35/dts-v1/;
36
37/ {
38 description = "Chrome OS kernel image with one or more FDT blobs";
39 #address-cells = <1>;
40
41 images {
42 kernel@1 {
43 data = /incbin/("%(kernel)s");
44 type = "kernel";
45 arch = "sandbox";
46 os = "linux";
47 compression = "none";
48 load = <0x40000>;
49 entry = <0x8>;
50 };
Karl Apsiteaad8dd72015-05-21 09:52:50 -040051 kernel@2 {
52 data = /incbin/("%(loadables1)s");
53 type = "kernel";
54 arch = "sandbox";
55 os = "linux";
56 compression = "none";
57 %(loadables1_load)s
58 entry = <0x0>;
59 };
Simon Glassdb749192013-05-16 13:53:28 +000060 fdt@1 {
61 description = "snow";
62 data = /incbin/("u-boot.dtb");
63 type = "flat_dt";
64 arch = "sandbox";
65 %(fdt_load)s
66 compression = "none";
67 signature@1 {
68 algo = "sha1,rsa2048";
69 key-name-hint = "dev";
70 };
71 };
72 ramdisk@1 {
73 description = "snow";
74 data = /incbin/("%(ramdisk)s");
75 type = "ramdisk";
76 arch = "sandbox";
77 os = "linux";
78 %(ramdisk_load)s
79 compression = "none";
80 };
Karl Apsiteaad8dd72015-05-21 09:52:50 -040081 ramdisk@2 {
82 description = "snow";
83 data = /incbin/("%(loadables2)s");
84 type = "ramdisk";
85 arch = "sandbox";
86 os = "linux";
87 %(loadables2_load)s
88 compression = "none";
89 };
Simon Glassdb749192013-05-16 13:53:28 +000090 };
91 configurations {
92 default = "conf@1";
93 conf@1 {
94 kernel = "kernel@1";
95 fdt = "fdt@1";
96 %(ramdisk_config)s
Karl Apsiteaad8dd72015-05-21 09:52:50 -040097 %(loadables_config)s
Simon Glassdb749192013-05-16 13:53:28 +000098 };
99 };
100};
101'''
102
103# Define a base FDT - currently we don't use anything in this
104base_fdt = '''
105/dts-v1/;
106
107/ {
108 model = "Sandbox Verified Boot Test";
109 compatible = "sandbox";
110
Simon Glass546bab12016-02-24 09:14:44 -0700111 reset@0 {
112 compatible = "sandbox,reset";
113 };
114
Simon Glassdb749192013-05-16 13:53:28 +0000115};
116'''
117
118# This is the U-Boot script that is run for each test. First load the fit,
119# then do the 'bootm' command, then save out memory from the places where
120# we expect 'bootm' to write things. Then quit.
121base_script = '''
Simon Glass943b4172014-08-22 14:26:44 -0600122sb load hostfs 0 %(fit_addr)x %(fit)s
Simon Glassdb749192013-05-16 13:53:28 +0000123fdt addr %(fit_addr)x
124bootm start %(fit_addr)x
125bootm loados
Simon Glass73a04452014-12-02 13:17:31 -0700126sb save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
127sb save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
128sb save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400129sb save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
130sb save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
Simon Glassdb749192013-05-16 13:53:28 +0000131reset
132'''
133
Simon Glassb5f97d52014-12-02 13:17:32 -0700134def debug_stdout(stdout):
135 if DEBUG:
136 print stdout
137
Simon Glassdb749192013-05-16 13:53:28 +0000138def make_fname(leaf):
139 """Make a temporary filename
140
141 Args:
142 leaf: Leaf name of file to create (within temporary directory)
143 Return:
144 Temporary filename
145 """
146 global base_dir
147
148 return os.path.join(base_dir, leaf)
149
150def filesize(fname):
151 """Get the size of a file
152
153 Args:
154 fname: Filename to check
155 Return:
156 Size of file in bytes
157 """
158 return os.stat(fname).st_size
159
160def read_file(fname):
161 """Read the contents of a file
162
163 Args:
164 fname: Filename to read
165 Returns:
166 Contents of file as a string
167 """
168 with open(fname, 'r') as fd:
169 return fd.read()
170
171def make_dtb():
172 """Make a sample .dts file and compile it to a .dtb
173
174 Returns:
175 Filename of .dtb file created
176 """
177 src = make_fname('u-boot.dts')
178 dtb = make_fname('u-boot.dtb')
179 with open(src, 'w') as fd:
180 print >>fd, base_fdt
181 command.Output('dtc', src, '-O', 'dtb', '-o', dtb)
182 return dtb
183
184def make_its(params):
185 """Make a sample .its file with parameters embedded
186
187 Args:
188 params: Dictionary containing parameters to embed in the %() strings
189 Returns:
190 Filename of .its file created
191 """
192 its = make_fname('test.its')
193 with open(its, 'w') as fd:
194 print >>fd, base_its % params
195 return its
196
197def make_fit(mkimage, params):
198 """Make a sample .fit file ready for loading
199
200 This creates a .its script with the selected parameters and uses mkimage to
201 turn this into a .fit image.
202
203 Args:
204 mkimage: Filename of 'mkimage' utility
205 params: Dictionary containing parameters to embed in the %() strings
206 Return:
207 Filename of .fit file created
208 """
209 fit = make_fname('test.fit')
210 its = make_its(params)
211 command.Output(mkimage, '-f', its, fit)
212 with open(make_fname('u-boot.dts'), 'w') as fd:
213 print >>fd, base_fdt
214 return fit
215
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400216def make_kernel(filename, text):
Simon Glassdb749192013-05-16 13:53:28 +0000217 """Make a sample kernel with test data
218
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400219 Args:
220 filename: the name of the file you want to create
Simon Glassdb749192013-05-16 13:53:28 +0000221 Returns:
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400222 Full path and filename of the kernel it created
Simon Glassdb749192013-05-16 13:53:28 +0000223 """
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400224 fname = make_fname(filename)
Simon Glassdb749192013-05-16 13:53:28 +0000225 data = ''
226 for i in range(100):
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400227 data += 'this %s %d is unlikely to boot\n' % (text, i)
Simon Glassdb749192013-05-16 13:53:28 +0000228 with open(fname, 'w') as fd:
229 print >>fd, data
230 return fname
231
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400232def make_ramdisk(filename, text):
Simon Glassdb749192013-05-16 13:53:28 +0000233 """Make a sample ramdisk with test data
234
235 Returns:
236 Filename of ramdisk created
237 """
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400238 fname = make_fname(filename)
Simon Glassdb749192013-05-16 13:53:28 +0000239 data = ''
240 for i in range(100):
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400241 data += '%s %d was seldom used in the middle ages\n' % (text, i)
Simon Glassdb749192013-05-16 13:53:28 +0000242 with open(fname, 'w') as fd:
243 print >>fd, data
244 return fname
245
246def find_matching(text, match):
247 """Find a match in a line of text, and return the unmatched line portion
248
249 This is used to extract a part of a line from some text. The match string
250 is used to locate the line - we use the first line that contains that
251 match text.
252
253 Once we find a match, we discard the match string itself from the line,
254 and return what remains.
255
256 TODO: If this function becomes more generally useful, we could change it
257 to use regex and return groups.
258
259 Args:
260 text: Text to check (each line separated by \n)
261 match: String to search for
262 Return:
263 String containing unmatched portion of line
264 Exceptions:
265 ValueError: If match is not found
266
267 >>> find_matching('first line:10\\nsecond_line:20', 'first line:')
268 '10'
269 >>> find_matching('first line:10\\nsecond_line:20', 'second linex')
270 Traceback (most recent call last):
271 ...
272 ValueError: Test aborted
273 >>> find_matching('first line:10\\nsecond_line:20', 'second_line:')
274 '20'
275 """
276 for line in text.splitlines():
277 pos = line.find(match)
278 if pos != -1:
279 return line[:pos] + line[pos + len(match):]
280
281 print "Expected '%s' but not found in output:"
282 print text
283 raise ValueError('Test aborted')
284
285def set_test(name):
286 """Set the name of the current test and print a message
287
288 Args:
289 name: Name of test
290 """
291 global test_name
292
293 test_name = name
294 print name
295
Simon Glass27620cc2013-06-11 11:14:36 -0700296def fail(msg, stdout):
Simon Glassdb749192013-05-16 13:53:28 +0000297 """Raise an error with a helpful failure message
298
299 Args:
300 msg: Message to display
301 """
Simon Glass27620cc2013-06-11 11:14:36 -0700302 print stdout
Simon Glassdb749192013-05-16 13:53:28 +0000303 raise ValueError("Test '%s' failed: %s" % (test_name, msg))
304
305def run_fit_test(mkimage, u_boot):
306 """Basic sanity check of FIT loading in U-Boot
307
308 TODO: Almost everything:
309 - hash algorithms - invalid hash/contents should be detected
310 - signature algorithms - invalid sig/contents should be detected
311 - compression
312 - checking that errors are detected like:
313 - image overwriting
314 - missing images
315 - invalid configurations
316 - incorrect os/arch/type fields
317 - empty data
318 - images too large/small
319 - invalid FDT (e.g. putting a random binary in instead)
320 - default configuration selection
321 - bootm command line parameters should have desired effect
322 - run code coverage to make sure we are testing all the code
323 """
324 global test_name
325
326 # Set up invariant files
327 control_dtb = make_dtb()
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400328 kernel = make_kernel('test-kernel.bin', 'kernel')
329 ramdisk = make_ramdisk('test-ramdisk.bin', 'ramdisk')
330 loadables1 = make_kernel('test-loadables1.bin', 'lenrek')
331 loadables2 = make_ramdisk('test-loadables2.bin', 'ksidmar')
Simon Glassdb749192013-05-16 13:53:28 +0000332 kernel_out = make_fname('kernel-out.bin')
333 fdt_out = make_fname('fdt-out.dtb')
334 ramdisk_out = make_fname('ramdisk-out.bin')
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400335 loadables1_out = make_fname('loadables1-out.bin')
336 loadables2_out = make_fname('loadables2-out.bin')
Simon Glassdb749192013-05-16 13:53:28 +0000337
338 # Set up basic parameters with default values
339 params = {
340 'fit_addr' : 0x1000,
341
342 'kernel' : kernel,
343 'kernel_out' : kernel_out,
344 'kernel_addr' : 0x40000,
345 'kernel_size' : filesize(kernel),
346
347 'fdt_out' : fdt_out,
348 'fdt_addr' : 0x80000,
349 'fdt_size' : filesize(control_dtb),
350 'fdt_load' : '',
351
352 'ramdisk' : ramdisk,
353 'ramdisk_out' : ramdisk_out,
354 'ramdisk_addr' : 0xc0000,
355 'ramdisk_size' : filesize(ramdisk),
356 'ramdisk_load' : '',
357 'ramdisk_config' : '',
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400358
359 'loadables1' : loadables1,
360 'loadables1_out' : loadables1_out,
361 'loadables1_addr' : 0x100000,
362 'loadables1_size' : filesize(loadables1),
363 'loadables1_load' : '',
364
365 'loadables2' : loadables2,
366 'loadables2_out' : loadables2_out,
367 'loadables2_addr' : 0x140000,
368 'loadables2_size' : filesize(loadables2),
369 'loadables2_load' : '',
370
371 'loadables_config' : '',
Simon Glassdb749192013-05-16 13:53:28 +0000372 }
373
374 # Make a basic FIT and a script to load it
375 fit = make_fit(mkimage, params)
376 params['fit'] = fit
377 cmd = base_script % params
378
379 # First check that we can load a kernel
380 # We could perhaps reduce duplication with some loss of readability
381 set_test('Kernel load')
382 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
Simon Glassb5f97d52014-12-02 13:17:32 -0700383 debug_stdout(stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000384 if read_file(kernel) != read_file(kernel_out):
Simon Glass27620cc2013-06-11 11:14:36 -0700385 fail('Kernel not loaded', stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000386 if read_file(control_dtb) == read_file(fdt_out):
Simon Glass27620cc2013-06-11 11:14:36 -0700387 fail('FDT loaded but should be ignored', stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000388 if read_file(ramdisk) == read_file(ramdisk_out):
Simon Glass27620cc2013-06-11 11:14:36 -0700389 fail('Ramdisk loaded but should not be', stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000390
391 # Find out the offset in the FIT where U-Boot has found the FDT
392 line = find_matching(stdout, 'Booting using the fdt blob at ')
393 fit_offset = int(line, 16) - params['fit_addr']
394 fdt_magic = struct.pack('>L', 0xd00dfeed)
395 data = read_file(fit)
396
397 # Now find where it actually is in the FIT (skip the first word)
398 real_fit_offset = data.find(fdt_magic, 4)
399 if fit_offset != real_fit_offset:
400 fail('U-Boot loaded FDT from offset %#x, FDT is actually at %#x' %
Simon Glass27620cc2013-06-11 11:14:36 -0700401 (fit_offset, real_fit_offset), stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000402
403 # Now a kernel and an FDT
404 set_test('Kernel + FDT load')
405 params['fdt_load'] = 'load = <%#x>;' % params['fdt_addr']
406 fit = make_fit(mkimage, params)
407 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
Simon Glassb5f97d52014-12-02 13:17:32 -0700408 debug_stdout(stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000409 if read_file(kernel) != read_file(kernel_out):
Simon Glass27620cc2013-06-11 11:14:36 -0700410 fail('Kernel not loaded', stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000411 if read_file(control_dtb) != read_file(fdt_out):
Simon Glass27620cc2013-06-11 11:14:36 -0700412 fail('FDT not loaded', stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000413 if read_file(ramdisk) == read_file(ramdisk_out):
Simon Glass27620cc2013-06-11 11:14:36 -0700414 fail('Ramdisk loaded but should not be', stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000415
416 # Try a ramdisk
417 set_test('Kernel + FDT + Ramdisk load')
418 params['ramdisk_config'] = 'ramdisk = "ramdisk@1";'
419 params['ramdisk_load'] = 'load = <%#x>;' % params['ramdisk_addr']
420 fit = make_fit(mkimage, params)
421 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
Simon Glassb5f97d52014-12-02 13:17:32 -0700422 debug_stdout(stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000423 if read_file(ramdisk) != read_file(ramdisk_out):
Simon Glass27620cc2013-06-11 11:14:36 -0700424 fail('Ramdisk not loaded', stdout)
Simon Glassdb749192013-05-16 13:53:28 +0000425
Karl Apsiteaad8dd72015-05-21 09:52:50 -0400426 # Configuration with some Loadables
427 set_test('Kernel + FDT + Ramdisk load + Loadables')
428 params['loadables_config'] = 'loadables = "kernel@2", "ramdisk@2";'
429 params['loadables1_load'] = 'load = <%#x>;' % params['loadables1_addr']
430 params['loadables2_load'] = 'load = <%#x>;' % params['loadables2_addr']
431 fit = make_fit(mkimage, params)
432 stdout = command.Output(u_boot, '-d', control_dtb, '-c', cmd)
433 debug_stdout(stdout)
434 if read_file(loadables1) != read_file(loadables1_out):
435 fail('Loadables1 (kernel) not loaded', stdout)
436 if read_file(loadables2) != read_file(loadables2_out):
437 fail('Loadables2 (ramdisk) not loaded', stdout)
438
Simon Glassdb749192013-05-16 13:53:28 +0000439def run_tests():
440 """Parse options, run the FIT tests and print the result"""
441 global base_path, base_dir
442
443 # Work in a temporary directory
444 base_dir = tempfile.mkdtemp()
445 parser = OptionParser()
446 parser.add_option('-u', '--u-boot',
447 default=os.path.join(base_path, 'u-boot'),
448 help='Select U-Boot sandbox binary')
449 parser.add_option('-k', '--keep', action='store_true',
450 help="Don't delete temporary directory even when tests pass")
451 parser.add_option('-t', '--selftest', action='store_true',
452 help='Run internal self tests')
453 (options, args) = parser.parse_args()
454
455 # Find the path to U-Boot, and assume mkimage is in its tools/mkimage dir
456 base_path = os.path.dirname(options.u_boot)
457 mkimage = os.path.join(base_path, 'tools/mkimage')
458
459 # There are a few doctests - handle these here
460 if options.selftest:
461 doctest.testmod()
462 return
463
464 title = 'FIT Tests'
465 print title, '\n', '=' * len(title)
466
467 run_fit_test(mkimage, options.u_boot)
468
469 print '\nTests passed'
470 print 'Caveat: this is only a sanity check - test coverage is poor'
471
472 # Remove the tempoerary directory unless we are asked to keep it
473 if options.keep:
474 print "Output files are in '%s'" % base_dir
475 else:
476 shutil.rmtree(base_dir)
477
478run_tests()