/*
 * kido-entry-arm64.c — Kido ARM64 entry shim, C continuation.
 *
 * _start (kido-entry-arm64.S) has already: dropped to EL1, set the
 * stack, zeroed BSS. This file fills kido_bootinfo_t from the firmware
 * handoff, then calls kido_boot(). If boot ever returns, halt LOUD.
 *
 * WHAT IS REAL vs STUB (deliberated 2026-10-14, integrated 2026-10-14):
 *  REAL: DTB-magic verification (0xd00dfeed), totalsize sanity cap,
 *        memory-map discovery via kido_mem_discover (Gate-approved),
 *        bootinfo fill shape, board assumption as a documented
 *        constant, the never-returns contract (kido_boot -> kido_halt),
 *        the relocation tripwire (2026-10-17): kido_reloc_verify() runs
 *        before anything else in C. Phase 3 (2026-10-19): the entry
 *        .S now FIXES UP the image before C runs (walks .rela.dyn,
 *        applies R_AARCH64_RELATIVE, carves out the probe constant;
 *        BSS zeroed at actual bounds), so verify()'s gated policy can
 *        let a relocated image PROCEED — but the gate defaults
 *        CLOSED (no audit stamp), so today a relocated image still
 *        halts LOUD here, now with fixed-up addresses. The wiring
 *        line below is UNCHANGED: phase 3 lives inside verify() and
 *        in the .S.
 *  STUB (loud): board DETECTION (assumes QEMU virt; kido-mem replaces
 *        with a DTB compatible-string parse). A DTB that fails magic
 *        or totalsize validation, or that kido_mem_discover rejects,
 *        leaves mem_valid=0 -> the HAL prober fails loud downstream.
 *
 * The filled bootinfo is kept in the shim's BSS for kido-mem and for
 * the pending one-line wiring of kido_hal_arm64_fill() into boot's
 * adapt stage — both read it via kido_entry_bootinfo().
 *
 * TESTING: KIDO_HOSTED_TEST builds a test double of the fill/DTB logic
 * (+KIDO_ENTRY_ARM64_SELFTEST for a runnable self-test). The .S path
 * is proven by assembling + linking for aarch64 and booting the ELF
 * under qemu-system-aarch64; the approved kido_boot_early() stack/BSS
 * checks are the shim's integration test on real hardware.
 */

#include "kido-entry-arm64.h"
#include "kido-mem.h"  /* DTB discovery: the queued integration (2026-10-14) */
#include "kido-reloc.h"  /* relocation tripwire: earliest C check (2026-10-17) */

/* FDT magic 0xd00dfeed is big-endian on the wire; a little-endian
 * ARM64 word-read of a valid DTB yields the byte-swapped constant. */
#define KIDO_FDT_MAGIC_LE 0xedfe0dd0u

/* FDT header: totalsize is a big-endian u32 at offset 4. Manual byte
 * load — the DTB format is big-endian by specification. */
#define KIDO_FDT_TOTALSIZE_OFF 4u
#define KIDO_FDT_MAX_SIZE (1u << 20)  /* 1 MiB sanity cap; virt DTB is ~5 KiB */

static uint32_t kido_entry_fdt_totalsize(const uint8_t *dtb)
{
    return ((uint32_t)dtb[KIDO_FDT_TOTALSIZE_OFF] << 24) |
           ((uint32_t)dtb[KIDO_FDT_TOTALSIZE_OFF + 1] << 16) |
           ((uint32_t)dtb[KIDO_FDT_TOTALSIZE_OFF + 2] << 8) |
           (uint32_t)dtb[KIDO_FDT_TOTALSIZE_OFF + 3];
}

static kido_bootinfo_t kido_entry_bi;      /* filled once, read by many */
static uint64_t        kido_entry_dtb = 0u;
static uint8_t         kido_entry_dtb_ok = 0u;

