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