/*
 * kido-reloc.c — Kido relocation detection + phase-2/3 adaptation.
 *
 * delta = runtime(probe) - linked(probe). The probe is a never-called
 * global function: its runtime address comes from PC-relative
 * adrp/add (true wherever we execute); its linked address comes from
 * a link-time absolute constant in .data.kido_probe_linked
 * (R_AARCH64_ABS64 at object level, unapplied R_AARCH64_RELATIVE in
 * the linked image — carved out of the phase-3 fixup walk, so the
 * word stays LINKED forever). The delta is the whole truth about
 * relocation.
 *
 * Phase 2 (2026-10-17): the entry .S measured the delta independently,
 * set SP = _stack_top + delta, stashed its measurement in BSS;
 * verify() crosschecked the two instruments and refused LOUD on
 * delta != 0 — safe environment, refused execution.
 *
 * Phase 3 (2026-10-19, deliberations/2026-10-19-kido-phase3-
 * selfreloc-design.md + 2026-10-19-kido-phase3-draft-design.md):
 * the entry .S now FIXES UP the image before C runs — it walks the
 * .rela.dyn manifest applying R_AARCH64_RELATIVE as *loc += delta
 * (loc = r_offset + delta), skipping the probe carve-out and its own
 * probe literal, and stashes the report (total/applied/carved/
 * skipped) in BSS. After the walk every GOT-based C access resolves
 * to the ACTUAL address: kido_image_bounds() reads ACTUAL, and the
 * LINKED base is derived here as actual - delta (the bounds
 * inversion; wrap-guarded, loud on wrap).
 *
 * The verify() policy FLIP is GATED and defaults CLOSED. The gate is
 * kido-reloc-audit-stamp.h, written ONLY by
 * scripts/kido-audit-abs-refs.sh --stamp on a passing image — NEVER
 * hand-write it. Gate closed: the phase-2 contract (delta != 0 ->
 * EARLY_ENV, loud). Gate open: the .S report must validate AND the
 * probe constant must still read linked; then a relocated image
 * PROCEEDS. Any failure -> EARLY_ENV, loud. The tripwire is not
 * deleted; phase 2's refusal is the fallback.
 *
 * LOAD-BEARING INVARIANT: never take &kido_reloc_probe at runtime.
 * With -fno-pic the compiler emits PC-relative adrp for that, which
 * would hide the delta. Only the .rodata constant holds the linked
 * address. The cross-compile session check (readelf -r) requires an
 * R_AARCH64_ABS64 relocation on the constant — a relative
 * relocation there means the technique is wrong and this module does
 * not ship. The same gate applies to the .S's probe_literal word
 * (queued: toolchain absent this session).
 *
 * TESTING: KIDO_HOSTED_TEST builds the hosted path + self-test.
 *  Gate closed (the default — pins "no flip without the audit"):
 *   gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST \
 *       -DKIDO_RELOC_SELFTEST modules/kido-reloc.c -o /tmp/kido-reloc-test
 *  Gate open (flip-engaged policy matrix; -D on the test line only —
 *  declared comparator testing, never a fake audit):
 *   gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST \
 *       -DKIDO_RELOC_SELFTEST -DKIDO_RELOC_AUDIT_PASS \
 *       modules/kido-reloc.c -o /tmp/kido-reloc-test-flip
 * Cross (ARM64, technique check): aarch64-linux-gnu-gcc
 *  -ffreestanding -O0 -Wall -Wextra -Werror -c modules/kido-reloc.c \
 *      -o /tmp/kido-reloc.o
 *  then: readelf -r /tmp/kido-reloc.o | grep kido_reloc_probe_linked
 *  must show R_AARCH64_ABS64 (link-time absolute), and the .o must
 *  contain the adrp/add sequence in kido_reloc_detect; the constant
 *  must land in .data.kido_probe_linked (readelf -s).
 */

/* The audit gate. scripts/kido-audit-abs-refs.sh --stamp is the ONLY
 * writer of kido-reloc-audit-stamp.h (it defines
 * KIDO_RELOC_AUDIT_PASS). NEVER hand-write the stamp: its presence
 * flips verify() from refuse-loud to relocated-and-fixed-proceed. */
