]> git.sur5r.net Git - u-boot/blob - test/image/test-fit.py
part_efi: document device-tree binding for part_efi configuration
[u-boot] / test / image / test-fit.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2013, Google Inc.
4 #
5 # Sanity check of the FIT handling in U-Boot
6 #
7 # SPDX-License-Identifier:      GPL-2.0+
8 #
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
15 import doctest
16 from optparse import OptionParser
17 import os
18 import shutil
19 import struct
20 import sys
21 import tempfile
22
23 # Enable printing of all U-Boot output
24 DEBUG = True
25
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)
30
31 import command
32
33 # Define a base ITS which we can adjust using % and a dictionary
34 base_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                 };
51                 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                 };
60                 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                 };
81                 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                 };
90         };
91         configurations {
92                 default = "conf@1";
93                 conf@1 {
94                         kernel = "kernel@1";
95                         fdt = "fdt@1";
96                         %(ramdisk_config)s
97                         %(loadables_config)s
98                 };
99         };
100 };
101 '''
102
103 # Define a base FDT - currently we don't use anything in this
104 base_fdt = '''
105 /dts-v1/;
106
107 / {
108         model = "Sandbox Verified Boot Test";
109         compatible = "sandbox";
110
111         reset@0 {
112                 compatible = "sandbox,reset";
113         };
114
115 };
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.
121 base_script = '''
122 sb load hostfs 0 %(fit_addr)x %(fit)s
123 fdt addr %(fit_addr)x
124 bootm start %(fit_addr)x
125 bootm loados
126 sb save hostfs 0 %(kernel_addr)x %(kernel_out)s %(kernel_size)x
127 sb save hostfs 0 %(fdt_addr)x %(fdt_out)s %(fdt_size)x
128 sb save hostfs 0 %(ramdisk_addr)x %(ramdisk_out)s %(ramdisk_size)x
129 sb save hostfs 0 %(loadables1_addr)x %(loadables1_out)s %(loadables1_size)x
130 sb save hostfs 0 %(loadables2_addr)x %(loadables2_out)s %(loadables2_size)x
131 reset
132 '''
133
134 def debug_stdout(stdout):
135     if DEBUG:
136         print stdout
137
138 def 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
150 def 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
160 def 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
171 def 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
184 def 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
197 def 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
216 def make_kernel(filename, text):
217     """Make a sample kernel with test data
218
219     Args:
220         filename: the name of the file you want to create
221     Returns:
222         Full path and filename of the kernel it created
223     """
224     fname = make_fname(filename)
225     data = ''
226     for i in range(100):
227         data += 'this %s %d is unlikely to boot\n' % (text, i)
228     with open(fname, 'w') as fd:
229         print >>fd, data
230     return fname
231
232 def make_ramdisk(filename, text):
233     """Make a sample ramdisk with test data
234
235     Returns:
236         Filename of ramdisk created
237     """
238     fname = make_fname(filename)
239     data = ''
240     for i in range(100):
241         data += '%s %d was seldom used in the middle ages\n' % (text, i)
242     with open(fname, 'w') as fd:
243         print >>fd, data
244     return fname
245
246 def 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
285 def 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
296 def fail(msg, stdout):
297     """Raise an error with a helpful failure message
298
299     Args:
300         msg: Message to display
301     """
302     print stdout
303     raise ValueError("Test '%s' failed: %s" % (test_name, msg))
304
305 def 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()
328     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')
332     kernel_out = make_fname('kernel-out.bin')
333     fdt_out = make_fname('fdt-out.dtb')
334     ramdisk_out = make_fname('ramdisk-out.bin')
335     loadables1_out = make_fname('loadables1-out.bin')
336     loadables2_out = make_fname('loadables2-out.bin')
337
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' : '',
358
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' : '',
372     }
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)
383     debug_stdout(stdout)
384     if read_file(kernel) != read_file(kernel_out):
385         fail('Kernel not loaded', stdout)
386     if read_file(control_dtb) == read_file(fdt_out):
387         fail('FDT loaded but should be ignored', stdout)
388     if read_file(ramdisk) == read_file(ramdisk_out):
389         fail('Ramdisk loaded but should not be', stdout)
390
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' %
401                 (fit_offset, real_fit_offset), stdout)
402
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)
408     debug_stdout(stdout)
409     if read_file(kernel) != read_file(kernel_out):
410         fail('Kernel not loaded', stdout)
411     if read_file(control_dtb) != read_file(fdt_out):
412         fail('FDT not loaded', stdout)
413     if read_file(ramdisk) == read_file(ramdisk_out):
414         fail('Ramdisk loaded but should not be', stdout)
415
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)
422     debug_stdout(stdout)
423     if read_file(ramdisk) != read_file(ramdisk_out):
424         fail('Ramdisk not loaded', stdout)
425
426     # 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
439 def 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
478 run_tests()