/*
 * kido-image.c — Kido kernel-image bounds.
 *
 * The one honest answer to "where does the kernel live": the linker
 * script's _image_start/_image_end on bare metal; an explicit test
 * injection on hosted (where no image exists). kido_sched_init feeds
 * these bounds to kido_alloc_init's reservation, closing sched D2.
 *
 * Design (deliberations/2026-10-16-kido-image-design.md):
 *  P1 one query, no coupling — the only new seam.
 *  P2 symbols are the truth — no doubles, no fallbacks on bare metal.
 *  P3 the boot stack is image (script places _image_end after it).
 *  P4 hosted: no image -> vacuous reservation, declared not faked.
 *  P5 link-at-load law — stated, not enforced (dissent D1).
 *
 * TESTING: KIDO_HOSTED_TEST builds the hosted path + self-test.
 *  gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST \
 *      -DKIDO_IMAGE_SELFTEST modules/kido-image.c modules/kido-reloc.c \
 *      -o /tmp/kido-image-test
 * (kido-reloc.c: the actual-bounds query reads kido_reloc_last(); the
 * test injects deltas via kido_reloc_test_set_delta.)
 * Cross (ARM64, symbol check): aarch64-linux-gnu-gcc -ffreestanding -c
 *  modules/kido-image.c  (the _image_start/_image_end references must
 *  assemble; resolution is proven at link time against the script)
 */

#include "kido-image.h"
#include "kido-reloc.h"  /* actual base: linked + last-delta (phase 2) */

#if defined(KIDO_HOSTED_TEST)

/* Hosted: no linked image exists. The test declares the fiction
 * explicitly; an undeclared query refuses loudly. */
static int      image_test_injected = 0;
static uint64_t image_test_base    = 0u;
static uint64_t image_test_size    = 0u;

kido_status_t kido_image_test_set_bounds(uint64_t base, uint64_t size)
{
    if (size == 0u)
        return KIDO_ERR_EARLY_ENV;  /* a zero-size image is nonsense */
    if (base + size < base)
        return KIDO_ERR_EARLY_ENV;  /* overflow: loud */
    image_test_base    = base;
    image_test_size    = size;
    image_test_injected = 1;
    return KIDO_OK;
}

kido_status_t kido_image_bounds(uint64_t *base_out, uint64_t *size_out)
{
    if (base_out == NULL || size_out == NULL)
        return KIDO_ERR_EARLY_ENV;
    if (!image_test_injected)
        return KIDO_ERR_STUB_REACHED;  /* no image on hosted: declared */
    *base_out = image_test_base;
    *size_out = image_test_size;
    return KIDO_OK;
}

#else /* bare metal: the linker script owns the truth */

/* Defined by kido-link-arm64.ld. `char` is the standard idiom: only
 * the addresses are meaningful, never the contents. */
extern char _image_start;
extern char _image_end;

kido_status_t kido_image_bounds(uint64_t *base_out, uint64_t *size_out)
{
    uintptr_t s, e;

    if (base_out == NULL || size_out == NULL)
        return KIDO_ERR_EARLY_ENV;
    s = (uintptr_t)&_image_start;
    e = (uintptr_t)&_image_end;
    if (e <= s)
        return KIDO_ERR_EARLY_ENV;  /* mislinked image: loud */
    *base_out = (uint64_t)s;
    *size_out = (uint64_t)(e - s);
    return KIDO_OK;
}

#endif /* KIDO_HOSTED_TEST */

/* The actual base, phase 3.
 *
 * Bare metal: the entry .S fixed up every GOT-based access before C
 * ran, so kido_image_bounds() already reads the ACTUAL location —
 * the thin alias kept for API stability (kido_sched_init's contract
 * is unchanged; the reservation follows the real image).
 *
 * Hosted: no fixup exists. The injected base is the linked base
 * (declared fiction) and the actual base is linked + the relocation
 * delta from kido_reloc_last() — one query, no duplicated
 * measurement. Size is invariant under translation. A hostile delta
 * that under/overflows the base fails LOUD — the allocator must
 * never carve from a wrapped address. */
kido_status_t kido_image_actual_bounds(uint64_t *base_out,
                                       uint64_t *size_out)
{
#if !defined(KIDO_HOSTED_TEST)
    /* Phase 3: bounds() is already actual (GOT fixed by the .S). */
    return kido_image_bounds(base_out, size_out);
#else
    kido_status_t st = kido_image_bounds(base_out, size_out);
    int64_t delta;
    uint64_t base;

    if (st != KIDO_OK)
        return st;
    delta = kido_reloc_last()->delta;
    if (delta == 0)
        return KIDO_OK;  /* the common path: linked == actual */
    base = *base_out;
    if (delta > 0) {
        /* Overflow of the shifted base: loud. */
        if (base > UINT64_MAX - (uint64_t)delta)
            return KIDO_ERR_EARLY_ENV;
        *base_out = base + (uint64_t)delta;
    } else {
        /* Underflow of the shifted base: loud. The -(delta+1)+1
         * dance avoids UB when delta == INT64_MIN. */
        uint64_t ad = (uint64_t)(-(delta + 1)) + 1u;
        if (ad > base)
            return KIDO_ERR_EARLY_ENV;
        *base_out = base - ad;
    }
    return KIDO_OK;
#endif
}