#if defined(__has_include)
#  if __has_include("kido-reloc-audit-stamp.h")
#    include "kido-reloc-audit-stamp.h"
#  endif
#endif

#include "kido-reloc.h"

#if defined(KIDO_HOSTED_TEST)

/* Hosted: no linked image exists, so there is no relocation to
 * detect. The test injects a delta to exercise the verify policy;
 * an undeclared query refuses loudly. */
static int     reloc_test_injected = 0;
static int64_t reloc_test_delta    = 0;

kido_status_t kido_reloc_test_set_delta(int64_t delta)
{
    reloc_test_delta    = delta;
    reloc_test_injected = 1;
    return KIDO_OK;
}

#if defined(KIDO_RELOC_AUDIT_PASS)
/* Synthetic probe-still-linked input (declared comparator testing —
 * hosted has no probe constant). The flip-engaged test drives it. */
static int reloc_test_probe_ok = 1;

void kido_reloc_test_set_probe_ok(int ok)
{
    reloc_test_probe_ok = (ok != 0);
}
#endif /* KIDO_RELOC_AUDIT_PASS */

#else /* bare metal: the probe technique is real */

#include "kido-image.h"  /* actual base: one query, no duplicated truth */

/* The probe. Never called; its address is the measurement. Global
 * (not static) so the inline asm can name the symbol textually and
 * the compiler cannot rename or discard it. The entry .S names the
 * same symbol for its independent measurement. */
void kido_reloc_probe(void)
{
}

/* The linked address of the probe, as a link-time absolute constant.
 * GNU C accepts the address-of in a static initializer; the linker
 * resolves it to the LINKED address (R_AARCH64_ABS64 at object
 * level). Phase 3: it lives in its own section
 * (.data.kido_probe_linked), which the entry .S relocator carves
 * out of the manifest walk — the word stays LINKED forever, so
 * reading it at runtime yields the linked address no matter where
 * the image actually runs. See the INVARIANT above.
 * The section is deliberately WRITABLE (.data, not .rodata — renamed
 * 2026-10-20 when the assembler flagged the misnomer): the static
 * linker emits an R_AARCH64_RELATIVE for the word only in a writable
 * section, and the build-time audit's carve-out accounting NEEDS that
 * entry (carved >= 1 is fail-closed). A readonly section would resolve
 * the absolute at static link time, leave no manifest entry, and the
 * gate could never open. Writability is load-bearing, not sloppiness. */
static const uintptr_t kido_reloc_probe_linked
    __attribute__((section(".data.kido_probe_linked"))) =
    (uintptr_t)&kido_reloc_probe;

#endif /* KIDO_HOSTED_TEST */

/* BSS slots for the entry .S's independent delta measurement
 * (phase 2) and its phase-3 relocation report. The .S writes these
 * via PC-relative adrp stores before C runs; kido_reloc_crosscheck()
 * compares the delta against the C instrument, and the gated policy
 * validates the report. Hosted: never written by a .S — the self-test
 * writes them directly to exercise the comparators (declared). */
int64_t kido_reloc_entry_delta = 0;
int64_t kido_reloc_entry_valid = 0;
int64_t kido_reloc_fix_total   = 0;
int64_t kido_reloc_fix_applied = 0;
int64_t kido_reloc_fix_carved  = 0;
int64_t kido_reloc_fix_skipped = 0;

/* Last report, kept for a future console. BSS: the entry .S zeroes
 * it before C runs, so "never called detect" reads as all-zero.
 * kido-image reads this for the actual-bounds query. */
static kido_reloc_info_t kido_reloc_last_cache;

const kido_reloc_info_t *kido_reloc_last(void)
{
    return &kido_reloc_last_cache;
}

