/*
 * kido-mem.c — Kido memory discovery: flattened device tree parsing.
 *
 * Takes the firmware DTB and produces the memory map that fills
 * kido_bootinfo_t for the entry shim -> HAL handoff. Portable C by
 * construction: the DTB format is big-endian by specification and every
 * field is read with manual byte loads, so this translation unit needs
 * no arch shim and no libc (the parser itself; the self-test harness
 * below is hosted-only).
 *
 * WHAT IS REAL: header validation (magic, totalsize sanity, block
 * bounds), /memreserve/ parsing, the structure-block walk with a depth
 * cap, memory-node identification (name prefix "memory" or
 * device_type="memory", status="disabled" skipped, reserved-memory
 * subtrees excluded), reg parsing with parent #address-cells /
 * #size-cells, region collection, DTB-extent trim (the firmware blob's
 * own pages leave the seed list before selection/publication),
 * largest-region primary selection, leading-reservation trimming,
 * UEFI memory-map discovery (descriptor v1, little-endian manual loads,
 * type classification, overlap audit, sort + coalesce, map-buffer trim,
 * shared publish).
 *
 * WHAT IS STUB: nothing in the discovery paths. The allocator seed
 * (region list) is exposed; the allocator is not.
 */

#include "kido-mem.h"

#ifdef KIDO_HOSTED_TEST
#include <stdio.h>
#endif

/* ------------------------------------------------------------------ */
/* DTB constants (devicetree specification, flattened format).         */
/* ------------------------------------------------------------------ */
#define FDT_MAGIC          0xd00dfeedu
#define FDT_BEGIN_NODE     1u
#define FDT_END_NODE       2u
#define FDT_PROP           3u
#define FDT_NOP            4u
#define FDT_END            9u

#define FDT_HEADER_SIZE    40u
#define FDT_MAX_DEPTH      16u
#define FDT_MAX_RSVMAP     8u
/* #address-cells / #size-cells sanity: DTB cells are u32 counts; a
 * reg tuple wider than this is malformed firmware, not memory. */
#define FDT_MAX_CELLS      4u

/* ------------------------------------------------------------------ */
/* Tiny libc-free helpers. The parser never touches libc so it can run */
/* on bare metal exactly as it runs in the hosted test.               */
/* ------------------------------------------------------------------ */
#ifdef KIDO_MEM_SELFTEST
/* Test-only: the parser itself uses kido_streq + bounded scans. */
static size_t kido_strlen(const char *s)
{
    size_t n = 0;
    while (s[n] != '\0')
        n++;
    return n;
}
#endif

static int kido_streq(const char *a, const char *b)
{
    size_t i = 0;
    for (;;) {
        if (a[i] != b[i])
            return 0;
        if (a[i] == '\0')
            return 1;
        i++;
    }
}

/* Bounded string length inside the DTB: returns (size_t)-1 if no NUL
 * is found within max bytes. */
static size_t kido_strnlen_dtb(const uint8_t *dtb, size_t len, size_t off,
                               size_t max)
{
    size_t n = 0;
    while (n < max) {
        if (off + n >= len)
            return (size_t)-1;
        if (dtb[off + n] == 0)
            return n;
        n++;
    }
    return (size_t)-1;
}

/* ------------------------------------------------------------------ */
/* Bounds-checked big-endian loads. Every DTB read goes through these. */
/* ------------------------------------------------------------------ */
static int fdt_u32(const uint8_t *dtb, size_t len, size_t off, uint32_t *out)
{
    if (off + 4 < off || off + 4 > len)
        return 0;
    *out = ((uint32_t)dtb[off] << 24) | ((uint32_t)dtb[off + 1] << 16) |
           ((uint32_t)dtb[off + 2] << 8) | (uint32_t)dtb[off + 3];
    return 1;
}

static int fdt_u64(const uint8_t *dtb, size_t len, size_t off, uint64_t *out)
{
    uint32_t hi, lo;
    if (!fdt_u32(dtb, len, off, &hi) || !fdt_u32(dtb, len, off + 4, &lo))
        return 0;
    *out = ((uint64_t)hi << 32) | (uint64_t)lo;
    return 1;
}

/* ------------------------------------------------------------------ */
/* Parser state.                                                       */
/* ------------------------------------------------------------------ */
typedef struct {
    uint32_t addr_cells;   /* cells governing THIS node's children's reg */
    uint32_t size_cells;
    uint8_t  is_memory;    /* node is a memory node (name or device_type) */
    uint8_t  in_reserved;  /* inside a reserved-memory subtree           */
    uint8_t  skipped;      /* status="disabled" (or malformed reg)       */
    uint8_t  has_reg;
    const uint8_t *reg_val; /* pointer into the DTB blob                 */
    uint32_t reg_len;
} fdt_frame_t;

typedef struct {
    const uint8_t *dtb;
    size_t len;
    size_t off_struct;
    size_t off_strings;
    size_t size_strings;
    fdt_frame_t stack[FDT_MAX_DEPTH];
    unsigned depth;
    kido_mem_region_t regions[KIDO_MEM_MAX_REGIONS];
    size_t nregions;
    uint64_t rsv_base[FDT_MAX_RSVMAP];
    uint64_t rsv_size[FDT_MAX_RSVMAP];
    size_t nrsv;
    int failed;
} fdt_walk_t;

static void fdt_fail(fdt_walk_t *w)
{
    w->failed = 1;
}

static int fdt_add_region(fdt_walk_t *w, uint64_t base, uint64_t size)
{
    if (size == 0)
        return 1; /* empty reg tuple: ignore, not an error */
    if (base + size < base)
        return 0; /* arithmetic overflow: malformed */
    if (w->nregions >= KIDO_MEM_MAX_REGIONS)
        return 0; /* bounded table: more regions than we track */
    w->regions[w->nregions].base = base;
    w->regions[w->nregions].size = size;
    w->nregions++;
    return 1;
}

/* Node name counts as a memory node if it is "memory" or "memory@...". */
static int fdt_name_is_memory(const char *name)
{
    if (!kido_streq(name, "memory")) {
        size_t i;
        const char *pre = "memory@";
        for (i = 0; i < 7; i++) {
            if (name[i] != pre[i])
                return 0;
        }
        if (name[7] == '\0')
            return 0; /* "memory@" with no unit address: not a node */
    }
    return 1;
}

/* Emit the top frame's reg (if it is a usable memory node) into regions. */
static void fdt_emit_frame(fdt_walk_t *w)
{
    fdt_frame_t *f = &w->stack[w->depth - 1];
    fdt_frame_t *parent;
    uint32_t naddr, nsize, tuplen;
    size_t off, k;

    if (!f->is_memory || f->in_reserved || f->skipped || !f->has_reg)
        return;

    /* reg tuples are governed by the PARENT's #address-cells/#size-cells. */
    if (w->depth >= 2) {
        parent = &w->stack[w->depth - 2];
        naddr = parent->addr_cells;
        nsize = parent->size_cells;
    } else {
        naddr = 2; /* DT spec defaults at root */
        nsize = 1;
    }
    if (naddr == 0 || nsize == 0 || naddr > FDT_MAX_CELLS ||
        nsize > FDT_MAX_CELLS || naddr + nsize < naddr) {
        fdt_fail(w);
        return;
    }
    tuplen = (naddr + nsize) * 4u;
    if (f->reg_len % tuplen != 0) {
        fdt_fail(w);
        return;
    }
    off = (size_t)(f->reg_val - w->dtb);
    for (k = 0; k < f->reg_len; k += tuplen) {
        uint64_t addr = 0, size = 0;
        uint32_t i;
        int ok = 1;
        for (i = 0; i < naddr; i++) {
            uint32_t c;
            if (!fdt_u32(w->dtb, w->len, off + k + (size_t)i * 4u, &c)) {
                ok = 0;
                break;
            }
            addr = (addr << 32) | (uint64_t)c;
        }
        for (i = 0; i < nsize && ok; i++) {
            uint32_t c;
            if (!fdt_u32(w->dtb, w->len,
                         off + k + (size_t)(naddr + i) * 4u, &c)) {
                ok = 0;
                break;
            }
            size = (size << 32) | (uint64_t)c;
        }
        if (!ok || !fdt_add_region(w, addr, size)) {
            fdt_fail(w);
            return;
        }
    }
}

