Skip to content
suit Documentation
Login

Documentation

// Unit tests for the config parser's API. The shell tests in run.sh cover the
// command line; these cover the parser directly, including the limits.

// nftw() and its flags are declared by glibc only when X/Open is asked for.
// macOS declares them by default, and defining this there would hide BSD
// names the tests use.
#if defined(__linux__) && !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 700
#endif

#include "conf.h"
#include "platform.h"
#include "ledger.h"
#include "place.h"
#include "resolve.h"
#include "stamp.h"
#include "store_fs.h"

#include <errno.h>
#include <fcntl.h>
#include <ftw.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static Conf conf;
static int checks;
static int failures;

#define CHECK(cond)                                                          \
    do {                                                                     \
        checks++;                                                            \
        if (!(cond)) {                                                       \
            failures++;                                                      \
            printf("FAIL unit %s:%d: %s\n", __FILE__, __LINE__, #cond);      \
        }                                                                    \
    } while (0)

static bool parse(const char *text, ConfError *e)
{
    return conf_parse(&conf, text, strlen(text), e);
}

static void expect_error(const char *text, int line, const char *part)
{
    ConfError e;
    bool ok = parse(text, &e);
    CHECK(!ok);
    CHECK(e.line == line);
    CHECK(strstr(e.msg, part) != nullptr);
    if (ok || e.line != line || strstr(e.msg, part) == nullptr)
        printf("  wanted line %d with '%s', got line %d '%s'\n", line, part, e.line,
            ok ? "(parsed)" : e.msg);
}

static void test_valid(void)
{
    ConfError e;
    CHECK(parse("", &e));
    CHECK(conf.nsections == 0);
    CHECK(parse("# only a comment\n\n   \n", &e));
    CHECK(parse("[harness a]", &e));  // no trailing newline
    CHECK(conf.nsections == 1);
    CHECK(parse("[harness a]\r\nrecord = x\r\n", &e));
    CHECK(strcmp(conf.entries[0].val, "x") == 0);
}

static void test_comments(void)
{
    ConfError e;
    CHECK(parse("[harness a]\nrecord = x # note\nevent E = a#b\n", &e));
    CHECK(strcmp(conf.entries[0].val, "x") == 0);
    CHECK(strcmp(conf.entries[1].val, "a#b") == 0);
    CHECK(parse("  # indented\n[harness a] # header\n", &e));
}

static void test_lists(void)
{
    ConfError e;
    CHECK(parse("[outfit a]\nskills =   x\t y   z*  \n", &e));
    const char *cur = conf.entries[0].val;
    const char *w;
    size_t n;
    CHECK(conf_list_next(&cur, &w, &n) && n == 1 && w[0] == 'x');
    CHECK(conf_list_next(&cur, &w, &n) && n == 1 && w[0] == 'y');
    CHECK(conf_list_next(&cur, &w, &n) && n == 2 && memcmp(w, "z*", 2) == 0);
    CHECK(!conf_list_next(&cur, &w, &n));
}

static void test_errors(void)
{
    expect_error("[bogus x]\n", 1, "unknown section kind");
    expect_error("[harness a]\nnope = 1\n", 2, "unknown key");
    expect_error("[harness a]\n[harness a]\n", 2, "duplicate section");
    expect_error("[outfit a]\nonly = h\nonly = h\n", 3, "duplicate key");
    expect_error("record = x\n", 1, "before any section");
    expect_error("[harness a\n", 1, "malformed");
    expect_error("[outfit a]\ninclude = b\n[outfit b]\ninclude = a\n", 2 + 2,
        "include cycle: a -> b -> a");
    expect_error("[outfit a]\ninclude = a\n", 2, "include cycle: a -> a");
    expect_error("[outfit a]\ninclude = zz\n", 2, "unknown outfit");
    expect_error("[wear user]\noutfits = zz\n", 2, "unknown outfit");
    expect_error("[outfit a]\nonly = zz\n", 2, "unknown harness");
}

static void test_more_errors(void)
{
    expect_error("[harness bad/name]\n", 1, "invalid harness name");
    expect_error("[need h bad/name]\n", 1, "invalid need");
    expect_error("[harness a b c d e]\n", 1, "too many words");
    expect_error("[wear user machine=bad/name]\n", 1, "invalid machine name");
    expect_error("[wear user machine=]\n", 1, "invalid machine name");
    expect_error("[wear shared bad$target]\n", 1, "invalid target");
    expect_error("[wear]\n", 1, "needs a SCOPE");
    expect_error("[wear shared a b]\n", 1, "too many arguments");
    expect_error("[harness a]\nx\n", 2, "expected KEY = VALUE");
    expect_error("[harness a]\nevent E = a b\n", 2, "takes one word");
    expect_error("[outfit o]\nslotx = a\n", 2, "unknown key 'slotx'");
    expect_error("[outfit o]\nslot = a\n", 2, "unknown key 'slot'");
    expect_error("[outfit o]\nslot a$b = f\n", 2, "invalid key");
    expect_error("[outfit o]\nslot a b = f\n", 2, "invalid key");
    expect_error("[outfit o]\nfile ~/a b = f\n", 2, "invalid key");
    expect_error("[harness a]\nbogus.user = x\n", 2, "unknown key 'bogus.user'");
    expect_error("[harness a]\nskills.galaxy = x\n", 2, "unknown key");
    expect_error("[outfit o]\nskills = x yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy/z\n", 2,
        "invalid name 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'");
    expect_error("[outfit abc]\n[outfit o]\ninclude = ab\n", 3, "include of unknown outfit 'ab'");
    expect_error("[outfit a]\ninclude = b\n[outfit b]\ninclude = c\n[outfit c]\ninclude = b\n", 6,
        "include cycle: b -> c -> b");
    expect_error("[wear user]\npublish = yes\n", 2, "publish is allowed only on wear shared");
}

static void test_valid_names(void)
{
    ConfError e;
    CHECK(parse("[harness a_b]\nevent Some_Event.v2-x/y = z\n[outfit Z.9]\nskills = A_b-c.d* x\n", &e));
    CHECK(parse("[wear shared g.com/o/n_x-y:z@h~w]\noutfits = \n", &e) == false);
    CHECK(parse("[wear shared g.com/o/n_x-y:z@h~w]\n", &e));
    CHECK(parse("[outfit o]\nfile ~/a/b = x\nslot hook/Stop = y\n", &e));
}

static void test_long_cycle_message(void)
{
    char names[3][121];
    for (int i = 0; i < 3; i++) {
        memset(names[i], 'a' + i, 120);
        names[i][120] = '\0';
    }
    char text[2048];
    int n = snprintf(text, sizeof text,
        "[outfit %s]\ninclude = %s\n[outfit %s]\ninclude = %s\n[outfit %s]\ninclude = %s\n",
        names[0], names[1], names[1], names[2], names[2], names[0]);
    ConfError e;
    CHECK(!conf_parse(&conf, text, (size_t)n, &e));
    CHECK(e.line == 6);
    CHECK(strlen(e.msg) == sizeof e.msg - 1);
    CHECK(strncmp(e.msg, "include cycle: aaaa", 19) == 0);
}

static void test_header_names_and_spacing(void)
{
    ConfError e;
    char text[256];
    char name[130];
    memset(name, 'n', 129);
    name[129] = '\0';
    snprintf(text, sizeof text, "[harness %s]\n", name);
    CHECK(!conf_parse(&conf, text, strlen(text), &e) && e.line == 1);
    name[128] = '\0';
    snprintf(text, sizeof text, "[harness %s]\n", name);
    CHECK(parse(text, &e));
    expect_error("[need bad/h n]\n", 1, "invalid need");
    CHECK(parse("[  harness   a  ]\n", &e));
    CHECK(conf.nsections == 1 && strcmp(conf.sections[0].arg[0], "a") == 0);
}

static void test_wear_headers(void)
{
    ConfError e;
    CHECK(parse("[wear enterprise]\n[wear user]\n[wear user machine=m]\n", &e));
    CHECK(parse("[wear shared g/o/n]\n[wear personal g/o/n machine=m]\n", &e));
    expect_error("[wear shared]\n", 1, "needs a TARGET");
    expect_error("[wear personal]\n", 1, "needs a TARGET");
    expect_error("[wear enterprise g/o/n]\n", 1, "takes no TARGET");
    expect_error("[wear user g/o/n]\n", 1, "takes no TARGET");
    expect_error("[wear enterprise machine=m]\n", 1, "machine=");
    expect_error("[wear shared g/o/n machine=m]\n", 1, "machine=");
    expect_error("[wear galaxy]\n", 1, "unknown scope");
    expect_error("[wear user]\npublish = yes\n", 2, "publish");
}

static char *repeat_lines(const char *pre, const char *post, int n, size_t *len)
{
    char *s = malloc((size_t)n * 64 + 1);
    size_t off = 0;
    for (int i = 1; i <= n; i++)
        off += (size_t)snprintf(s + off, 64, "%s%d%s", pre, i, post);
    *len = off;
    return s;
}

static bool parse_n(const char *pre, const char *post, int n, ConfError *e)
{
    size_t len;
    char *s = repeat_lines(pre, post, n, &len);
    bool ok = conf_parse(&conf, s, len, e);
    free(s);
    return ok;
}

static void test_limits(void)
{
    ConfError e;
    CHECK(parse_n("[harness h", "]\n", 64, &e));
    CHECK(!parse_n("[harness h", "]\n", 65, &e) && e.line == 65);
    CHECK(parse_n("[outfit o", "]\n", 512, &e));
    CHECK(!parse_n("[outfit o", "]\n", 513, &e) && e.line == 513);
    CHECK(parse_n("[wear personal g/o/n", "]\n", 256, &e));
    CHECK(!parse_n("[wear personal g/o/n", "]\n", 257, &e) && e.line == 257);
    CHECK(parse_n("[upstream u", "]\n", 128, &e));
    CHECK(!parse_n("[upstream u", "]\n", 129, &e) && e.line == 129);

    // 256 needs, then 257. Needs name a harness, so lead with one.
    size_t len;
    char *s = repeat_lines("[need h n", "]\n", 257, &len);
    char *text = malloc(len + 32);
    int head = snprintf(text, 32, "[harness h]\n");
    memcpy(text + head, s, len);
    CHECK(!conf_parse(&conf, text, (size_t)head + len, &e) && e.line == 258);
    CHECK(strstr(e.msg, "too many need") != nullptr);
    free(s);
    free(text);

    // 8192 entries fit, the 8193rd does not.
    char *big = malloc(8200 * 16);
    size_t off = (size_t)snprintf(big, 32, "[harness h]\n");
    for (int i = 0; i < 8192; i++) off += (size_t)snprintf(big + off, 16, "record = r\n");
    CHECK(conf_parse(&conf, big, off, &e));
    off += (size_t)snprintf(big + off, 16, "record = r\n");
    CHECK(!conf_parse(&conf, big, off, &e) && e.line == 8194);
    free(big);
}

static void test_line_and_file(void)
{
    ConfError e;
    static char line[CONF_FILE_MAX + 64];

    memset(line, '#', CONF_LINE_MAX);
    line[CONF_LINE_MAX] = '\n';
    CHECK(conf_parse(&conf, line, CONF_LINE_MAX + 1, &e));
    memset(line, '#', CONF_LINE_MAX + 1);
    line[CONF_LINE_MAX + 1] = '\n';
    CHECK(!conf_parse(&conf, line, CONF_LINE_MAX + 2, &e) && e.line == 1);

    memset(line, '\n', CONF_FILE_MAX);
    CHECK(conf_parse(&conf, line, CONF_FILE_MAX, &e));
    CHECK(!conf_parse(&conf, line, CONF_FILE_MAX + 1, &e) && e.line == 0);

    CHECK(!conf_parse(&conf, "[harness a]\nrecord = x\0y\n", 24, &e) && e.line == 2);
}

static void test_dump_is_stable(void)
{
    ConfError e;
    CHECK(parse("[outfit b]\n[outfit a]\nskills = z y\n", &e));
    char path[] = "/tmp/suit-unit.XXXXXX";
    int fd = mkstemp(path);
    CHECK(fd >= 0);
    CHECK(conf_dump(&conf, fd));
    char got[256] = {};
    CHECK(pread(fd, got, sizeof got - 1, 0) > 0);
    CHECK(strcmp(got, "outfit a\noutfit a skills = z y\noutfit b\n") == 0);

    // Entries equal in key and value keep their file order.
    CHECK(ftruncate(fd, 0) == 0 && lseek(fd, 0, SEEK_SET) == 0);
    CHECK(parse("[harness h]\nrecord = x\nrecord = x\nrecord = a\n", &e));
    CHECK(conf_dump(&conf, fd));
    memset(got, 0, sizeof got);
    CHECK(pread(fd, got, sizeof got - 1, 0) > 0);
    CHECK(strcmp(got, "harness h\nharness h record = a\nharness h record = x\nharness h record = x\n") == 0);
    close(fd);
    unlink(path);
}

// ---- platform -------------------------------------------------------------

// Run FN in a child with SUIT_FAULT=SPEC; returns the child's exit status.
static int in_child(const char *spec, int (*fn)(void))
{
    fflush(nullptr);
    pid_t pid = fork();
    if (pid == 0) {
        setenv("SUIT_FAULT", spec, 1);
        fault_reset();
        int rc = fn();
        fflush(nullptr);
        exit(rc);
    }
    int status = 0;
    waitpid(pid, &status, 0);
    return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}

// Each of these makes one wrapper call and returns 0 if it failed with EIO.
static int fails_eio(bool failed) { return failed && errno == EIO ? 0 : 1; }
static int w_open(void) { return fails_eio(sys_open("/dev/null", O_RDONLY, 0) < 0); }
static int w_read(void) { char b[1]; return fails_eio(sys_read(0, b, 1) < 0); }
static int w_write(void) { return fails_eio(sys_write(1, "", 1) < 0); }
static int w_close(void) { return fails_eio(sys_close(-1) < 0 && errno == EIO); }
static int w_fsync(void) { return fails_eio(sys_fsync(1) < 0); }
static int w_stat(void) { struct stat st; return fails_eio(sys_stat("/", &st) < 0); }
static int w_fstatat(void) { struct stat st; return fails_eio(sys_fstatat(AT_FDCWD, "/", &st) < 0); }
static int w_rename(void) { return fails_eio(sys_rename("/nonexistent-a", "/nonexistent-b") < 0); }
static int w_mkdir(void) { return fails_eio(sys_mkdir("/", 0755) < 0); }
static int w_unlink(void) { return fails_eio(sys_unlink("/nonexistent-a") < 0); }
static int w_getenv(void) { return sys_getenv("PATH") == nullptr ? 0 : 1; }
static int w_lstat(void) { struct stat st; return fails_eio(sys_lstat("/", &st) < 0); }
static int w_readlink(void) { char b[8]; return fails_eio(sys_readlink("/", b, sizeof b) < 0); }
static int w_symlink(void) { return fails_eio(sys_symlink("x", "/nonexistent-a/y") < 0); }
static int w_rmdir(void) { return fails_eio(sys_rmdir("/nonexistent-a") < 0); }
static int w_kill(void) { return fails_eio(sys_kill0(getpid()) < 0); }
static int none_cb(void *state, const char *name) { (void)state; (void)name; return 0; }
static int w_listdir(void) { return fails_eio(sys_listdir("/", none_cb, nullptr) < 0); }
static int w_spawn(void) { pid_t p; char *argv[] = {(char *)"true", nullptr}; return sys_spawn(&p, "/usr/bin/true", argv) == EIO ? 0 : 1; }
static int w_wait4(void) { int st; return fails_eio(sys_wait4(-1, &st, nullptr) < 0); }
static int w_clock(void) { uint64_t ns; return sys_now_ns(&ns) ? 1 : 0; }
static int w_self(void) { char b[4096]; return platform_self_path(b, sizeof b) ? 1 : 0; }

static void test_wrapper_faults(void)
{
    static const struct {
        const char *spec;
        int (*fn)(void);
    } cases[] = {
        {"open:1", w_open}, {"read:1", w_read}, {"write:1", w_write},
        {"close:1:EIO", w_close}, {"fsync:1", w_fsync}, {"stat:1", w_stat},
        {"fstatat:1", w_fstatat}, {"rename:1", w_rename}, {"mkdir:1", w_mkdir},
        {"unlink:1", w_unlink}, {"getenv:1", w_getenv}, {"spawn:1", w_spawn},
        {"wait4:1", w_wait4}, {"clock_gettime:1", w_clock}, {"self_path:1", w_self},
        {"lstat:1", w_lstat}, {"readlink:1", w_readlink}, {"symlink:1", w_symlink},
        {"rmdir:1", w_rmdir}, {"kill:1", w_kill}, {"listdir:1", w_listdir},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        CHECK(in_child(cases[i].spec, cases[i].fn) == 0);
        if (in_child(cases[i].spec, cases[i].fn) != 0) printf("  case %s\n", cases[i].spec);
    }
}

static int second_call(void)  // the fault fires on call 2 only
{
    struct stat st;
    return sys_stat("/", &st) == 0 && sys_stat("/", &st) < 0 && sys_stat("/", &st) == 0 ? 0 : 1;
}

static void test_fault_counts_calls(void)
{
    CHECK(in_child("stat:2", second_call) == 0);
}

static void test_self_path(void)
{
    char big[4096];
    char tiny[2];
    CHECK(platform_self_path(big, sizeof big));
    CHECK(big[0] != '\0');
    CHECK(!platform_self_path(tiny, sizeof tiny));
}

static void test_say_and_out(void)
{
    char path[] = "/tmp/suit-unit-out.XXXXXX";
    int fd = mkstemp(path);
    CHECK(fd >= 0);
    static char text[SAY_MAX * 2];
    memset(text, 'x', sizeof text - 1);
    say(fd, "%s", text);
    struct stat st;
    CHECK(fstat(fd, &st) == 0 && (size_t)st.st_size == SAY_MAX - 1);
    char last = 0;
    CHECK(pread(fd, &last, 1, (off_t)(SAY_MAX - 2)) == 1 && last == '\n');

    // A string bigger than the buffer, then a write error.
    CHECK(ftruncate(fd, 0) == 0 && lseek(fd, 0, SEEK_SET) == 0);
    Out o;
    out_init(&o, fd);
    out_str(&o, text);
    out_str(&o, "tail");
    CHECK(out_finish(&o));
    CHECK(fstat(fd, &st) == 0 && (size_t)st.st_size == sizeof text - 1 + 4);
    close(fd);
    unlink(path);

    out_init(&o, -1);
    out_str(&o, text);
    CHECK(!out_finish(&o) && errno == EBADF);
}

#ifndef SUIT_COVER
static int ensure_false(void)
{
    ensure(1 == 2);
    return 0;
}

static void test_ensure_aborts(void)
{
    fflush(stdout);
    pid_t pid = fork();
    if (pid == 0) {
        int null = open("/dev/null", O_WRONLY);
        if (null < 0 || dup2(null, STDERR_FILENO) < 0) exit(99);
        exit(ensure_false());
    }
    int status = 0;
    waitpid(pid, &status, 0);
    // ensure() must end the process abnormally. Natively that is SIGABRT;
    // a memory-safe runtime may end it with a different signal.
    if (!WIFSIGNALED(status)) {
        fprintf(stderr, "ensure child: exited=%d code=%d\n",
            WIFEXITED(status), WIFEXITED(status) ? WEXITSTATUS(status) : -1);
    }
    CHECK(WIFSIGNALED(status));
#ifndef __PIZLONATOR_WAS_HERE__
    CHECK(WTERMSIG(status) == SIGABRT);
#endif
}
#endif

static void test_stamp_too_large(void)
{
    char dir[] = "/tmp/suit-unit-home.XXXXXX";
    CHECK(mkdtemp(dir) != nullptr);
    setenv("SUIT_HOME", dir, 1);
    enum { N = 70000 };
    static char *paths[N];
    for (int i = 0; i < N; i++) paths[i] = (char *)"/suit-no-such-file-for-the-limit-test";
    CHECK(stamp_write(N, paths) == 1);
    char file[256];
    snprintf(file, sizeof file, "%s/stamp", dir);
    CHECK(access(file, F_OK) != 0);
    unsetenv("SUIT_HOME");
    rmdir(dir);
}

// ---- the store's file writer ------------------------------------------------

static fsl_cx *wcx;
static fsl_ckout_fs wfs;
static char wdir[64];
static char wfile[128];

static void writer_setup(void)
{
    snprintf(wdir, sizeof wdir, "/tmp/suit-unit-w.XXXXXX");
    CHECK(mkdtemp(wdir) != nullptr);
    snprintf(wfile, sizeof wfile, "%s/file", wdir);
    CHECK(fsl_cx_init(&wcx, nullptr) == 0);
    CHECK(store_fs_install(wcx) == 0);
    fsl_cx_ckout_fs_get(wcx, &wfs);
}

static bool has_temp_file(void)
{
    char cmd[256];
    snprintf(cmd, sizeof cmd, "ls %s/.suit-tmp.* >/dev/null 2>&1", wdir);
    return system(cmd) == 0;
}

static int write_new(void)
{
    return wfs.xWrite(wfs.state, wfile, "abc", 3) == 0 ? 0 : 1;
}

// A write that is made to fail fails, and leaves no temporary file and the old bytes.
static int write_fails(void)
{
    int rc = wfs.xWrite(wfs.state, wfile, "new", 3);
    char got[8] = {};
    FILE *f = fopen(wfile, "r");
    size_t n = f != nullptr ? fread(got, 1, sizeof got - 1, f) : 0;
    if (f != nullptr) fclose(f);
    return rc != 0 && !has_temp_file() && n == 3 && strcmp(got, "old") == 0 ? 0 : 1;
}

static void put(const char *path, const char *text, mode_t mode)
{
    FILE *f = fopen(path, "w");
    CHECK(f != nullptr);
    fputs(text, f);
    fclose(f);
    chmod(path, mode);
}

typedef struct {
    int count;
    int ours;
} Seen;

static int collect(void *state, char const *entry)
{
    Seen *seen = state;
    seen->count++;
    if (strncmp(entry, SUIT_TMP_PREFIX, strlen(SUIT_TMP_PREFIX)) == 0) seen->ours++;
    return 0;
}

static void test_writer(void)
{
    writer_setup();
    CHECK(write_new() == 0);
    char got[8] = {};
    FILE *f = fopen(wfile, "r");
    CHECK(f != nullptr && fread(got, 1, 7, f) == 3 && strcmp(got, "abc") == 0);
    fclose(f);
    struct stat st;
    CHECK(stat(wfile, &st) == 0 && (st.st_mode & 0111) == 0);

    // An executable file stays executable when it is replaced.
    put(wfile, "old", 0755);
    CHECK(wfs.xWrite(wfs.state, wfile, "new", 3) == 0);
    CHECK(stat(wfile, &st) == 0 && (st.st_mode & 0100) != 0 && st.st_size == 3);
    CHECK(!has_temp_file());

    // A call that fails leaves the old bytes and no temporary file.
    static const char *const specs[] = {"open:1", "write:1", "fsync:1", "close:1", "rename:1"};
    for (size_t i = 0; i < sizeof specs / sizeof specs[0]; i++) {
        put(wfile, "old", 0644);
        CHECK(in_child(specs[i], write_fails) == 0);
    }
    put(wfile, "old", 0644);
    CHECK(in_child("stat:1", write_new) == 0);  // no stat: treated as not executable
    CHECK(in_child("write:1:short", write_new) == 0);

    // The listing never shows our temporary names.
    put(wfile, "x", 0644);
    char tmp[160];
    snprintf(tmp, sizeof tmp, "%s/" SUIT_TMP_PREFIX "1.1", wdir);
    put(tmp, "x", 0644);
    Seen seen = {0, 0};
    CHECK(wfs.xDirList(wfs.state, wdir, collect, &seen) == 0);
    CHECK(seen.count == 1 && seen.ours == 0);
    unlink(tmp);
    unlink(wfile);
    rmdir(wdir);
    fsl_cx_finalize(wcx);
}

// ---- SUIT_FAULT lists and delays ----------------------------------------------

static int stat_twice(void)
{
    struct stat st;
    return sys_stat("/", &st) == 0 && sys_stat("/", &st) == 0 ? 0 : 1;
}

static int parse_dies(void)
{
    struct stat st;
    (void)sys_stat("/", &st);
    return 0;
}

static void test_fault_lists(void)
{
    CHECK(in_child("stat:1:delay", stat_twice) == 0);  // every call from the first
    CHECK(in_child("stat:2:delay", stat_twice) == 0);  // only from the second
    CHECK(in_child("read:1,write:1,stat:9", stat_twice) == 0);  // other names are left alone
    CHECK(in_child("open:1,open:2,open:3,open:4,open:5", parse_dies) == 99);
    char big[300];
    memset(big, 'x', sizeof big - 1);
    big[sizeof big - 1] = '\0';
    CHECK(in_child(big, parse_dies) == 99);
}

// ---- resolve ------------------------------------------------------------------

static Assets assets;
static Plan plan;

static void have(AssetKind kind, const char *name, const char *file)
{
    NameList *l = &assets.list[kind];
    l->name[l->n] = name;
    l->file[l->n++] = file;
}

static void have_reset(void)
{
    for (int k = AK_SKILL; k <= AK_COMMAND; k++) assets.list[k].n = 0;
}

static const char *test_machine = "";

static bool resolve_text(const char *text, ResolveError *e)
{
    ConfError ce;
    CHECK(parse(text, &ce));
    return resolve(&conf, &assets, "/home/u", "/sh", "/sh/store/mine", test_machine, &plan, e);
}

// The plan as text: "dest <- src [harness kind]" lines.
static void plan_text(char *out, size_t cap)
{
    out[0] = '\0';
    for (uint32_t i = 0; i < plan.n; i++) {
        size_t len = strlen(out);
        snprintf(out + len, cap - len, "%s <- %s [%s %s]\n", plan.p[i].dest, plan.p[i].src,
            plan.p[i].harness, asset_kind_name(plan.p[i].kind));
    }
}

static void test_glob(void)
{
    CHECK(glob_match("abc", "abc"));
    CHECK(!glob_match("abc", "abd"));
    CHECK(!glob_match("abc", "ab"));
    CHECK(!glob_match("ab", "abc"));
    CHECK(glob_match("*", "anything"));
    CHECK(glob_match("*", ""));
    CHECK(glob_match("vault-*", "vault-query"));
    CHECK(!glob_match("vault-*", "vault"));
    CHECK(glob_match("*-query", "vault-query"));
    CHECK(glob_match("a*c*e", "abcde"));
    CHECK(glob_match("a*b*c", "aXbXbXc"));  // backtracks
    CHECK(!glob_match("a*b*c", "aXbXbX"));
    CHECK(glob_match("a**b", "ab"));
    CHECK(!glob_match("", "x"));
}

static const char *const three =
    "[harness claude]\nskills.user = ~/.claude/skills\nagents.user = ~/.claude/agents\n"
    "commands.user = ~/.claude/commands\ninstructions.user = ~/.claude/CLAUDE.md\n"
    "[harness codex]\nskills.user = /abs/codex/skills\ninstructions.user = ~\n"
    "[outfit a]\nskills = s1 t*\nagents = ag\ncommands = cm\ninstructions = instructions/u.md\n"
    "[outfit b]\ninclude = a\nonly = claude\nskills = s2\nslot hook/Stop = files/h.sh\n"
    "file ~/.claude/x.json = files/x.json\n"
    "[wear user]\noutfits = b\n"
    "[wear user machine=m1]\noutfits = a\n";

static void test_resolve(void)
{
    have_reset();
    have(AK_SKILL, "s1", "s1");
    have(AK_SKILL, "s2", "s2");
    have(AK_SKILL, "t1", "t1");
    have(AK_SKILL, "unused", "unused");
    have(AK_AGENT, "ag", "ag.md");
    have(AK_COMMAND, "cm", "cm.md");
    ResolveError e;
    char got[4096];
    CHECK(resolve_text(three, &e));
    plan_text(got, sizeof got);
    const char *want =
        "/abs/codex/skills/s1 <- /sh/store/mine/skills/s1 [codex skills]\n"
        "/abs/codex/skills/t1 <- /sh/store/mine/skills/t1 [codex skills]\n"
        "/home/u <- /sh/store/mine/instructions/u.md [codex instructions]\n"
        "/home/u/.claude/CLAUDE.md <- /sh/store/mine/instructions/u.md [claude instructions]\n"
        "/home/u/.claude/agents/ag.md <- /sh/store/mine/agents/ag.md [claude agents]\n"
        "/home/u/.claude/commands/cm.md <- /sh/store/mine/commands/cm.md [claude commands]\n"
        "/home/u/.claude/skills/s1 <- /sh/store/mine/skills/s1 [claude skills]\n"
        "/home/u/.claude/skills/s2 <- /sh/store/mine/skills/s2 [claude skills]\n"
        "/home/u/.claude/skills/t1 <- /sh/store/mine/skills/t1 [claude skills]\n"
        "/home/u/.claude/x.json <- /sh/store/mine/files/x.json [- file]\n"
        "/sh/slots/hook/Stop <- /sh/store/mine/files/h.sh [- slot]\n";
    CHECK(strcmp(got, want) == 0);
    if (strcmp(got, want) != 0) printf("%s", got);
    // Only claude takes s2 (outfit b has only = claude) and nothing is for codex agents.
    CHECK(plan.nskips == 2);
    CHECK(strcmp(plan.skips[0], "skipped codex agents ag (no folder)") == 0);
    CHECK(strcmp(plan.skips[1], "skipped codex commands cm (no folder)") == 0);
}

// The machine limit: which wears apply, and which source wins or joins.
static void test_resolve_machine(void)
{
    have_reset();
    have(AK_SKILL, "s1", "s1");
    ResolveError e;
    const char *head = "[harness h]\nskills.user = ~/s\ninstructions.user = ~/I.md\n";
    char text[2048];
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\nfile ~/f = files/a\n[outfit m]\nfile ~/f = files/b\nskills = s1\n", head);
    // The wear for m1 is ignored on another machine and when there is no name.
    test_machine = "other";
    CHECK(resolve_text(text, &e) && plan.n == 1 && strcmp(plan.p[0].src, "/sh/store/mine/files/a") == 0);
    test_machine = "";
    CHECK(resolve_text(text, &e) && plan.n == 1 && strcmp(plan.p[0].src, "/sh/store/mine/files/a") == 0);
    // On m1 its file wins and its skill is added.
    test_machine = "m1";
    CHECK(resolve_text(text, &e) && plan.n == 2 && plan.njoins == 0);
    CHECK(strcmp(plan.p[0].dest, "/home/u/f") == 0 && strcmp(plan.p[0].src, "/sh/store/mine/files/b") == 0);
    CHECK(plan.p[0].limited);

    // Two instruction files for one harness are joined; the plan has the winner only.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\ninstructions = a.md\n[outfit m]\ninstructions = b.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 1);
    CHECK(strcmp(plan.p[0].src, "/sh/joined/h") == 0 && strcmp(plan.joins[0].path, "/sh/joined/h") == 0);
    CHECK(strcmp(plan.joins[0].first, "/sh/store/mine/a.md") == 0);
    CHECK(strcmp(plan.joins[0].second, "/sh/store/mine/b.md") == 0);
    // The same file from both is one placement and no join.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\ninstructions = a.md\n[outfit m]\ninstructions = a.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 0);
    CHECK(strcmp(plan.p[0].src, "/sh/store/mine/a.md") == 0);
    // ... but with a third, limited file the limited wins over the unlimited a.md.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m n\n"
        "[outfit u]\nfile ~/I.md = a.md\n[outfit m]\nfile ~/I.md = a.md\n[outfit n]\nfile ~/I.md = c.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && strcmp(plan.p[0].src, "/sh/store/mine/c.md") == 0);
    // An instruction file and a file for the same path: no join, the limited one wins.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\ninstructions = a.md\n[outfit m]\nfile ~/I.md = b.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 0);
    CHECK(strcmp(plan.p[0].src, "/sh/store/mine/b.md") == 0);
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\nfile ~/I.md = a.md\n[outfit m]\ninstructions = b.md\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1 && plan.njoins == 0);
    CHECK(strcmp(plan.p[0].src, "/sh/store/mine/b.md") == 0);

    // Two limited sources, or two unlimited ones, for one destination stay an error.
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u\n[wear user machine=m1]\noutfits = m n\n"
        "[outfit u]\ninstructions = a.md\n[outfit m]\ninstructions = b.md\n[outfit n]\ninstructions = c.md\n", head);
    CHECK(!resolve_text(text, &e));
    CHECK(strstr(e.msg, "two assets want /home/u/I.md: /sh/store/mine/b.md and /sh/store/mine/c.md") != nullptr);
    snprintf(text, sizeof text,
        "%s[wear user]\noutfits = u v\n[wear user machine=m1]\noutfits = m\n"
        "[outfit u]\ninstructions = a.md\n[outfit v]\ninstructions = c.md\n[outfit m]\ninstructions = b.md\n", head);
    CHECK(!resolve_text(text, &e));
    CHECK(strstr(e.msg, "two assets want /home/u/I.md: /sh/store/mine/a.md and /sh/store/mine/c.md") != nullptr);
    test_machine = "";
}

