blob: 0b716f4029cd99e7a8bdc3a91dfaf1210088c25c [file] [log] [blame]
Stephen Warren770fe172016-02-08 14:44:16 -07001# SPDX-License-Identifier: GPL-2.0
Simon Glass08631802024-09-01 16:26:14 -06002"""
3Unit-test runner
Stephen Warren770fe172016-02-08 14:44:16 -07004
Simon Glass08631802024-09-01 16:26:14 -06005Provides a test_ut() function which is used by conftest.py to run each unit
6test one at a time, as well setting up some files needed by the tests.
7
8# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
9"""
Simon Glassfff928c2023-08-24 13:55:41 -060010import collections
Simon Glassd2bc33ed2023-01-06 08:52:41 -060011import getpass
Simon Glassd3203bd2022-04-24 23:31:25 -060012import gzip
13import os
Stephen Warren770fe172016-02-08 14:44:16 -070014import os.path
15import pytest
16
Simon Glassd3203bd2022-04-24 23:31:25 -060017import u_boot_utils
Tom Rini50ad0192023-12-09 14:52:46 -050018# pylint: disable=E0611
Simon Glass2c7b0e42022-10-29 19:47:19 -060019from tests import fs_helper
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +020020from test_android import test_abootimg
Simon Glassd3203bd2022-04-24 23:31:25 -060021
22def mkdir_cond(dirname):
23 """Create a directory if it doesn't already exist
24
25 Args:
Simon Glassd2bc33ed2023-01-06 08:52:41 -060026 dirname (str): Name of directory to create
Simon Glassd3203bd2022-04-24 23:31:25 -060027 """
28 if not os.path.exists(dirname):
29 os.mkdir(dirname)
30
Simon Glassd157d3f2024-11-21 15:32:09 -070031def setup_image(cons, devnum, part_type, img_size=20, second_part=False,
32 basename='mmc'):
33 """Create a disk image with a single partition
Simon Glassd2bc33ed2023-01-06 08:52:41 -060034
35 Args:
36 cons (ConsoleBase): Console to use
Simon Glass64c63252024-11-07 14:31:49 -070037 devnum (int): Device number to use, e.g. 1
Simon Glassd2bc33ed2023-01-06 08:52:41 -060038 part_type (int): Partition type, e.g. 0xc for FAT32
Simon Glassd157d3f2024-11-21 15:32:09 -070039 img_size (int): Image size in MiB
Simon Glassf5e2df02023-01-17 10:47:41 -070040 second_part (bool): True to contain a small second partition
Simon Glass64c63252024-11-07 14:31:49 -070041 basename (str): Base name to use in the filename, e.g. 'mmc'
Simon Glassd2bc33ed2023-01-06 08:52:41 -060042
43 Returns:
44 tuple:
45 str: Filename of MMC image
46 str: Directory name of 'mnt' directory
47 """
Simon Glass64c63252024-11-07 14:31:49 -070048 fname = os.path.join(cons.config.source_dir, f'{basename}{devnum}.img')
Simon Glassd3203bd2022-04-24 23:31:25 -060049 mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
50 mkdir_cond(mnt)
51
Simon Glassd157d3f2024-11-21 15:32:09 -070052 spec = f'type={part_type:x}, size={img_size - 2}M, start=1M, bootable'
Simon Glassf5e2df02023-01-17 10:47:41 -070053 if second_part:
54 spec += '\ntype=c'
55
Simon Glassd157d3f2024-11-21 15:32:09 -070056 u_boot_utils.run_and_log(cons, f'qemu-img create {fname} {img_size}M')
Simon Glass08631802024-09-01 16:26:14 -060057 u_boot_utils.run_and_log(cons, f'sudo sfdisk {fname}',
Simon Glassf5e2df02023-01-17 10:47:41 -070058 stdin=spec.encode('utf-8'))
Simon Glassd2bc33ed2023-01-06 08:52:41 -060059 return fname, mnt
60
61def mount_image(cons, fname, mnt, fstype):
62 """Create a filesystem and mount it on partition 1
63
64 Args:
65 cons (ConsoleBase): Console to use
66 fname (str): Filename of MMC image
67 mnt (str): Directory name of 'mnt' directory
68 fstype (str): Filesystem type ('vfat' or 'ext4')
69
70 Returns:
71 str: Name of loop device used
72 """
Simon Glass08631802024-09-01 16:26:14 -060073 out = u_boot_utils.run_and_log(cons, f'sudo losetup --show -f -P {fname}')
Simon Glassd2bc33ed2023-01-06 08:52:41 -060074 loop = out.strip()
75 part = f'{loop}p1'
76 u_boot_utils.run_and_log(cons, f'sudo mkfs.{fstype} {part}')
77 opts = ''
78 if fstype == 'vfat':
Simon Glass08631802024-09-01 16:26:14 -060079 opts += f' -o uid={os.getuid()},gid={os.getgid()}'
Simon Glassd2bc33ed2023-01-06 08:52:41 -060080 u_boot_utils.run_and_log(cons, f'sudo mount -o loop {part} {mnt}{opts}')
81 u_boot_utils.run_and_log(cons, f'sudo chown {getpass.getuser()} {mnt}')
82 return loop
83
Simon Glass64c63252024-11-07 14:31:49 -070084def copy_prepared_image(cons, devnum, fname, basename='mmc'):
Simon Glassd2bc33ed2023-01-06 08:52:41 -060085 """Use a prepared image since we cannot create one
86
87 Args:
88 cons (ConsoleBase): Console touse
Simon Glass64c63252024-11-07 14:31:49 -070089 devnum (int): device number
Simon Glassd2bc33ed2023-01-06 08:52:41 -060090 fname (str): Filename of MMC image
Simon Glass64c63252024-11-07 14:31:49 -070091 basename (str): Base name to use in the filename, e.g. 'mmc'
Simon Glassd2bc33ed2023-01-06 08:52:41 -060092 """
93 infname = os.path.join(cons.config.source_dir,
Simon Glass64c63252024-11-07 14:31:49 -070094 f'test/py/tests/bootstd/{basename}{devnum}.img.xz')
Simon Glass08631802024-09-01 16:26:14 -060095 u_boot_utils.run_and_log(cons, ['sh', '-c', f'xz -dc {infname} >{fname}'])
Simon Glassd2bc33ed2023-01-06 08:52:41 -060096
97def setup_bootmenu_image(cons):
98 """Create a 20MB disk image with a single ext4 partition
99
100 This is modelled on Armbian 22.08 Jammy
101 """
102 mmc_dev = 4
103 fname, mnt = setup_image(cons, mmc_dev, 0x83)
Simon Glassd3203bd2022-04-24 23:31:25 -0600104
105 loop = None
106 mounted = False
107 complete = False
108 try:
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600109 loop = mount_image(cons, fname, mnt, 'ext4')
110 mounted = True
111
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600112 script = '''# DO NOT EDIT THIS FILE
113#
114# Please edit /boot/armbianEnv.txt to set supported parameters
115#
116
117setenv load_addr "0x9000000"
118setenv overlay_error "false"
119# default values
120setenv rootdev "/dev/mmcblk%dp1"
121setenv verbosity "1"
122setenv console "both"
123setenv bootlogo "false"
124setenv rootfstype "ext4"
125setenv docker_optimizations "on"
126setenv earlycon "off"
127
128echo "Boot script loaded from ${devtype} ${devnum}"
129
130if test -e ${devtype} ${devnum} ${prefix}armbianEnv.txt; then
131 load ${devtype} ${devnum} ${load_addr} ${prefix}armbianEnv.txt
132 env import -t ${load_addr} ${filesize}
133fi
134
135if test "${logo}" = "disabled"; then setenv logo "logo.nologo"; fi
136
137if test "${console}" = "display" || test "${console}" = "both"; then setenv consoleargs "console=tty1"; fi
138if test "${console}" = "serial" || test "${console}" = "both"; then setenv consoleargs "console=ttyS2,1500000 ${consoleargs}"; fi
139if test "${earlycon}" = "on"; then setenv consoleargs "earlycon ${consoleargs}"; fi
140if test "${bootlogo}" = "true"; then setenv consoleargs "bootsplash.bootfile=bootsplash.armbian ${consoleargs}"; fi
141
142# get PARTUUID of first partition on SD/eMMC the boot script was loaded from
143if test "${devtype}" = "mmc"; then part uuid mmc ${devnum}:1 partuuid; fi
144
145setenv bootargs "root=${rootdev} rootwait rootfstype=${rootfstype} ${consoleargs} consoleblank=0 loglevel=${verbosity} ubootpart=${partuuid} usb-storage.quirks=${usbstoragequirks} ${extraargs} ${extraboardargs}"
146
147if test "${docker_optimizations}" = "on"; then setenv bootargs "${bootargs} cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1"; fi
148
149load ${devtype} ${devnum} ${ramdisk_addr_r} ${prefix}uInitrd
150load ${devtype} ${devnum} ${kernel_addr_r} ${prefix}Image
151
152load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
153fdt addr ${fdt_addr_r}
154fdt resize 65536
155for overlay_file in ${overlays}; do
156 if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-${overlay_file}.dtbo; then
157 echo "Applying kernel provided DT overlay ${overlay_prefix}-${overlay_file}.dtbo"
158 fdt apply ${load_addr} || setenv overlay_error "true"
159 fi
160done
161for overlay_file in ${user_overlays}; do
162 if load ${devtype} ${devnum} ${load_addr} ${prefix}overlay-user/${overlay_file}.dtbo; then
163 echo "Applying user provided DT overlay ${overlay_file}.dtbo"
164 fdt apply ${load_addr} || setenv overlay_error "true"
165 fi
166done
167if test "${overlay_error}" = "true"; then
168 echo "Error applying DT overlays, restoring original DT"
169 load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
170else
171 if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-fixup.scr; then
172 echo "Applying kernel provided DT fixup script (${overlay_prefix}-fixup.scr)"
173 source ${load_addr}
174 fi
175 if test -e ${devtype} ${devnum} ${prefix}fixup.scr; then
176 load ${devtype} ${devnum} ${load_addr} ${prefix}fixup.scr
177 echo "Applying user provided fixup script (fixup.scr)"
178 source ${load_addr}
179 fi
180fi
181booti ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr_r}
182
183# Recompile with:
184# mkimage -C none -A arm -T script -d /boot/boot.cmd /boot/boot.scr
Simon Glass08631802024-09-01 16:26:14 -0600185'''
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600186 bootdir = os.path.join(mnt, 'boot')
187 mkdir_cond(bootdir)
188 cmd_fname = os.path.join(bootdir, 'boot.cmd')
189 scr_fname = os.path.join(bootdir, 'boot.scr')
Simon Glass08631802024-09-01 16:26:14 -0600190 with open(cmd_fname, 'w', encoding='ascii') as outf:
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600191 print(script, file=outf)
192
193 infname = os.path.join(cons.config.source_dir,
194 'test/py/tests/bootstd/armbian.bmp.xz')
195 bmp_file = os.path.join(bootdir, 'boot.bmp')
196 u_boot_utils.run_and_log(
197 cons,
198 ['sh', '-c', f'xz -dc {infname} >{bmp_file}'])
199
200 u_boot_utils.run_and_log(
201 cons, f'mkimage -C none -A arm -T script -d {cmd_fname} {scr_fname}')
202
203 kernel = 'vmlinuz-5.15.63-rockchip64'
204 target = os.path.join(bootdir, kernel)
205 with open(target, 'wb') as outf:
206 print('kernel', outf)
207
208 symlink = os.path.join(bootdir, 'Image')
209 if os.path.exists(symlink):
210 os.remove(symlink)
211 u_boot_utils.run_and_log(
212 cons, f'echo here {kernel} {symlink}')
213 os.symlink(kernel, symlink)
214
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600215 complete = True
216
217 except ValueError as exc:
Simon Glass08631802024-09-01 16:26:14 -0600218 print(f'Falled to create image, failing back to prepared copy: {exc}')
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600219 finally:
220 if mounted:
Simon Glass08631802024-09-01 16:26:14 -0600221 u_boot_utils.run_and_log(cons, f'sudo umount --lazy {mnt}')
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600222 if loop:
Simon Glass08631802024-09-01 16:26:14 -0600223 u_boot_utils.run_and_log(cons, f'sudo losetup -d {loop}')
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600224
225 if not complete:
226 copy_prepared_image(cons, mmc_dev, fname)
227
228def setup_bootflow_image(cons):
229 """Create a 20MB disk image with a single FAT partition"""
230 mmc_dev = 1
Simon Glassf5e2df02023-01-17 10:47:41 -0700231 fname, mnt = setup_image(cons, mmc_dev, 0xc, second_part=True)
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600232
233 loop = None
234 mounted = False
235 complete = False
236 try:
237 loop = mount_image(cons, fname, mnt, 'vfat')
Simon Glassd3203bd2022-04-24 23:31:25 -0600238 mounted = True
239
240 vmlinux = 'vmlinuz-5.3.7-301.fc31.armv7hl'
241 initrd = 'initramfs-5.3.7-301.fc31.armv7hl.img'
242 dtbdir = 'dtb-5.3.7-301.fc31.armv7hl'
243 script = '''# extlinux.conf generated by appliance-creator
244ui menu.c32
245menu autoboot Welcome to Fedora-Workstation-armhfp-31-1.9. Automatic boot in # second{,s}. Press a key for options.
246menu title Fedora-Workstation-armhfp-31-1.9 Boot Options.
247menu hidden
248timeout 20
249totaltimeout 600
250
251label Fedora-Workstation-armhfp-31-1.9 (5.3.7-301.fc31.armv7hl)
252 kernel /%s
253 append ro root=UUID=9732b35b-4cd5-458b-9b91-80f7047e0b8a rhgb quiet LANG=en_US.UTF-8 cma=192MB cma=256MB
254 fdtdir /%s/
255 initrd /%s''' % (vmlinux, dtbdir, initrd)
256 ext = os.path.join(mnt, 'extlinux')
257 mkdir_cond(ext)
258
Simon Glass08631802024-09-01 16:26:14 -0600259 conf = os.path.join(ext, 'extlinux.conf')
260 with open(conf, 'w', encoding='ascii') as fd:
Simon Glassd3203bd2022-04-24 23:31:25 -0600261 print(script, file=fd)
262
263 inf = os.path.join(cons.config.persistent_data_dir, 'inf')
264 with open(inf, 'wb') as fd:
265 fd.write(gzip.compress(b'vmlinux'))
Simon Glass08631802024-09-01 16:26:14 -0600266 u_boot_utils.run_and_log(
267 cons, f'mkimage -f auto -d {inf} {os.path.join(mnt, vmlinux)}')
Simon Glassd3203bd2022-04-24 23:31:25 -0600268
Simon Glass08631802024-09-01 16:26:14 -0600269 with open(os.path.join(mnt, initrd), 'w', encoding='ascii') as fd:
Simon Glassd3203bd2022-04-24 23:31:25 -0600270 print('initrd', file=fd)
271
272 mkdir_cond(os.path.join(mnt, dtbdir))
273
Simon Glass08631802024-09-01 16:26:14 -0600274 dtb_file = os.path.join(mnt, f'{dtbdir}/sandbox.dtb')
Simon Glassd3203bd2022-04-24 23:31:25 -0600275 u_boot_utils.run_and_log(
Simon Glass08631802024-09-01 16:26:14 -0600276 cons, f'dtc -o {dtb_file}', stdin=b'/dts-v1/; / {};')
Simon Glassd3203bd2022-04-24 23:31:25 -0600277 complete = True
278 except ValueError as exc:
Simon Glass08631802024-09-01 16:26:14 -0600279 print(f'Falled to create image, failing back to prepared copy: {exc}')
Simon Glassd3203bd2022-04-24 23:31:25 -0600280 finally:
281 if mounted:
Simon Glass08631802024-09-01 16:26:14 -0600282 u_boot_utils.run_and_log(cons, f'sudo umount --lazy {mnt}')
Simon Glassd3203bd2022-04-24 23:31:25 -0600283 if loop:
Simon Glass08631802024-09-01 16:26:14 -0600284 u_boot_utils.run_and_log(cons, f'sudo losetup -d {loop}')
Simon Glassd3203bd2022-04-24 23:31:25 -0600285
286 if not complete:
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600287 copy_prepared_image(cons, mmc_dev, fname)
Simon Glassd3203bd2022-04-24 23:31:25 -0600288
289
Simon Glassfff928c2023-08-24 13:55:41 -0600290def setup_cros_image(cons):
291 """Create a 20MB disk image with ChromiumOS partitions"""
292 Partition = collections.namedtuple('part', 'start,size,name')
293 parts = {}
294 disk_data = None
295
296 def pack_kernel(cons, arch, kern, dummy):
297 """Pack a kernel containing some fake data
298
299 Args:
300 cons (ConsoleBase): Console to use
301 arch (str): Architecture to use ('x86' or 'arm')
302 kern (str): Filename containing kernel
303 dummy (str): Dummy filename to use for config and bootloader
304
305 Return:
306 bytes: Packed-kernel data
307 """
Simon Glass08631802024-09-01 16:26:14 -0600308 kern_part = os.path.join(cons.config.result_dir,
309 f'kern-part-{arch}.bin')
Simon Glassfff928c2023-08-24 13:55:41 -0600310 u_boot_utils.run_and_log(
311 cons,
312 f'futility vbutil_kernel --pack {kern_part} '
313 '--keyblock doc/chromium/files/devkeys/kernel.keyblock '
314 '--signprivate doc/chromium/files/devkeys/kernel_data_key.vbprivk '
315 f'--version 1 --config {dummy} --bootloader {dummy} '
316 f'--vmlinuz {kern}')
317
318 with open(kern_part, 'rb') as inf:
319 kern_part_data = inf.read()
320 return kern_part_data
321
322 def set_part_data(partnum, data):
323 """Set the contents of a disk partition
324
325 This updates disk_data by putting data in the right place
326
327 Args:
328 partnum (int): Partition number to set
329 data (bytes): Data for that partition
330 """
331 nonlocal disk_data
332
333 start = parts[partnum].start * sect_size
334 disk_data = disk_data[:start] + data + disk_data[start + len(data):]
335
336 mmc_dev = 5
337 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
Simon Glass08631802024-09-01 16:26:14 -0600338 u_boot_utils.run_and_log(cons, f'qemu-img create {fname} 20M')
Simon Glassfff928c2023-08-24 13:55:41 -0600339 #mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
340 #mkdir_cond(mnt)
341 u_boot_utils.run_and_log(cons, f'cgpt create {fname}')
342
343 uuid_state = 'ebd0a0a2-b9e5-4433-87c0-68b6b72699c7'
344 uuid_kern = 'fe3a2a5d-4f32-41a7-b725-accc3285a309'
345 uuid_root = '3cb8e202-3b7e-47dd-8a3c-7ff2a13cfcec'
346 uuid_rwfw = 'cab6e88e-abf3-4102-a07a-d4bb9be3c1d3'
347 uuid_reserved = '2e0a753d-9e48-43b0-8337-b15192cb1b5e'
348 uuid_efi = 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b'
349
350 ptr = 40
351
352 # Number of sectors in 1MB
353 sect_size = 512
354 sect_1mb = (1 << 20) // sect_size
355
356 required_parts = [
357 {'num': 0xb, 'label':'RWFW', 'type': uuid_rwfw, 'size': '1'},
358 {'num': 6, 'label':'KERN_C', 'type': uuid_kern, 'size': '1'},
359 {'num': 7, 'label':'ROOT_C', 'type': uuid_root, 'size': '1'},
360 {'num': 9, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
361 {'num': 0xa, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
362
363 {'num': 2, 'label':'KERN_A', 'type': uuid_kern, 'size': '1M'},
364 {'num': 4, 'label':'KERN_B', 'type': uuid_kern, 'size': '1M'},
365
366 {'num': 8, 'label':'OEM', 'type': uuid_state, 'size': '1M'},
367 {'num': 0xc, 'label':'EFI-SYSTEM', 'type': uuid_efi, 'size': '1M'},
368
369 {'num': 5, 'label':'ROOT_B', 'type': uuid_root, 'size': '1'},
370 {'num': 3, 'label':'ROOT_A', 'type': uuid_root, 'size': '1'},
371 {'num': 1, 'label':'STATE', 'type': uuid_state, 'size': '1M'},
372 ]
373
374 for part in required_parts:
375 size_str = part['size']
376 if 'M' in size_str:
377 size = int(size_str[:-1]) * sect_1mb
378 else:
379 size = int(size_str)
380 u_boot_utils.run_and_log(
381 cons,
382 f"cgpt add -i {part['num']} -b {ptr} -s {size} -t {part['type']} {fname}")
383 ptr += size
384
385 u_boot_utils.run_and_log(cons, f'cgpt boot -p {fname}')
386 out = u_boot_utils.run_and_log(cons, f'cgpt show -q {fname}')
Simon Glass08631802024-09-01 16:26:14 -0600387
388 # We expect something like this:
389 # 8239 2048 1 Basic data
390 # 45 2048 2 ChromeOS kernel
391 # 8238 1 3 ChromeOS rootfs
392 # 2093 2048 4 ChromeOS kernel
393 # 8237 1 5 ChromeOS rootfs
394 # 41 1 6 ChromeOS kernel
395 # 42 1 7 ChromeOS rootfs
396 # 4141 2048 8 Basic data
397 # 43 1 9 ChromeOS reserved
398 # 44 1 10 ChromeOS reserved
399 # 40 1 11 ChromeOS firmware
400 # 6189 2048 12 EFI System Partition
Simon Glassfff928c2023-08-24 13:55:41 -0600401
402 # Create a dict (indexed by partition number) containing the above info
403 for line in out.splitlines():
404 start, size, num, name = line.split(maxsplit=3)
405 parts[int(num)] = Partition(int(start), int(size), name)
406
407 dummy = os.path.join(cons.config.result_dir, 'dummy.txt')
408 with open(dummy, 'wb') as outf:
409 outf.write(b'dummy\n')
410
411 # For now we just use dummy kernels. This limits testing to just detecting
412 # a signed kernel. We could add support for the x86 data structures so that
413 # testing could cover getting the cmdline, setup.bin and other pieces.
414 kern = os.path.join(cons.config.result_dir, 'kern.bin')
415 with open(kern, 'wb') as outf:
416 outf.write(b'kernel\n')
417
418 with open(fname, 'rb') as inf:
419 disk_data = inf.read()
420
421 # put x86 kernel in partition 2 and arm one in partition 4
422 set_part_data(2, pack_kernel(cons, 'x86', kern, dummy))
423 set_part_data(4, pack_kernel(cons, 'arm', kern, dummy))
424
425 with open(fname, 'wb') as outf:
426 outf.write(disk_data)
427
428 return fname
429
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200430def setup_android_image(cons):
431 """Create a 20MB disk image with Android partitions"""
432 Partition = collections.namedtuple('part', 'start,size,name')
433 parts = {}
434 disk_data = None
435
436 def set_part_data(partnum, data):
437 """Set the contents of a disk partition
438
439 This updates disk_data by putting data in the right place
440
441 Args:
442 partnum (int): Partition number to set
443 data (bytes): Data for that partition
444 """
445 nonlocal disk_data
446
447 start = parts[partnum].start * sect_size
448 disk_data = disk_data[:start] + data + disk_data[start + len(data):]
449
450 mmc_dev = 7
451 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
Simon Glass08631802024-09-01 16:26:14 -0600452 u_boot_utils.run_and_log(cons, f'qemu-img create {fname} 20M')
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200453 u_boot_utils.run_and_log(cons, f'cgpt create {fname}')
454
455 ptr = 40
456
457 # Number of sectors in 1MB
458 sect_size = 512
459 sect_1mb = (1 << 20) // sect_size
460
461 required_parts = [
462 {'num': 1, 'label':'misc', 'size': '1M'},
463 {'num': 2, 'label':'boot_a', 'size': '4M'},
464 {'num': 3, 'label':'boot_b', 'size': '4M'},
465 {'num': 4, 'label':'vendor_boot_a', 'size': '4M'},
466 {'num': 5, 'label':'vendor_boot_b', 'size': '4M'},
467 ]
468
469 for part in required_parts:
470 size_str = part['size']
471 if 'M' in size_str:
472 size = int(size_str[:-1]) * sect_1mb
473 else:
474 size = int(size_str)
475 u_boot_utils.run_and_log(
476 cons,
477 f"cgpt add -i {part['num']} -b {ptr} -s {size} -l {part['label']} -t basicdata {fname}")
478 ptr += size
479
480 u_boot_utils.run_and_log(cons, f'cgpt boot -p {fname}')
481 out = u_boot_utils.run_and_log(cons, f'cgpt show -q {fname}')
482
483 # Create a dict (indexed by partition number) containing the above info
484 for line in out.splitlines():
485 start, size, num, name = line.split(maxsplit=3)
486 parts[int(num)] = Partition(int(start), int(size), name)
487
488 with open(fname, 'rb') as inf:
489 disk_data = inf.read()
490
491 test_abootimg.AbootimgTestDiskImage(cons, 'bootv4.img', test_abootimg.boot_img_hex)
492 boot_img = os.path.join(cons.config.result_dir, 'bootv4.img')
493 with open(boot_img, 'rb') as inf:
494 set_part_data(2, inf.read())
495
496 test_abootimg.AbootimgTestDiskImage(cons, 'vendor_boot.img', test_abootimg.vboot_img_hex)
497 vendor_boot_img = os.path.join(cons.config.result_dir, 'vendor_boot.img')
498 with open(vendor_boot_img, 'rb') as inf:
499 set_part_data(4, inf.read())
500
501 with open(fname, 'wb') as outf:
502 outf.write(disk_data)
503
Simon Glass08631802024-09-01 16:26:14 -0600504 print(f'wrote to {fname}')
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200505
506 return fname
Simon Glassfff928c2023-08-24 13:55:41 -0600507
Simon Glassb8c26552023-06-01 10:23:03 -0600508def setup_cedit_file(cons):
Simon Glass08631802024-09-01 16:26:14 -0600509 """Set up a .dtb file for use with testing expo and configuration editor"""
Simon Glassb8c26552023-06-01 10:23:03 -0600510 infname = os.path.join(cons.config.source_dir,
511 'test/boot/files/expo_layout.dts')
Simon Glassb1263bc2023-08-14 16:40:28 -0600512 inhname = os.path.join(cons.config.source_dir,
513 'test/boot/files/expo_ids.h')
Simon Glassb8c26552023-06-01 10:23:03 -0600514 expo_tool = os.path.join(cons.config.source_dir, 'tools/expo.py')
515 outfname = 'cedit.dtb'
516 u_boot_utils.run_and_log(
Simon Glassb1263bc2023-08-14 16:40:28 -0600517 cons, f'{expo_tool} -e {inhname} -l {infname} -o {outfname}')
Simon Glassb8c26552023-06-01 10:23:03 -0600518
Stephen Warren770fe172016-02-08 14:44:16 -0700519@pytest.mark.buildconfigspec('ut_dm')
520def test_ut_dm_init(u_boot_console):
521 """Initialize data for ut dm tests."""
522
523 fn = u_boot_console.config.source_dir + '/testflash.bin'
524 if not os.path.exists(fn):
Tom Rini439ed3e2019-10-24 11:59:22 -0400525 data = b'this is a test'
526 data += b'\x00' * ((4 * 1024 * 1024) - len(data))
Stephen Warren770fe172016-02-08 14:44:16 -0700527 with open(fn, 'wb') as fh:
528 fh.write(data)
529
530 fn = u_boot_console.config.source_dir + '/spi.bin'
531 if not os.path.exists(fn):
Tom Rini439ed3e2019-10-24 11:59:22 -0400532 data = b'\x00' * (2 * 1024 * 1024)
Stephen Warren770fe172016-02-08 14:44:16 -0700533 with open(fn, 'wb') as fh:
534 fh.write(data)
535
Simon Glass509f32e2022-09-21 16:21:47 +0200536 # Create a file with a single partition
537 fn = u_boot_console.config.source_dir + '/scsi.img'
538 if not os.path.exists(fn):
539 data = b'\x00' * (2 * 1024 * 1024)
540 with open(fn, 'wb') as fh:
541 fh.write(data)
542 u_boot_utils.run_and_log(
543 u_boot_console, f'sfdisk {fn}', stdin=b'type=83')
544
Richard Weinberger41eca322024-11-21 15:32:07 -0700545 fs_helper.mk_fs(u_boot_console.config, 'ext2', 0x200000, '2MB', None)
546 fs_helper.mk_fs(u_boot_console.config, 'fat32', 0x100000, '1MB', None)
Simon Glass2c7b0e42022-10-29 19:47:19 -0600547
Alexander Gendin038cb022023-10-09 01:24:36 +0000548 mmc_dev = 6
549 fn = os.path.join(u_boot_console.config.source_dir, f'mmc{mmc_dev}.img')
550 data = b'\x00' * (12 * 1024 * 1024)
551 with open(fn, 'wb') as fh:
552 fh.write(data)
553
Simon Glass64c63252024-11-07 14:31:49 -0700554
555def setup_efi_image(cons):
556 """Create a 20MB disk image with an EFI app on it"""
557 devnum = 1
558 basename = 'flash'
559 fname, mnt = setup_image(cons, devnum, 0xc, second_part=True,
560 basename=basename)
561
562 loop = None
563 mounted = False
564 complete = False
565 try:
566 loop = mount_image(cons, fname, mnt, 'ext4')
567 mounted = True
568 efi_dir = os.path.join(mnt, 'EFI')
569 mkdir_cond(efi_dir)
570 bootdir = os.path.join(efi_dir, 'BOOT')
571 mkdir_cond(bootdir)
572 efi_src = os.path.join(cons.config.build_dir,
573 f'lib/efi_loader/testapp.efi')
574 efi_dst = os.path.join(bootdir, 'BOOTSBOX.EFI')
575 with open(efi_src, 'rb') as inf:
576 with open(efi_dst, 'wb') as outf:
577 outf.write(inf.read())
578 complete = True
579 except ValueError as exc:
580 print(f'Falled to create image, failing back to prepared copy: {exc}')
581
582 finally:
583 if mounted:
584 u_boot_utils.run_and_log(cons, 'sudo umount --lazy %s' % mnt)
585 if loop:
586 u_boot_utils.run_and_log(cons, 'sudo losetup -d %s' % loop)
587
588 if not complete:
589 copy_prepared_image(cons, devnum, fname, basename)
590
591
Simon Glassd3203bd2022-04-24 23:31:25 -0600592@pytest.mark.buildconfigspec('cmd_bootflow')
Simon Glass84712cd2024-06-23 14:30:27 -0600593@pytest.mark.buildconfigspec('sandbox')
Simon Glassd3203bd2022-04-24 23:31:25 -0600594def test_ut_dm_init_bootstd(u_boot_console):
595 """Initialise data for bootflow tests"""
596
597 setup_bootflow_image(u_boot_console)
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600598 setup_bootmenu_image(u_boot_console)
Simon Glassb8c26552023-06-01 10:23:03 -0600599 setup_cedit_file(u_boot_console)
Simon Glassfff928c2023-08-24 13:55:41 -0600600 setup_cros_image(u_boot_console)
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200601 setup_android_image(u_boot_console)
Simon Glass64c63252024-11-07 14:31:49 -0700602 setup_efi_image(u_boot_console)
Simon Glassd3203bd2022-04-24 23:31:25 -0600603
604 # Restart so that the new mmc1.img is picked up
605 u_boot_console.restart_uboot()
606
607
Stephen Warren770fe172016-02-08 14:44:16 -0700608def test_ut(u_boot_console, ut_subtest):
Heinrich Schuchardtdf6c36c2020-05-06 18:26:07 +0200609 """Execute a "ut" subtest.
610
611 The subtests are collected in function generate_ut_subtest() from linker
612 generated lists by applying a regular expression to the lines of file
613 u-boot.sym. The list entries are created using the C macro UNIT_TEST().
614
615 Strict naming conventions have to be followed to match the regular
616 expression. Use UNIT_TEST(foo_test_bar, _flags, foo_test) for a test bar in
617 test suite foo that can be executed via command 'ut foo bar' and is
618 implemented in C function foo_test_bar().
619
620 Args:
621 u_boot_console (ConsoleBase): U-Boot console
622 ut_subtest (str): test to be executed via command ut, e.g 'foo bar' to
623 execute command 'ut foo bar'
624 """
Stephen Warren770fe172016-02-08 14:44:16 -0700625
Francis Laniel91ec8702023-12-22 22:02:24 +0100626 if ut_subtest == 'hush hush_test_simple_dollar':
627 # ut hush hush_test_simple_dollar prints "Unknown command" on purpose.
628 with u_boot_console.disable_check('unknown_command'):
629 output = u_boot_console.run_command('ut ' + ut_subtest)
Simon Glass08631802024-09-01 16:26:14 -0600630 assert 'Unknown command \'quux\' - try \'help\'' in output
Francis Laniel91ec8702023-12-22 22:02:24 +0100631 else:
632 output = u_boot_console.run_command('ut ' + ut_subtest)
Stephen Warren770fe172016-02-08 14:44:16 -0700633 assert output.endswith('Failures: 0')