HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

test/units/TEST-58-REPART.sh

119,614 bytesGit mode 100755Download original fileLGPL-2.1-or-later

Git blob: 2a6c369b38488296167b647fad74b8af7f70be19

Lines 2001–3000 of 3,527

 
    if command -v mksquashfs >/dev/null; then
        tee "$defs/root-squashfs.conf" <<EOF
[Partition]
Type=root-${architecture}
Format=squashfs
CopyFiles=${defs}
Minimize=best
EOF
    fi
 
    output=$(systemd-repart --offline="$OFFLINE" \
                            --definitions="$defs" \
                            --seed="$seed" \
                            --dry-run=no \
                            --empty=create \
                            --size=auto \
                            --json=pretty \
                            "$imgs/zzz")
 
    # Check that we can dissect, mount and unmount a minimized image.
 
    if systemd-detect-virt --quiet --container; then
        echo "Skipping minimize dissect, mount and unmount test in container."
        return
    fi
 
    systemd-dissect "$imgs/zzz"
    systemd-dissect "$imgs/zzz" -M "$imgs/mnt"
    systemd-dissect -U "$imgs/mnt"
}
 
testcase_free_area_calculation() {
    local defs imgs output
 
    if ! command -v mksquashfs >/dev/null; then
        echo "Skipping free area calculation test without squashfs."
        return
    fi
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs'" RETURN
    chmod 0755 "$defs"
 
    # https://github.com/systemd/systemd/issues/28225
    echo "*** free area calculation ***"
 
    tee "$defs/00-ESP.conf" <<EOF
[Partition]
Type         = esp
Label        = ESP
Format       = vfat
 
SizeMinBytes = 128M
SizeMaxBytes = 128M
 
# Sufficient for testing
CopyFiles    = /etc:/
EOF
 
    tee "$defs/10-os.conf" <<EOF
[Partition]
Type           = root-${architecture}
Label          = test
Format         = squashfs
 
Minimize       = best
# Sufficient for testing
CopyFiles      = /etc/:/
 
VerityMatchKey = os
Verity         = data
EOF
 
    tee "$defs/11-os-verity.conf" <<EOF
[Partition]
Type           = root-${architecture}-verity
Label          = test
 
Minimize       = best
 
VerityMatchKey = os
Verity         = hash
EOF
 
    # Set sector size for VFAT to 512 bytes because there will not be enough FAT clusters otherwise
    output1=$(SYSTEMD_REPART_MKFS_OPTIONS_VFAT="-S 512" systemd-repart \
                                              --definitions="$defs" \
                                              --seed="$seed" \
                                              --dry-run=no \
                                              --empty=create \
                                              --size=auto \
                                              --sector-size=4096 \
                                              --defer-partitions=esp \
                                              --json=pretty \
                                              "$imgs/zzz")
 
    # The second invocation
    output2=$(SYSTEMD_REPART_MKFS_OPTIONS_VFAT="-S 512" systemd-repart \
                                              --definitions="$defs" \
                                              --seed="$seed" \
                                              --dry-run=no \
                                              --empty=allow \
                                              --size=auto \
                                              --sector-size=4096 \
                                              --defer-partitions=esp \
                                              --json=pretty \
                                              "$imgs/zzz")
 
    diff -u <(echo "$output1" | grep -E "(offset|raw_size|raw_padding)") \
            <(echo "$output2" | grep -E "(offset|raw_size|raw_padding)")
}
 
test_sector() {
    local defs imgs output loop
    local start size ratio
    local sector="${1?}"
 
    if systemd-detect-virt --quiet --container; then
        echo "Skipping sector size tests in container."
        return
    fi
 
    echo "*** sector sizes ***"
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs'" RETURN
 
    tee "$defs/a.conf" <<EOF
[Partition]
Type=root
SizeMaxBytes=15M
SizeMinBytes=15M
EOF
    tee "$defs/b.conf" <<EOF
[Partition]
Type=linux-generic
Weight=250
EOF
 
    tee "$defs/c.conf" <<EOF
[Partition]
Type=linux-generic
Weight=750
EOF
 
    truncate -s 100m "$imgs/$sector.img"
    loop=$(losetup -b "$sector" -P --show -f "$imgs/$sector.img" )
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --settle "${loop:?}"
 
    systemd-repart --offline="$OFFLINE" \
                   --pretty=yes \
                   --definitions="$defs" \
                   --seed="$seed" \
                   --empty=require \
                   --dry-run=no \
                   "$loop"
 
    sfdisk --verify "$loop"
    output=$(sfdisk --dump "$loop")
    losetup -d "$loop"
 
    ratio=$(( sector / 512 ))
    start=$(( 2048 / ratio ))
    size=$(( 30720 / ratio ))
    assert_in "${loop}p1 : start= *${start}, size= *${size}, type=${root_guid}, uuid=${root_uuid}, name=\"root-${architecture}\", attrs=\"GUID:59\"" "$output"
    start=$(( start + size ))
    size=$(( 42992 / ratio ))
    assert_in "${loop}p2 : start= *${start}, size= *${size}, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4, uuid=DF71F5E3-080A-4D16-824B-18591B881380, name=\"linux-generic\"" "$output"
    start=$(( start + size ))
    size=$(( 129000 / ratio ))
    assert_in "${loop}p3 : start= *${start}, size= *${size}, type=0FC63DAF-8483-4772-8E79-3D69D8477DE4, uuid=DB081670-07AE-48CA-9F5E-813D5E40B976, name=\"linux-generic-2\"" "$output"
}
 