static void test_resolve_errors(void)
{
    have_reset();
    have(AK_SKILL, "s1", "s1");
    have(AK_AGENT, "ag", "ag.md");
    ResolveError e;
    const char *head = "[harness h]\nskills.user = ~/s\nagents.user = ~/a\ninstructions.user = ~/I.md\n"
                       "[wear user]\noutfits = o\n";
    char text[2048];
    snprintf(text, sizeof text, "%s[outfit o]\nskills = s1 nope\n", head);
    CHECK(!resolve_text(text, &e) && strstr(e.msg, "outfit o: skills 'nope' matches nothing in the store") != nullptr);
    snprintf(text, sizeof text, "%s[outfit o]\nagents = zz*\n", head);
    CHECK(!resolve_text(text, &e) && strstr(e.msg, "outfit o: agents 'zz*' matches nothing") != nullptr);

    // Two outfits wanting one destination from different sources.
    snprintf(text, sizeof text, "%s[outfit o]\ninclude = p\ninstructions = a.md\n[outfit p]\ninstructions = b.md\n", head);
    CHECK(!resolve_text(text, &e));
    CHECK(strstr(e.msg, "two assets want /home/u/I.md: /sh/store/mine/a.md and /sh/store/mine/b.md") != nullptr);

    // The same source twice is one placement.
    snprintf(text, sizeof text, "%s[outfit o]\ninclude = p\nskills = s1\n[outfit p]\nskills = s1\n", head);
    CHECK(resolve_text(text, &e) && plan.n == 1);

    // A harness folder that is not absolute, and a path with a space.
    snprintf(text, sizeof text, "[harness h]\nskills.user = .claude/skills\n[wear user]\noutfits = o\n[outfit o]\nskills = s1\n");
    CHECK(!resolve_text(text, &e) && strstr(e.msg, ".claude/skills/s1 is not an absolute path") != nullptr);
    snprintf(text, sizeof text, "[harness h]\nskills.user = /a b\n[wear user]\noutfits = o\n[outfit o]\nskills = s1\n");
    CHECK(!resolve_text(text, &e) && strstr(e.msg, "a space in") != nullptr);
    snprintf(text, sizeof text, "%s[outfit o]\nfile ~/f = a b\n", head);
    CHECK(!resolve_text(text, &e) && strstr(e.msg, "a space in") != nullptr);

    // A wear with no outfits and an outfit with nothing in it place nothing.
    CHECK(resolve_text("[wear user]\n[outfit o]\n", &e) && plan.n == 0 && plan.nskips == 0);
}