kido_status_t kido_entry_fill_bootinfo(uint64_t dtb_ptr,
                                       kido_bootinfo_t *bi)
{
    if (bi == NULL)
        return KIDO_ERR_EARLY_ENV;

    /* LOUD ASSUMPTION: this image is built for the QEMU virt -kernel
     * path, whose board table entry is real. kido-mem replaces this
     * constant with a DTB compatible-string parse. An unknown board
     * is refused by the HAL at fill() time — never guessed here. */
    bi->board_id  = KIDO_BOARD_QEMU_VIRT;

    /* Memory map: the queued integration (2026-10-14). The DTB parser
     * (kido-mem, Gate-approved) fills the map when the firmware DTB
     * validates; any failure leaves mem_valid == 0 and the HAL prober
     * fails LOUD downstream. Nothing is invented here. */
    bi->mem_base  = 0u;
    bi->mem_size  = 0u;
    bi->mem_valid = 0u;

    kido_entry_dtb    = dtb_ptr;
    kido_entry_dtb_ok = 0u;
    if (dtb_ptr != 0u) {
        /* MMU is off: physical == virtual, identity-mapped RAM. */
        uint32_t magic =
            *(volatile uint32_t *)(uintptr_t)dtb_ptr;
        if (magic == KIDO_FDT_MAGIC_LE) {
            const uint8_t *dtb = (const uint8_t *)(uintptr_t)dtb_ptr;
            uint32_t totalsize = kido_entry_fdt_totalsize(dtb);
            kido_entry_dtb_ok = 1u;
            if (totalsize >= 48u && totalsize <= KIDO_FDT_MAX_SIZE) {
                /* discover() guarantees mem_valid == 0 on failure. */
                (void)kido_mem_discover(dtb, (size_t)totalsize, bi);
            }
        }
    }
    return KIDO_OK;
}

const kido_bootinfo_t *kido_entry_bootinfo(void)
{
    return &kido_entry_bi;
}

uint64_t kido_entry_dtb_ptr(void)
{
    return kido_entry_dtb;
}

uint8_t kido_entry_dtb_valid(void)
{
    return kido_entry_dtb_ok;
}

void kido_entry_c_main(uint64_t dtb_ptr)
{
    kido_status_t st;

    /* The relocation tripwire (2026-10-17; phase 3 gated 2026-10-19):
     * the earliest C check. verify() = detect() + crosscheck(.S vs C
     * instruments) + policy. The .S already fixed up the image and
     * set a delta-aware SP, so this runs on a real stack under
     * relocation; with the audit gate closed (no stamp) a relocated
     * image fails LOUD here instead of corrupting silently
     * downstream. (verify()'s contract is unchanged: OK or
     * EARLY_ENV — phase 3 lives inside it and in the .S.) */
    st = kido_reloc_verify();
    if (st != KIDO_OK)
        kido_halt(st);

    /* The fill never fails loudly itself; mem_valid=0 carries the
     * loud signal into probe(). A NULL-bi bug would be ours, so we
     * still check the return like every other stage. */
    st = kido_entry_fill_bootinfo(dtb_ptr, &kido_entry_bi);
    if (st != KIDO_OK)
        kido_halt(st);

    st = kido_boot();
    /* Boot returned. A stage failed, or the kernel proper refused the
     * handoff. Either way: LOUD halt. */
    kido_halt(st);
}

/* ------------------------------------------------------------------ */
/* Self-test: proves the fill/DTB contract on the dev machine. Build:  */
/*  gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST              */
/*      -DKIDO_ENTRY_ARM64_SELFTEST kido-entry-arm64.c kido-mem.c       */
/*      kido-reloc.c -o entry-selftest                                  */
/* (kido-boot.c is NOT linked: this TU carries local kido_boot /       */
/* kido_halt / main stubs for the fill/DTB contract only.)             */
/* The never-returns contract and the .S path are proven by the QEMU   */
/* boot (see deliberations); they cannot run hosted.                   */
/* ------------------------------------------------------------------ */
#ifdef KIDO_ENTRY_ARM64_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_ENTRY_ARM64_SELFTEST needs KIDO_HOSTED_TEST."
#endif
#include <stdio.h>
#include <string.h>