#ifdef KIDO_IMAGE_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_IMAGE_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)

int main(void)
{
    uint64_t base = 0u, size = 0u;
    kido_reloc_info_t info;  /* detect() populates kido_reloc_last(),
                                mirroring the entry's real call order:
                                detect (verify) before actual_bounds */

    printf("== kido-image self-test (hosted) ==\n");

    /* 1-2: NULL guards are loud */
    CHECK(kido_image_bounds(NULL, &size) == KIDO_ERR_EARLY_ENV,
          "NULL base_out -> EARLY_ENV");
    CHECK(kido_image_bounds(&base, NULL) == KIDO_ERR_EARLY_ENV,
          "NULL size_out -> EARLY_ENV");

    /* 3: uninjected query refuses — hosted has no image (P4) */
    CHECK(kido_image_bounds(&base, &size) == KIDO_ERR_STUB_REACHED,
          "uninjected -> STUB_REACHED (no image on hosted)");

    /* 4-5: bad injections are loud */
    CHECK(kido_image_test_set_bounds(0x40000000u, 0u) == KIDO_ERR_EARLY_ENV,
          "zero-size injection -> EARLY_ENV");
    CHECK(kido_image_test_set_bounds(0xFFFFFFFFFFFFFFF0u, 0x20u) == KIDO_ERR_EARLY_ENV,
          "overflowing injection -> EARLY_ENV");

    /* 6-7: injection is returned exactly */
    CHECK(kido_image_test_set_bounds(0x40000000u, 0x10000u) == KIDO_OK,
          "inject (0x40000000, 64KiB) -> OK");
    CHECK(kido_image_bounds(&base, &size) == KIDO_OK &&
          base == 0x40000000u && size == 0x10000u,
          "bounds return the injected values exactly");

    /* 8-9: re-injection replaces (test-harness state, not kernel state) */
    CHECK(kido_image_test_set_bounds(0x50000000u, 0x2000u) == KIDO_OK,
          "re-inject -> OK");
    CHECK(kido_image_bounds(&base, &size) == KIDO_OK &&
          base == 0x50000000u && size == 0x2000u,
          "bounds track the latest injection");

    /* 10: actual bounds with no reloc delta -> linked == actual */
    CHECK(kido_image_actual_bounds(&base, &size) == KIDO_OK &&
          base == 0x50000000u && size == 0x2000u,
          "actual, delta 0 -> linked == actual");

    /* 11-12: injected deltas shift the actual base exactly.
     * detect() runs after each injection — the entry's real order
     * (verify before sched_init) is what populates kido_reloc_last. */
    CHECK(kido_reloc_test_set_delta(0x1000) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK &&
          kido_image_actual_bounds(&base, &size) == KIDO_OK &&
          base == 0x50001000u && size == 0x2000u,
          "actual, delta +0x1000 -> base shifted exactly");
    CHECK(kido_reloc_test_set_delta(-0x1000) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK &&
          kido_image_actual_bounds(&base, &size) == KIDO_OK &&
          base == 0x4FFFF000u && size == 0x2000u,
          "actual, delta -0x1000 -> base shifted exactly");

    /* 13: NULL guards on the actual query are loud */
    CHECK(kido_image_actual_bounds(NULL, &size) == KIDO_ERR_EARLY_ENV,
          "actual NULL base_out -> EARLY_ENV");

    /* 14: underflowing shift fails LOUD, never wraps */
    CHECK(kido_image_test_set_bounds(0x1000u, 0x1000u) == KIDO_OK &&
          kido_reloc_test_set_delta(-0x2000) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK &&
          kido_image_actual_bounds(&base, &size) == KIDO_ERR_EARLY_ENV,
          "actual, delta underflows base -> EARLY_ENV (loud)");

    /* 15: overflowing shift fails LOUD, never wraps */
    CHECK(kido_image_test_set_bounds(0xFFFFFFFFFFFFFE00u, 0x100u) == KIDO_OK &&
          kido_reloc_test_set_delta(0x200) == KIDO_OK &&
          kido_reloc_detect(&info) == KIDO_OK &&
          kido_image_actual_bounds(&base, &size) == KIDO_ERR_EARLY_ENV,
          "actual, delta overflows base -> EARLY_ENV (loud)");

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