static void test_resolve_limits(void)
{
    // 2048 skills for 3 harnesses is more placements than there can be.
    static char names[ASSET_MAX][16];
    have_reset();
    for (uint32_t i = 0; i < ASSET_MAX; i++) {
        snprintf(names[i], sizeof names[i], "s%u", i);
        have(AK_SKILL, names[i], names[i]);
    }
    ResolveError e;
    CHECK(!resolve_text("[harness a]\nskills.user = /a\n[harness b]\nskills.user = /b\n[harness c]\nskills.user = /c\n"
                        "[wear user]\noutfits = o\n[outfit o]\nskills = *\n", &e));
    CHECK(strstr(e.msg, "more than 4096 placements") != nullptr);
    CHECK(resolve_text("[harness a]\nskills.user = /a\n[wear user]\noutfits = o\n[outfit o]\nskills = *\n", &e));
    CHECK(plan.n == ASSET_MAX);

    // Too many skipped lines: agents for a harness with no agent folder.
    static char agents[ASSET_MAX][16];
    have_reset();
    for (uint32_t i = 0; i < SKIP_MAX + 1; i++) {
        snprintf(agents[i], sizeof agents[i], "g%u", i);
        have(AK_AGENT, agents[i], agents[i]);
    }
    CHECK(!resolve_text("[harness a]\nskills.user = /a\n[wear user]\noutfits = o\n[outfit o]\nagents = *\n", &e));
    CHECK(strstr(e.msg, "more than 1024 skipped lines") != nullptr);

    // Paths that do not fit in the plan: long names, many of them.
    static char longs[ASSET_MAX][130];
    have_reset();
    for (uint32_t i = 0; i < ASSET_MAX; i++) {
        memset(longs[i], 'x', 120);
        snprintf(longs[i] + 120, 10, "%07u", i);
        have(AK_SKILL, longs[i], longs[i]);
    }
    CHECK(!resolve_text("[harness a]\nskills.user = /a\n[wear user]\noutfits = o\n[outfit o]\nskills = *\n", &e));
    CHECK(strstr(e.msg, "the plan is larger than") != nullptr);
    have_reset();
}