testcase_sector() {
    # Valid block sizes on the Linux block layer are >= 512 and <= PAGE_SIZE, and
    # must be powers of 2. Which leaves exactly four different ones to test on
    # typical hardware
    test_sector 512
    test_sector 1024
    test_sector 2048
    test_sector 4096
}
 
testcase_dropped_partitions() {
    local workdir image defs
 
    workdir="$(mktemp --directory "/tmp/test-repart.dropped-partitions.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '${workdir:?}'" RETURN
 
    image="$workdir/image.img"
    truncate -s 32M "$image"
 
    defs="$workdir/defs"
    mkdir "$defs"
    echo -ne "[Partition]\nType=root\n" >"$defs/10-part1.conf"
    echo -ne "[Partition]\nType=root\nSizeMinBytes=1T\nPriority=1\n" >"$defs/11-dropped-first.conf"
    echo -ne "[Partition]\nType=root\n" >"$defs/12-part2.conf"
    echo -ne "[Partition]\nType=root\nSizeMinBytes=1T\nPriority=2\n" >"$defs/13-dropped-second.conf"
 
    systemd-repart --empty=allow --pretty=yes --dry-run=no --definitions="$defs" "$image"
 
    sfdisk -q -l "$image"
    [[ "$(sfdisk -q -l "$image" | grep -c "$image")" -eq 2 ]]
}
 
testcase_urandom() {
    local workdir image defs
 
    workdir="$(mktemp --directory "/tmp/test-repart.urandom.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '${workdir:?}'" RETURN
 
    image="$workdir/image.img"
    truncate -s 32M "$image"
 
    defs="$workdir/defs"
    mkdir "$defs"
    echo -ne "[Partition]\nType=swap\nCopyBlocks=/dev/urandom\n" >"$defs/10-urandom.conf"
 
    systemd-repart --empty=force --pretty=yes --dry-run=no --definitions="$defs" "$image"
 
    sfdisk -q -l "$image"
    [[ "$(sfdisk -q -l "$image" | grep -c "$image")" -eq 1 ]]
}
 
testcase_list_devices() {
    systemd-repart --list-devices
}
 
testcase_compression() {
    local workdir image defs
 
    workdir="$(mktemp --directory "/tmp/test-repart.compression.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '${workdir:?}'" RETURN
 
    image="$workdir/image.img"
    defs="$workdir/defs"
    mkdir "$defs"
 
    # TODO: add btrfs once btrfs-progs v6.11 is available in distributions.
    for format in squashfs erofs; do
        case "$format" in
            squashfs)
                command -v mksquashfs >/dev/null || continue ;;
            *)
                command -v "mkfs.$format" || continue ;;
        esac
 
        [[ "$format" == "squashfs" ]] && compression=zstd
        [[ "$format" == "erofs" ]] && compression=lz4hc
 
        tee "$defs/10-root.conf" <<EOF
[Partition]
Type=root
Format=$format
Compression=$compression
CompressionLevel=3
CopyFiles=$defs:/def
SizeMinBytes=48M
EOF
 
        rm -f "$image"
        systemd-repart --empty=create --size=auto --pretty=yes --dry-run=no --definitions="$defs" "$image"
    done
}
 
testcase_random_seed() {
    local defs imgs output
 
    # For issue #34257
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs'" RETURN
    chmod 0755 "$defs"
 
    tee "$defs/root.conf" <<EOF
[Partition]
Type=root
EOF
 
    tee "$defs/home.conf" <<EOF
[Partition]
Type=home
Label=home-first
EOF
 
    tee "$defs/swap.conf" <<EOF
[Partition]
Type=swap
SizeMaxBytes=64M
PaddingMinBytes=92M
EOF
 
    systemd-repart --offline="$OFFLINE" \
                   --definitions="$defs" \
                   --empty=create \
                   --size=1G \
                   --dry-run=no \
                   --seed=random \
                   --offline="$OFFLINE" \
                   --json=pretty \
                   "$imgs/zzz"
 
    sfdisk -d "$imgs/zzz"
    [[ "$(sfdisk -d "$imgs/zzz" | grep -F 'uuid=' | awk '{ print $8 }' | sort -u | wc -l)" == "3" ]]
}
 