/* Handle one property of the current (top) node. */
static void fdt_property(fdt_walk_t *w, const char *pname,
                         const uint8_t *pval, uint32_t plen)
{
    fdt_frame_t *f = &w->stack[w->depth - 1];
    uint32_t v;

    if (kido_streq(pname, "#address-cells")) {
        if (plen == 4 && fdt_u32(w->dtb, w->len,
                                (size_t)(pval - w->dtb), &v))
            f->addr_cells = v;
        /* Malformed #address-cells: keep inherited value, walk on. */
    } else if (kido_streq(pname, "#size-cells")) {
        if (plen == 4 && fdt_u32(w->dtb, w->len,
                                (size_t)(pval - w->dtb), &v))
            f->size_cells = v;
    } else if (kido_streq(pname, "device_type")) {
        if (kido_strnlen_dtb(w->dtb, w->len, (size_t)(pval - w->dtb),
                             plen) != (size_t)-1 &&
            kido_streq((const char *)pval, "memory"))
            f->is_memory = 1;
    } else if (kido_streq(pname, "status")) {
        if (plen >= 8 && pval[0] == 'd' && pval[1] == 'i' &&
            pval[2] == 's' && pval[3] == 'a' && pval[4] == 'b' &&
            pval[5] == 'l' && pval[6] == 'e' && pval[7] == 'd')
            f->skipped = 1;
    } else if (kido_streq(pname, "reg")) {
        f->has_reg = 1;
        f->reg_val = pval;
        f->reg_len = plen;
    }
}

/* The structure-block walk. Returns 1 on a clean walk, 0 on any error. */
static int fdt_walk_struct(fdt_walk_t *w)
{
    size_t off = w->off_struct;

    for (;;) {
        uint32_t tok;
        if (!fdt_u32(w->dtb, w->len, off, &tok)) {
            fdt_fail(w);
            return 0;
        }
        off += 4;
        if (tok == FDT_END)
            return w->failed ? 0 : 1;
        if (tok == FDT_NOP)
            continue;
        if (tok == FDT_BEGIN_NODE) {
            size_t nlen;
            fdt_frame_t *f;
            const char *name;
            if (w->depth >= FDT_MAX_DEPTH) {
                fdt_fail(w);
                return 0;
            }
            nlen = kido_strnlen_dtb(w->dtb, w->len, off, w->len - off);
            if (nlen == (size_t)-1) {
                fdt_fail(w);
                return 0;
            }
            name = (const char *)(w->dtb + off);
            off += (nlen + 1 + 3) & ~(size_t)3; /* name + NUL, 4-aligned */
            if (off < nlen || off > w->len) {
                fdt_fail(w);
                return 0;
            }
            f = &w->stack[w->depth];
            if (w->depth == 0) {
                f->addr_cells = 2; /* DT spec root defaults */
                f->size_cells = 1;
                f->in_reserved = 0;
            } else {
                f->addr_cells = w->stack[w->depth - 1].addr_cells;
                f->size_cells = w->stack[w->depth - 1].size_cells;
                f->in_reserved =
                    w->stack[w->depth - 1].in_reserved ||
                    kido_streq(name, "reserved-memory");
            }
            f->is_memory = (uint8_t)fdt_name_is_memory(name);
            f->skipped = 0;
            f->has_reg = 0;
            f->reg_val = NULL;
            f->reg_len = 0;
            w->depth++;
            continue;
        }
        if (tok == FDT_END_NODE) {
            if (w->depth == 0) {
                fdt_fail(w);
                return 0;
            }
            fdt_emit_frame(w);
            w->depth--;
            if (w->failed)
                return 0;
            continue;
        }
        if (tok == FDT_PROP) {
            uint32_t plen, nameoff;
            const uint8_t *pval;
            size_t snlen;
            char pname[64];
            size_t i;
            if (w->depth == 0) {
                fdt_fail(w);
                return 0;
            }
            if (!fdt_u32(w->dtb, w->len, off, &plen) ||
                !fdt_u32(w->dtb, w->len, off + 4, &nameoff)) {
                fdt_fail(w);
                return 0;
            }
            off += 8;
            if (nameoff >= w->size_strings) {
                fdt_fail(w);
                return 0;
            }
            snlen = kido_strnlen_dtb(w->dtb, w->len,
                                    w->off_strings + nameoff,
                                    w->size_strings - nameoff);
            if (snlen == (size_t)-1 || snlen >= sizeof(pname)) {
                fdt_fail(w);
                return 0;
            }
            for (i = 0; i <= snlen; i++)
                pname[i] = (char)w->dtb[w->off_strings + nameoff + i];
            if (off + plen < off || off + plen > w->len) {
                fdt_fail(w);
                return 0;
            }
            pval = w->dtb + off;
            fdt_property(w, pname, pval, plen);
            off += (plen + 3) & ~(size_t)3; /* value, 4-aligned */
            if (off > w->len) {
                fdt_fail(w);
                return 0;
            }
            if (w->failed)
                return 0;
            continue;
        }
        /* Unknown token: malformed structure block. */
        fdt_fail(w);
        return 0;
    }
}

/* ------------------------------------------------------------------ */
/* DTB-extent trim (2026-10-21). Pure portable C: (regions, extent)   */
/* in, survivors out. One input region yields 0-2 survivors (a split   */
/* around the extent); the output bound is KIDO_MEM_MAX_REGIONS.      */
/* Returns 0 on arithmetic overflow or bound-exceeded — the caller     */
/* fails LOUD. Half-open intervals throughout: [base, base+size).     */
/* ------------------------------------------------------------------ */

static int kido_mem_trim_emit(kido_mem_region_t *out, size_t *nout,
                              uint64_t base, uint64_t size)
{
    if (size == 0)
        return 1; /* degenerate survivor: drop it, not an error */
    if (*nout >= KIDO_MEM_MAX_REGIONS)
        return 0; /* bounded table: pathological firmware */
    out[*nout].base = base;
    out[*nout].size = size;
    (*nout)++;
    return 1;
}

/* Trim [eb, eb+es) out of one region, appending 0-2 survivors. */
static int kido_mem_trim_one(const kido_mem_region_t *r,
                             uint64_t eb, uint64_t es,
                             kido_mem_region_t *out, size_t *nout)
{
    uint64_t rb = r->base, rs = r->size, re, ee;

    re = rb + rs;
    if (re < rb)
        return 0; /* region arithmetic overflow: malformed */
    if (es == 0)
        return kido_mem_trim_emit(out, nout, rb, rs); /* vacuous: no-op */
    ee = eb + es;
    if (ee < eb)
        return 0; /* extent overflow: malformed */
    if (ee <= rb || eb >= re)
        return kido_mem_trim_emit(out, nout, rb, rs); /* no overlap */
    if (eb > rb) {
        /* head survivor: [rb, eb) */
        if (!kido_mem_trim_emit(out, nout, rb, eb - rb))
            return 0;
    }
    if (ee < re) {
        /* tail survivor: [ee, re) */
        if (!kido_mem_trim_emit(out, nout, ee, re - ee))
            return 0;
    }
    return 1; /* extent covered the region whole: dropped, 0 survivors */
}

static int kido_mem_trim_regions(const kido_mem_region_t *regions, size_t n,
                                 uint64_t eb, uint64_t es,
                                 kido_mem_region_t *out, size_t *nout)
{
    size_t i;
    *nout = 0;
    for (i = 0; i < n; i++) {
        if (!kido_mem_trim_one(&regions[i], eb, es, out, nout))
            return 0;
    }
    return 1;
}