// ---- ledger ---------------------------------------------------------------------

static Ledger ledger;

static void ledger_error(const char *text, int line, const char *part)
{
    LedgerError e;
    bool ok = ledger_parse(&ledger, text, strlen(text), &e);
    CHECK(!ok && ledger.n == 0 && e.line == line && strstr(e.msg, part) != nullptr);
    if (ok || e.line != line || strstr(e.msg, part) == nullptr)
        printf("  ledger wanted line %d '%s', got %d '%s'\n", line, part, e.line, ok ? "(parsed)" : e.msg);
}

static void test_ledger(void)
{
    LedgerError e;
    CHECK(ledger_parse(&ledger, "", 0, &e) && ledger.n == 0);
    CHECK(ledger_parse(&ledger, "link /a /s/a\ndir /a\n", 20, &e) && ledger.n == 2);
    CHECK(ledger.e[0].kind == ENTRY_LINK && strcmp(ledger.e[0].src, "/s/a") == 0);
    CHECK(ledger.e[1].kind == ENTRY_DIR && ledger.e[1].src == nullptr);
    CHECK(ledger_find_link(&ledger, "/a") == &ledger.e[0] && ledger_find_link(&ledger, "/b") == nullptr);
    CHECK(ledger_find_link(&ledger, "/a") != nullptr);
    CHECK(ledger_parse(&ledger, "file /a\nlink /a /s\ndir /a\n", 26, &e) && ledger.n == 3);
    CHECK(ledger.e[0].kind == ENTRY_FILE && ledger.e[0].src == nullptr);
    ledger_error("link /a\n", 1, "link needs DEST and SOURCE");
    ledger_error("dir /a /b\n", 1, "dir takes only DEST");
    ledger_error("bogus /a\n", 1, "unknown record 'bogus'");
    ledger_error("link\n", 1, "expected");
    ledger_error("file /a /b\n", 1, "file takes only DEST");
    ledger_error("file a\n", 1, "absolute");
    ledger_error("file /a\nfile /a\n", 2, "duplicate file /a");
    ledger_error("link a /b\n", 1, "absolute");
    ledger_error("link /a b\n", 1, "absolute");
    ledger_error("dir a\n", 1, "absolute");
    ledger_error("link /a /b /c\n", 1, "absolute");
    ledger_error("link /a /b\nlink /a /c\n", 2, "duplicate link /a");
    ledger_error("link /a /b\ndir /a\ndir /a\n", 3, "duplicate dir /a");
    ledger_error("link /a /b", 1, "no newline");
    ledger_error("link /a /b\nlink /c /d", 2, "no newline");
    char big[LEDGER_LINE_MAX + 100];
    memset(big, 'x', sizeof big);
    memcpy(big, "dir /", 5);
    big[LEDGER_LINE_MAX + 1] = '\n';
    LedgerError le;
    CHECK(!ledger_parse(&ledger, big, LEDGER_LINE_MAX + 2, &le) && le.line == 1 && strstr(le.msg, "limit is 8192") != nullptr);
    CHECK(!ledger_parse(&ledger, "dir /a\0b\n", 9, &le) && le.line == 1 && strstr(le.msg, "NUL") != nullptr);
    static char file[LEDGER_FILE_MAX + 16];
    memset(file, '\n', sizeof file);
    CHECK(!ledger_parse(&ledger, file, LEDGER_FILE_MAX + 1, &le) && le.line == 0 && strstr(le.msg, "limit is") != nullptr);

    // 4096 entries fit and the 4097th does not.
    static char many[LEDGER_ENTRY_MAX * 16 + 64];
    size_t off = 0;
    for (uint32_t i = 0; i <= LEDGER_ENTRY_MAX; i++) {
        off += (size_t)snprintf(many + off, 16, "dir /d%u\n", i);
        if (i == LEDGER_ENTRY_MAX - 1) CHECK(ledger_parse(&ledger, many, off, &le) && ledger.n == LEDGER_ENTRY_MAX);
    }
    CHECK(!ledger_parse(&ledger, many, off, &le) && le.line == (int)LEDGER_ENTRY_MAX + 1 && strstr(le.msg, "too many entries") != nullptr);

    // Written sorted, links before dirs, and the same entries read back.
    char path[] = "/tmp/suit-unit-ledger.XXXXXX";
    int fd = mkstemp(path);
    CHECK(fd >= 0);
    close(fd);
    Ledger out;
    out.n = 0;
    out.e[out.n++] = (LedgerEntry){ENTRY_DIR, "/z", nullptr};
    out.e[out.n++] = (LedgerEntry){ENTRY_LINK, "/b", "/s/b"};
    out.e[out.n++] = (LedgerEntry){ENTRY_DIR, "/y", nullptr};
    out.e[out.n++] = (LedgerEntry){ENTRY_LINK, "/a", "/s/a"};
    out.e[out.n++] = (LedgerEntry){ENTRY_FILE, "/f", nullptr};
    CHECK(ledger_write(&out, path) == 0);
    CHECK(ledger_load(&ledger, path, &le) && ledger.n == 5);
    CHECK(strcmp(ledger.e[0].dest, "/a") == 0 && strcmp(ledger.e[1].dest, "/b") == 0 &&
          strcmp(ledger.e[2].dest, "/y") == 0 && strcmp(ledger.e[3].dest, "/z") == 0);
    CHECK(ledger.e[4].kind == ENTRY_FILE && strcmp(ledger.e[4].dest, "/f") == 0);
    // Too much to write.
    static char longpath[LEDGER_LINE_MAX];
    memset(longpath, 'p', sizeof longpath - 1);
    longpath[0] = '/';
    out.n = 0;
    for (int i = 0; i < 200; i++) out.e[out.n++] = (LedgerEntry){ENTRY_DIR, longpath, nullptr};
    CHECK(ledger_write(&out, path) == EFBIG);
    unlink(path);
}