kido_status_t kido_reloc_detect(kido_reloc_info_t *info_out)
{
    if (info_out == NULL)
        return KIDO_ERR_EARLY_ENV;

#if defined(KIDO_HOSTED_TEST)
    if (!reloc_test_injected)
        return KIDO_ERR_STUB_REACHED;  /* no relocation concept here */

    /* Declared fiction for policy testing: no linked image on
     * hosted, so the "linked base" is 0 and actual == delta. The
     * bounds inversion does NOT apply here — there is no fixup. */
    info_out->delta       = reloc_test_delta;
    info_out->linked_base = 0u;
    info_out->actual_base  = (uint64_t)reloc_test_delta;
    kido_reloc_last_cache  = *info_out;
    return KIDO_OK;
#else
    {
        uintptr_t runtime_addr, linked_addr;
        uint64_t  base, size;  /* the ACTUAL base: the entry .S fixed
                                  up every GOT access before C ran */
        int64_t   delta;
        kido_status_t st;

        /* Runtime address of the probe: PC-relative adrp/add, full
         * range, true wherever we execute. */
        __asm__ volatile(
            "adrp %0, kido_reloc_probe\n\t"
            "add  %0, %0, :lo12:kido_reloc_probe"
            : "=r"(runtime_addr));

        /* Linked address of the probe: the carved-out .rodata word —
         * still LINKED after the fixup walk, by design. */
        linked_addr = kido_reloc_probe_linked;

        /* Phase 3 (the bounds inversion): the image query reads the
         * ACTUAL base now (GOT fixed); the LINKED base is derived as
         * actual - delta. A mislinked image fails LOUD here, before
         * any base is trusted for the report. */
        st = kido_image_bounds(&base, &size);
        if (st != KIDO_OK)
            return st;

        delta = (int64_t)(runtime_addr - linked_addr);
        info_out->delta       = delta;
        info_out->actual_base = base;
        if (delta >= 0) {
            uint64_t d = (uint64_t)delta;
            if (d > base)
                return KIDO_ERR_EARLY_ENV;  /* underflow: loud */
            info_out->linked_base = base - d;
        } else {
            /* The -(delta+1)+1 dance avoids UB when
             * delta == INT64_MIN. */
            uint64_t ad = (uint64_t)(-(delta + 1)) + 1u;
            if (ad > UINT64_MAX - base)
                return KIDO_ERR_EARLY_ENV;  /* overflow: loud */
            info_out->linked_base = base + ad;
        }
        kido_reloc_last_cache = *info_out;
        return KIDO_OK;
    }
#endif
}

kido_status_t kido_reloc_crosscheck(const kido_reloc_info_t *info)
{
    if (info == NULL)
        return KIDO_ERR_EARLY_ENV;

#if defined(KIDO_HOSTED_TEST)
    /* Hosted: no .S ran. valid == 0 is vacuous OK; a test-set valid
     * flag exercises the comparator below (declared, never a fake
     * .S). */
    if (kido_reloc_entry_valid == 0)
        return KIDO_OK;
#else
    /* Bare metal: the current .S always writes the slot. Zero means
     * a stale .S that predates it — a build inconsistency, loud. */
    if (kido_reloc_entry_valid == 0)
        return KIDO_ERR_EARLY_ENV;
#endif

    /* Two instruments, one physical fact. Disagreement is an
     * instrument fault — loud, never averaged or ignored. */
    if (kido_reloc_entry_delta != info->delta)
        return KIDO_ERR_EARLY_ENV;
    return KIDO_OK;
}

#ifdef KIDO_RELOC_AUDIT_PASS
/* ------------------------------------------------------------------ */
/* Gated phase-3 policy helpers. Only compiled when the build-time    */
/* audit stamped the image (KIDO_RELOC_AUDIT_PASS).                   */
/* ------------------------------------------------------------------ */

/* The .S relocation report must validate: a manifest was walked, no
 * unknown entry type was seen, every entry was accounted for, and at
 * least one carve-out was taken. The carve-out pin matters: the
 * audit guarantees the probe constant's entry is manifest-visible,
 * so carved == 0 means the booted image differs from the audited
 * one — fail closed. */
static kido_status_t kido_reloc_report_check(void)
{
    int64_t total   = kido_reloc_fix_total;
    int64_t applied = kido_reloc_fix_applied;
    int64_t carved  = kido_reloc_fix_carved;
    int64_t skipped = kido_reloc_fix_skipped;

    if (total <= 0)
        return KIDO_ERR_EARLY_ENV;   /* empty manifest: fail closed */
    if (skipped != 0)
        return KIDO_ERR_EARLY_ENV;   /* unknown reloc type walked */
    if (applied < 0 || carved < 1 || carved > total)
        return KIDO_ERR_EARLY_ENV;   /* impossible counts / carve-out pin */
    /* applied == total - carved - skipped, overflow-free: carved is
     * in [1, total] and skipped is 0, so total - carved is exact. */
    if (applied != total - carved)
        return KIDO_ERR_EARLY_ENV;   /* unaccounted entry */
    return KIDO_OK;
}