testcase_make_symlinks() {
    local defs imgs output epoch
 
    if systemd-detect-virt --quiet --container; then
        echo "Skipping MakeSymlinks= test in container."
        return
    fi
 
    # For issue #34257
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs'" RETURN
    chmod 0755 "$defs"
 
    tee "$defs/root.conf" <<EOF
[Partition]
Type=root
MakeDirectories=/dir
MakeSymlinks=/foo:/bar
MakeSymlinks=/dir/foo:/bar
MakeSymlinks=/dir/foo-%a:/bar-%a
MakeSymlinks=/dir/bar-%a:../bar-%a
EOF
 
    # Build with an epoch, so that this also covers do_make_symlinks()' time stamping. It has to
    # stamp the symlink itself and repair the directory it lands in, because creating an entry there
    # bumps that directory back to the wall clock.
    epoch=1700000000
 
    env SOURCE_DATE_EPOCH="$epoch" \
        systemd-repart --offline="$OFFLINE" \
                   --definitions="$defs" \
                   --empty=create \
                   --size=1G \
                   --dry-run=no \
                   --offline="$OFFLINE" \
                   --json=pretty \
                   "$imgs/zzz"
 
    systemd-dissect "$imgs/zzz" -M "$imgs/mnt"
    assert_eq "$(readlink "$imgs/mnt/foo")" "/bar"
    assert_eq "$(readlink "$imgs/mnt/dir/foo")" "/bar"
    assert_eq "$(readlink "$imgs/mnt/dir/foo-${architecture}")" "/bar-${architecture}"
    assert_eq "$(readlink "$imgs/mnt/dir/bar-${architecture}")" "../bar-${architecture}"
 
    # the symlink's own mtime (no -L)
    assert_eq "$(stat -c %Y "$imgs/mnt/dir/foo")" "$epoch"
    # a MakeDirectories= dir, stamped with the epoch and then bumped by the symlinks below it.
    assert_eq "$(stat -c %Y "$imgs/mnt/dir")" "$epoch"
 
    systemd-dissect -U "$imgs/mnt"
}
 
testcase_fallback_partitions() {
    local workdir image defs
 
    workdir="$(mktemp --directory "/tmp/test-repart.fallback.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '${workdir:?}'" RETURN
 
    image="$workdir/image.img"
    defs="$workdir/defs"
    mkdir "$defs"
 
    tee "$defs/10-esp.conf" <<EOF
[Partition]
Type=esp
Format=vfat
SizeMinBytes=10M
EOF
 
    tee "$defs/20-xbootldr.conf" <<EOF
[Partition]
Type=xbootldr
Format=vfat
SizeMinBytes=100M
SupplementFor=10-esp
EOF
 
    # Blank disk => big ESP should be created
 
    systemd-repart --empty=create --size=auto --dry-run=no --definitions="$defs" "$image"
 
    output=$(sfdisk -d "$image")
    assert_in "${image}1 : start=        2048, size=      532480, type=${esp_guid}" "$output"
    assert_not_in "${image}2" "$output"
 
    # Disk with small ESP => ESP grows
 
    sfdisk "$image" <<EOF
label: gpt
size=10M, type=${esp_guid}
EOF
 
    systemd-repart --dry-run=no --definitions="$defs" "$image"
 
    output=$(sfdisk -d "$image")
    assert_in "${image}1 : start=        2048, size=      532480, type=${esp_guid}" "$output"
    assert_not_in "${image}2" "$output"
 
    # Disk with small ESP that can't grow => XBOOTLDR created
 
    truncate -s 400M "$image"
    sfdisk "$image" <<EOF
label: gpt
size=10M, type=${esp_guid},
size=10M, type=${root_guid},
EOF
 
    systemd-repart --dry-run=no --definitions="$defs" "$image"
 
    output=$(sfdisk -d "$image")
    assert_in "${image}1 : start=        2048, size=       20480, type=${esp_guid}" "$output"
    assert_in "${image}3 : start=       43008, size=      776152, type=${xbootldr_guid}" "$output"
 
    # Disk with existing XBOOTLDR partition => XBOOTLDR grows, small ESP created
 
    sfdisk "$image" <<EOF
label: gpt
size=10M, type=${xbootldr_guid},
EOF
 
    systemd-repart --dry-run=no --definitions="$defs" "$image"
 
    output=$(sfdisk -d "$image")
    assert_in "${image}1 : start=        2048, size=      284632, type=${xbootldr_guid}" "$output"
    assert_in "${image}2 : start=      286680, size=      532480, type=${esp_guid}" "$output"
}
 
