]> Git Repo - u-boot.git/blob - test/py/tests/test_ut.py
test: Make bootstd init run only on sandbox
[u-boot.git] / test / py / tests / test_ut.py
1 # SPDX-License-Identifier: GPL-2.0
2 # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
3
4 import collections
5 import getpass
6 import gzip
7 import os
8 import os.path
9 import pytest
10
11 import u_boot_utils
12 # pylint: disable=E0611
13 from tests import fs_helper
14
15 def mkdir_cond(dirname):
16     """Create a directory if it doesn't already exist
17
18     Args:
19         dirname (str): Name of directory to create
20     """
21     if not os.path.exists(dirname):
22         os.mkdir(dirname)
23
24 def setup_image(cons, mmc_dev, part_type, second_part=False):
25     """Create a 20MB disk image with a single partition
26
27     Args:
28         cons (ConsoleBase): Console to use
29         mmc_dev (int): MMC device number to use, e.g. 1
30         part_type (int): Partition type, e.g. 0xc for FAT32
31         second_part (bool): True to contain a small second partition
32
33     Returns:
34         tuple:
35             str: Filename of MMC image
36             str: Directory name of 'mnt' directory
37     """
38     fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
39     mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
40     mkdir_cond(mnt)
41
42     spec = f'type={part_type:x}, size=18M, bootable'
43     if second_part:
44         spec += '\ntype=c'
45
46     u_boot_utils.run_and_log(cons, 'qemu-img create %s 20M' % fname)
47     u_boot_utils.run_and_log(cons, 'sudo sfdisk %s' % fname,
48                              stdin=spec.encode('utf-8'))
49     return fname, mnt
50
51 def mount_image(cons, fname, mnt, fstype):
52     """Create a filesystem and mount it on partition 1
53
54     Args:
55         cons (ConsoleBase): Console to use
56         fname (str): Filename of MMC image
57         mnt (str): Directory name of 'mnt' directory
58         fstype (str): Filesystem type ('vfat' or 'ext4')
59
60     Returns:
61         str: Name of loop device used
62     """
63     out = u_boot_utils.run_and_log(cons, 'sudo losetup --show -f -P %s' % fname)
64     loop = out.strip()
65     part = f'{loop}p1'
66     u_boot_utils.run_and_log(cons, f'sudo mkfs.{fstype} {part}')
67     opts = ''
68     if fstype == 'vfat':
69          opts += f' -o uid={os.getuid()},gid={os.getgid()}'
70     u_boot_utils.run_and_log(cons, f'sudo mount -o loop {part} {mnt}{opts}')
71     u_boot_utils.run_and_log(cons, f'sudo chown {getpass.getuser()} {mnt}')
72     return loop
73
74 def copy_prepared_image(cons, mmc_dev, fname):
75     """Use a prepared image since we cannot create one
76
77     Args:
78         cons (ConsoleBase): Console touse
79         mmc_dev (int): MMC device number
80         fname (str): Filename of MMC image
81     """
82     infname = os.path.join(cons.config.source_dir,
83                            f'test/py/tests/bootstd/mmc{mmc_dev}.img.xz')
84     u_boot_utils.run_and_log(
85         cons,
86         ['sh', '-c', 'xz -dc %s >%s' % (infname, fname)])
87
88 def setup_bootmenu_image(cons):
89     """Create a 20MB disk image with a single ext4 partition
90
91     This is modelled on Armbian 22.08 Jammy
92     """
93     mmc_dev = 4
94     fname, mnt = setup_image(cons, mmc_dev, 0x83)
95
96     loop = None
97     mounted = False
98     complete = False
99     try:
100         loop = mount_image(cons, fname, mnt, 'ext4')
101         mounted = True
102
103         vmlinux = 'Image'
104         initrd = 'uInitrd'
105         dtbdir = 'dtb'
106         script = '''# DO NOT EDIT THIS FILE
107 #
108 # Please edit /boot/armbianEnv.txt to set supported parameters
109 #
110
111 setenv load_addr "0x9000000"
112 setenv overlay_error "false"
113 # default values
114 setenv rootdev "/dev/mmcblk%dp1"
115 setenv verbosity "1"
116 setenv console "both"
117 setenv bootlogo "false"
118 setenv rootfstype "ext4"
119 setenv docker_optimizations "on"
120 setenv earlycon "off"
121
122 echo "Boot script loaded from ${devtype} ${devnum}"
123
124 if test -e ${devtype} ${devnum} ${prefix}armbianEnv.txt; then
125         load ${devtype} ${devnum} ${load_addr} ${prefix}armbianEnv.txt
126         env import -t ${load_addr} ${filesize}
127 fi
128
129 if test "${logo}" = "disabled"; then setenv logo "logo.nologo"; fi
130
131 if test "${console}" = "display" || test "${console}" = "both"; then setenv consoleargs "console=tty1"; fi
132 if test "${console}" = "serial" || test "${console}" = "both"; then setenv consoleargs "console=ttyS2,1500000 ${consoleargs}"; fi
133 if test "${earlycon}" = "on"; then setenv consoleargs "earlycon ${consoleargs}"; fi
134 if test "${bootlogo}" = "true"; then setenv consoleargs "bootsplash.bootfile=bootsplash.armbian ${consoleargs}"; fi
135
136 # get PARTUUID of first partition on SD/eMMC the boot script was loaded from
137 if test "${devtype}" = "mmc"; then part uuid mmc ${devnum}:1 partuuid; fi
138
139 setenv bootargs "root=${rootdev} rootwait rootfstype=${rootfstype} ${consoleargs} consoleblank=0 loglevel=${verbosity} ubootpart=${partuuid} usb-storage.quirks=${usbstoragequirks} ${extraargs} ${extraboardargs}"
140
141 if test "${docker_optimizations}" = "on"; then setenv bootargs "${bootargs} cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1"; fi
142
143 load ${devtype} ${devnum} ${ramdisk_addr_r} ${prefix}uInitrd
144 load ${devtype} ${devnum} ${kernel_addr_r} ${prefix}Image
145
146 load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
147 fdt addr ${fdt_addr_r}
148 fdt resize 65536
149 for overlay_file in ${overlays}; do
150         if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-${overlay_file}.dtbo; then
151                 echo "Applying kernel provided DT overlay ${overlay_prefix}-${overlay_file}.dtbo"
152                 fdt apply ${load_addr} || setenv overlay_error "true"
153         fi
154 done
155 for overlay_file in ${user_overlays}; do
156         if load ${devtype} ${devnum} ${load_addr} ${prefix}overlay-user/${overlay_file}.dtbo; then
157                 echo "Applying user provided DT overlay ${overlay_file}.dtbo"
158                 fdt apply ${load_addr} || setenv overlay_error "true"
159         fi
160 done
161 if test "${overlay_error}" = "true"; then
162         echo "Error applying DT overlays, restoring original DT"
163         load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
164 else
165         if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-fixup.scr; then
166                 echo "Applying kernel provided DT fixup script (${overlay_prefix}-fixup.scr)"
167                 source ${load_addr}
168         fi
169         if test -e ${devtype} ${devnum} ${prefix}fixup.scr; then
170                 load ${devtype} ${devnum} ${load_addr} ${prefix}fixup.scr
171                 echo "Applying user provided fixup script (fixup.scr)"
172                 source ${load_addr}
173         fi
174 fi
175 booti ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr_r}
176
177 # Recompile with:
178 # mkimage -C none -A arm -T script -d /boot/boot.cmd /boot/boot.scr
179 ''' % (mmc_dev)
180         bootdir = os.path.join(mnt, 'boot')
181         mkdir_cond(bootdir)
182         cmd_fname = os.path.join(bootdir, 'boot.cmd')
183         scr_fname = os.path.join(bootdir, 'boot.scr')
184         with open(cmd_fname, 'w') as outf:
185             print(script, file=outf)
186
187         infname = os.path.join(cons.config.source_dir,
188                                'test/py/tests/bootstd/armbian.bmp.xz')
189         bmp_file = os.path.join(bootdir, 'boot.bmp')
190         u_boot_utils.run_and_log(
191             cons,
192             ['sh', '-c', f'xz -dc {infname} >{bmp_file}'])
193
194         u_boot_utils.run_and_log(
195             cons, f'mkimage -C none -A arm -T script -d {cmd_fname} {scr_fname}')
196
197         kernel = 'vmlinuz-5.15.63-rockchip64'
198         target = os.path.join(bootdir, kernel)
199         with open(target, 'wb') as outf:
200             print('kernel', outf)
201
202         symlink = os.path.join(bootdir, 'Image')
203         if os.path.exists(symlink):
204             os.remove(symlink)
205         u_boot_utils.run_and_log(
206             cons, f'echo here {kernel} {symlink}')
207         os.symlink(kernel, symlink)
208
209         u_boot_utils.run_and_log(
210             cons, f'mkimage -C none -A arm -T script -d {cmd_fname} {scr_fname}')
211         complete = True
212
213     except ValueError as exc:
214         print('Falled to create image, failing back to prepared copy: %s',
215               str(exc))
216     finally:
217         if mounted:
218             u_boot_utils.run_and_log(cons, 'sudo umount --lazy %s' % mnt)
219         if loop:
220             u_boot_utils.run_and_log(cons, 'sudo losetup -d %s' % loop)
221
222     if not complete:
223         copy_prepared_image(cons, mmc_dev, fname)
224
225 def setup_bootflow_image(cons):
226     """Create a 20MB disk image with a single FAT partition"""
227     mmc_dev = 1
228     fname, mnt = setup_image(cons, mmc_dev, 0xc, second_part=True)
229
230     loop = None
231     mounted = False
232     complete = False
233     try:
234         loop = mount_image(cons, fname, mnt, 'vfat')
235         mounted = True
236
237         vmlinux = 'vmlinuz-5.3.7-301.fc31.armv7hl'
238         initrd = 'initramfs-5.3.7-301.fc31.armv7hl.img'
239         dtbdir = 'dtb-5.3.7-301.fc31.armv7hl'
240         script = '''# extlinux.conf generated by appliance-creator
241 ui menu.c32
242 menu autoboot Welcome to Fedora-Workstation-armhfp-31-1.9. Automatic boot in # second{,s}. Press a key for options.
243 menu title Fedora-Workstation-armhfp-31-1.9 Boot Options.
244 menu hidden
245 timeout 20
246 totaltimeout 600
247
248 label Fedora-Workstation-armhfp-31-1.9 (5.3.7-301.fc31.armv7hl)
249         kernel /%s
250         append ro root=UUID=9732b35b-4cd5-458b-9b91-80f7047e0b8a rhgb quiet LANG=en_US.UTF-8 cma=192MB cma=256MB
251         fdtdir /%s/
252         initrd /%s''' % (vmlinux, dtbdir, initrd)
253         ext = os.path.join(mnt, 'extlinux')
254         mkdir_cond(ext)
255
256         with open(os.path.join(ext, 'extlinux.conf'), 'w') as fd:
257             print(script, file=fd)
258
259         inf = os.path.join(cons.config.persistent_data_dir, 'inf')
260         with open(inf, 'wb') as fd:
261             fd.write(gzip.compress(b'vmlinux'))
262         u_boot_utils.run_and_log(cons, 'mkimage -f auto -d %s %s' %
263                                  (inf, os.path.join(mnt, vmlinux)))
264
265         with open(os.path.join(mnt, initrd), 'w') as fd:
266             print('initrd', file=fd)
267
268         mkdir_cond(os.path.join(mnt, dtbdir))
269
270         dtb_file = os.path.join(mnt, '%s/sandbox.dtb' % dtbdir)
271         u_boot_utils.run_and_log(
272             cons, 'dtc -o %s' % dtb_file, stdin=b'/dts-v1/; / {};')
273         complete = True
274     except ValueError as exc:
275         print('Falled to create image, failing back to prepared copy: %s',
276               str(exc))
277     finally:
278         if mounted:
279             u_boot_utils.run_and_log(cons, 'sudo umount --lazy %s' % mnt)
280         if loop:
281             u_boot_utils.run_and_log(cons, 'sudo losetup -d %s' % loop)
282
283     if not complete:
284         copy_prepared_image(cons, mmc_dev, fname)
285
286
287 def setup_cros_image(cons):
288     """Create a 20MB disk image with ChromiumOS partitions"""
289     Partition = collections.namedtuple('part', 'start,size,name')
290     parts = {}
291     disk_data = None
292
293     def pack_kernel(cons, arch, kern, dummy):
294         """Pack a kernel containing some fake data
295
296         Args:
297             cons (ConsoleBase): Console to use
298             arch (str): Architecture to use ('x86' or 'arm')
299             kern (str): Filename containing kernel
300             dummy (str): Dummy filename to use for config and bootloader
301
302         Return:
303             bytes: Packed-kernel data
304         """
305         kern_part = os.path.join(cons.config.result_dir, 'kern-part-{arch}.bin')
306         u_boot_utils.run_and_log(
307             cons,
308             f'futility vbutil_kernel --pack {kern_part} '
309             '--keyblock doc/chromium/files/devkeys/kernel.keyblock '
310             '--signprivate doc/chromium/files/devkeys/kernel_data_key.vbprivk '
311             f'--version 1  --config {dummy} --bootloader {dummy} '
312             f'--vmlinuz {kern}')
313
314         with open(kern_part, 'rb') as inf:
315             kern_part_data = inf.read()
316         return kern_part_data
317
318     def set_part_data(partnum, data):
319         """Set the contents of a disk partition
320
321         This updates disk_data by putting data in the right place
322
323         Args:
324             partnum (int): Partition number to set
325             data (bytes): Data for that partition
326         """
327         nonlocal disk_data
328
329         start = parts[partnum].start * sect_size
330         disk_data = disk_data[:start] + data + disk_data[start + len(data):]
331
332     mmc_dev = 5
333     fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
334     u_boot_utils.run_and_log(cons, 'qemu-img create %s 20M' % fname)
335     #mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
336     #mkdir_cond(mnt)
337     u_boot_utils.run_and_log(cons, f'cgpt create {fname}')
338
339     uuid_state = 'ebd0a0a2-b9e5-4433-87c0-68b6b72699c7'
340     uuid_kern = 'fe3a2a5d-4f32-41a7-b725-accc3285a309'
341     uuid_root = '3cb8e202-3b7e-47dd-8a3c-7ff2a13cfcec'
342     uuid_rwfw = 'cab6e88e-abf3-4102-a07a-d4bb9be3c1d3'
343     uuid_reserved = '2e0a753d-9e48-43b0-8337-b15192cb1b5e'
344     uuid_efi = 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b'
345
346     ptr = 40
347
348     # Number of sectors in 1MB
349     sect_size = 512
350     sect_1mb = (1 << 20) // sect_size
351
352     required_parts = [
353         {'num': 0xb, 'label':'RWFW', 'type': uuid_rwfw, 'size': '1'},
354         {'num': 6, 'label':'KERN_C', 'type': uuid_kern, 'size': '1'},
355         {'num': 7, 'label':'ROOT_C', 'type': uuid_root, 'size': '1'},
356         {'num': 9, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
357         {'num': 0xa, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
358
359         {'num': 2, 'label':'KERN_A', 'type': uuid_kern, 'size': '1M'},
360         {'num': 4, 'label':'KERN_B', 'type': uuid_kern, 'size': '1M'},
361
362         {'num': 8, 'label':'OEM', 'type': uuid_state, 'size': '1M'},
363         {'num': 0xc, 'label':'EFI-SYSTEM', 'type': uuid_efi, 'size': '1M'},
364
365         {'num': 5, 'label':'ROOT_B', 'type': uuid_root, 'size': '1'},
366         {'num': 3, 'label':'ROOT_A', 'type': uuid_root, 'size': '1'},
367         {'num': 1, 'label':'STATE', 'type': uuid_state, 'size': '1M'},
368         ]
369
370     for part in required_parts:
371         size_str = part['size']
372         if 'M' in size_str:
373             size = int(size_str[:-1]) * sect_1mb
374         else:
375             size = int(size_str)
376         u_boot_utils.run_and_log(
377             cons,
378             f"cgpt add -i {part['num']} -b {ptr} -s {size} -t {part['type']} {fname}")
379         ptr += size
380
381     u_boot_utils.run_and_log(cons, f'cgpt boot -p {fname}')
382     out = u_boot_utils.run_and_log(cons, f'cgpt show -q {fname}')
383     '''We expect something like this:
384         8239        2048       1  Basic data
385           45        2048       2  ChromeOS kernel
386         8238           1       3  ChromeOS rootfs
387         2093        2048       4  ChromeOS kernel
388         8237           1       5  ChromeOS rootfs
389           41           1       6  ChromeOS kernel
390           42           1       7  ChromeOS rootfs
391         4141        2048       8  Basic data
392           43           1       9  ChromeOS reserved
393           44           1      10  ChromeOS reserved
394           40           1      11  ChromeOS firmware
395         6189        2048      12  EFI System Partition
396     '''
397
398     # Create a dict (indexed by partition number) containing the above info
399     for line in out.splitlines():
400         start, size, num, name = line.split(maxsplit=3)
401         parts[int(num)] = Partition(int(start), int(size), name)
402
403     dummy = os.path.join(cons.config.result_dir, 'dummy.txt')
404     with open(dummy, 'wb') as outf:
405         outf.write(b'dummy\n')
406
407     # For now we just use dummy kernels. This limits testing to just detecting
408     # a signed kernel. We could add support for the x86 data structures so that
409     # testing could cover getting the cmdline, setup.bin and other pieces.
410     kern = os.path.join(cons.config.result_dir, 'kern.bin')
411     with open(kern, 'wb') as outf:
412         outf.write(b'kernel\n')
413
414     with open(fname, 'rb') as inf:
415         disk_data = inf.read()
416
417     # put x86 kernel in partition 2 and arm one in partition 4
418     set_part_data(2, pack_kernel(cons, 'x86', kern, dummy))
419     set_part_data(4, pack_kernel(cons, 'arm', kern, dummy))
420
421     with open(fname, 'wb') as outf:
422         outf.write(disk_data)
423
424     return fname
425
426
427 def setup_cedit_file(cons):
428     infname = os.path.join(cons.config.source_dir,
429                            'test/boot/files/expo_layout.dts')
430     inhname = os.path.join(cons.config.source_dir,
431                            'test/boot/files/expo_ids.h')
432     expo_tool = os.path.join(cons.config.source_dir, 'tools/expo.py')
433     outfname = 'cedit.dtb'
434     u_boot_utils.run_and_log(
435         cons, f'{expo_tool} -e {inhname} -l {infname} -o {outfname}')
436
437 @pytest.mark.buildconfigspec('ut_dm')
438 def test_ut_dm_init(u_boot_console):
439     """Initialize data for ut dm tests."""
440
441     fn = u_boot_console.config.source_dir + '/testflash.bin'
442     if not os.path.exists(fn):
443         data = b'this is a test'
444         data += b'\x00' * ((4 * 1024 * 1024) - len(data))
445         with open(fn, 'wb') as fh:
446             fh.write(data)
447
448     fn = u_boot_console.config.source_dir + '/spi.bin'
449     if not os.path.exists(fn):
450         data = b'\x00' * (2 * 1024 * 1024)
451         with open(fn, 'wb') as fh:
452             fh.write(data)
453
454     # Create a file with a single partition
455     fn = u_boot_console.config.source_dir + '/scsi.img'
456     if not os.path.exists(fn):
457         data = b'\x00' * (2 * 1024 * 1024)
458         with open(fn, 'wb') as fh:
459             fh.write(data)
460         u_boot_utils.run_and_log(
461             u_boot_console, f'sfdisk {fn}', stdin=b'type=83')
462
463     fs_helper.mk_fs(u_boot_console.config, 'ext2', 0x200000, '2MB')
464     fs_helper.mk_fs(u_boot_console.config, 'fat32', 0x100000, '1MB')
465
466     mmc_dev = 6
467     fn = os.path.join(u_boot_console.config.source_dir, f'mmc{mmc_dev}.img')
468     data = b'\x00' * (12 * 1024 * 1024)
469     with open(fn, 'wb') as fh:
470         fh.write(data)
471
472 @pytest.mark.buildconfigspec('cmd_bootflow')
473 @pytest.mark.buildconfigspec('sandbox')
474 def test_ut_dm_init_bootstd(u_boot_console):
475     """Initialise data for bootflow tests"""
476
477     setup_bootflow_image(u_boot_console)
478     setup_bootmenu_image(u_boot_console)
479     setup_cedit_file(u_boot_console)
480     setup_cros_image(u_boot_console)
481
482     # Restart so that the new mmc1.img is picked up
483     u_boot_console.restart_uboot()
484
485
486 def test_ut(u_boot_console, ut_subtest):
487     """Execute a "ut" subtest.
488
489     The subtests are collected in function generate_ut_subtest() from linker
490     generated lists by applying a regular expression to the lines of file
491     u-boot.sym. The list entries are created using the C macro UNIT_TEST().
492
493     Strict naming conventions have to be followed to match the regular
494     expression. Use UNIT_TEST(foo_test_bar, _flags, foo_test) for a test bar in
495     test suite foo that can be executed via command 'ut foo bar' and is
496     implemented in C function foo_test_bar().
497
498     Args:
499         u_boot_console (ConsoleBase): U-Boot console
500         ut_subtest (str): test to be executed via command ut, e.g 'foo bar' to
501             execute command 'ut foo bar'
502     """
503
504     if ut_subtest == 'hush hush_test_simple_dollar':
505         # ut hush hush_test_simple_dollar prints "Unknown command" on purpose.
506         with u_boot_console.disable_check('unknown_command'):
507             output = u_boot_console.run_command('ut ' + ut_subtest)
508         assert('Unknown command \'quux\' - try \'help\'' in output)
509     else:
510         output = u_boot_console.run_command('ut ' + ut_subtest)
511     assert output.endswith('Failures: 0')
This page took 0.056846 seconds and 4 git commands to generate.