/* The carve-out pin, from the C side: the probe constant's word must
 * still hold the LINKED probe address after the fixup walk. Bare
 * metal reads it for real (same-TU adrp: the actual word; the word
 * must still be LINKED). Hosted drives the synthetic flag. */
static kido_status_t kido_reloc_probe_still_linked(int64_t delta)
{
#if defined(KIDO_HOSTED_TEST)
    (void)delta;  /* hosted drives the synthetic flag (declared) */
    return reloc_test_probe_ok ? KIDO_OK : KIDO_ERR_EARLY_ENV;
#else
    uintptr_t runtime_probe, linked_const;

    __asm__ volatile(
        "adrp %0, kido_reloc_probe\n\t"
        "add  %0, %0, :lo12:kido_reloc_probe"
        : "=r"(runtime_probe));
    linked_const = kido_reloc_probe_linked;  /* must still be LINKED */

    /* linked == actual - delta, wrap-guarded. */
    if (delta >= 0) {
        uint64_t d = (uint64_t)delta;
        if (d > runtime_probe)
            return KIDO_ERR_EARLY_ENV;
        return (linked_const == runtime_probe - d)
            ? KIDO_OK : KIDO_ERR_EARLY_ENV;
    }
    {
        uint64_t ad = (uint64_t)(-(delta + 1)) + 1u;
        if (ad > UINT64_MAX - runtime_probe)
            return KIDO_ERR_EARLY_ENV;
        return (linked_const == runtime_probe + ad)
            ? KIDO_OK : KIDO_ERR_EARLY_ENV;
    }
#endif
}
#endif /* KIDO_RELOC_AUDIT_PASS */

kido_status_t kido_reloc_verify(void)
{
    kido_reloc_info_t info;
    kido_status_t st = kido_reloc_detect(&info);

    if (st != KIDO_OK)
        return st;
    /* The crosscheck precedes the policy: a disagreeing instrument
     * must not feed the tripwire either way. */
    st = kido_reloc_crosscheck(&info);
    if (st != KIDO_OK)
        return st;
#ifdef KIDO_RELOC_AUDIT_PASS
    /* Phase-3 policy (gated): the build-time audit proved every
     * absolute reference covered. The .S report must validate and
     * the probe constant must still read linked — then a relocated
     * image PROCEEDS. Any failure -> EARLY_ENV, loud, exactly as
     * the tripwire always did. */
    st = kido_reloc_report_check();
    if (st != KIDO_OK)
        return st;
    st = kido_reloc_probe_still_linked(info.delta);
    if (st != KIDO_OK)
        return st;
    return KIDO_OK;
#else
    if (info.delta != 0)
        return KIDO_ERR_EARLY_ENV;  /* gate closed: refuse LOUD
                                       (phase-2 contract, unchanged) */
    return KIDO_OK;
#endif
}

#ifdef KIDO_RELOC_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_RELOC_SELFTEST needs KIDO_HOSTED_TEST."
#endif

#include <stdio.h>

static int test_failures = 0;
static int test_count = 0;
#define CHECK(cond, label) do { \
    test_count++; \
    if (cond) { printf("[ ok ] %s\n", label); } \
    else { printf("[FAIL] %s\n", label); test_failures++; } \
} while (0)

/* Write the .S report slots directly (declared — hosted has no .S). */
static void set_report(int64_t total, int64_t applied,
                       int64_t carved, int64_t skipped)
{
    kido_reloc_fix_total   = total;
    kido_reloc_fix_applied = applied;
    kido_reloc_fix_carved  = carved;
    kido_reloc_fix_skipped = skipped;
}