testcase_btrfs() {
    local defs imgs output root
 
    if ! systemd-analyze compare-versions "$(btrfs --version | head -n 1 | awk '{ print $2 }')" ge v6.12; then
        echo "btrfs-progs is not installed or older than v6.12, skipping test."
        return 0
    fi
 
    if [[ "$OFFLINE" != "yes" ]]; then
        return 0
    fi
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    root="$(mktemp --directory "/var/test-repart.root.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs' '$root'" RETURN
    chmod 0755 "$defs"
 
    echo "*** testcase for btrfs ***"
 
    tee "$defs/root.conf" <<EOF
[Partition]
Type=root
Format=btrfs
MakeDirectories=/@ /@home
Subvolumes=/@ /@home
DefaultSubvolume=/@
MountPoint=/:"subvol=@,zstd:1,noatime,lazytime"
MountPoint=/home:"subvol=@home,zstd:1,noatime,lazytime"
EOF
 
    mkdir -p "$root"/etc
 
    systemd-repart --pretty=yes \
                   --definitions "$defs" \
                   --empty=create \
                   --size=1G \
                   --seed="$seed" \
                   --dry-run=no \
                   --offline=yes \
                   --generate-fstab "$root"/etc/fstab \
                   "$imgs/btrfs.img"
 
    sfdisk --dump "$imgs/btrfs.img"
 
    cat "$root"/etc/fstab
    grep -q 'UUID=[0-9a-f-]* / btrfs discard,rw,nodev,suid,exec,subvol=@,zstd:1,noatime,lazytime 0 1' "$root"/etc/fstab
    grep -q 'UUID=[0-9a-f-]* /home btrfs discard,rw,nodev,suid,exec,subvol=@home,zstd:1,noatime,lazytime 0 1' "$root"/etc/fstab
}
 
testcase_btrfs_compression() {
    local defs imgs loop output
 
    if ! systemd-analyze compare-versions "$(btrfs --version | head -n 1 | awk '{ print $2 }')" ge v6.13; then
        echo "btrfs-progs is not installed or older than v6.13, skipping test."
        return 0
    fi
 
    defs="$(mktemp -d)"
    imgs="$(mktemp -d)"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs'" RETURN
    chmod 0755 "$defs"
 
    echo "*** testcase for btrfs compression with CopyFiles (OFFLINE=$OFFLINE) ***"
 
    # Must not be in tmpfs due to exclusions. It also must be large and
    # compressible so that the compression check succeeds later.
    src=/etc/test-source-file
    fallocate -l 1M "$src"
 
    tee "$defs/btrfs-compressed.conf" <<EOF
[Partition]
Type=linux-generic
Format=btrfs
Compression=zstd
CopyFiles=$src:/test-file
SizeMinBytes=100M
SizeMaxBytes=100M
EOF
 
    systemd-repart --offline="$OFFLINE" \
                   --definitions="$defs" \
                   --empty=create \
                   --size=auto \
                   --dry-run=no \
                   --seed="$seed" \
                   "$imgs/btrfs-compressed.img" 2>&1 | tee "$imgs/repart-output.txt"
    rm "$src"
 
    output=$(cat "$imgs/repart-output.txt")
 
    assert_in "Rootdir from:" "$output"
    assert_in "Compress:" "$output"
 
    if [[ "$OFFLINE" == "yes" ]] || systemd-detect-virt --quiet --container; then
        echo "Skipping mount verification (requires loop devices)"
        return 0
    fi
    loop="$(losetup -P --show --find "$imgs/btrfs-compressed.img")"
    # shellcheck disable=SC2064
    trap "umount '$imgs/mount' 2>/dev/null || true; losetup -d '$loop' 2>/dev/null || true; rm -rf '$defs' '$imgs'" RETURN
    echo "Loop device: $loop"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --settle "${loop:?}p1"
 
    mkdir -p "$imgs/mount"
    mount -t btrfs "${loop:?}p1" "$imgs/mount"
 
    [[ -f "$imgs/mount/test-file" ]]
    [[ "$(stat -c%s "$imgs/mount/test-file")" == "1048576" ]]
 
    if command -v compsize &>/dev/null; then
        output=$(compsize "$imgs/mount/test-file" 2>&1)
        assert_in "zstd" "$output"
    fi
 
    umount "$imgs/mount"
    losetup -d "$loop"
}
 