// ---- place: limits that need no disk to reach -----------------------------------

static Actions actions;
static Plan big_plan;

static void test_place_limits(void)
{
    // Placements in folders that do not exist: two new folders each.
    static char dests[2100][64];
    big_plan.n = 0;
    for (int i = 0; i < 2100; i++) {
        snprintf(dests[i], sizeof dests[i], "/suit-no-such/d%d/e%d/link", i, i);
        big_plan.p[big_plan.n++] = (Placement){dests[i], "/s", "h", AK_SKILL, false};
    }
    Ledger none;
    none.n = 0;
    CHECK(place_plan(&big_plan, &none, &actions) == 1);  // too many folders

    // Folder names too long for the list, fewer of them.
    static char longdests[300][1100];
    big_plan.n = 0;
    for (int i = 0; i < 300; i++) {
        memset(longdests[i], 'q', 1000);
        snprintf(longdests[i], 40, "/suit-no-such/%d", i);
        longdests[i][strlen(longdests[i])] = 'q';
        snprintf(longdests[i] + 1000, 90, "/%d/link", i);
        big_plan.p[big_plan.n++] = (Placement){longdests[i], "/s", "h", AK_SKILL, false};
    }
    CHECK(place_plan(&big_plan, &none, &actions) == 1);
}

// ---- place: what a failed call or an odd disk does ---------------------------------