int main(void)
{
    kido_reloc_info_t info;

#ifdef KIDO_RELOC_AUDIT_PASS
    printf("== kido-reloc self-test (hosted, audit gate OPEN) ==\n");
#else
    printf("== kido-reloc self-test (hosted, audit gate CLOSED) ==\n");
#endif

    /* 1: NULL guard is loud */
    CHECK(kido_reloc_detect(NULL) == KIDO_ERR_EARLY_ENV,
          "NULL info_out -> EARLY_ENV");

    /* 2: uninjected query refuses — hosted has no relocation concept */
    CHECK(kido_reloc_detect(&info) == KIDO_ERR_STUB_REACHED,
          "uninjected -> STUB_REACHED (no relocation on hosted)");

    /* 3-6: injected zero delta -> linked-at-load, verify passes */
    CHECK(kido_reloc_test_set_delta(0) == KIDO_OK,
          "inject delta 0 -> OK");
    CHECK(kido_reloc_detect(&info) == KIDO_OK &&
          info.delta == 0 && info.linked_base == 0u &&
          info.actual_base == 0u,
          "delta 0 -> report {0, 0, 0} (declared fiction)");
    set_report(10, 9, 1, 0);  /* a walked manifest, even at delta 0 */
    kido_reloc_entry_valid = 0;  /* hosted-vacuous crosscheck */
#ifdef KIDO_RELOC_AUDIT_PASS
    kido_reloc_test_set_probe_ok(1);
    CHECK(kido_reloc_verify() == KIDO_OK,
          "verify on delta 0 + valid report -> OK");
#else
    CHECK(kido_reloc_verify() == KIDO_OK,
          "verify on delta 0 -> OK (gate closed)");
#endif
    CHECK(kido_reloc_last()->delta == 0,
          "last() caches the zero-delta report");

#ifdef KIDO_RELOC_AUDIT_PASS
    /* ---- Flip-engaged policy matrix (declared comparator testing) ---- */

    /* 7-8: relocated + valid report -> PROCEEDS */
    CHECK(kido_reloc_test_set_delta(0x1000) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK &&
          info.delta == 0x1000 && info.actual_base == 0x1000u,
          "delta +0x1000 -> report exact");
    set_report(10, 9, 1, 0);
    kido_reloc_test_set_probe_ok(1);
    kido_reloc_entry_valid = 1;
    kido_reloc_entry_delta = 0x1000;  /* .S agrees with C */
    CHECK(kido_reloc_verify() == KIDO_OK,
          "relocated + valid report + probe-ok -> OK (proceeds)");

    /* 9: applied short of the manifest -> loud */
    set_report(10, 8, 1, 0);
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "report applied 8/10 -> EARLY_ENV (unaccounted entry)");

    /* 10: an unknown reloc type walked -> loud */
    set_report(10, 9, 1, 1);
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "report skipped 1 -> EARLY_ENV (fail closed)");

    /* 11: empty manifest -> loud */
    set_report(0, 0, 0, 0);
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "report total 0 -> EARLY_ENV (fail closed)");

    /* 12: carve-out pin — the probe entry must have been among them */
    set_report(10, 10, 0, 0);
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "report carved 0 -> EARLY_ENV (carve-out pin)");

    /* 13: probe constant moved -> loud */
    set_report(10, 9, 1, 0);
    kido_reloc_test_set_probe_ok(0);
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "probe-ok 0 -> EARLY_ENV (carve-out violated)");
    kido_reloc_test_set_probe_ok(1);

    /* 14: crosscheck disagreement precedes the policy */
    kido_reloc_entry_delta = 0x2000;  /* .S disagrees with C */
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "disagreeing instruments -> EARLY_ENV (crosscheck first)");
    kido_reloc_entry_delta = 0x1000;

    /* 15: delta 0 still requires a valid report */
    CHECK(kido_reloc_test_set_delta(0) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK,
          "re-inject 0 for the delta-0 report check");
    kido_reloc_entry_delta = 0;
    set_report(10, 5, 1, 0);
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "delta 0 + bad report -> EARLY_ENV (walk validates)");

    /* 16: delta 0 + valid report -> OK */
    set_report(10, 9, 1, 0);
    CHECK(kido_reloc_verify() == KIDO_OK,
          "delta 0 + valid report -> OK");

    /* 17: negative delta + valid report -> OK (the -0x80000 shape) */
    CHECK(kido_reloc_test_set_delta(-0x80000) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK &&
          info.delta == -0x80000,
          "delta -0x80000 -> sign preserved in report");
    kido_reloc_entry_delta = -0x80000;
    set_report(10, 9, 1, 0);
    CHECK(kido_reloc_verify() == KIDO_OK,
          "relocated -0x80000 + valid report -> OK (proceeds)");

    /* 18: reset to clean */
    kido_reloc_entry_valid = 0;
    kido_reloc_entry_delta = 0;
    CHECK(kido_reloc_test_set_delta(0) == KIDO_OK &&
          kido_reloc_verify() == KIDO_OK,
          "verify clean again after reset");