testcase_varlink_list_devices() {
    REPART="$(which systemd-repart)"
    varlinkctl introspect "$REPART"
    varlinkctl call "$REPART" --graceful=io.systemd.Repart.NoCandidateDevices --collect io.systemd.Repart.ListCandidateDevices '{}'
    varlinkctl call "$REPART" --graceful=io.systemd.Repart.NoCandidateDevices --collect io.systemd.Repart.ListCandidateDevices '{"ignoreRoot":true}'
    varlinkctl call "$REPART" --graceful=io.systemd.Repart.NoCandidateDevices --collect io.systemd.Repart.ListCandidateDevices '{"ignoreEmpty":true}'
    varlinkctl call "$REPART" --graceful=io.systemd.Repart.NoCandidateDevices --collect io.systemd.Repart.ListCandidateDevices '{"ignoreEmpty":true,"ignoreRoot":true}'
 
    varlinkctl call /run/systemd/io.systemd.Repart --graceful=io.systemd.Repart.NoCandidateDevices --collect io.systemd.Repart.ListCandidateDevices '{"ignoreEmpty":true,"ignoreRoot":true}'
}
 
testcase_varlink_subscribe_devices() {
    local imgs subscribe_log pre_existing_log loop loop2 mark non_sub_output
    local sub_unit="test-repart-subscribe.service"
    local pre_unit="test-repart-subscribe-pre.service"
 
    # The uevent monitor in the spawned systemd-repart only sees events from the host's kernel
    # uevent namespace, which an nspawn container with --private-network filters away. Loopback
    # creation also fails inside many container setups.
    if systemd-detect-virt --container >/dev/null 2>&1; then
        echo "Skipping subscribe tests inside container."
        return
    fi
 
    REPART="$(which systemd-repart)"
    imgs="$(mktemp --directory "/var/tmp/test-repart.subscribe.XXXXXXXXXX")"
    subscribe_log="$(mktemp "/var/tmp/test-repart.subscribe-log.XXXXXXXXXX")"
    pre_existing_log="$(mktemp "/var/tmp/test-repart.pre-log.XXXXXXXXXX")"
    loop=""
    loop2=""
 
    # Single-quoted trap body so $loop / $loop2 are expanded at trap-fire time, not now.
    # shellcheck disable=SC2016
    trap '
        systemctl stop "$sub_unit" "$pre_unit" 2>/dev/null || true
        [[ -n "${loop:-}"  ]] && systemd-dissect --detach "$loop"  2>/dev/null || true
        [[ -n "${loop2:-}" ]] && systemd-dissect --detach "$loop2" 2>/dev/null || true
        rm -rf "$imgs" "$subscribe_log" "$subscribe_log.err" "$pre_existing_log" "$pre_existing_log.err"
    ' RETURN
 
    # systemd-dissect --attach requires a dissectable image; a plain ext4 single-filesystem image
    # is the simplest thing it accepts.
    truncate -s 50M "$imgs/loop.img"
    truncate -s 50M "$imgs/loop2.img"
    mkfs.ext4 -F -q -L test-repart-1 "$imgs/loop.img"
    mkfs.ext4 -F -q -L test-repart-2 "$imgs/loop2.img"
 
    # Make sure no stale unit is sitting around from a previous failed run, then arrange cleanup.
    systemctl reset-failed "$sub_unit" "$pre_unit" 2>/dev/null || true
    systemctl stop "$sub_unit" "$pre_unit" 2>/dev/null || true
 
    # Start a varlinkctl subscriber as a transient Type=notify service. systemd-run blocks until the
    # service notifies READY=1 -- which varlinkctl does on receipt of the first reply (see
    # src/varlinkctl/varlinkctl.c reply_callback). For us that's either the first "add" of the
    # initial enumeration or the "ready" sentinel; either way we are guaranteed the server-side
    # monitor is up before we trigger any uevents.
    start_subscriber() {
        local unit="$1" log="$2" params="$3"
 
        systemd-run \
            --quiet \
            --unit="$unit" \
            --collect \
            --service-type=notify \
            --property=StandardOutput="truncate:$log" \
            --property=StandardError="truncate:$log.err" \
            -- \
            varlinkctl --more --timeout=infinity --json=short call \
            "$REPART" io.systemd.Repart.ListCandidateDevices "$params"
    }
 
    # Poll for a regex match in $1 of the named log file ($3, default $subscribe_log), starting from
    # byte offset $2. Prints the new byte offset (post-match) on stdout so the caller can advance.
    expect_event() {
        local pat="$1" mark_="$2" file="${3:-$subscribe_log}"
        local deadline_=$((SECONDS + UDEVADM_WAIT_TIMEOUT))
        local cur
 
        while (( SECONDS < deadline_ )); do
            cur=$(stat -c%s "$file" 2>/dev/null || echo 0)
            if (( cur > mark_ )) && \
               tail -c +"$((mark_ + 1))" "$file" | grep -a -E "$pat" >/dev/null; then
                printf '%s\n' "$cur"
                return 0
            fi
            sleep 0.1
        done
 
        echo "FAIL: pattern '$pat' did not appear within ${UDEVADM_WAIT_TIMEOUT}s. Output past offset $mark_:" >&2
        tail -c +"$((mark_ + 1))" "$file" >&2 || true
        return 1
    }
 
    # === Test 1: subscribing produces a "ready" sentinel even on an empty initial set ===
    start_subscriber "$sub_unit" "$subscribe_log" \
        '{"ignoreRoot":true,"ignoreEmpty":true,"subscribe":true}'
    mark=$(expect_event '"action":"ready"' 0) || return 1
 
    # === Test 2: a freshly-added loopback produces an "add" event ===
    loop="$(systemd-dissect --attach --loop-ref=test-repart-1 "$imgs/loop.img")"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --settle "$loop"
    mark=$(expect_event "\"action\":\"add\".*\"node\":\"$loop\"" "$mark") || return 1
 
    # === Test 3: detaching the loopback produces a "remove" event ===
    systemd-dissect --detach "$loop"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --removed --settle "$loop"
    mark=$(expect_event "\"action\":\"remove\".*\"node\":\"$loop\"" "$mark") || return 1
    loop=""
 
    # === Test 4: five add/remove cycles in a row stay in sync ===
    for _ in 1 2 3 4 5; do
        loop="$(systemd-dissect --attach --loop-ref=test-repart-1 "$imgs/loop.img")"
        udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --settle "$loop"
        mark=$(expect_event "\"action\":\"add\".*\"node\":\"$loop\"" "$mark") || return 1
 
        systemd-dissect --detach "$loop"
        udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --removed --settle "$loop"
        mark=$(expect_event "\"action\":\"remove\".*\"node\":\"$loop\"" "$mark") || return 1
        loop=""
    done
 
    # === Test 5: two coexisting loop devices each produce their own events ===
    # Set them up (and tear them down) one at a time and wait for each device in turn, so events
    # appear in a strict order and we can advance our mark monotonically.
    loop="$(systemd-dissect --attach --loop-ref=test-repart-1 "$imgs/loop.img")"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --settle "$loop"
    mark=$(expect_event "\"action\":\"add\".*\"node\":\"$loop\"" "$mark") || return 1
 
    loop2="$(systemd-dissect --attach --loop-ref=test-repart-2 "$imgs/loop2.img")"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --settle "$loop2"
    mark=$(expect_event "\"action\":\"add\".*\"node\":\"$loop2\"" "$mark") || return 1
 
    systemd-dissect --detach "$loop2"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --removed --settle "$loop2"
    mark=$(expect_event "\"action\":\"remove\".*\"node\":\"$loop2\"" "$mark") || return 1
    loop2=""
 
    systemd-dissect --detach "$loop"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --removed --settle "$loop"
    mark=$(expect_event "\"action\":\"remove\".*\"node\":\"$loop\"" "$mark") || return 1
    loop=""
 
    # Tear down the first subscriber before starting the next one.
    systemctl stop "$sub_unit"
 
    # === Test 6: a device that exists *before* subscribe starts shows up in the initial enumeration,
    # and "ready" arrives only after it ===
    loop="$(systemd-dissect --attach --loop-ref=test-repart-1 "$imgs/loop.img")"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --settle "$loop"
 
    start_subscriber "$pre_unit" "$pre_existing_log" \
        '{"ignoreRoot":true,"subscribe":true}'
 
    # systemd-run returned (Type=notify => first reply already received), but "ready" may not be
    # written yet -- poll for it.
    expect_event '"action":"ready"' 0 "$pre_existing_log" >/dev/null || return 1
 
    # Everything up to (but excluding) "ready" is the initial enumeration; it must contain $loop.
    if ! sed -n '/"action":"ready"/q;p' "$pre_existing_log" | \
            grep -a -E "\"action\":\"add\".*\"node\":\"$loop\"" >/dev/null; then
        echo "FAIL: pre-existing loop device $loop not in initial enumeration:" >&2
        cat "$pre_existing_log" >&2
        return 1
    fi
 
    systemctl stop "$pre_unit"
 
    # === Test 7: without subscribe the reply has no "action" field (back-compat for older clients) ===
    non_sub_output="$(varlinkctl --collect --json=short call \
        "$REPART" --graceful=io.systemd.Repart.NoCandidateDevices \
        io.systemd.Repart.ListCandidateDevices '{"ignoreRoot":true}')"
    assert_not_in '"action"' "$non_sub_output"
    # Sanity-check: our $loop *is* in that output (so the assertion above wasn't vacuous).
    assert_in "\"node\":\"$loop\"" "$non_sub_output"
 
    systemd-dissect --detach "$loop"
    loop=""
}
 