/* ------------------------------------------------------------------ */
/* UEFI memory-map constants (UEFI specification, descriptor v1).       */
/* The descriptor is little-endian by specification on AArch64; every  */
/* field is read with manual little-endian loads — no struct casts,   */
/* so a misaligned loader buffer can never fault the parse.            */
/* ------------------------------------------------------------------ */
#define KIDO_UEFI_DESC_V1_SIZE  40u
#define KIDO_UEFI_DESC_VERSION  1u
/* Raw-entry walk bound: every bound is a bet. 64 is generous (QEMU
 * virt hands ~10-20) and keeps the pairwise overlap audit trivial;
 * more is pathological firmware -> loud. */
#define KIDO_UEFI_MAX_ENTRIES   64u

#define KIDO_UEFI_RESERVED      0u
#define KIDO_UEFI_LOADER_CODE   1u
#define KIDO_UEFI_LOADER_DATA   2u
#define KIDO_UEFI_BS_CODE       3u
#define KIDO_UEFI_BS_DATA       4u
#define KIDO_UEFI_RT_CODE       5u
#define KIDO_UEFI_RT_DATA       6u
#define KIDO_UEFI_CONVENTIONAL  7u
#define KIDO_UEFI_UNUSABLE      8u
#define KIDO_UEFI_ACPI_RECLAIM  9u
#define KIDO_UEFI_ACPI_NVS      10u
#define KIDO_UEFI_MMIO          11u
#define KIDO_UEFI_MMIO_PORT     12u
#define KIDO_UEFI_PAL_CODE      13u
#define KIDO_UEFI_PERSISTENT    14u

#define KIDO_UEFI_PAGE_SHIFT    12u

/* Bounds-checked little-endian loads. Every UEFI descriptor read goes
 * through these — the fdt_u32 idiom's little-endian twin. */
static int uefi_u32(const uint8_t *m, size_t len, size_t off, uint32_t *out)
{
    if (off + 4 < off || off + 4 > len)
        return 0;
    *out = (uint32_t)m[off] | ((uint32_t)m[off + 1] << 8) |
           ((uint32_t)m[off + 2] << 16) | ((uint32_t)m[off + 3] << 24);
    return 1;
}

static int uefi_u64(const uint8_t *m, size_t len, size_t off, uint64_t *out)
{
    uint32_t lo, hi;
    if (!uefi_u32(m, len, off, &lo) || !uefi_u32(m, len, off + 4, &hi))
        return 0;
    *out = (uint64_t)lo | ((uint64_t)hi << 32);
    return 1;
}

/* The type law: what Kido may seed. Conventional is free RAM;
 * BootServices code/data are reclaimable AFTER ExitBootServices —
 * the caller contract in the header owns that ordering. Everything
 * else is excluded, each for a declared reason (see the header). */
static int uefi_type_usable(uint32_t type)
{
    return type == KIDO_UEFI_CONVENTIONAL || type == KIDO_UEFI_BS_CODE ||
           type == KIDO_UEFI_BS_DATA;
}

/* One parsed descriptor: the ground truth the overlap audit sees. */
typedef struct {
    uint32_t type;
    uint64_t base;
    uint64_t size;
} uefi_entry_t;

/* ------------------------------------------------------------------ */
/* Public interface.                                                   */
/* ------------------------------------------------------------------ */

static kido_mem_region_t g_regions[KIDO_MEM_MAX_REGIONS];
static size_t g_nregions = 0;

#ifdef KIDO_HOSTED_TEST
/* Hosted-only DTB-extent injector (deliberated 2026-10-21). Bare metal
 * computes the extent from the real firmware pointer; the dev host
 * has no firmware DTB, so hosted defaults to the vacuous (0,0) and
 * the trim no-ops — the kido-image hosted-vacuity precedent. */
static uint64_t g_test_dtb_base = 0u;
static uint64_t g_test_dtb_size = 0u;

void kido_mem_test_set_dtb_extent(uint64_t base, uint64_t size)
{
    g_test_dtb_base = base;
    g_test_dtb_size = size;
}
#endif

size_t kido_mem_region_count(void)
{
    return g_nregions;
}

const kido_mem_region_t *kido_mem_regions(void)
{
    return g_regions;
}

/* Shared publish: primary = largest region (ties: lowest base),
 * fill the bootinfo, publish the seed list. Extracted from
 * kido_mem_discover's tail (2026-10-23) so the DTB and UEFI paths
 * obey one selection law — no duplicated truth. Callers guarantee
 * n >= 1 (both paths fail loud on the empty list before calling). */
static kido_status_t kido_mem_publish(const kido_mem_region_t *regions,
                                      size_t n, kido_bootinfo_t *bi)
{
    size_t i, best;

    best = 0;
    for (i = 1; i < n; i++) {
        if (regions[i].size > regions[best].size ||
            (regions[i].size == regions[best].size &&
             regions[i].base < regions[best].base))
            best = i;
    }
    bi->mem_base = regions[best].base;
    bi->mem_size = regions[best].size;
    bi->mem_valid = 1;
    /* board_id is the entry shim's call (board detection), not mem's. */

    for (i = 0; i < n; i++)
        g_regions[i] = regions[i];
    g_nregions = n;
    return KIDO_OK;
}

