blob: 7a0bde4da256460a9c5b003afb8913d9ec963583 [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 Glass64c63252024-11-07 14:31:49 -070031def setup_image(cons, devnum, part_type, second_part=False, basename='mmc'):
Simon Glassd2bc33ed2023-01-06 08:52:41 -060032 """Create a 20MB disk image with a single partition
33
34 Args:
35 cons (ConsoleBase): Console to use
Simon Glass64c63252024-11-07 14:31:49 -070036 devnum (int): Device number to use, e.g. 1
Simon Glassd2bc33ed2023-01-06 08:52:41 -060037 part_type (int): Partition type, e.g. 0xc for FAT32
Simon Glassf5e2df02023-01-17 10:47:41 -070038 second_part (bool): True to contain a small second partition
Simon Glass64c63252024-11-07 14:31:49 -070039 basename (str): Base name to use in the filename, e.g. 'mmc'
Simon Glassd2bc33ed2023-01-06 08:52:41 -060040
41 Returns:
42 tuple:
43 str: Filename of MMC image
44 str: Directory name of 'mnt' directory
45 """
Simon Glass64c63252024-11-07 14:31:49 -070046 fname = os.path.join(cons.config.source_dir, f'{basename}{devnum}.img')
Simon Glassd3203bd2022-04-24 23:31:25 -060047 mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
48 mkdir_cond(mnt)
49
Simon Glassf5e2df02023-01-17 10:47:41 -070050 spec = f'type={part_type:x}, size=18M, bootable'
51 if second_part:
52 spec += '\ntype=c'
53
Simon Glass08631802024-09-01 16:26:14 -060054 u_boot_utils.run_and_log(cons, f'qemu-img create {fname} 20M')
55 u_boot_utils.run_and_log(cons, f'sudo sfdisk {fname}',
Simon Glassf5e2df02023-01-17 10:47:41 -070056 stdin=spec.encode('utf-8'))
Simon Glassd2bc33ed2023-01-06 08:52:41 -060057 return fname, mnt
58
59def mount_image(cons, fname, mnt, fstype):
60 """Create a filesystem and mount it on partition 1
61
62 Args:
63 cons (ConsoleBase): Console to use
64 fname (str): Filename of MMC image
65 mnt (str): Directory name of 'mnt' directory
66 fstype (str): Filesystem type ('vfat' or 'ext4')
67
68 Returns:
69 str: Name of loop device used
70 """
Simon Glass08631802024-09-01 16:26:14 -060071 out = u_boot_utils.run_and_log(cons, f'sudo losetup --show -f -P {fname}')
Simon Glassd2bc33ed2023-01-06 08:52:41 -060072 loop = out.strip()
73 part = f'{loop}p1'
74 u_boot_utils.run_and_log(cons, f'sudo mkfs.{fstype} {part}')
75 opts = ''
76 if fstype == 'vfat':
Simon Glass08631802024-09-01 16:26:14 -060077 opts += f' -o uid={os.getuid()},gid={os.getgid()}'
Simon Glassd2bc33ed2023-01-06 08:52:41 -060078 u_boot_utils.run_and_log(cons, f'sudo mount -o loop {part} {mnt}{opts}')
79 u_boot_utils.run_and_log(cons, f'sudo chown {getpass.getuser()} {mnt}')
80 return loop
81
Simon Glass64c63252024-11-07 14:31:49 -070082def copy_prepared_image(cons, devnum, fname, basename='mmc'):
Simon Glassd2bc33ed2023-01-06 08:52:41 -060083 """Use a prepared image since we cannot create one
84
85 Args:
86 cons (ConsoleBase): Console touse
Simon Glass64c63252024-11-07 14:31:49 -070087 devnum (int): device number
Simon Glassd2bc33ed2023-01-06 08:52:41 -060088 fname (str): Filename of MMC image
Simon Glass64c63252024-11-07 14:31:49 -070089 basename (str): Base name to use in the filename, e.g. 'mmc'
Simon Glassd2bc33ed2023-01-06 08:52:41 -060090 """
91 infname = os.path.join(cons.config.source_dir,
Simon Glass64c63252024-11-07 14:31:49 -070092 f'test/py/tests/bootstd/{basename}{devnum}.img.xz')
Simon Glass08631802024-09-01 16:26:14 -060093 u_boot_utils.run_and_log(cons, ['sh', '-c', f'xz -dc {infname} >{fname}'])
Simon Glassd2bc33ed2023-01-06 08:52:41 -060094
95def setup_bootmenu_image(cons):
96 """Create a 20MB disk image with a single ext4 partition
97
98 This is modelled on Armbian 22.08 Jammy
99 """
100 mmc_dev = 4
101 fname, mnt = setup_image(cons, mmc_dev, 0x83)
Simon Glassd3203bd2022-04-24 23:31:25 -0600102
103 loop = None
104 mounted = False
105 complete = False
106 try:
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600107 loop = mount_image(cons, fname, mnt, 'ext4')
108 mounted = True
109
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600110 script = '''# DO NOT EDIT THIS FILE
111#
112# Please edit /boot/armbianEnv.txt to set supported parameters
113#
114
115setenv load_addr "0x9000000"
116setenv overlay_error "false"
117# default values
118setenv rootdev "/dev/mmcblk%dp1"
119setenv verbosity "1"
120setenv console "both"
121setenv bootlogo "false"
122setenv rootfstype "ext4"
123setenv docker_optimizations "on"
124setenv earlycon "off"
125
126echo "Boot script loaded from ${devtype} ${devnum}"
127
128if test -e ${devtype} ${devnum} ${prefix}armbianEnv.txt; then
129 load ${devtype} ${devnum} ${load_addr} ${prefix}armbianEnv.txt
130 env import -t ${load_addr} ${filesize}
131fi
132
133if test "${logo}" = "disabled"; then setenv logo "logo.nologo"; fi
134
135if test "${console}" = "display" || test "${console}" = "both"; then setenv consoleargs "console=tty1"; fi
136if test "${console}" = "serial" || test "${console}" = "both"; then setenv consoleargs "console=ttyS2,1500000 ${consoleargs}"; fi
137if test "${earlycon}" = "on"; then setenv consoleargs "earlycon ${consoleargs}"; fi
138if test "${bootlogo}" = "true"; then setenv consoleargs "bootsplash.bootfile=bootsplash.armbian ${consoleargs}"; fi
139
140# get PARTUUID of first partition on SD/eMMC the boot script was loaded from
141if test "${devtype}" = "mmc"; then part uuid mmc ${devnum}:1 partuuid; fi
142
143setenv bootargs "root=${rootdev} rootwait rootfstype=${rootfstype} ${consoleargs} consoleblank=0 loglevel=${verbosity} ubootpart=${partuuid} usb-storage.quirks=${usbstoragequirks} ${extraargs} ${extraboardargs}"
144
145if test "${docker_optimizations}" = "on"; then setenv bootargs "${bootargs} cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1"; fi
146
147load ${devtype} ${devnum} ${ramdisk_addr_r} ${prefix}uInitrd
148load ${devtype} ${devnum} ${kernel_addr_r} ${prefix}Image
149
150load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
151fdt addr ${fdt_addr_r}
152fdt resize 65536
153for overlay_file in ${overlays}; do
154 if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-${overlay_file}.dtbo; then
155 echo "Applying kernel provided DT overlay ${overlay_prefix}-${overlay_file}.dtbo"
156 fdt apply ${load_addr} || setenv overlay_error "true"
157 fi
158done
159for overlay_file in ${user_overlays}; do
160 if load ${devtype} ${devnum} ${load_addr} ${prefix}overlay-user/${overlay_file}.dtbo; then
161 echo "Applying user provided DT overlay ${overlay_file}.dtbo"
162 fdt apply ${load_addr} || setenv overlay_error "true"
163 fi
164done
165if test "${overlay_error}" = "true"; then
166 echo "Error applying DT overlays, restoring original DT"
167 load ${devtype} ${devnum} ${fdt_addr_r} ${prefix}dtb/${fdtfile}
168else
169 if load ${devtype} ${devnum} ${load_addr} ${prefix}dtb/rockchip/overlay/${overlay_prefix}-fixup.scr; then
170 echo "Applying kernel provided DT fixup script (${overlay_prefix}-fixup.scr)"
171 source ${load_addr}
172 fi
173 if test -e ${devtype} ${devnum} ${prefix}fixup.scr; then
174 load ${devtype} ${devnum} ${load_addr} ${prefix}fixup.scr
175 echo "Applying user provided fixup script (fixup.scr)"
176 source ${load_addr}
177 fi
178fi
179booti ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr_r}
180
181# Recompile with:
182# mkimage -C none -A arm -T script -d /boot/boot.cmd /boot/boot.scr
Simon Glass08631802024-09-01 16:26:14 -0600183'''
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600184 bootdir = os.path.join(mnt, 'boot')
185 mkdir_cond(bootdir)
186 cmd_fname = os.path.join(bootdir, 'boot.cmd')
187 scr_fname = os.path.join(bootdir, 'boot.scr')
Simon Glass08631802024-09-01 16:26:14 -0600188 with open(cmd_fname, 'w', encoding='ascii') as outf:
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600189 print(script, file=outf)
190
191 infname = os.path.join(cons.config.source_dir,
192 'test/py/tests/bootstd/armbian.bmp.xz')
193 bmp_file = os.path.join(bootdir, 'boot.bmp')
194 u_boot_utils.run_and_log(
195 cons,
196 ['sh', '-c', f'xz -dc {infname} >{bmp_file}'])
197
198 u_boot_utils.run_and_log(
199 cons, f'mkimage -C none -A arm -T script -d {cmd_fname} {scr_fname}')
200
201 kernel = 'vmlinuz-5.15.63-rockchip64'
202 target = os.path.join(bootdir, kernel)
203 with open(target, 'wb') as outf:
204 print('kernel', outf)
205
206 symlink = os.path.join(bootdir, 'Image')
207 if os.path.exists(symlink):
208 os.remove(symlink)
209 u_boot_utils.run_and_log(
210 cons, f'echo here {kernel} {symlink}')
211 os.symlink(kernel, symlink)
212
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600213 complete = True
214
215 except ValueError as exc:
Simon Glass08631802024-09-01 16:26:14 -0600216 print(f'Falled to create image, failing back to prepared copy: {exc}')
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600217 finally:
218 if mounted:
Simon Glass08631802024-09-01 16:26:14 -0600219 u_boot_utils.run_and_log(cons, f'sudo umount --lazy {mnt}')
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600220 if loop:
Simon Glass08631802024-09-01 16:26:14 -0600221 u_boot_utils.run_and_log(cons, f'sudo losetup -d {loop}')
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600222
223 if not complete:
224 copy_prepared_image(cons, mmc_dev, fname)
225
226def setup_bootflow_image(cons):
227 """Create a 20MB disk image with a single FAT partition"""
228 mmc_dev = 1
Simon Glassf5e2df02023-01-17 10:47:41 -0700229 fname, mnt = setup_image(cons, mmc_dev, 0xc, second_part=True)
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600230
231 loop = None
232 mounted = False
233 complete = False
234 try:
235 loop = mount_image(cons, fname, mnt, 'vfat')
Simon Glassd3203bd2022-04-24 23:31:25 -0600236 mounted = True
237
238 vmlinux = 'vmlinuz-5.3.7-301.fc31.armv7hl'
239 initrd = 'initramfs-5.3.7-301.fc31.armv7hl.img'
240 dtbdir = 'dtb-5.3.7-301.fc31.armv7hl'
241 script = '''# extlinux.conf generated by appliance-creator
242ui menu.c32
243menu autoboot Welcome to Fedora-Workstation-armhfp-31-1.9. Automatic boot in # second{,s}. Press a key for options.
244menu title Fedora-Workstation-armhfp-31-1.9 Boot Options.
245menu hidden
246timeout 20
247totaltimeout 600
248
249label Fedora-Workstation-armhfp-31-1.9 (5.3.7-301.fc31.armv7hl)
250 kernel /%s
251 append ro root=UUID=9732b35b-4cd5-458b-9b91-80f7047e0b8a rhgb quiet LANG=en_US.UTF-8 cma=192MB cma=256MB
252 fdtdir /%s/
253 initrd /%s''' % (vmlinux, dtbdir, initrd)
254 ext = os.path.join(mnt, 'extlinux')
255 mkdir_cond(ext)
256
Simon Glass08631802024-09-01 16:26:14 -0600257 conf = os.path.join(ext, 'extlinux.conf')
258 with open(conf, 'w', encoding='ascii') as fd:
Simon Glassd3203bd2022-04-24 23:31:25 -0600259 print(script, file=fd)
260
261 inf = os.path.join(cons.config.persistent_data_dir, 'inf')
262 with open(inf, 'wb') as fd:
263 fd.write(gzip.compress(b'vmlinux'))
Simon Glass08631802024-09-01 16:26:14 -0600264 u_boot_utils.run_and_log(
265 cons, f'mkimage -f auto -d {inf} {os.path.join(mnt, vmlinux)}')
Simon Glassd3203bd2022-04-24 23:31:25 -0600266
Simon Glass08631802024-09-01 16:26:14 -0600267 with open(os.path.join(mnt, initrd), 'w', encoding='ascii') as fd:
Simon Glassd3203bd2022-04-24 23:31:25 -0600268 print('initrd', file=fd)
269
270 mkdir_cond(os.path.join(mnt, dtbdir))
271
Simon Glass08631802024-09-01 16:26:14 -0600272 dtb_file = os.path.join(mnt, f'{dtbdir}/sandbox.dtb')
Simon Glassd3203bd2022-04-24 23:31:25 -0600273 u_boot_utils.run_and_log(
Simon Glass08631802024-09-01 16:26:14 -0600274 cons, f'dtc -o {dtb_file}', stdin=b'/dts-v1/; / {};')
Simon Glassd3203bd2022-04-24 23:31:25 -0600275 complete = True
276 except ValueError as exc:
Simon Glass08631802024-09-01 16:26:14 -0600277 print(f'Falled to create image, failing back to prepared copy: {exc}')
Simon Glassd3203bd2022-04-24 23:31:25 -0600278 finally:
279 if mounted:
Simon Glass08631802024-09-01 16:26:14 -0600280 u_boot_utils.run_and_log(cons, f'sudo umount --lazy {mnt}')
Simon Glassd3203bd2022-04-24 23:31:25 -0600281 if loop:
Simon Glass08631802024-09-01 16:26:14 -0600282 u_boot_utils.run_and_log(cons, f'sudo losetup -d {loop}')
Simon Glassd3203bd2022-04-24 23:31:25 -0600283
284 if not complete:
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600285 copy_prepared_image(cons, mmc_dev, fname)
Simon Glassd3203bd2022-04-24 23:31:25 -0600286
287
Simon Glassfff928c2023-08-24 13:55:41 -0600288def setup_cros_image(cons):
289 """Create a 20MB disk image with ChromiumOS partitions"""
290 Partition = collections.namedtuple('part', 'start,size,name')
291 parts = {}
292 disk_data = None
293
294 def pack_kernel(cons, arch, kern, dummy):
295 """Pack a kernel containing some fake data
296
297 Args:
298 cons (ConsoleBase): Console to use
299 arch (str): Architecture to use ('x86' or 'arm')
300 kern (str): Filename containing kernel
301 dummy (str): Dummy filename to use for config and bootloader
302
303 Return:
304 bytes: Packed-kernel data
305 """
Simon Glass08631802024-09-01 16:26:14 -0600306 kern_part = os.path.join(cons.config.result_dir,
307 f'kern-part-{arch}.bin')
Simon Glassfff928c2023-08-24 13:55:41 -0600308 u_boot_utils.run_and_log(
309 cons,
310 f'futility vbutil_kernel --pack {kern_part} '
311 '--keyblock doc/chromium/files/devkeys/kernel.keyblock '
312 '--signprivate doc/chromium/files/devkeys/kernel_data_key.vbprivk '
313 f'--version 1 --config {dummy} --bootloader {dummy} '
314 f'--vmlinuz {kern}')
315
316 with open(kern_part, 'rb') as inf:
317 kern_part_data = inf.read()
318 return kern_part_data
319
320 def set_part_data(partnum, data):
321 """Set the contents of a disk partition
322
323 This updates disk_data by putting data in the right place
324
325 Args:
326 partnum (int): Partition number to set
327 data (bytes): Data for that partition
328 """
329 nonlocal disk_data
330
331 start = parts[partnum].start * sect_size
332 disk_data = disk_data[:start] + data + disk_data[start + len(data):]
333
334 mmc_dev = 5
335 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
Simon Glass08631802024-09-01 16:26:14 -0600336 u_boot_utils.run_and_log(cons, f'qemu-img create {fname} 20M')
Simon Glassfff928c2023-08-24 13:55:41 -0600337 #mnt = os.path.join(cons.config.persistent_data_dir, 'mnt')
338 #mkdir_cond(mnt)
339 u_boot_utils.run_and_log(cons, f'cgpt create {fname}')
340
341 uuid_state = 'ebd0a0a2-b9e5-4433-87c0-68b6b72699c7'
342 uuid_kern = 'fe3a2a5d-4f32-41a7-b725-accc3285a309'
343 uuid_root = '3cb8e202-3b7e-47dd-8a3c-7ff2a13cfcec'
344 uuid_rwfw = 'cab6e88e-abf3-4102-a07a-d4bb9be3c1d3'
345 uuid_reserved = '2e0a753d-9e48-43b0-8337-b15192cb1b5e'
346 uuid_efi = 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b'
347
348 ptr = 40
349
350 # Number of sectors in 1MB
351 sect_size = 512
352 sect_1mb = (1 << 20) // sect_size
353
354 required_parts = [
355 {'num': 0xb, 'label':'RWFW', 'type': uuid_rwfw, 'size': '1'},
356 {'num': 6, 'label':'KERN_C', 'type': uuid_kern, 'size': '1'},
357 {'num': 7, 'label':'ROOT_C', 'type': uuid_root, 'size': '1'},
358 {'num': 9, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
359 {'num': 0xa, 'label':'reserved', 'type': uuid_reserved, 'size': '1'},
360
361 {'num': 2, 'label':'KERN_A', 'type': uuid_kern, 'size': '1M'},
362 {'num': 4, 'label':'KERN_B', 'type': uuid_kern, 'size': '1M'},
363
364 {'num': 8, 'label':'OEM', 'type': uuid_state, 'size': '1M'},
365 {'num': 0xc, 'label':'EFI-SYSTEM', 'type': uuid_efi, 'size': '1M'},
366
367 {'num': 5, 'label':'ROOT_B', 'type': uuid_root, 'size': '1'},
368 {'num': 3, 'label':'ROOT_A', 'type': uuid_root, 'size': '1'},
369 {'num': 1, 'label':'STATE', 'type': uuid_state, 'size': '1M'},
370 ]
371
372 for part in required_parts:
373 size_str = part['size']
374 if 'M' in size_str:
375 size = int(size_str[:-1]) * sect_1mb
376 else:
377 size = int(size_str)
378 u_boot_utils.run_and_log(
379 cons,
380 f"cgpt add -i {part['num']} -b {ptr} -s {size} -t {part['type']} {fname}")
381 ptr += size
382
383 u_boot_utils.run_and_log(cons, f'cgpt boot -p {fname}')
384 out = u_boot_utils.run_and_log(cons, f'cgpt show -q {fname}')
Simon Glass08631802024-09-01 16:26:14 -0600385
386 # We expect something like this:
387 # 8239 2048 1 Basic data
388 # 45 2048 2 ChromeOS kernel
389 # 8238 1 3 ChromeOS rootfs
390 # 2093 2048 4 ChromeOS kernel
391 # 8237 1 5 ChromeOS rootfs
392 # 41 1 6 ChromeOS kernel
393 # 42 1 7 ChromeOS rootfs
394 # 4141 2048 8 Basic data
395 # 43 1 9 ChromeOS reserved
396 # 44 1 10 ChromeOS reserved
397 # 40 1 11 ChromeOS firmware
398 # 6189 2048 12 EFI System Partition
Simon Glassfff928c2023-08-24 13:55:41 -0600399
400 # Create a dict (indexed by partition number) containing the above info
401 for line in out.splitlines():
402 start, size, num, name = line.split(maxsplit=3)
403 parts[int(num)] = Partition(int(start), int(size), name)
404
405 dummy = os.path.join(cons.config.result_dir, 'dummy.txt')
406 with open(dummy, 'wb') as outf:
407 outf.write(b'dummy\n')
408
409 # For now we just use dummy kernels. This limits testing to just detecting
410 # a signed kernel. We could add support for the x86 data structures so that
411 # testing could cover getting the cmdline, setup.bin and other pieces.
412 kern = os.path.join(cons.config.result_dir, 'kern.bin')
413 with open(kern, 'wb') as outf:
414 outf.write(b'kernel\n')
415
416 with open(fname, 'rb') as inf:
417 disk_data = inf.read()
418
419 # put x86 kernel in partition 2 and arm one in partition 4
420 set_part_data(2, pack_kernel(cons, 'x86', kern, dummy))
421 set_part_data(4, pack_kernel(cons, 'arm', kern, dummy))
422
423 with open(fname, 'wb') as outf:
424 outf.write(disk_data)
425
426 return fname
427
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200428def setup_android_image(cons):
429 """Create a 20MB disk image with Android partitions"""
430 Partition = collections.namedtuple('part', 'start,size,name')
431 parts = {}
432 disk_data = None
433
434 def set_part_data(partnum, data):
435 """Set the contents of a disk partition
436
437 This updates disk_data by putting data in the right place
438
439 Args:
440 partnum (int): Partition number to set
441 data (bytes): Data for that partition
442 """
443 nonlocal disk_data
444
445 start = parts[partnum].start * sect_size
446 disk_data = disk_data[:start] + data + disk_data[start + len(data):]
447
448 mmc_dev = 7
449 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
Simon Glass08631802024-09-01 16:26:14 -0600450 u_boot_utils.run_and_log(cons, f'qemu-img create {fname} 20M')
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200451 u_boot_utils.run_and_log(cons, f'cgpt create {fname}')
452
453 ptr = 40
454
455 # Number of sectors in 1MB
456 sect_size = 512
457 sect_1mb = (1 << 20) // sect_size
458
459 required_parts = [
460 {'num': 1, 'label':'misc', 'size': '1M'},
461 {'num': 2, 'label':'boot_a', 'size': '4M'},
462 {'num': 3, 'label':'boot_b', 'size': '4M'},
463 {'num': 4, 'label':'vendor_boot_a', 'size': '4M'},
464 {'num': 5, 'label':'vendor_boot_b', 'size': '4M'},
465 ]
466
467 for part in required_parts:
468 size_str = part['size']
469 if 'M' in size_str:
470 size = int(size_str[:-1]) * sect_1mb
471 else:
472 size = int(size_str)
473 u_boot_utils.run_and_log(
474 cons,
475 f"cgpt add -i {part['num']} -b {ptr} -s {size} -l {part['label']} -t basicdata {fname}")
476 ptr += size
477
478 u_boot_utils.run_and_log(cons, f'cgpt boot -p {fname}')
479 out = u_boot_utils.run_and_log(cons, f'cgpt show -q {fname}')
480
481 # Create a dict (indexed by partition number) containing the above info
482 for line in out.splitlines():
483 start, size, num, name = line.split(maxsplit=3)
484 parts[int(num)] = Partition(int(start), int(size), name)
485
486 with open(fname, 'rb') as inf:
487 disk_data = inf.read()
488
489 test_abootimg.AbootimgTestDiskImage(cons, 'bootv4.img', test_abootimg.boot_img_hex)
490 boot_img = os.path.join(cons.config.result_dir, 'bootv4.img')
491 with open(boot_img, 'rb') as inf:
492 set_part_data(2, inf.read())
493
494 test_abootimg.AbootimgTestDiskImage(cons, 'vendor_boot.img', test_abootimg.vboot_img_hex)
495 vendor_boot_img = os.path.join(cons.config.result_dir, 'vendor_boot.img')
496 with open(vendor_boot_img, 'rb') as inf:
497 set_part_data(4, inf.read())
498
499 with open(fname, 'wb') as outf:
500 outf.write(disk_data)
501
Simon Glass08631802024-09-01 16:26:14 -0600502 print(f'wrote to {fname}')
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200503
Guillaume La Roque368ad9e2024-11-26 09:06:13 +0100504 mmc_dev = 8
505 fname = os.path.join(cons.config.source_dir, f'mmc{mmc_dev}.img')
506 u_boot_utils.run_and_log(cons, f'qemu-img create {fname} 20M')
507 u_boot_utils.run_and_log(cons, f'cgpt create {fname}')
508
509 ptr = 40
510
511 # Number of sectors in 1MB
512 sect_size = 512
513 sect_1mb = (1 << 20) // sect_size
514
515 required_parts = [
516 {'num': 1, 'label':'misc', 'size': '1M'},
517 {'num': 2, 'label':'boot_a', 'size': '4M'},
518 {'num': 3, 'label':'boot_b', 'size': '4M'},
519 ]
520
521 for part in required_parts:
522 size_str = part['size']
523 if 'M' in size_str:
524 size = int(size_str[:-1]) * sect_1mb
525 else:
526 size = int(size_str)
527 u_boot_utils.run_and_log(
528 cons,
529 f"cgpt add -i {part['num']} -b {ptr} -s {size} -l {part['label']} -t basicdata {fname}")
530 ptr += size
531
532 u_boot_utils.run_and_log(cons, f'cgpt boot -p {fname}')
533 out = u_boot_utils.run_and_log(cons, f'cgpt show -q {fname}')
534
535 # Create a dict (indexed by partition number) containing the above info
536 for line in out.splitlines():
537 start, size, num, name = line.split(maxsplit=3)
538 parts[int(num)] = Partition(int(start), int(size), name)
539
540 with open(fname, 'rb') as inf:
541 disk_data = inf.read()
542
543 test_abootimg.AbootimgTestDiskImage(cons, 'boot.img', test_abootimg.img_hex)
544 boot_img = os.path.join(cons.config.result_dir, 'boot.img')
545 with open(boot_img, 'rb') as inf:
546 set_part_data(2, inf.read())
547
548 with open(fname, 'wb') as outf:
549 outf.write(disk_data)
550
551 print(f'wrote to {fname}')
552
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200553 return fname
Simon Glassfff928c2023-08-24 13:55:41 -0600554
Simon Glassb8c26552023-06-01 10:23:03 -0600555def setup_cedit_file(cons):
Simon Glass08631802024-09-01 16:26:14 -0600556 """Set up a .dtb file for use with testing expo and configuration editor"""
Simon Glassb8c26552023-06-01 10:23:03 -0600557 infname = os.path.join(cons.config.source_dir,
558 'test/boot/files/expo_layout.dts')
Simon Glassb1263bc2023-08-14 16:40:28 -0600559 inhname = os.path.join(cons.config.source_dir,
560 'test/boot/files/expo_ids.h')
Simon Glassb8c26552023-06-01 10:23:03 -0600561 expo_tool = os.path.join(cons.config.source_dir, 'tools/expo.py')
562 outfname = 'cedit.dtb'
563 u_boot_utils.run_and_log(
Simon Glassb1263bc2023-08-14 16:40:28 -0600564 cons, f'{expo_tool} -e {inhname} -l {infname} -o {outfname}')
Simon Glassb8c26552023-06-01 10:23:03 -0600565
Stephen Warren770fe172016-02-08 14:44:16 -0700566@pytest.mark.buildconfigspec('ut_dm')
567def test_ut_dm_init(u_boot_console):
568 """Initialize data for ut dm tests."""
569
570 fn = u_boot_console.config.source_dir + '/testflash.bin'
571 if not os.path.exists(fn):
Tom Rini439ed3e2019-10-24 11:59:22 -0400572 data = b'this is a test'
573 data += b'\x00' * ((4 * 1024 * 1024) - len(data))
Stephen Warren770fe172016-02-08 14:44:16 -0700574 with open(fn, 'wb') as fh:
575 fh.write(data)
576
577 fn = u_boot_console.config.source_dir + '/spi.bin'
578 if not os.path.exists(fn):
Tom Rini439ed3e2019-10-24 11:59:22 -0400579 data = b'\x00' * (2 * 1024 * 1024)
Stephen Warren770fe172016-02-08 14:44:16 -0700580 with open(fn, 'wb') as fh:
581 fh.write(data)
582
Simon Glass509f32e2022-09-21 16:21:47 +0200583 # Create a file with a single partition
584 fn = u_boot_console.config.source_dir + '/scsi.img'
585 if not os.path.exists(fn):
586 data = b'\x00' * (2 * 1024 * 1024)
587 with open(fn, 'wb') as fh:
588 fh.write(data)
589 u_boot_utils.run_and_log(
590 u_boot_console, f'sfdisk {fn}', stdin=b'type=83')
591
Simon Glass08709212023-08-24 13:55:38 -0600592 fs_helper.mk_fs(u_boot_console.config, 'ext2', 0x200000, '2MB')
593 fs_helper.mk_fs(u_boot_console.config, 'fat32', 0x100000, '1MB')
Simon Glass2c7b0e42022-10-29 19:47:19 -0600594
Alexander Gendin038cb022023-10-09 01:24:36 +0000595 mmc_dev = 6
596 fn = os.path.join(u_boot_console.config.source_dir, f'mmc{mmc_dev}.img')
597 data = b'\x00' * (12 * 1024 * 1024)
598 with open(fn, 'wb') as fh:
599 fh.write(data)
600
Simon Glass64c63252024-11-07 14:31:49 -0700601
602def setup_efi_image(cons):
603 """Create a 20MB disk image with an EFI app on it"""
604 devnum = 1
605 basename = 'flash'
606 fname, mnt = setup_image(cons, devnum, 0xc, second_part=True,
607 basename=basename)
608
609 loop = None
610 mounted = False
611 complete = False
612 try:
613 loop = mount_image(cons, fname, mnt, 'ext4')
614 mounted = True
615 efi_dir = os.path.join(mnt, 'EFI')
616 mkdir_cond(efi_dir)
617 bootdir = os.path.join(efi_dir, 'BOOT')
618 mkdir_cond(bootdir)
619 efi_src = os.path.join(cons.config.build_dir,
620 f'lib/efi_loader/testapp.efi')
621 efi_dst = os.path.join(bootdir, 'BOOTSBOX.EFI')
622 with open(efi_src, 'rb') as inf:
623 with open(efi_dst, 'wb') as outf:
624 outf.write(inf.read())
625 complete = True
626 except ValueError as exc:
627 print(f'Falled to create image, failing back to prepared copy: {exc}')
628
629 finally:
630 if mounted:
631 u_boot_utils.run_and_log(cons, 'sudo umount --lazy %s' % mnt)
632 if loop:
633 u_boot_utils.run_and_log(cons, 'sudo losetup -d %s' % loop)
634
635 if not complete:
636 copy_prepared_image(cons, devnum, fname, basename)
637
638
Simon Glassd3203bd2022-04-24 23:31:25 -0600639@pytest.mark.buildconfigspec('cmd_bootflow')
Simon Glass84712cd2024-06-23 14:30:27 -0600640@pytest.mark.buildconfigspec('sandbox')
Simon Glassd3203bd2022-04-24 23:31:25 -0600641def test_ut_dm_init_bootstd(u_boot_console):
642 """Initialise data for bootflow tests"""
643
644 setup_bootflow_image(u_boot_console)
Simon Glassd2bc33ed2023-01-06 08:52:41 -0600645 setup_bootmenu_image(u_boot_console)
Simon Glassb8c26552023-06-01 10:23:03 -0600646 setup_cedit_file(u_boot_console)
Simon Glassfff928c2023-08-24 13:55:41 -0600647 setup_cros_image(u_boot_console)
Mattijs Korpershoekd77f8152024-07-10 10:40:06 +0200648 setup_android_image(u_boot_console)
Simon Glass64c63252024-11-07 14:31:49 -0700649 setup_efi_image(u_boot_console)
Simon Glassd3203bd2022-04-24 23:31:25 -0600650
651 # Restart so that the new mmc1.img is picked up
652 u_boot_console.restart_uboot()
653
654
Stephen Warren770fe172016-02-08 14:44:16 -0700655def test_ut(u_boot_console, ut_subtest):
Heinrich Schuchardtdf6c36c2020-05-06 18:26:07 +0200656 """Execute a "ut" subtest.
657
658 The subtests are collected in function generate_ut_subtest() from linker
659 generated lists by applying a regular expression to the lines of file
660 u-boot.sym. The list entries are created using the C macro UNIT_TEST().
661
662 Strict naming conventions have to be followed to match the regular
663 expression. Use UNIT_TEST(foo_test_bar, _flags, foo_test) for a test bar in
664 test suite foo that can be executed via command 'ut foo bar' and is
665 implemented in C function foo_test_bar().
666
667 Args:
668 u_boot_console (ConsoleBase): U-Boot console
669 ut_subtest (str): test to be executed via command ut, e.g 'foo bar' to
670 execute command 'ut foo bar'
671 """
Stephen Warren770fe172016-02-08 14:44:16 -0700672
Francis Laniel91ec8702023-12-22 22:02:24 +0100673 if ut_subtest == 'hush hush_test_simple_dollar':
674 # ut hush hush_test_simple_dollar prints "Unknown command" on purpose.
675 with u_boot_console.disable_check('unknown_command'):
676 output = u_boot_console.run_command('ut ' + ut_subtest)
Simon Glass08631802024-09-01 16:26:14 -0600677 assert 'Unknown command \'quux\' - try \'help\'' in output
Francis Laniel91ec8702023-12-22 22:02:24 +0100678 else:
679 output = u_boot_console.run_command('ut ' + ut_subtest)
Stephen Warren770fe172016-02-08 14:44:16 -0700680 assert output.endswith('Failures: 0')