#else
    /* ---- Gate-closed pin: even a PERFECT report refuses ---- */

    /* 7-8: nonzero delta + perfect report -> still loud (no flip
     * without the audit) */
    set_report(10, 9, 1, 0);
    kido_reloc_entry_valid = 1;
    kido_reloc_entry_delta = 0x1000;
    CHECK(kido_reloc_test_set_delta(0x1000) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK,
          "inject delta +0x1000 -> OK");
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "gate closed: perfect report still -> EARLY_ENV (loud)");

    /* 9-10: negative delta, same pin */
    kido_reloc_entry_delta = -0x2000;
    CHECK(kido_reloc_test_set_delta(-0x2000) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK &&
          info.delta == -0x2000,
          "delta -0x2000 -> sign preserved in report");
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "gate closed: delta -0x2000 -> EARLY_ENV (loud)");

    /* 11: re-injection back to zero clears the tripwire */
    kido_reloc_entry_valid = 0;
    kido_reloc_entry_delta = 0;
    CHECK(kido_reloc_test_set_delta(0) == KIDO_OK &&
          kido_reloc_verify() == KIDO_OK,
          "re-inject 0 -> verify OK again");
#endif

    /* Crosscheck, hosted vacuous — no .S ran, valid == 0 */
    kido_reloc_entry_valid = 0;
    kido_reloc_entry_delta = 0xdead;  /* garbage must be ignored */
    CHECK(kido_reloc_crosscheck(&info) == KIDO_OK,
          "crosscheck, valid==0 (hosted) -> OK, delta ignored");
    CHECK(kido_reloc_crosscheck(NULL) == KIDO_ERR_EARLY_ENV,
          "crosscheck NULL info -> EARLY_ENV");

    /* Crosscheck comparator — test-set slots (declared) */
    CHECK(kido_reloc_test_set_delta(0x1000) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK,
          "re-inject +0x1000 for crosscheck");
    kido_reloc_entry_valid = 1;
    kido_reloc_entry_delta = 0x1000;  /* .S agrees with C */
    CHECK(kido_reloc_crosscheck(&info) == KIDO_OK,
          "crosscheck, instruments agree -> OK");
    kido_reloc_entry_delta = 0x2000;  /* .S disagrees with C */
    CHECK(kido_reloc_crosscheck(&info) == KIDO_ERR_EARLY_ENV,
          "crosscheck, instruments disagree -> EARLY_ENV (loud)");

    /* verify() runs the crosscheck before the policy */
    kido_reloc_entry_delta = 0x2000;  /* still disagreeing */
    CHECK(kido_reloc_verify() == KIDO_ERR_EARLY_ENV,
          "verify with disagreeing instruments -> EARLY_ENV");
    kido_reloc_entry_valid = 0;  /* back to hosted-vacuous */
    kido_reloc_entry_delta = 0;
    set_report(10, 9, 1, 0);  /* flip flavor: the report must validate */
    CHECK(kido_reloc_test_set_delta(0) == KIDO_OK &&
          kido_reloc_verify() == KIDO_OK,
          "verify clean again after reset");

    /* last() tracks the latest detect across injections */
    CHECK(kido_reloc_test_set_delta(-0x400) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK &&
          kido_reloc_last()->delta == -0x400 &&
          kido_reloc_last()->actual_base == (uint64_t)(-0x400),
          "last() tracks negative-delta report");

    printf("== %d checks, %d failures ==\n", test_count, test_failures);
    return test_failures == 0 ? 0 : 1;
}
#endif /* KIDO_RELOC_SELFTEST */
