/*
 * kido-reloc.h — Kido relocation detection + adaptation, public interface.
 *
 * Owns image-deliberation D1 (2026-10-16): self-relocation detection
 * was overruled there as out of scope for kido-image — "a future
 * kido-reloc module can own detection." Detection drafted 2026-10-17
 * (session 12); phase-2 adaptation landed 2026-10-17; phase-3
 * self-relocation drafted 2026-10-19 (this session).
 *
 * The equation: delta = runtime(probe) - linked(probe), where the
 * probe is a never-called global function. runtime(probe) is
 * PC-relative (true wherever we run); linked(probe) is a link-time
 * absolute constant in .data.kido_probe_linked (its own section,
 * carved out of the phase-3 fixup walk — it stays LINKED forever).
 * delta != 0 means the image was not loaded at its linked address
 * and the link-at-load law (kido-link-arm64.ld) is broken.
 *
 * HONESTY LAW (phase 3):
 *  - Bare metal (ARM64): detection is REAL (adrp/add inline asm vs
 *    the .rodata absolute constant). 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. After
 *    the walk every GOT-based C access resolves to the ACTUAL
 *    address — so kido_image_bounds() reads ACTUAL, and the LINKED
 *    base is DERIVED as actual - delta (kido-reloc owns the delta;
 *    one query, reversed — the bounds inversion). The .S stashes its
 *    report (total/applied/carved/skipped) in BSS alongside the
 *    phase-2 delta/valid slots.
 *  - The verify() policy FLIP is GATED and defaults CLOSED. The gate
 *    is modules/kido-reloc-audit-stamp.h, written ONLY by
 *    scripts/kido-audit-abs-refs.sh --stamp on a passing image —
 *    NEVER hand-write it. With the gate closed, verify() keeps the
 *    phase-2 contract (delta != 0 -> KIDO_ERR_EARLY_ENV, loud; the
 *    refusal now runs with fixed-up addresses — strictly safer).
 *    With the gate open (audit proved every absolute reference
 *    covered), verify() additionally requires the .S report to
 *    validate (total > 0, skipped == 0, applied+carved+skipped ==
 *    total, carved >= 1) and the probe constant to still read linked
 *    — then a relocated image PROCEEDS. Any check fails -> LOUD,
 *    exactly as before. The tripwire is not deleted; phase 2's
 *    refusal is the fallback, not the policy.
 *  - The entry .S measures the delta independently (adrp/add vs the
 *    probe_literal word — one probe, two instruments) and the C
 *    crosscheck still precedes the policy: disagreement is an
 *    instrument fault (KIDO_ERR_EARLY_ENV, loud). A BSS slot the
 *    .S never wrote (valid == 0) on bare metal is a stale-.S build
 *    inconsistency (loud). Hosted has no .S: valid == 0 is
 *    vacuously OK there.
 *  - Hosted: no linked image, no relocation concept, no fixup. The
 *    bounds inversion does NOT apply — the injected base IS the
 *    linked base (declared fiction) and actual = linked + delta, as
 *    before. detect() refuses KIDO_ERR_STUB_REACHED unless the test
 *    injects a delta. The test writes the BSS report slots directly
 *    to exercise the policy comparator (declared, never a fake .S),
 *    and flips the synthetic probe-ok flag via
 *    kido_reloc_test_set_probe_ok(). The flip-engaged test build
 *    passes -DKIDO_RELOC_AUDIT_PASS on its own compile line only.
 *  - PROOF STATUS: phase-3 gates CLOSED 2026-10-20 (session 18).
 *    .S assembled + readelf + disassembly-verified; audit script
 *    run on the real linked image (PASS 14/5/9, all three link
 *    addresses); QEMU relocated-proceed runs LANDED (+0x80000 and
 *    -0x80000 both proceed to ABCABCABCABC, zero exceptions;
 *    gate-closed control refuses silent). Two draft bugs caught at
 *    the gate and fixed (linker-script manifest bounds; finding-4
 *    refuted -> literal-pool range carve-out). All C logic proven
 *    on hosted (both gate flavors); the C/assembly addressing
 *    split is documented in
 *    deliberations/2026-10-18-kido-phase2-proof-design.md (P2) and
 *    the phase-3 records.
 *
 * Draft status: detection + tripwire + phase-2 environment
 * adaptation real; phase-3 mechanism PROVEN on QEMU (relocated
 * proceed), policy flip gated on the build-time audit (stamp
 * generated per build, never hand-written). Nothing here finalizes
 * a bootable kernel; first boot is N8toriousAi's to witness.
 */
#ifndef KIDO_RELOC_H
#define KIDO_RELOC_H

#include "kido-boot.h"  /* kido_status_t, int64_t via stdint.h */

#if !defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
#error "kido-reloc: ARM64 or hosted only. Define KIDO_HOSTED_TEST for the hosted draft harness."
#endif