kido_status_t kido_mem_discover_uefi(const void *mmap, size_t mmap_len,
                                    uint32_t desc_size, uint32_t desc_version,
                                    kido_bootinfo_t *bi)
{
    const uint8_t *m;
    size_t nentries, nparsed, nusable, ntrimmed, i, j;
    uefi_entry_t entries[KIDO_UEFI_MAX_ENTRIES];
    kido_mem_region_t usable[KIDO_UEFI_MAX_ENTRIES];
    kido_mem_region_t trimmed[KIDO_MEM_MAX_REGIONS];
    uint64_t map_eb, map_es; /* the map buffer's own extent, trimmed out */

    if (bi == NULL)
        return KIDO_ERR_NO_MEMORY;
    bi->mem_valid = 0; /* guilty until proven innocent */
    if (mmap == NULL || mmap_len == 0)
        return KIDO_ERR_NO_MEMORY;
    /* The version gate comes first: Kido implements descriptor v1,
     * and a newer layout must never be silently mis-parsed. */
    if (desc_version != KIDO_UEFI_DESC_VERSION)
        return KIDO_ERR_NO_MEMORY;
    if (desc_size < KIDO_UEFI_DESC_V1_SIZE)
        return KIDO_ERR_NO_MEMORY; /* cannot hold the v1 fields */
    if (mmap_len % desc_size != 0)
        return KIDO_ERR_NO_MEMORY; /* ragged map: malformed loader */

    nentries = mmap_len / desc_size;
    if (nentries > KIDO_UEFI_MAX_ENTRIES)
        return KIDO_ERR_NO_MEMORY; /* pathological firmware: loud */
    m = (const uint8_t *)mmap;

    /* Parse + classify. The v1 fields are a prefix of any wider
     * stride, so desc_size > 40 parses honestly. VirtualStart and
     * Attribute are deliberately unread (header documents why). */
    nparsed = 0;
    for (i = 0; i < nentries; i++) {
        uint32_t type;
        uint64_t phys, pages, size;
        size_t off = i * (size_t)desc_size;
        if (!uefi_u32(m, mmap_len, off, &type) ||
            !uefi_u64(m, mmap_len, off + 8, &phys) ||
            !uefi_u64(m, mmap_len, off + 24, &pages))
            return KIDO_ERR_NO_MEMORY; /* bounds-checked: loud anyway */
        if (pages == 0)
            continue; /* zero-length entry: no-op, not an error */
        if (pages > (UINT64_MAX >> KIDO_UEFI_PAGE_SHIFT))
            return KIDO_ERR_NO_MEMORY; /* pages*4096 would wrap */
        size = pages << KIDO_UEFI_PAGE_SHIFT;
        if (phys + size < phys)
            return KIDO_ERR_NO_MEMORY; /* address wrap: loud */
        entries[nparsed].type = type;
        entries[nparsed].base = phys;
        entries[nparsed].size = size;
        nparsed++;
    }

    /* Overlap audit: a self-contradictory map is untrustworthy ground
     * truth. Overlapping descriptors fail loud — never merged, never
     * guessed. Sizes are nonzero and wrap-checked above, so the
     * half-open comparisons are exact. */
    for (i = 0; i < nparsed; i++) {
        for (j = i + 1; j < nparsed; j++) {
            uint64_t a1 = entries[i].base + entries[i].size;
            uint64_t b1 = entries[j].base + entries[j].size;
            if (entries[i].base < b1 && entries[j].base < a1)
                return KIDO_ERR_NO_MEMORY; /* contradictory firmware */
        }
    }

    /* Collect the usable. */
    nusable = 0;
    for (i = 0; i < nparsed; i++) {
        if (!uefi_type_usable(entries[i].type))
            continue;
        usable[nusable].base = entries[i].base;
        usable[nusable].size = entries[i].size;
        nusable++;
    }
    if (nusable == 0)
        return KIDO_ERR_NO_MEMORY; /* nothing seedable: loud */

    /* Sort by base — no documented bet on firmware ordering. The
     * audit above proved disjointness, so sorting is total. */
    for (i = 1; i < nusable; i++) {
        kido_mem_region_t key = usable[i];
        j = i;
        while (j > 0 && usable[j - 1].base > key.base) {
            usable[j] = usable[j - 1];
            j--;
        }
        usable[j] = key;
    }

    /* Coalesce adjacent contiguous usable regions. Disjointness is
     * audited, so end == next base is the only merge case; the add
     * cannot wrap (it would imply an overlap the audit rejected). */
    {
        size_t w = 0;
        for (i = 1; i < nusable; i++) {
            if (usable[i].base == usable[w].base + usable[w].size) {
                usable[w].size += usable[i].size;
            } else {
                w++;
                usable[w] = usable[i];
            }
        }
        nusable = w + 1;
    }

    /* Trim the map buffer's own extent — the DTB-extent-trim
     * precedent (2026-10-21). The loader owns this buffer, but a
     * loader quirk must not hand the buffer's pages to the
     * allocator; trim-and-survive beats fail-loud here, and the
     * buffer holds our already-parsed ground truth, so trimming
     * cannot corrupt the parse. Vacuous when disjoint. */
    map_eb = (uint64_t)(uintptr_t)mmap;
    map_es = (uint64_t)mmap_len;
    if (!kido_mem_trim_regions(usable, nusable, map_eb, map_es,
                               trimmed, &ntrimmed))
        return KIDO_ERR_NO_MEMORY; /* overflow / bound-exceeded: loud */
    if (ntrimmed == 0)
        return KIDO_ERR_NO_MEMORY; /* the map ate all memory: loud */

    return kido_mem_publish(trimmed, ntrimmed, bi);
}