testcase_get_size() {
    local defs
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs'" RETURN
 
    tee "$defs/a.conf" <<EOF
[Partition]
Type=root
SizeMinBytes=15M
EOF
    tee "$defs/b.conf" <<EOF
[Partition]
Type=linux-generic
SizeMinBytes=23M
EOF
 
    output="$(systemd-repart --definitions="$defs" - 2>&1)"
    assert_in "Automatically determined minimal disk image size as 39M." "$output"
}
 
testcase_varlink_run() {
    local defs
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs'" RETURN
 
    tee "$defs/a.conf" <<EOF
[Partition]
Type=root
Format=empty
EOF
    tee "$defs/b.conf" <<EOF
[Partition]
Type=linux-generic
Format=empty
EOF
 
    systemd-repart --pretty=yes \
                   --definitions "$defs" \
                   --empty=create \
                   --size=50M \
                   --seed="$seed" \
                   --dry-run=no \
                   --offline=yes \
                   "$imgs/disk1.img"
 
    REPART="$(which systemd-repart)"
    truncate -s 50M "$imgs/disk2.img"
    varlinkctl call "$REPART" io.systemd.Repart.Run '{"definitions":["'"$defs"'"],"empty":"force","seed":"'"$seed"'","dryRun":false,"node":"'"$imgs/disk2.img"'"}'
 
    # Compare that the version from the command line and via Varlink result in the bit exact same output
    cmp "$imgs/disk1.img" "$imgs/disk2.img"
 
    # Try once more, this time with progress info
    truncate -s 50M "$imgs/disk3.img"
    varlinkctl --more --collect call "$REPART" io.systemd.Repart.Run '{"definitions":["'"$defs"'"],"empty":"force","seed":"'"$seed"'","dryRun":false,"node":"'"$imgs/disk3.img"'"}'
 
    cmp "$imgs/disk1.img" "$imgs/disk3.img"
}
 
