test/py: Create a test for launching UEFI binaries from FIT images
[oweals/u-boot.git] / test / py / tests / test_efi_fit.py
1 # SPDX-License-Identifier: GPL-2.0
2 # Copyright (c) 2019, Cristian Ciocaltea <cristian.ciocaltea@gmail.com>
3 #
4 # Work based on:
5 # - test_net.py
6 # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
7 # - test_fit.py
8 # Copyright (c) 2013, Google Inc.
9 #
10 # Test launching UEFI binaries from FIT images.
11
12 import os.path
13 import pytest
14 import u_boot_utils as util
15
16 """
17 Note: This test relies on boardenv_* containing configuration values to define
18 which network environment is available for testing. Without this, the parts
19 that rely on network will be automatically skipped.
20
21 For example:
22
23 # Boolean indicating whether the Ethernet device is attached to USB, and hence
24 # USB enumeration needs to be performed prior to network tests.
25 # This variable may be omitted if its value is False.
26 env__net_uses_usb = False
27
28 # Boolean indicating whether the Ethernet device is attached to PCI, and hence
29 # PCI enumeration needs to be performed prior to network tests.
30 # This variable may be omitted if its value is False.
31 env__net_uses_pci = True
32
33 # True if a DHCP server is attached to the network, and should be tested.
34 # If DHCP testing is not possible or desired, this variable may be omitted or
35 # set to False.
36 env__net_dhcp_server = True
37
38 # A list of environment variables that should be set in order to configure a
39 # static IP. If solely relying on DHCP, this variable may be omitted or set to
40 # an empty list.
41 env__net_static_env_vars = [
42     ('ipaddr', '10.0.0.100'),
43     ('netmask', '255.255.255.0'),
44     ('serverip', '10.0.0.1'),
45 ]
46
47 # Details regarding a file that may be read from a TFTP server. This variable
48 # may be omitted or set to None if TFTP testing is not possible or desired.
49 # Additionally, when the 'size' is not available, the file will be generated
50 # automatically in the TFTP root directory, as specified by the 'dn' field.
51 env__efi_fit_tftp_file = {
52     'fn': 'test-efi-fit.img',   # File path relative to TFTP root
53     'size': 3831,               # File size
54     'crc32': '9fa3f79c',        # Checksum using CRC-32 algorithm, optional
55     'addr': 0x40400000,         # Loading address, integer, optional
56     'dn': 'tftp/root/dir',      # TFTP root directory path, optional
57 }
58 """
59
60 # Define the parametrized ITS data to be used for FIT images generation.
61 its_data = '''
62 /dts-v1/;
63
64 / {
65     description = "EFI image with FDT blob";
66     #address-cells = <1>;
67
68     images {
69         efi {
70             description = "Test EFI";
71             data = /incbin/("%(efi-bin)s");
72             type = "%(kernel-type)s";
73             arch = "%(sys-arch)s";
74             os = "efi";
75             compression = "%(efi-comp)s";
76             load = <0x0>;
77             entry = <0x0>;
78         };
79         fdt {
80             description = "Test FDT";
81             data = /incbin/("%(fdt-bin)s");
82             type = "flat_dt";
83             arch = "%(sys-arch)s";
84             compression = "%(fdt-comp)s";
85         };
86     };
87
88     configurations {
89         default = "config-efi-fdt";
90         config-efi-fdt {
91             description = "EFI FIT w/ FDT";
92             kernel = "efi";
93             fdt = "fdt";
94         };
95         config-efi-nofdt {
96             description = "EFI FIT w/o FDT";
97             kernel = "efi";
98         };
99     };
100 };
101 '''
102
103 # Define the parametrized FDT data to be used for DTB images generation.
104 fdt_data = '''
105 /dts-v1/;
106
107 / {
108     #address-cells = <1>;
109     #size-cells = <0>;
110
111     model = "%(sys-arch)s %(fdt_type)s EFI FIT Boot Test";
112     compatible = "%(sys-arch)s";
113
114     reset@0 {
115         compatible = "%(sys-arch)s,reset";
116         reg = <0>;
117     };
118 };
119 '''
120
121 @pytest.mark.buildconfigspec('bootm_efi')
122 @pytest.mark.buildconfigspec('cmd_bootefi_hello_compile')
123 @pytest.mark.buildconfigspec('fit')
124 @pytest.mark.notbuildconfigspec('generate_acpi_table')
125 @pytest.mark.requiredtool('dtc')
126 def test_efi_fit_launch(u_boot_console):
127     """Test handling of UEFI binaries inside FIT images.
128
129     The tests are trying to launch U-Boot's helloworld.efi embedded into
130     FIT images, in uncompressed or gzip compressed format.
131
132     Additionally, a sample FDT blob is created and embedded into the above
133     mentioned FIT images, in uncompressed or gzip compressed format.
134
135     For more details, see launch_efi().
136
137     The following test cases are currently defined and enabled:
138      - Launch uncompressed FIT EFI & internal FDT
139      - Launch uncompressed FIT EFI & FIT FDT
140      - Launch compressed FIT EFI & internal FDT
141      - Launch compressed FIT EFI & FIT FDT
142     """
143
144     def net_pre_commands():
145         """Execute any commands required to enable network hardware.
146
147         These commands are provided by the boardenv_* file; see the comment
148         at the beginning of this file.
149         """
150
151         init_usb = cons.config.env.get('env__net_uses_usb', False)
152         if init_usb:
153             cons.run_command('usb start')
154
155         init_pci = cons.config.env.get('env__net_uses_pci', False)
156         if init_pci:
157             cons.run_command('pci enum')
158
159     def net_dhcp():
160         """Execute the dhcp command.
161
162         The boardenv_* file may be used to enable/disable DHCP; see the
163         comment at the beginning of this file.
164         """
165
166         has_dhcp = cons.config.buildconfig.get('config_cmd_dhcp', 'n') == 'y'
167         if not has_dhcp:
168             cons.log.warning('CONFIG_CMD_DHCP != y: Skipping DHCP network setup')
169             return False
170
171         test_dhcp = cons.config.env.get('env__net_dhcp_server', False)
172         if not test_dhcp:
173             cons.log.info('No DHCP server available')
174             return False
175
176         cons.run_command('setenv autoload no')
177         output = cons.run_command('dhcp')
178         assert 'DHCP client bound to address ' in output
179         return True
180
181     def net_setup_static():
182         """Set up a static IP configuration.
183
184         The configuration is provided by the boardenv_* file; see the comment at
185         the beginning of this file.
186         """
187
188         has_dhcp = cons.config.buildconfig.get('config_cmd_dhcp', 'n') == 'y'
189         if not has_dhcp:
190             cons.log.warning('CONFIG_NET != y: Skipping static network setup')
191             return False
192
193         env_vars = cons.config.env.get('env__net_static_env_vars', None)
194         if not env_vars:
195             cons.log.info('No static network configuration is defined')
196             return False
197
198         for (var, val) in env_vars:
199             cons.run_command('setenv %s %s' % (var, val))
200         return True
201
202     def make_fpath(fname):
203         """Compute the path of a given (temporary) file.
204
205         Args:
206             fname: The name of a file within U-Boot build dir.
207         Return:
208             The computed file path.
209         """
210
211         return os.path.join(cons.config.build_dir, fname)
212
213     def make_efi(fname, comp):
214         """Create an UEFI binary.
215
216         This simply copies lib/efi_loader/helloworld.efi into U-Boot
217         build dir and, optionally, compresses the file using gzip.
218
219         Args:
220             fname: The target file name within U-Boot build dir.
221             comp: Flag to enable gzip compression.
222         Return:
223             The path of the created file.
224         """
225
226         bin_path = make_fpath(fname)
227         util.run_and_log(cons,
228                 ['cp', make_fpath('lib/efi_loader/helloworld.efi'), bin_path])
229         if comp:
230             util.run_and_log(cons, ['gzip', '-f', bin_path])
231             bin_path += '.gz'
232         return bin_path
233
234     def make_dtb(fdt_type, comp):
235         """Create a sample DTB file.
236
237         Creates a DTS file and compiles it to a DTB.
238
239         Args:
240             fdt_type: The type of the FDT, i.e. internal, user.
241             comp: Flag to enable gzip compression.
242         Return:
243             The path of the created file.
244         """
245
246         # Generate resources referenced by FDT.
247         fdt_params = {
248             'sys-arch': sys_arch,
249             'fdt_type': fdt_type,
250         }
251
252         # Generate a test FDT file.
253         dts = make_fpath('test-efi-fit-%s.dts' % fdt_type)
254         with open(dts, 'w') as fd:
255             fd.write(fdt_data % fdt_params)
256
257         # Build the test FDT.
258         dtb = make_fpath('test-efi-fit-%s.dtb' % fdt_type)
259         util.run_and_log(cons, ['dtc', '-I', 'dts', '-O', 'dtb', '-o', dtb, dts])
260         if comp:
261             util.run_and_log(cons, ['gzip', '-f', dtb])
262             dtb += '.gz'
263         return dtb
264
265     def make_fit(comp):
266         """Create a sample FIT image.
267
268         Runs 'mkimage' to create a FIT image within U-Boot build dir.
269         Args:
270             comp: Enable gzip compression for the EFI binary and FDT blob.
271         Return:
272             The path of the created file.
273         """
274
275         # Generate resources referenced by ITS.
276         its_params = {
277             'sys-arch': sys_arch,
278             'efi-bin': os.path.basename(make_efi('test-efi-fit-helloworld.efi', comp)),
279             'kernel-type': 'kernel' if comp else 'kernel_noload',
280             'efi-comp': 'gzip' if comp else 'none',
281             'fdt-bin': os.path.basename(make_dtb('user', comp)),
282             'fdt-comp': 'gzip' if comp else 'none',
283         }
284
285         # Generate a test ITS file.
286         its_path = make_fpath('test-efi-fit-helloworld.its')
287         with open(its_path, 'w') as fd:
288             fd.write(its_data % its_params)
289
290         # Build the test ITS.
291         fit_path = make_fpath('test-efi-fit-helloworld.fit')
292         util.run_and_log(
293                 cons, [make_fpath('tools/mkimage'), '-f', its_path, fit_path])
294         return fit_path
295
296     def load_fit_from_host(f):
297         """Load the FIT image using the 'host load' command and return its address.
298
299         Args:
300             f: Dictionary describing the FIT image to load, see env__efi_fit_test_file
301                 in the comment at the beginning of this file.
302         Return:
303             The address where the file has been loaded.
304         """
305
306         addr = f.get('addr', None)
307         if not addr:
308             addr = util.find_ram_base(cons)
309
310         output = cons.run_command(
311                     'host load hostfs - %x %s/%s' % (addr, f['dn'], f['fn']))
312         expected_text = ' bytes read'
313         sz = f.get('size', None)
314         if sz:
315             expected_text = '%d' % sz + expected_text
316         assert(expected_text in output)
317
318         return addr
319
320     def load_fit_from_tftp(f):
321         """Load the FIT image using the tftpboot command and return its address.
322
323         The file is downloaded from the TFTP server, its size and optionally its
324         CRC32 are validated.
325
326         Args:
327             f: Dictionary describing the FIT image to load, see env__efi_fit_tftp_file
328                 in the comment at the beginning of this file.
329         Return:
330             The address where the file has been loaded.
331         """
332
333         addr = f.get('addr', None)
334         if not addr:
335             addr = util.find_ram_base(cons)
336
337         fn = f['fn']
338         output = cons.run_command('tftpboot %x %s' % (addr, fn))
339         expected_text = 'Bytes transferred = '
340         sz = f.get('size', None)
341         if sz:
342             expected_text += '%d' % sz
343         assert expected_text in output
344
345         expected_crc = f.get('crc32', None)
346         if not expected_crc:
347             return addr
348
349         if cons.config.buildconfig.get('config_cmd_crc32', 'n') != 'y':
350             return addr
351
352         output = cons.run_command('crc32 $fileaddr $filesize')
353         assert expected_crc in output
354
355         return addr
356
357     def launch_efi(enable_fdt, enable_comp):
358         """Launch U-Boot's helloworld.efi binary from a FIT image.
359
360         An external image file can be downloaded from TFTP, when related
361         details are provided by the boardenv_* file; see the comment at the
362         beginning of this file.
363
364         If the size of the TFTP file is not provided within env__efi_fit_tftp_file,
365         the test image is generated automatically and placed in the TFTP root
366         directory specified via the 'dn' field.
367
368         When running the tests on Sandbox, the image file is loaded directly
369         from the host filesystem.
370
371         Once the load address is available on U-Boot console, the 'bootm'
372         command is executed for either 'config-efi-fdt' or 'config-efi-nofdt'
373         FIT configuration, depending on the value of the 'enable_fdt' function
374         argument.
375
376         Eventually the 'Hello, world' message is expected in the U-Boot console.
377
378         Args:
379             enable_fdt: Flag to enable using the FDT blob inside FIT image.
380             enable_comp: Flag to enable GZIP compression on EFI and FDT
381                 generated content.
382         """
383
384         with cons.log.section('FDT=%s;COMP=%s' % (enable_fdt, enable_comp)):
385             if is_sandbox:
386                 fit = {
387                     'dn': cons.config.build_dir,
388                 }
389             else:
390                 # Init networking.
391                 net_pre_commands()
392                 net_set_up = net_dhcp()
393                 net_set_up = net_setup_static() or net_set_up
394                 if not net_set_up:
395                     pytest.skip('Network not initialized')
396
397                 fit = cons.config.env.get('env__efi_fit_tftp_file', None)
398                 if not fit:
399                     pytest.skip('No env__efi_fit_tftp_file binary specified in environment')
400
401             sz = fit.get('size', None)
402             if not sz:
403                 if not fit.get('dn', None):
404                     pytest.skip('Neither "size", nor "dn" info provided in env__efi_fit_tftp_file')
405
406                 # Create test FIT image.
407                 fit_path = make_fit(enable_comp)
408                 fit['fn'] = os.path.basename(fit_path)
409                 fit['size'] = os.path.getsize(fit_path)
410
411                 # Copy image to TFTP root directory.
412                 if fit['dn'] != cons.config.build_dir:
413                     util.run_and_log(cons, ['mv', '-f', fit_path, '%s/' % fit['dn']])
414
415             # Load FIT image.
416             addr = load_fit_from_host(fit) if is_sandbox else load_fit_from_tftp(fit)
417
418             # Select boot configuration.
419             fit_config = 'config-efi-fdt' if enable_fdt else 'config-efi-nofdt'
420
421             # Try booting.
422             cons.run_command(
423                     'bootm %x#%s' % (addr, fit_config), wait_for_prompt=False)
424             if enable_fdt:
425                 cons.wait_for('Booting using the fdt blob')
426             cons.wait_for('Hello, world')
427             cons.wait_for('## Application terminated, r = 0')
428             cons.restart_uboot();
429
430     cons = u_boot_console
431     # Array slice removes leading/trailing quotes.
432     sys_arch = cons.config.buildconfig.get('config_sys_arch', '"sandbox"')[1:-1]
433     is_sandbox = sys_arch == 'sandbox'
434
435     try:
436         if is_sandbox:
437             # Use our own device tree file, will be restored afterwards.
438             control_dtb = make_dtb('internal', False)
439             old_dtb = cons.config.dtb
440             cons.config.dtb = control_dtb
441
442         # Run tests
443         # - fdt OFF, gzip OFF
444         launch_efi(False, False)
445         # - fdt ON, gzip OFF
446         launch_efi(True, False)
447
448         if is_sandbox:
449             # - fdt OFF, gzip ON
450             launch_efi(False, True)
451             # - fdt ON, gzip ON
452             launch_efi(True, True)
453
454     finally:
455         if is_sandbox:
456             # Go back to the original U-Boot with the correct dtb.
457             cons.config.dtb = old_dtb
458             cons.restart_uboot()