kido_status_t kido_mem_discover(const uint8_t *dtb, size_t dtb_len,
                                kido_bootinfo_t *bi)
{
    uint32_t magic, totalsize, off_struct, off_strings, off_rsv, size_strings;
    uint32_t size_struct;
    fdt_walk_t w;
    size_t i;
    uint64_t base, size;
    kido_status_t st;
    uint64_t dtb_eb, dtb_es; /* the DTB extent the trimmer removes */
    kido_mem_region_t trimmed[KIDO_MEM_MAX_REGIONS];
    size_t ntrimmed = 0;

    if (bi == NULL)
        return KIDO_ERR_NO_MEMORY;
    bi->mem_valid = 0; /* guilty until proven innocent */
    if (dtb == NULL || dtb_len < FDT_HEADER_SIZE)
        return KIDO_ERR_NO_MEMORY;

    if (!fdt_u32(dtb, dtb_len, 0, &magic) || magic != FDT_MAGIC)
        return KIDO_ERR_NO_MEMORY; /* corrupt magic: loud, no regions */
    if (!fdt_u32(dtb, dtb_len, 4, &totalsize) ||
        !fdt_u32(dtb, dtb_len, 8, &off_struct) ||
        !fdt_u32(dtb, dtb_len, 12, &off_strings) ||
        !fdt_u32(dtb, dtb_len, 16, &off_rsv) ||
        !fdt_u32(dtb, dtb_len, 32, &size_strings) ||
        !fdt_u32(dtb, dtb_len, 36, &size_struct))
        return KIDO_ERR_NO_MEMORY;

    /* Totalsize sanity: must cover the header and every block it names. */
    if (totalsize < FDT_HEADER_SIZE || totalsize > dtb_len)
        return KIDO_ERR_NO_MEMORY;
    if (off_struct + size_struct < off_struct ||
        off_struct + size_struct > totalsize)
        return KIDO_ERR_NO_MEMORY;
    if (off_strings + size_strings < off_strings ||
        off_strings + size_strings > totalsize)
        return KIDO_ERR_NO_MEMORY;
    if (off_rsv >= totalsize)
        return KIDO_ERR_NO_MEMORY;

    w.dtb = dtb;
    w.len = totalsize; /* parse only what the DTB claims, never past it */
    w.off_struct = off_struct;
    w.off_strings = off_strings;
    w.size_strings = size_strings;
    w.depth = 0;
    w.nregions = 0;
    w.nrsv = 0;
    w.failed = 0;

    /* /memreserve/: u64 pairs until {0,0}. */
    {
        size_t roff = off_rsv;
        for (;;) {
            uint64_t rb, rs;
            if (!fdt_u64(dtb, totalsize, roff, &rb) ||
                !fdt_u64(dtb, totalsize, roff + 8, &rs))
                return KIDO_ERR_NO_MEMORY;
            roff += 16;
            if (rb == 0 && rs == 0)
                break;
            if (w.nrsv >= FDT_MAX_RSVMAP)
                return KIDO_ERR_NO_MEMORY; /* bounded: too many */
            w.rsv_base[w.nrsv] = rb;
            w.rsv_size[w.nrsv] = rs;
            w.nrsv++;
        }
    }

    if (!fdt_walk_struct(&w))
        return KIDO_ERR_NO_MEMORY;
    if (w.depth != 0 || w.nregions == 0)
        return KIDO_ERR_NO_MEMORY; /* truncated walk / no memory nodes */

    /* DTB-extent trim (2026-10-21): the firmware blob lives in RAM at
     * [dtb, dtb+totalsize) — inside the /memory regions on real
     * firmware — so the raw seed list contains the DTB's own pages.
     * The trim removes the extent from every region BEFORE primary
     * selection and seed publication: the seed list is
     * usable-by-construction, and the allocator never sees the DTB's
     * pages. Bare metal: the real firmware pointer + the re-validated
     * totalsize (exactly what discover vouches for, never the
     * dtb_len slack). Hosted: the test injector, vacuous by default.
     * No overlap anywhere is a no-op — absence is a fact, not an
     * error. */
#if defined(KIDO_HOSTED_TEST)
    dtb_eb = g_test_dtb_base;
    dtb_es = g_test_dtb_size;
#else
    dtb_eb = (uint64_t)(uintptr_t)dtb;
    dtb_es = (uint64_t)totalsize;
#endif
    if (!kido_mem_trim_regions(w.regions, w.nregions, dtb_eb, dtb_es,
                               trimmed, &ntrimmed))
        return KIDO_ERR_NO_MEMORY; /* overflow / bound-exceeded: loud */
    if (ntrimmed == 0)
        return KIDO_ERR_NO_MEMORY; /* the DTB ate all memory: loud */

    /* Publish first (the shared selection law), then honor
     * /memreserve/ against the published primary: a leading reservation
     * trims the base upward; a strictly interior reservation cannot be
     * represented in the single-region bootinfo -> fail LOUD rather
     * than hand the allocator a region with a firmware hole in it. The
     * seed list keeps the trimmed regions unadjusted; the memreserve
     * adjustment is the bootinfo's single-region view only. Loud paths
     * clear mem_valid — publish proved it, the reservation un-proves
     * it. Observable behavior is byte-identical to the pre-extraction
     * tail (pinned by the suite). */
    st = kido_mem_publish(trimmed, ntrimmed, bi);
    if (st != KIDO_OK)
        return st; /* unreachable: ntrimmed >= 1 checked above */
    base = bi->mem_base;
    size = bi->mem_size;
    for (i = 0; i < w.nrsv; i++) {
        uint64_t rb = w.rsv_base[i], rs = w.rsv_size[i];
        uint64_t re = rb + rs;
        if (rs == 0 || re < rb)
            continue;
        if (rb <= base && base < re) {
            uint64_t shift = re - base;
            if (shift >= size) {
                bi->mem_valid = 0;
                return KIDO_ERR_NO_MEMORY;
            }
            base = re;
            size -= shift;
        } else if (base < rb && rb < base + size) {
            bi->mem_valid = 0;
            return KIDO_ERR_NO_MEMORY; /* interior hole: loud */
        }
    }
    bi->mem_base = base;
    bi->mem_size = size;
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* Hosted self-test: builds synthetic DTBs in memory and runs the      */
/* REAL parser against them. No fixtures, no mocks of the parser       */
/* itself — the bytes are the test.                                    */
/* ------------------------------------------------------------------ */
#ifdef KIDO_MEM_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "kido-mem self-test requires KIDO_HOSTED_TEST"
#endif

/* Minimal DTB emitter: structure block and strings block built in
 * separate buffers, then assembled with a back-patched header. */
typedef struct {
    uint8_t sbuf[2048];
    size_t spos;
    uint8_t tbuf[512];
    size_t tpos;
    struct {
        const char *s;
        uint32_t off;
    } stab[16];
    size_t nstab;
} tb_t;

static void tb_put_u32(uint8_t *b, size_t *p, uint32_t v)
{
    b[(*p)++] = (uint8_t)(v >> 24);
    b[(*p)++] = (uint8_t)(v >> 16);
    b[(*p)++] = (uint8_t)(v >> 8);
    b[(*p)++] = (uint8_t)v;
}

static void tb_put_u64(uint8_t *b, size_t *p, uint64_t v)
{
    tb_put_u32(b, p, (uint32_t)(v >> 32));
    tb_put_u32(b, p, (uint32_t)v);
}

static void tb_s_u32(tb_t *t, uint32_t v)
{
    tb_put_u32(t->sbuf, &t->spos, v);
}

static void tb_s_pad4(tb_t *t)
{
    while (t->spos % 4 != 0)
        t->sbuf[t->spos++] = 0;
}

static uint32_t tb_stroff(tb_t *t, const char *s)
{
    size_t i;
    for (i = 0; i < t->nstab; i++) {
        if (kido_streq(t->stab[i].s, s))
            return t->stab[i].off;
    }
    {
        uint32_t off = (uint32_t)t->tpos;
        size_t n = kido_strlen(s);
        for (i = 0; i <= n; i++)
            t->tbuf[t->tpos++] = (uint8_t)s[i];
        t->stab[t->nstab].s = s;
        t->stab[t->nstab].off = off;
        t->nstab++;
        return off;
    }
}

static void tb_begin_node(tb_t *t, const char *name)
{
    size_t n = kido_strlen(name);
    size_t i;
    tb_s_u32(t, FDT_BEGIN_NODE);
    for (i = 0; i <= n; i++)
        t->sbuf[t->spos++] = (uint8_t)name[i];
    tb_s_pad4(t);
}

static void tb_end_node(tb_t *t)
{
    tb_s_u32(t, FDT_END_NODE);
}

static void tb_prop_u32(tb_t *t, const char *name, uint32_t v)
{
    tb_s_u32(t, FDT_PROP);
    tb_s_u32(t, 4);
    tb_s_u32(t, tb_stroff(t, name));
    tb_s_u32(t, v);
}

static void tb_prop_str(tb_t *t, const char *name, const char *s)
{
    size_t n = kido_strlen(s);
    size_t i;
    tb_s_u32(t, FDT_PROP);
    tb_s_u32(t, (uint32_t)(n + 1));
    tb_s_u32(t, tb_stroff(t, name));
    for (i = 0; i <= n; i++)
        t->sbuf[t->spos++] = (uint8_t)s[i];
    tb_s_pad4(t);
}

/* reg with #address-cells=2, #size-cells=2: <a_hi a_lo s_hi s_lo>. */
static void tb_prop_reg2(tb_t *t, uint64_t addr, uint64_t size)
{
    tb_s_u32(t, FDT_PROP);
    tb_s_u32(t, 16);
    tb_s_u32(t, tb_stroff(t, "reg"));
    tb_put_u64(t->sbuf, &t->spos, addr);
    tb_put_u64(t->sbuf, &t->spos, size);
}

static void tb_begin(tb_t *t)
{
    t->spos = 0;
    t->tpos = 0;
    t->nstab = 0;
}

/*
 * Assemble: [header 40][memreserve][struct][strings]. rsv_n entries of
 * (rsv_base[i], rsv_size[i]) precede the {0,0} terminator. The finished
 * blob is written to out; returns its length.
 */
static size_t tb_assemble(tb_t *t, uint8_t *out,
                          const uint64_t *rsv_base, const uint64_t *rsv_size,
                          size_t rsv_n)
{
    size_t p = 0, i;
    size_t off_rsv, off_struct, off_strings;
    size_t size_struct, size_strings, total;

    for (i = 0; i < 40; i++)
        out[p++] = 0;
    off_rsv = p;
    for (i = 0; i < rsv_n; i++) {
        tb_put_u64(out, &p, rsv_base[i]);
        tb_put_u64(out, &p, rsv_size[i]);
    }
    tb_put_u64(out, &p, 0);
    tb_put_u64(out, &p, 0);
    off_struct = p;
    tb_s_u32(t, FDT_END);
    for (i = 0; i < t->spos; i++)
        out[p++] = t->sbuf[i];
    size_struct = t->spos;
    off_strings = p;
    for (i = 0; i < t->tpos; i++)
        out[p++] = t->tbuf[i];
    size_strings = t->tpos;
    total = p;

    /* Back-patch the header. */
    {
        size_t hp = 0;
        tb_put_u32(out, &hp, FDT_MAGIC);
        tb_put_u32(out, &hp, (uint32_t)total);
        tb_put_u32(out, &hp, (uint32_t)off_struct);
        tb_put_u32(out, &hp, (uint32_t)off_strings);
        tb_put_u32(out, &hp, (uint32_t)off_rsv);
        tb_put_u32(out, &hp, 17); /* version */
        tb_put_u32(out, &hp, 16); /* last_comp_version */
        tb_put_u32(out, &hp, 0);  /* boot_cpuid_phys */
        tb_put_u32(out, &hp, (uint32_t)size_strings);
        tb_put_u32(out, &hp, (uint32_t)size_struct);
    }
    return total;
}

/* Standard root: #address-cells=2, #size-cells=2. */
static void tb_root(tb_t *t)
{
    tb_begin_node(t, "");
    tb_prop_u32(t, "#address-cells", 2);
    tb_prop_u32(t, "#size-cells", 2);
}

/* Trim-test fixtures (2026-10-21): synthetic DTBs whose /memory
 * regions live in the firmware address space; the DTB load extent
 * comes from kido_mem_test_set_dtb_extent, exactly like the
 * kido-image injected-bounds pattern. */
static size_t tb_one_region(tb_t *t, uint8_t *blob)
{
    tb_begin(t);
    tb_root(t);
    tb_begin_node(t, "memory@40000000");
    tb_prop_str(t, "device_type", "memory");
    tb_prop_reg2(t, 0x40000000ull, 0x20000000ull); /* 512 MiB */
    tb_end_node(t);
    tb_end_node(t);
    return tb_assemble(t, blob, NULL, NULL, 0);
}

static size_t tb_two_regions(tb_t *t, uint8_t *blob)
{
    tb_begin(t);
    tb_root(t);
    tb_begin_node(t, "memory@40000000");
    tb_prop_str(t, "device_type", "memory");
    tb_prop_reg2(t, 0x40000000ull, 0x20000000ull); /* 512 MiB */
    tb_end_node(t);
    tb_begin_node(t, "memory@80000000");
    tb_prop_str(t, "device_type", "memory");
    tb_prop_reg2(t, 0x80000000ull, 0x10000000ull); /* 256 MiB */
    tb_end_node(t);
    tb_end_node(t);
    return tb_assemble(t, blob, NULL, NULL, 0);
}

static int region_is(size_t idx, uint64_t base, uint64_t size)
{
    const kido_mem_region_t *r = kido_mem_regions();
    return idx < kido_mem_region_count() &&
           r[idx].base == base && r[idx].size == size;
}

static int g_failures = 0;

#define CHECK(cond, label) do { \
    if (!(cond)) { printf("[FAIL] %s\n", label); g_failures++; } \
    else { printf("[ok] %s\n", label); } \
} while (0)