_test_luks2_integrity() {
    local defs imgs output root
 
    if [[ "$OFFLINE" != "no" ]]; then
        return 0
    fi
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    root="$(mktemp --directory "/var/test-repart.root.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs' '$root'" RETURN
    chmod 0755 "$defs"
 
    echo "*** testcase for LUKS2 integrity ***"
 
    tee "$defs/root.conf" <<EOF
[Partition]
Type=root
Format=ext4
Encrypt=key-file
Integrity=inline
EOF
 
    [ -n "$1" ] && echo "IntegrityAlgorithm=$1" >> "$defs/root.conf"
 
    systemd-repart --pretty=yes \
                   --definitions "$defs" \
                   --empty=create \
                   --size=100M \
                   --seed="$seed" \
                   --dry-run=no \
                   --offline=no \
                   "$imgs/encint.img"
 
    loop="$(losetup -P --show --find "$imgs/encint.img")"
    udevadm wait --timeout="$UDEVADM_WAIT_TIMEOUT" --settle "${loop:?}p1"
 
    volume="test-repart-luksint-$RANDOM"
    dmstatus="$imgs/dmsetup-$RANDOM"
 
    touch "$imgs/empty-password"
 
    # the expectation for hmac-sha256 is 'integrity: hmac(sha256)'
    cryptsetup luksDump "${loop}p1" | grep "integrity: $(echo "$1" | sed -r 's/^hmac-(.*)$/hmac(\1)/')" >/dev/null
 
    cryptsetup open --type=luks2 --key-file="$imgs/empty-password" "${loop}p1" "$volume"
    dmsetup status > "$dmstatus"
    cryptsetup close "$volume"
    losetup -d "$loop"
    # Check that there's a dm-integrity entry
    grep -q "$volume""_dif.* integrity " "$dmstatus"
}
 
testcase_luks2_integrity() {
    _test_luks2_integrity ""
    _test_luks2_integrity "hmac-sha1"
    _test_luks2_integrity "hmac-sha256"
    _test_luks2_integrity "hmac-sha512"
}
 