static int count_cb(void *state, const char *name)
{
    (void)name;
    ++*(int *)state;
    return 0;
}

static int stop_cb(void *state, const char *name)
{
    (void)state;
    (void)name;
    return 7;
}

static void test_listdir(void)
{
    char dir[] = "/tmp/suit-unit-list.XXXXXX";
    CHECK(mkdtemp(dir) != nullptr);
    char file[256];
    for (int i = 0; i < 2; i++) {
        snprintf(file, sizeof file, "%s/f%d", dir, i);
        int fd = open(file, O_WRONLY | O_CREAT, 0644);
        CHECK(fd >= 0);
        close(fd);
    }
    int n = 0;
    CHECK(sys_listdir(dir, count_cb, &n) == 0 && n == 2);
    CHECK(sys_listdir(dir, stop_cb, nullptr) == 7);  // the callback stops the walk
    CHECK(sys_listdir("/suit-no-such-folder", count_cb, &n) == -1 && errno == ENOENT);
    for (int i = 0; i < 2; i++) {
        snprintf(file, sizeof file, "%s/f%d", dir, i);
        unlink(file);
    }
    rmdir(dir);
}

static char pbase[160];
static int loud_fd = 2;
static Ledger pled;
static Ledger pchk;

#define EXPECT(cond)                                                                     \
    do {                                                                                 \
        if (!(cond)) {                                                                   \
            dprintf(loud_fd, "FAIL unit %s:%d: %s\n", __FILE__, __LINE__, #cond);        \
            return 1;                                                                    \
        }                                                                                \
    } while (0)

// PBASE/REL, in one of a ring of buffers so a case can hold many at once.
static const char *pp(const char *rel)
{
    static char ring[64][512];
    static unsigned next;
    char *s = ring[next++ % 64];
    snprintf(s, sizeof ring[0], "%s/%s", pbase, rel);
    return s;
}

static void must(int rc)
{
    if (rc != 0) {
        dprintf(loud_fd, "FAIL unit: scratch setup\n");
        _exit(97);
    }
}

static void pl_put(const char *rel, const char *text)
{
    int fd = open(pp(rel), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    must(fd < 0);
    must(write(fd, text, strlen(text)) < 0);
    close(fd);
}

static void sl(const char *target, const char *rel) { must(symlink(target, pp(rel))); }
static void md(const char *rel) { must(mkdir(pp(rel), 0755)); }
static bool there(const char *rel)
{
    struct stat st;
    return lstat(pp(rel), &st) == 0;
}

static pid_t dead_pid(void)
{
    pid_t pid = fork();
    if (pid == 0) _exit(0);
    int status;
    waitpid(pid, &status, 0);
    return pid;
}

static void reset(void)
{
    pled.n = 0;
    big_plan.n = 0;
    big_plan.nskips = 0;
    actions.n = 0;
    actions.ndirs = 0;
    actions.used = 0;
}

static void want(const char *dest, const char *src) { big_plan.p[big_plan.n++] = (Placement){dest, src, "h", AK_SKILL, false}; }
static void lk(const char *dest, const char *src) { pled.e[pled.n++] = (LedgerEntry){ENTRY_LINK, dest, src}; }
static void dr(const char *dest) { pled.e[pled.n++] = (LedgerEntry){ENTRY_DIR, dest, nullptr}; }
static void act(ActKind kind, const char *dest, const char *src) { actions.a[actions.n++] = (Action){kind, dest, src, nullptr, nullptr, nullptr, nullptr}; }
static int pl_plan(void) { return place_plan(&big_plan, &pled, &actions); }
static int apply(void) { return place_apply(&pled, &actions, pp("ledger")); }
static int off(void) { return place_off(&pled, pp("ledger")); }

static bool ledger_has(uint32_t n)
{
    LedgerError le;
    return ledger_load(&pchk, pp("ledger"), &le) && pchk.n == n;
}

static int entries(void)
{
    int n = 0;
    return sys_listdir(pbase, count_cb, &n) == 0 ? n : -1;
}

static int c_plan_blocked(void)
{
    reset();
    pl_put("f", "x");
    want(pp("f/x/link"), "/s");  // a file where a folder should be
    EXPECT(pl_plan() == 0 && actions.n == 1 && actions.a[0].kind == ACT_CLASH && actions.ndirs == 0);
    return 0;
}

static int c_plan_lstat_fails(void)
{
    reset();
    want(pp("a/link"), "/s");
    EXPECT(pl_plan() == 1);
    return 0;
}

static int c_plan_readlink_fails(void)
{
    reset();
    sl("/x", "l");
    want(pp("l"), "/s");
    EXPECT(pl_plan() == 1);
    return 0;
}

static int c_plan_parent_stat_fails(void)
{
    reset();
    want(pp("m/n/link"), "/s");
    EXPECT(pl_plan() == 1);
    return 0;
}

static int c_plan_link_not_ours(void)
{
    reset();
    sl("/other", "l");
    lk(pp("l"), "/old");  // the ledger says /old, the want is /new, the disk has /other
    want(pp("l"), "/new");
    EXPECT(pl_plan() == 0 && actions.n == 1 && actions.a[0].kind == ACT_CLASH);
    return 0;
}

static int c_plan_stale(void)
{
    reset();
    pl_put("file", "x");
    md("dir");
    sl("/else", "other");
    sl("/s", "mine");
    lk(pp("gone"), "/s");
    lk(pp("file"), "/s");
    lk(pp("dir"), "/s");
    lk(pp("other"), "/s");
    lk(pp("mine"), "/s");
    EXPECT(pl_plan() == 0 && actions.n == 5);
    EXPECT(actions.a[0].kind == ACT_CLASH && actions.a[1].kind == ACT_CLASH);  // dir, file
    EXPECT(actions.a[2].kind == ACT_DROP && actions.a[3].kind == ACT_REMOVE);  // gone, mine
    EXPECT(actions.a[4].kind == ACT_CLASH);                                    // other
    return 0;
}

static int c_plan_stale_lstat_fails(void)
{
    reset();
    lk(pp("x"), "/s");
    EXPECT(pl_plan() == 1);
    return 0;
}

static int c_missing(void)
{
    reset();
    pl_put("here", "x");
    lk(pp("gone"), "/s");
    lk(pp("here"), "/s");
    dr(pp("somedir"));
    EXPECT(place_missing(&pled, false) == 1 && place_missing(&pled, true) == 1);
    return 0;
}

static int c_missing_lstat_fails(void)
{
    reset();
    lk(pp("gone"), "/s");
    EXPECT(place_missing(&pled, false) == 0);  // not told to be gone, so not counted
    return 0;
}

static int c_lock_taken_over(void)
{
    char text[32];
    snprintf(text, sizeof text, "%d\n", (int)dead_pid());
    pl_put("lock", text);
    EXPECT(place_lock(pp("lock")) == 0);
    place_unlock(pp("lock"));
    return 0;
}

static int c_apply_limit(void)
{
    reset();
    for (uint32_t i = 0; i < LEDGER_ENTRY_MAX; i++) dr("/x");
    actions.dirs[actions.ndirs++] = "/y";
    EXPECT(apply() == 1 && !there("ledger"));
    return 0;
}

static int c_apply_mkdir_fails(void)
{
    reset();
    actions.dirs[actions.ndirs++] = pp("nd");
    EXPECT(apply() == 1 && !there("nd") && ledger_has(0));
    return 0;
}

static int c_apply_mkdir_exists(void)
{
    reset();
    actions.dirs[actions.ndirs++] = pp("nd");
    EXPECT(apply() == 0 && ledger_has(1));
    return 0;
}

static int c_apply_link_fails(void)
{
    reset();
    act(ACT_CREATE, pp("l"), "/s");
    EXPECT(apply() == 1 && !there("l") && ledger_has(0) && entries() == 1);
    return 0;
}

static int c_apply_remove_fails(void)
{
    reset();
    sl("/s", "l");
    lk(pp("l"), "/s");
    act(ACT_REMOVE, pp("l"), "/s");
    EXPECT(apply() == 1 && there("l") && ledger_has(1));
    return 0;
}

static int c_apply_first_ledger_fails(void)
{
    reset();
    act(ACT_CREATE, pp("l"), "/s");
    EXPECT(apply() == 1 && !there("l"));
    return 0;
}

static int c_apply_last_ledger_fails(void)
{
    reset();
    EXPECT(apply() == 1);
    return 0;
}

static int c_off_mixed(void)
{
    reset();
    pl_put("file", "x");
    sl("/x", "other");
    sl("/s", "mine");
    md("z");
    md("a");
    md("full");
    pl_put("full/f", "x");
    lk(pp("gone"), "/s");
    lk(pp("file"), "/s");
    lk(pp("other"), "/y");
    lk(pp("mine"), "/s");
    dr(pp("z"));
    dr(pp("a"));
    dr(pp("full"));
    dr(pp("nodir"));
    EXPECT(off() == 0 && ledger_has(0));
    EXPECT(!there("mine") && there("file") && there("other") && !there("z") && !there("a") && there("full"));
    return 0;
}

static int c_off_rmdir_exist(void)
{
    reset();
    md("d");
    dr(pp("d"));
    EXPECT(off() == 0 && there("d") && ledger_has(0));
    return 0;
}

static int c_off_rmdir_fails(void)
{
    reset();
    md("d1");
    md("d2");
    dr(pp("d1"));
    dr(pp("d2"));
    EXPECT(off() == 1 && there("d1") && there("d2") && ledger_has(2));
    return 0;
}

static int c_off_unlink_fails(void)
{
    reset();
    sl("/s", "mine");
    md("d");
    lk(pp("mine"), "/s");
    dr(pp("d"));
    EXPECT(off() == 1 && there("mine") && there("d") && ledger_has(2));
    return 0;
}

static int c_off_lstat_fails(void)
{
    reset();
    lk(pp("gone"), "/s");
    EXPECT(off() == 1 && ledger_has(1));
    return 0;
}

static int (*case_cur)(void);

// A case runs in a child, with its output off and its failures on the real stderr.
static int case_cur_run(void)
{
    loud_fd = dup(2);
    int null = open("/dev/null", O_WRONLY);
    dup2(null, 1);
    dup2(null, 2);
    close(null);
    return case_cur();
}

static int nftw_remove(const char *path, const struct stat *st, int type, struct FTW *ftw)
{
    (void)st;
    (void)type;
    (void)ftw;
    return remove(path);
}

static void test_place_faults(void)
{
    char root[] = "/tmp/suit-unit-place.XXXXXX";
    CHECK(mkdtemp(root) != nullptr);
    static const struct {
        const char *spec;
        int (*fn)(void);
    } cases[] = {
        {"", c_plan_blocked},
        {"lstat:1", c_plan_lstat_fails},
        {"readlink:1", c_plan_readlink_fails},
        {"stat:1", c_plan_parent_stat_fails},
        {"", c_plan_link_not_ours},
        {"", c_plan_stale},
        {"lstat:1", c_plan_stale_lstat_fails},
        {"", c_missing},
        {"lstat:1", c_missing_lstat_fails},
        {"read:1", c_lock_taken_over},
        {"kill:1:EPERM", c_lock_taken_over},
        {"", c_apply_limit},
        {"mkdir:1", c_apply_mkdir_fails},
        {"mkdir:1:EEXIST", c_apply_mkdir_exists},
        {"symlink:1", c_apply_link_fails},
        {"rename:2", c_apply_link_fails},
        {"unlink:1", c_apply_remove_fails},
        {"open:1", c_apply_first_ledger_fails},
        {"rename:2", c_apply_last_ledger_fails},
        {"", c_off_mixed},
        {"rmdir:1:EEXIST", c_off_rmdir_exist},
        {"rmdir:1", c_off_rmdir_fails},
        {"unlink:1", c_off_unlink_fails},
        {"lstat:1", c_off_lstat_fails},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        snprintf(pbase, sizeof pbase, "%s/c%zu", root, i);
        CHECK(mkdir(pbase, 0755) == 0);
        case_cur = cases[i].fn;
        CHECK(in_child(cases[i].spec, case_cur_run) == 0);
    }
    CHECK(nftw(root, nftw_remove, 16, FTW_DEPTH | FTW_PHYS) == 0);
}

int main(void)
{
    test_valid();
    test_comments();
    test_lists();
    test_errors();
    test_wear_headers();
    test_more_errors();
    test_header_names_and_spacing();
    test_valid_names();
    test_long_cycle_message();
    test_limits();
    test_line_and_file();
    test_dump_is_stable();
    test_wrapper_faults();
    test_fault_counts_calls();
    test_self_path();
    test_say_and_out();
#ifndef SUIT_COVER
    test_ensure_aborts();
#endif
    test_stamp_too_large();
    test_writer();
    test_glob();
    test_resolve();
    test_resolve_machine();
    test_resolve_errors();
    test_resolve_limits();
    test_ledger();
    test_place_limits();
    test_listdir();
    test_place_faults();
    test_fault_lists();
    printf("unit: %d checks, %d failed\n", checks, failures);
    return failures == 0 ? 0 : 1;
}