/* Minimal UEFI map emitter: v1 descriptors (40 bytes, little-endian)
 * laid at a caller-chosen stride. VirtualStart carries garbage to
 * prove it is ignored; Attribute carries garbage to prove it is
 * unread. The bytes are the test. */
typedef struct {
    uint8_t *buf;
    size_t cap;
    size_t len;
    uint32_t stride;
} uefi_tb_t;

static void uefi_put_u32le(uint8_t *p, uint32_t v)
{
    p[0] = (uint8_t)v;
    p[1] = (uint8_t)(v >> 8);
    p[2] = (uint8_t)(v >> 16);
    p[3] = (uint8_t)(v >> 24);
}

static void uefi_put_u64le(uint8_t *p, uint64_t v)
{
    uefi_put_u32le(p, (uint32_t)v);
    uefi_put_u32le(p + 4, (uint32_t)(v >> 32));
}

static void uefi_tb_begin(uefi_tb_t *t, uint8_t *buf, size_t cap,
                          uint32_t stride)
{
    size_t i;
    t->buf = buf;
    t->cap = cap;
    t->len = 0;
    t->stride = stride;
    for (i = 0; i < cap; i++)
        buf[i] = 0;
}

static int uefi_tb_desc(uefi_tb_t *t, uint32_t type, uint64_t phys,
                        uint64_t pages)
{
    uint8_t *p;
    if (t->len + t->stride > t->cap)
        return 0;
    p = t->buf + t->len;
    uefi_put_u32le(p + 0, type);
    uefi_put_u32le(p + 4, 0);                  /* Pad */
    uefi_put_u64le(p + 8, phys);               /* PhysicalStart */
    uefi_put_u64le(p + 16, 0xdeadbeefull);     /* VirtualStart: ignored */
    uefi_put_u64le(p + 24, pages);             /* NumberOfPages */
    uefi_put_u64le(p + 32, 0x8000000000000001ull); /* Attribute: unread */
    t->len += t->stride;
    return 1;
}