testcase_ext_reproducibility() {
    local defs imgs ts
 
    # Online mode mounts the filesystem which updates inode timestamps non-deterministically
    if [[ "$OFFLINE" != "yes" ]]; then
        echo "Skipping ext reproducibility test in online mode."
        return 0
    fi
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs'" RETURN
 
    tee "$defs/root.conf" <<EOF
[Partition]
Type=root
Format=ext4
EOF
 
    # Build the image twice with the same seed and verify they are identical
    ts=$(date +%s)
    env SOURCE_DATE_EPOCH="$ts" \
        systemd-repart \
        --offline="$OFFLINE" \
        --definitions="$defs" \
        --empty=create \
        --size=50M \
        --seed="$seed" \
        --dry-run=no \
        "$imgs/test1.img"
 
    sleep 2
 
    env SOURCE_DATE_EPOCH="$ts" \
        systemd-repart \
        --offline="$OFFLINE" \
        --definitions="$defs" \
        --empty=create \
        --size=50M \
        --seed="$seed" \
        --dry-run=no \
        "$imgs/test2.img"
 
    cmp "$imgs/test1.img" "$imgs/test2.img"
}
 
testcase_vfat_reproducibility() {
    local defs imgs img dot_efi dot_linux
 
    if ! command -v mdir >/dev/null; then
        echo "Skipping vfat reproducibility test, mtools is not installed."
        return 0
    fi
 
    defs="$(mktemp --directory "/tmp/test-repart.defs.XXXXXXXXXX")"
    imgs="$(mktemp --directory "/var/tmp/test-repart.imgs.XXXXXXXXXX")"
    # shellcheck disable=SC2064
    trap "rm -rf '$defs' '$imgs'" RETURN
 
    tee "$defs/esp.conf" <<EOF
[Partition]
Type=esp
Format=vfat
CopyFiles=/:/
EOF
 
    # $SOURCE_DATE_EPOCH is a clamp, not an override, so put one file on either side of it to cover
    # both directions.
    mkdir -p "$imgs/tree/EFI/Linux"
    echo old >"$imgs/tree/EFI/Linux/old.efi"
    echo new >"$imgs/tree/EFI/Linux/new.efi"
    touch --date=@1600000000 "$imgs/tree/EFI/Linux/old.efi"
    touch --date=@1750000000 "$imgs/tree/EFI/Linux/new.efi"
 
    # The timestamps as mdir(1) reports them.
    local -r time_epoch="2023-11-14  22:13"   # $SOURCE_DATE_EPOCH below, i.e. @1700000000
    local -r time_old="2020-09-13  12:26"     # old.efi's mtime, before the epoch
    local -r time_new="2025-06-15  15:06"     # new.efi's mtime, after the epoch
 
    # Build $1 from the tree and set $img to it, in the "file@@offset" form mdir(1) wants. The
    # remaining arguments are passed to env(1), to control $SOURCE_DATE_EPOCH.
    build_image() {
        local name="$1" output offset
        shift
 
        output=$(env "$@" \
            systemd-repart \
            --offline="$OFFLINE" \
            --definitions="$defs" \
            --empty=create \
            --size=auto \
            --seed="$seed" \
            --dry-run=no \
            --root="$imgs/tree" \
            --json=pretty \
            "$imgs/$name")
 
        offset=$(jq -r '.[0].offset' <<<"$output")
        img="$imgs/$name@@$offset"
 
        # dump listing for debugging
        fat_entry -/ ::/
    }
 
    # Print $img's mdir(1) entry for the given path. mdir lists a directory's contents; a trailing `*`
    # gets the directory's own entry instead. Insensitive path matching, thus works with mtools' 8.3
    # lower case and kernel vfat's upper case names.
    fat_entry() {
        env MTOOLS_SKIP_CHECK=1 TZ=UTC mdir -i "$img" "$@"
    }
 
    # Same, for the "." entry of directory $1, which cannot be addressed directly.
    fat_dot_entry() {
        fat_entry "$1" | grep -E '^\. +<DIR>'
    }
 
    build_image epoch.img SOURCE_DATE_EPOCH=1700000000
 
    # The directories and the file newer than the epoch are clamped down to it, ...
    assert_in "$time_epoch" "$(fat_entry '::/EFI*')"
    assert_in "$time_epoch" "$(fat_entry '::/EFI/Linux*')"
    assert_in "$time_epoch" "$(fat_entry '::/EFI/Linux/new.efi')"
    # ... while the older one keeps its own mtime.
    assert_in "$time_old" "$(fat_entry '::/EFI/Linux/old.efi')"
 
    # "." and ".." behave differently
    dot_efi=$(fat_dot_entry '::/EFI')