1# SPDX-License-Identifier:      GPL-2.0+
2""" Unit test for UEFI bootmanager
3"""
4
5import shutil
6import pytest
7from subprocess import call, check_call, CalledProcessError
8from tests import fs_helper
9
10@pytest.mark.boardspec('sandbox')
11@pytest.mark.buildconfigspec('cmd_efidebug')
12@pytest.mark.buildconfigspec('cmd_bootefi_bootmgr')
13@pytest.mark.singlethread
14def test_efi_bootmgr(ubman):
15    """ Unit test for UEFI bootmanager
16    The efidebug command is used to set up UEFI load options.
17    The bootefi bootmgr loads initrddump.efi as a payload.
18    The crc32 of the loaded initrd.img is checked
19
20    Args:
21        ubman -- U-Boot console
22    """
23    try:
24        efi_bootmgr_data, mnt = fs_helper.setup_image(ubman, 0, 0xc,
25                                                      basename='test_efi_bootmgr')
26
27        with open(mnt + '/initrd-1.img', 'w', encoding = 'ascii') as file:
28            file.write("initrd 1")
29
30        with open(mnt + '/initrd-2.img', 'w', encoding = 'ascii') as file:
31            file.write("initrd 2")
32
33        shutil.copyfile(ubman.config.build_dir + '/lib/efi_loader/initrddump.efi',
34                        mnt + '/initrddump.efi')
35
36        fsfile = fs_helper.mk_fs(ubman.config, 'vfat', 0x100000,
37                                 'test_efi_bootmgr', mnt)
38        check_call(f'dd if={fsfile} of={efi_bootmgr_data} bs=1M seek=1', shell=True)
39
40        ubman.run_command(cmd = f'host bind 0 {efi_bootmgr_data}')
41
42        ubman.run_command(cmd = 'efidebug boot add ' \
43            '-b 0001 label-1 host 0:1 initrddump.efi ' \
44            '-i host 0:1 initrd-1.img -s nocolor')
45        ubman.run_command(cmd = 'efidebug boot dump')
46        ubman.run_command(cmd = 'efidebug boot order 0001')
47        ubman.run_command(cmd = 'bootefi bootmgr')
48        response = ubman.run_command(cmd = 'load', wait_for_echo=False)
49        assert 'crc32: 0x181464af' in response
50        ubman.run_command(cmd = 'exit', wait_for_echo=False)
51
52        ubman.run_command(cmd = 'efidebug boot add ' \
53            '-B 0002 label-2 host 0:1 initrddump.efi ' \
54            '-I host 0:1 initrd-2.img -s nocolor')
55        ubman.run_command(cmd = 'efidebug boot dump')
56        ubman.run_command(cmd = 'efidebug boot order 0002')
57        ubman.run_command(cmd = 'bootefi bootmgr')
58        response = ubman.run_command(cmd = 'load', wait_for_echo=False)
59        assert 'crc32: 0x811d3515' in response
60        ubman.run_command(cmd = 'exit', wait_for_echo=False)
61
62        ubman.run_command(cmd = 'efidebug boot rm 0001')
63        ubman.run_command(cmd = 'efidebug boot rm 0002')
64    except CalledProcessError as err:
65        pytest.skip('Preparing test_efi_bootmgr image failed')
66        call('rm -f %s' % efi_bootmgr_data, shell=True)
67        return
68    finally:
69        call('rm -rf %s' % mnt, shell=True)
70        call('rm -f %s' % efi_bootmgr_data, shell=True)
71