/* The self-test exercises the fill/DTB contract only. kido_boot() and
 * kido_halt() are the never-returns path — proven by the QEMU boot,
 * not here — so this TU carries minimal local stubs instead of
 * linking the approved kido-boot.c (whose own hosted main would
 * collide with this one). */
kido_status_t kido_boot(void) { return KIDO_ERR_STUB_REACHED; }
void kido_halt(kido_status_t code)
{
    (void)code;
    for (;;) {
    }
}

int main(void)
{
    int failures = 0;
    kido_bootinfo_t bi;
    /* Fake DTB: big-endian magic, as on the wire. */
    static uint8_t fake_dtb[16] = {
        0xd0, 0x0d, 0xfe, 0xed, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    };
    static uint8_t junk[16];
    uint64_t dtb_addr = (uint64_t)(uintptr_t)fake_dtb;
    uint64_t junk_addr = (uint64_t)(uintptr_t)junk;

    memset(junk, 0xAA, sizeof(junk));

    /* 1. Valid magic but insane totalsize (16-byte stub) -> accepted
     * as DTB, discover skipped by the totalsize gate, map loud-empty. */
    memset(&bi, 0xAA, sizeof(bi));
    if (kido_entry_fill_bootinfo(dtb_addr, &bi) != KIDO_OK) {
        printf("[FAIL] fill(valid dtb) did not return OK\n");
        failures++;
    }
    if (kido_entry_dtb_valid() != 1u ||
        kido_entry_dtb_ptr() != dtb_addr) {
        printf("[FAIL] valid DTB not recognized/stashed\n");
        failures++;
    }
    if (bi.board_id != KIDO_BOARD_QEMU_VIRT) {
        printf("[FAIL] board assumption wrong\n");
        failures++;
    }
    if (bi.mem_valid != 0u || bi.mem_size != 0u) {
        printf("[FAIL] memory map faked instead of loud-empty\n");
        failures++;
    }

    /* 2. Junk pointer content -> DTB rejected, still loud-empty map. */
    if (kido_entry_fill_bootinfo(junk_addr, &bi) != KIDO_OK ||
        kido_entry_dtb_valid() != 0u) {
        printf("[FAIL] junk DTB not rejected\n");
        failures++;
    }
    if (bi.mem_valid != 0u) {
        printf("[FAIL] junk DTB produced a fake map\n");
        failures++;
    }

    /* 3. NULL DTB -> rejected, no crash, loud-empty map. */
    if (kido_entry_fill_bootinfo(0u, &bi) != KIDO_OK ||
        kido_entry_dtb_valid() != 0u ||
        kido_entry_dtb_ptr() != 0u) {
        printf("[FAIL] NULL DTB handling broken\n");
        failures++;
    }

    /* 4. NULL bi -> EARLY_ENV, never a scribble. */
    if (kido_entry_fill_bootinfo(dtb_addr, NULL) !=
        KIDO_ERR_EARLY_ENV) {
        printf("[FAIL] NULL bi guard broken\n");
        failures++;
    }

    /* 5. Accessor returns the filled struct (kido-mem's read path). */
    kido_entry_fill_bootinfo(dtb_addr, &kido_entry_bi);
    if (kido_entry_bootinfo()->board_id != KIDO_BOARD_QEMU_VIRT ||
        kido_entry_bootinfo()->mem_valid != 0u) {
        printf("[FAIL] bootinfo accessor broken\n");
        failures++;
    }

    printf("[test] entry-arm64 self-test: %s (%d failures)\n",
           failures == 0 ? "PASS" : "FAIL", failures);
    return failures == 0 ? 0 : 1;
}
#endif