int main(void)
{
    tb_t t;
    uint8_t blob[4096];
    size_t len;
    kido_bootinfo_t bi;
    kido_status_t st;

    /* ---- 1. valid DTB: two memory regions, largest wins ---- */
    tb_begin(&t);
    tb_root(&t);
    tb_begin_node(&t, "memory@40000000");
    tb_prop_str(&t, "device_type", "memory");
    tb_prop_reg2(&t, 0x40000000ull, 0x20000000ull); /* 512 MiB */
    tb_end_node(&t);
    tb_begin_node(&t, "memory@80000000");
    tb_prop_str(&t, "device_type", "memory");
    tb_prop_reg2(&t, 0x80000000ull, 0x10000000ull); /* 256 MiB */
    tb_end_node(&t);
    tb_end_node(&t); /* root */
    len = tb_assemble(&t, blob, NULL, NULL, 0);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK, "valid DTB returns OK");
    CHECK(bi.mem_valid == 1, "valid DTB sets mem_valid");
    CHECK(bi.mem_base == 0x40000000ull && bi.mem_size == 0x20000000ull,
          "largest region selected (0x40000000, 512MiB)");
    CHECK(kido_mem_region_count() == 2, "both regions in the seed list");

    /* ---- 2. corrupt magic fails loud ---- */
    blob[0] ^= 0xff;
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_ERR_NO_MEMORY, "corrupt magic -> NO_MEMORY");
    CHECK(bi.mem_valid == 0, "corrupt magic leaves mem_valid=0");
    blob[0] ^= 0xff; /* restore */

    /* ---- 3. truncated DTB fails loud ---- */
    st = kido_mem_discover(blob, 60, &bi);
    CHECK(st == KIDO_ERR_NO_MEMORY, "truncated DTB -> NO_MEMORY");
    CHECK(bi.mem_valid == 0, "truncated DTB leaves mem_valid=0");

    /* ---- 4. NULL guards ---- */
    CHECK(kido_mem_discover(NULL, 100, &bi) == KIDO_ERR_NO_MEMORY,
          "NULL dtb -> NO_MEMORY");
    CHECK(kido_mem_discover(blob, len, NULL) == KIDO_ERR_NO_MEMORY,
          "NULL bi -> NO_MEMORY");

    /* ---- 5. no memory node ---- */
    tb_begin(&t);
    tb_root(&t);
    tb_begin_node(&t, "cpus");
    tb_end_node(&t);
    tb_end_node(&t);
    len = tb_assemble(&t, blob, NULL, NULL, 0);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_ERR_NO_MEMORY, "no memory node -> NO_MEMORY");

    /* ---- 6. disabled memory node is skipped ---- */
    tb_begin(&t);
    tb_root(&t);
    tb_begin_node(&t, "memory@40000000");
    tb_prop_str(&t, "device_type", "memory");
    tb_prop_str(&t, "status", "disabled");
    tb_prop_reg2(&t, 0x40000000ull, 0x20000000ull);
    tb_end_node(&t);
    tb_end_node(&t);
    len = tb_assemble(&t, blob, NULL, NULL, 0);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_ERR_NO_MEMORY, "disabled memory node skipped");

    /* ---- 7. reserved-memory subtree excluded ---- */
    tb_begin(&t);
    tb_root(&t);
    tb_begin_node(&t, "memory@40000000");
    tb_prop_str(&t, "device_type", "memory");
    tb_prop_reg2(&t, 0x40000000ull, 0x20000000ull);
    tb_end_node(&t);
    tb_begin_node(&t, "reserved-memory");
    tb_begin_node(&t, "memory@50000000");
    tb_prop_str(&t, "device_type", "memory");
    tb_prop_reg2(&t, 0x50000000ull, 0x01000000ull);
    tb_end_node(&t);
    tb_end_node(&t);
    tb_end_node(&t);
    len = tb_assemble(&t, blob, NULL, NULL, 0);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK, "reserved-memory sibling does not break walk");
    CHECK(kido_mem_region_count() == 1,
          "reserved-memory child NOT counted as a region");

    /* ---- 8. device_type identifies a non-"memory@" node ---- */
    tb_begin(&t);
    tb_root(&t);
    tb_begin_node(&t, "ram@60000000");
    tb_prop_str(&t, "device_type", "memory");
    tb_prop_reg2(&t, 0x60000000ull, 0x08000000ull);
    tb_end_node(&t);
    tb_end_node(&t);
    len = tb_assemble(&t, blob, NULL, NULL, 0);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK && bi.mem_base == 0x60000000ull,
          "device_type=memory identifies ram@ node");

    /* ---- 9. leading /memreserve/ trims the base upward ---- */
    {
        uint64_t rb[1] = { 0x40000000ull };
        uint64_t rs[1] = { 0x00010000ull }; /* 64 KiB at region start */
        tb_begin(&t);
        tb_root(&t);
        tb_begin_node(&t, "memory@40000000");
        tb_prop_str(&t, "device_type", "memory");
        tb_prop_reg2(&t, 0x40000000ull, 0x20000000ull);
        tb_end_node(&t);
        tb_end_node(&t);
        len = tb_assemble(&t, blob, rb, rs, 1);
        st = kido_mem_discover(blob, len, &bi);
        CHECK(st == KIDO_OK, "leading reservation still discovers");
        CHECK(bi.mem_base == 0x40010000ull &&
              bi.mem_size == 0x20000000ull - 0x10000ull,
              "leading reservation trims base upward");
    }

    /* ---- 10. interior /memreserve/ fails LOUD ---- */
    {
        uint64_t rb[1] = { 0x41000000ull };
        uint64_t rs[1] = { 0x00010000ull }; /* hole inside the region */
        tb_begin(&t);
        tb_root(&t);
        tb_begin_node(&t, "memory@40000000");
        tb_prop_str(&t, "device_type", "memory");
        tb_prop_reg2(&t, 0x40000000ull, 0x20000000ull);
        tb_end_node(&t);
        tb_end_node(&t);
        len = tb_assemble(&t, blob, rb, rs, 1);
        st = kido_mem_discover(blob, len, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY,
              "interior reservation fails loud (no silent hole)");
        CHECK(bi.mem_valid == 0, "interior reservation leaves mem_valid=0");
    }

    /* ---- 11. UEFI: arg guards (replaces the old stub test) ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, 0x8000ull);
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(NULL, u.len, 40, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI NULL map fails loud");
        CHECK(bi.mem_valid == 0, "UEFI NULL map clears mem_valid");
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, NULL);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI NULL bi fails loud");
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, 0, 40, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI empty map fails loud");
        CHECK(bi.mem_valid == 0, "UEFI empty map clears mem_valid");
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, u.len, 40, 2, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI version 2 fails loud");
        CHECK(bi.mem_valid == 0, "UEFI version 2 clears mem_valid");
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, u.len, 32, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI short stride fails loud");
        CHECK(bi.mem_valid == 0, "UEFI short stride clears mem_valid");
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, u.len + 7, 40, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI ragged map fails loud");
        CHECK(bi.mem_valid == 0, "UEFI ragged map clears mem_valid");
    }

    /* ---- 12. DTB extent strictly interior: region splits in two ---- */
    kido_mem_test_set_dtb_extent(0x50000000ull, 0x00010000ull);
    len = tb_one_region(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK, "interior DTB extent still discovers");
    CHECK(kido_mem_region_count() == 2,
          "interior extent splits one region into two");
    CHECK(region_is(0, 0x40000000ull, 0x10000000ull),
          "head survivor [0x40000000, 0x50000000)");
    CHECK(region_is(1, 0x50010000ull, 0x0FFF0000ull),
          "tail survivor [0x50010000, 0x60000000)");
    CHECK(bi.mem_base == 0x40000000ull && bi.mem_size == 0x10000000ull,
          "primary is the largest trimmed piece");

    /* ---- 13. DTB extent at the region head: base shifts upward ---- */
    kido_mem_test_set_dtb_extent(0x40000000ull, 0x00010000ull);
    len = tb_one_region(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK, "head DTB extent still discovers");
    CHECK(kido_mem_region_count() == 1, "head extent: one survivor");
    CHECK(region_is(0, 0x40010000ull, 0x1FFF0000ull),
          "head extent: base shifts upward past it");
    CHECK(bi.mem_base == 0x40010000ull && bi.mem_size == 0x1FFF0000ull,
          "head extent: primary trimmed at head");

    /* ---- 14. DTB extent at the region tail: size shrinks ---- */
    kido_mem_test_set_dtb_extent(0x5FFF0000ull, 0x00010000ull);
    len = tb_one_region(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK, "tail DTB extent still discovers");
    CHECK(kido_mem_region_count() == 1, "tail extent: one survivor");
    CHECK(region_is(0, 0x40000000ull, 0x1FFF0000ull),
          "tail extent: size shrinks to the extent base");
    CHECK(bi.mem_base == 0x40000000ull && bi.mem_size == 0x1FFF0000ull,
          "tail extent: primary trimmed at tail");

    /* ---- 15. DTB extent covering the whole region: loud ---- */
    kido_mem_test_set_dtb_extent(0x40000000ull, 0x20000000ull);
    len = tb_one_region(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_ERR_NO_MEMORY,
          "DTB covering the whole region -> NO_MEMORY");
    CHECK(bi.mem_valid == 0, "full cover leaves mem_valid=0");

    /* ---- 16. DTB extent outside all regions: no-op ---- */
    kido_mem_test_set_dtb_extent(0x70000000ull, 0x00010000ull);
    len = tb_two_regions(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK, "non-overlapping extent still discovers");
    CHECK(kido_mem_region_count() == 2,
          "no overlap: region count unchanged");
    CHECK(region_is(0, 0x40000000ull, 0x20000000ull) &&
          region_is(1, 0x80000000ull, 0x10000000ull),
          "no overlap: regions byte-identical");
    CHECK(bi.mem_base == 0x40000000ull && bi.mem_size == 0x20000000ull,
          "no overlap: primary untrimmed");

    /* ---- 17. DTB extent straddling two regions: both trimmed ---- */
    kido_mem_test_set_dtb_extent(0x5FF00000ull, 0x20110000ull);
    len = tb_two_regions(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK, "straddling extent still discovers");
    CHECK(kido_mem_region_count() == 2, "straddle: still two regions");
    CHECK(region_is(0, 0x40000000ull, 0x1FF00000ull),
          "straddle: first region tail-trimmed");
    CHECK(region_is(1, 0x80010000ull, 0x0FFF0000ull),
          "straddle: second region head-trimmed");
    CHECK(bi.mem_base == 0x40000000ull && bi.mem_size == 0x1FF00000ull,
          "straddle: primary is the trimmed largest");

    /* ---- 18. zero-size extent: vacuous no-op ---- */
    kido_mem_test_set_dtb_extent(0x50000000ull, 0u);
    len = tb_one_region(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK && kido_mem_region_count() == 1,
          "zero-size extent: no-op");
    CHECK(region_is(0, 0x40000000ull, 0x20000000ull),
          "zero-size extent: region raw");

    /* ---- 19. DTB kills the largest region: primary falls through -- */
    kido_mem_test_set_dtb_extent(0x40000000ull, 0x20000000ull);
    len = tb_two_regions(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK, "killed largest still discovers");
    CHECK(kido_mem_region_count() == 1, "killed largest: region dropped");
    CHECK(bi.mem_base == 0x80000000ull && bi.mem_size == 0x10000000ull,
          "primary falls to the surviving region");

    /* ---- 20. injector reset: vacuous default, raw behavior ---- */
    kido_mem_test_set_dtb_extent(0u, 0u);
    len = tb_two_regions(&t, blob);
    st = kido_mem_discover(blob, len, &bi);
    CHECK(st == KIDO_OK && kido_mem_region_count() == 2,
          "injector reset: vacuous default");
    CHECK(bi.mem_base == 0x40000000ull && bi.mem_size == 0x20000000ull,
          "injector reset: raw primary");

    /* ---- 21. UEFI: mixed map classifies, largest wins ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_RESERVED,     0x00000000ull, 0x100ull);
        uefi_tb_desc(&u, KIDO_UEFI_MMIO,         0x09000000ull, 0x100ull);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, 0x8000ull);
        uefi_tb_desc(&u, KIDO_UEFI_BS_DATA,      0x50000000ull, 0x1000ull);
        uefi_tb_desc(&u, KIDO_UEFI_BS_CODE,      0x60000000ull, 0x1000ull);
        uefi_tb_desc(&u, KIDO_UEFI_ACPI_RECLAIM, 0x70000000ull, 0x1000ull);
        uefi_tb_desc(&u, KIDO_UEFI_PERSISTENT,   0x80000000ull, 0x2000ull);
        uefi_tb_desc(&u, KIDO_UEFI_LOADER_DATA,  0x90000000ull, 0x800ull);
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_OK, "UEFI mixed map discovers");
        CHECK(kido_mem_region_count() == 3,
              "UEFI seeds conventional + 2 BootServices");
        CHECK(region_is(0, 0x40000000ull, 0x08000000ull),
              "UEFI conventional region (128 MiB)");
        CHECK(region_is(1, 0x50000000ull, 0x01000000ull),
              "UEFI BootServices data region (16 MiB)");
        CHECK(region_is(2, 0x60000000ull, 0x01000000ull),
              "UEFI BootServices code region (16 MiB)");
        CHECK(bi.mem_valid == 1 && bi.mem_base == 0x40000000ull &&
              bi.mem_size == 0x08000000ull,
              "UEFI primary is the largest");
    }

    /* ---- 22. UEFI: all-excluded map fails loud ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_RESERVED, 0x40000000ull, 0x8000ull);
        uefi_tb_desc(&u, KIDO_UEFI_MMIO,     0x09000000ull, 0x100ull);
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI all-excluded fails loud");
        CHECK(bi.mem_valid == 0, "UEFI all-excluded clears mem_valid");
    }

    /* ---- 23. UEFI: zero-page entry is a no-op ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, 0);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x50000000ull, 0x1000ull);
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_OK, "UEFI zero-page entry still discovers");
        CHECK(kido_mem_region_count() == 1, "UEFI zero-page entry skipped");
        CHECK(region_is(0, 0x50000000ull, 0x01000000ull),
              "UEFI survivor intact");
    }

    /* ---- 24. UEFI: page-count and address overflow fail loud ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, UINT64_MAX);
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY,
              "UEFI page-count overflow fails loud");
        CHECK(bi.mem_valid == 0,
              "UEFI page-count overflow clears mem_valid");
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0xFFFFFFFFFFFFF000ull, 2);
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI address wrap fails loud");
        CHECK(bi.mem_valid == 0, "UEFI address wrap clears mem_valid");
    }

    /* ---- 25. UEFI: adjacent usable regions coalesce ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, 0x8000ull);
        uefi_tb_desc(&u, KIDO_UEFI_BS_DATA,      0x48000000ull, 0x1000ull);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x60000000ull, 0x1000ull);
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_OK, "UEFI coalescing map discovers");
        CHECK(kido_mem_region_count() == 2, "UEFI adjacent pair coalesced");
        CHECK(region_is(0, 0x40000000ull, 0x09000000ull),
              "UEFI coalesced [0x40000000, 144 MiB)");
        CHECK(region_is(1, 0x60000000ull, 0x01000000ull),
              "UEFI apart region intact");
        CHECK(bi.mem_base == 0x40000000ull && bi.mem_size == 0x09000000ull,
              "UEFI primary is the coalesced region");
    }

    /* ---- 26. UEFI: overlapping descriptors fail loud ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, 0x8000ull);
        uefi_tb_desc(&u, KIDO_UEFI_BS_DATA,      0x47000000ull, 0x1000ull);
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI overlap fails loud");
        CHECK(bi.mem_valid == 0, "UEFI overlap clears mem_valid");
    }

    /* ---- 27. UEFI: entry-count bound is loud ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        int k;
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        for (k = 0; k < 65; k++)
            uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL,
                         0x40000000ull + (uint64_t)k * 0x2000000ull,
                         0x1000ull);
        bi.mem_valid = 1;
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_ERR_NO_MEMORY, "UEFI 65 entries fails loud");
        CHECK(bi.mem_valid == 0, "UEFI entry bound clears mem_valid");
    }

    /* ---- 28. UEFI: unknown type is skipped, never loud ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, 0xF0000000u,          0x40000000ull, 0x8000ull);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x50000000ull, 0x1000ull);
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_OK, "UEFI unknown type still discovers");
        CHECK(kido_mem_region_count() == 1, "UEFI unknown type skipped");
        CHECK(bi.mem_base == 0x50000000ull,
              "UEFI primary skips the unknown type");
    }

    /* ---- 29. UEFI: wider stride parses the v1 prefix ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 48);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, 0x8000ull);
        st = kido_mem_discover_uefi(umap, u.len, 48, 1, &bi);
        CHECK(st == KIDO_OK, "UEFI stride-48 map discovers");
        CHECK(kido_mem_region_count() == 1 &&
              region_is(0, 0x40000000ull, 0x08000000ull),
              "UEFI stride-48 region intact");
    }

    /* ---- 30. UEFI: a larger BootServices region becomes primary ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, 0x8000ull);
        uefi_tb_desc(&u, KIDO_UEFI_BS_DATA,      0x50000000ull, 0x10000ull);
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_OK, "UEFI BS-large map discovers");
        CHECK(bi.mem_base == 0x50000000ull && bi.mem_size == 0x10000000ull,
              "UEFI primary is the larger BootServices region");
    }

    /* ---- 31. UEFI: the map buffer's own extent is trimmed ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uint64_t ubase = (uint64_t)(uintptr_t)umap;
        uint64_t ulo = ubase > 0x100000ull ? ubase - 0x100000ull : 0;
        uint64_t uhi = ubase + (uint64_t)sizeof(umap) + 0x100000ull;
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        /* One conventional region straddling the REAL buffer address:
         * the shared trimmer runs on real addresses, not fixtures. */
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, ulo, (uhi - ulo) >> 12);
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_OK, "UEFI buffer-straddle discovers");
        CHECK(kido_mem_region_count() == 2,
              "UEFI buffer extent splits the region");
        CHECK(region_is(0, ulo, ubase - ulo),
              "UEFI head survivor ends at the buffer");
        CHECK(region_is(1, ubase + (uint64_t)u.len,
                        uhi - (ubase + (uint64_t)u.len)),
              "UEFI tail survivor starts past the buffer");
    }

    /* ---- 32. UEFI: unsorted input still sorts and coalesces ---- */
    {
        uefi_tb_t u;
        static uint8_t umap[4096];
        uefi_tb_begin(&u, umap, sizeof(umap), 40);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x60000000ull, 0x1000ull);
        uefi_tb_desc(&u, KIDO_UEFI_CONVENTIONAL, 0x40000000ull, 0x8000ull);
        uefi_tb_desc(&u, KIDO_UEFI_BS_DATA,      0x48000000ull, 0x1000ull);
        st = kido_mem_discover_uefi(umap, u.len, 40, 1, &bi);
        CHECK(st == KIDO_OK, "UEFI unsorted map discovers");
        CHECK(kido_mem_region_count() == 2, "UEFI unsorted coalesces");
        CHECK(region_is(0, 0x40000000ull, 0x09000000ull),
              "UEFI sorted+coalesced head region");
        CHECK(region_is(1, 0x60000000ull, 0x01000000ull),
              "UEFI sorted tail region");
    }

    printf(g_failures == 0 ? "[test] ALL PASS\n" : "[test] %d FAILURES\n",
           g_failures);
    return g_failures == 0 ? 0 : 1;
}
#endif /* KIDO_MEM_SELFTEST */