/* ------------------------------------------------------------------ */
/* kido_reloc_info_t: the relocation report. delta == 0 means the     */
/* image runs at its linked address. actual_base = linked_base +      */
/* delta (the address the image REALLY starts at). Phase 3: on bare   */
/* metal linked_base is DERIVED as actual_base - delta (the entry .S  */
/* fixed up every GOT access before C ran, so the image query reads   */
/* actual); on hosted the injected base is the linked base and        */
/* actual = linked + delta (declared fiction, no fixup there).        */
/* ------------------------------------------------------------------ */
typedef struct kido_reloc_info {
    int64_t  delta;        /* actual - linked, bytes; 0 = linked at load */
    uint64_t linked_base;  /* bare metal: actual - delta (derived);
                              hosted: the injected base (declared)      */
    uint64_t actual_base;  /* linked_base + delta                        */
} kido_reloc_info_t;

/* ------------------------------------------------------------------ */
/* kido_reloc_detect: fill info_out with the relocation report.       */
/* NULL out -> KIDO_ERR_EARLY_ENV. Bare metal: real detection; a      */
/* mislinked image (kido_image_bounds failure) propagates LOUD        */
/* before any base is trusted; linked_base = actual - delta           */
/* (wrap-guarded, loud on wrap). Hosted: KIDO_ERR_STUB_REACHED        */
/* unless the test injected a delta (linked_base is then a declared   */
/* 0).                                                                */
/* ------------------------------------------------------------------ */
kido_status_t kido_reloc_detect(kido_reloc_info_t *info_out);

/* ------------------------------------------------------------------ */
/* kido_reloc_crosscheck: the .S instrument vs the C instrument.      */
/* (Unchanged from phase 2 — it precedes the policy either way.)      */
/* ------------------------------------------------------------------ */
kido_status_t kido_reloc_crosscheck(const kido_reloc_info_t *info);

/* ------------------------------------------------------------------ */
/* kido_reloc_verify: the tripwire. detect() + crosscheck(); then     */
/* the policy. Gate CLOSED (no audit stamp): delta != 0 ->            */
/* KIDO_ERR_EARLY_ENV (loud) — the phase-2 contract, unchanged.      */
/* Gate OPEN (KIDO_RELOC_AUDIT_PASS, stamp generated by the audit     */
/* script): the .S relocation report must validate (total > 0,        */
/* skipped == 0, applied+carved+skipped == total, carved >= 1) and     */
/* the probe constant must still read linked; then OK — a relocated   */
/* image proceeds. Any failure -> KIDO_ERR_EARLY_ENV, loud.            */
/* Wired at the top of kido_entry_c_main. Contract: OK or EARLY_ENV   */
/* (STUB_REACHED propagates on hosted-uninjected, as before).         */
/* ------------------------------------------------------------------ */
kido_status_t kido_reloc_verify(void);

/* ------------------------------------------------------------------ */
/* kido_reloc_last: the last detect()/verify() report, kept in BSS    */
/* for a future console to print (the delta belongs in the loud      */
/* halt message one day). Never NULL. kido-image reads this for the   */
/* actual-bounds query — one query, no duplicated truth.              */
/* ------------------------------------------------------------------ */
const kido_reloc_info_t *kido_reloc_last(void);

/* ------------------------------------------------------------------ */
/* BSS slots written by the entry .S (kido-entry-arm64.S) before C    */
/* runs: its independent delta measurement + validity flag (phase 2)  */
/* and the phase-3 relocation report (total/applied/carved/skipped).  */
/* Defined here (the delta domain); the .S stores via PC-relative     */
/* adrp, correct wherever the image runs. Hosted: never written by    */
/* any .S — the self-test writes them to exercise the policy          */
/* comparator (declared).                                             */
/* ------------------------------------------------------------------ */
extern int64_t kido_reloc_entry_delta;
extern int64_t kido_reloc_entry_valid;
extern int64_t kido_reloc_fix_total;    /* manifest entries walked      */
extern int64_t kido_reloc_fix_applied;  /* *loc += delta applied        */
extern int64_t kido_reloc_fix_carved;   /* carve-outs taken (stayed linked) */
extern int64_t kido_reloc_fix_skipped;  /* non-RELATIVE entries seen    */

#ifdef KIDO_HOSTED_TEST
/* ------------------------------------------------------------------ */
/* kido_reloc_test_set_delta: inject the fake delta for the hosted    */
/* self-test (exercises the verify policy, never a fake relocation).  */
/* Not compiled on bare metal.                                        */
/* ------------------------------------------------------------------ */
kido_status_t kido_reloc_test_set_delta(int64_t delta);

/* ------------------------------------------------------------------ */
/* kido_reloc_test_set_probe_ok: flip the synthetic probe-still-     */
/* linked input for the hosted self-test. Bare metal runs the real    */
/* check (probe constant word vs runtime probe - delta); hosted has   */
/* no probe constant, so the test drives this flag (declared         */
/* comparator testing). Not compiled on bare metal.                   */
/* ------------------------------------------------------------------ */
void kido_reloc_test_set_probe_ok(int ok);
#endif

#endif /* KIDO_RELOC_H */
