#!/bin/bash
# kido-audit-abs-refs.sh — build-time completeness audit for kido-reloc phase 3.
#
# THE GATE the verify() policy flip waits on
# (deliberations/2026-10-19-kido-phase3-draft-design.md, P6/C6).
# Enumerates every absolute reference in the linked image and FAILS THE
# BUILD on any uncovered one. Covered categories:
#   (i)   .rela.dyn R_AARCH64_RELATIVE -> applied at boot by the entry
#         .S relocator (*loc += delta), except the probe carve-out.
#   (ii)  Entry-.S literal-pool absolute words -> allowlisted below;
#         each names its manual +delta or its by-design-linked status.
#         C code needs no allowlist: same-TU references compile
#         PC-relative (relocation-true by construction) and cross-TU
#         references compile GOT-relative (covered by (i)).
#   (iii) Any non-RELATIVE dynamic relocation -> FAIL, no exceptions.
# NOT scanned (stated openly): movz/movk-built immediates. Under
# -fno-pic the compiler emits adrp/add for symbol addresses
# (session-14 finding 1); integer constants are not addresses. If the
# toolchain ever changes this, extend the audit — the manifest walk
# and the literal allowlist still bound the behavior meanwhile.
#
# Checks:
#   A. Manifest exists, non-empty, inside [_image_start, _image_end).
#   B. Probe section inside the image; exactly one OBJECT symbol lives
#      in it (the probe constant — the carve-out's only occupant).
#   C. Every dynamic relocation is R_AARCH64_RELATIVE. Each r_offset:
#        in the manifest range            -> FAIL (self-target)
#        in the probe-section range       -> carved (stays linked)
#        in the .S literal-pool range     -> carved (stays linked;
#                                           the .S adds delta manually —
#                                           finding 4 refuted 2026-10-20:
#                                           the pool words DO carry
#                                           RELATIVEs, so the range
#                                           carve-out is load-bearing)
#        in .text (outside the pool)      -> FAIL (unexpected absolute)
#        anywhere else (.got/.data/...)   -> applied (patched at boot)
#      Requires total >= 1 and carved >= 1 (fail closed).
#   D. Entry-object allowlist: every R_AARCH64_ABS* relocation in
#      kido-entry-arm64.o must name an allowlisted symbol (below).
#      This pins the .S's manual-+delta contract: each literal either
#      gets +delta at its use or stays linked by design.
#
# Usage: kido-audit-abs-refs.sh <linked-image.elf> <kido-entry-arm64.o> [--stamp]
#   --stamp: on PASS, write modules/kido-reloc-audit-stamp.h — the ONLY
#            way KIDO_RELOC_AUDIT_PASS gets defined. NEVER hand-write
#            the stamp. Build flow: audit -> stamp -> rebuild ->
#            re-audit -> QEMU.
#
# PROOF STATUS (honest): WRITTEN, NOT RUN (2026-10-19) — the cross
# toolchain is absent (VM replacement; session-13 pattern), so no
# linked image exists to audit. The parsing/decision core below is
# fixture-tested (scripts/fixtures/ + scripts/test-audit-fixtures.sh,
# real pass/fail); the thin readelf-invocation layer is untested by
# construction and its exact commands are documented here.
#
set -u

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# ------------------------------------------------------------------
# Parsing / decision functions. Pure: they take file paths, so the
# fixture test can drive them without a toolchain.
# ------------------------------------------------------------------

# sym_val <name> <symtab-file> : hex value (no 0x prefix), or empty.
sym_val() {
    awk -v n="$1" '$8 == n { print $2; exit }' "$2"
}

# sec_addr <name> <sections-file> : hex address (no 0x prefix), or empty.
# Sections file must be bracket-normalized (see analyze): stable fields
# $1="[N]" $2=name $3=type $4=addr $5=off $6=size.
sec_addr() {
    awk -v n="$1" '$2 == n { print $4; exit }' "$2"
}

# sec_size <name> <sections-file> : hex size, or empty.
sec_size() {
    awk -v n="$1" '$2 == n { print $6; exit }' "$2"
}

# sec_index <name> <sections-file> : numeric index, or empty.
sec_index() {
    awk -v n="$1" '$2 == n { gsub(/[\[\]]/, "", $1); print $1; exit }' "$2"
}

# in_range <val> <start> <end> : 0 if start <= val < end (hex, no 0x).
in_range() {
    local v=$((16#$1)) s=$((16#$2)) e=$((16#$3))
    [ "$v" -ge "$s" ] && [ "$v" -lt "$e" ]
}

# Entry-object ABS* allowlist: symbol -> justification.
# Every literal-pool absolute in the hand-written .S must be one of
# these; anything else is an uncovered absolute and fails the build.
allowlisted() {
    case "$1" in
        kido_reloc_probe)  return 0 ;;  # BY DESIGN LINKED: the detector's
                                       # linked instrument (probe_literal word)
        _stack_top)        return 0 ;;  # MANUAL +delta at SP setup
        _bss_start)        return 0 ;;  # MANUAL +delta (BSS-at-actual)
        _bss_end)          return 0 ;;  # MANUAL +delta (BSS-at-actual)
        __rela_dyn_start)  return 0 ;;  # MANUAL +delta (manifest walk bounds)
        __rela_dyn_end)    return 0 ;;  # MANUAL +delta (manifest walk bounds)
        __probe_sec_start) return 0 ;;  # MANUAL +delta (carve-out range)
        __probe_sec_end)   return 0 ;;  # MANUAL +delta (carve-out range)
        *)                 return 1 ;;
    esac
}

AUDIT_TOTAL=0
AUDIT_APPLIED=0
AUDIT_CARVED=0

# analyze <symtab> <relocs> <sections> <objrelocs> : run checks A-D.
# Prints the verdict; returns 0 on PASS, 1 on FAIL.
analyze() {
    local symtab="$1" relocs="$2" sections="$3" objrelocs="$4"
    local img_start img_end rela_start rela_end probe_start probe_end
    local got_addr got_size probe_ndx probe_sec_ndx obj_count
    local line off type name

    # Bracket normalization (2026-10-20): readelf -SW prints "[ 2]"
    # (two fields) for single-digit section indices but "[13]" (one
    # field) for double-digit ones, shifting Name/Type/Addr/Off/Size
    # left by one on wide rows. Real images have 20+ sections, so the
    # un-normalized parser silently misread every double-digit row
    # (caught live: ".got section absent" on a present .got). Collapse
    # to "[N]" so the columns sit at $2..$6 on every row.
    local nsec
    nsec=$(mktemp)
    trap "rm -f $nsec" RETURN
    sed -E 's/\[ *([0-9]+)\]/[\1]/' "$sections" > "$nsec"
    sections="$nsec"

    img_start=$(sym_val "_image_start" "$symtab")
    img_end=$(sym_val "_image_end" "$symtab")
    rela_start=$(sym_val "__rela_dyn_start" "$symtab")
    rela_end=$(sym_val "__rela_dyn_end" "$symtab")
    probe_start=$(sym_val "__probe_sec_start" "$symtab")
    probe_end=$(sym_val "__probe_sec_end" "$symtab")
    lit_start=$(sym_val "literal_pool_start" "$symtab")
    lit_end=$(sym_val "literal_pool_end" "$symtab")
    for v in "$img_start" "$img_end" "$rela_start" "$rela_end" \
             "$probe_start" "$probe_end" "$lit_start" "$lit_end"; do
        [ -n "$v" ] || { echo "AUDIT FAIL: required linker symbol absent from symtab"; return 1; }
    done

    # --- Check A: manifest sane and inside the image ---
    if [ "$((16#$rela_start))" -ge "$((16#$rela_end))" ]; then
        echo "AUDIT FAIL: empty manifest (__rela_dyn_start >= __rela_dyn_end)"
        return 1
    fi
    in_range "$rela_start" "$img_start" "$img_end" \
        || { echo "AUDIT FAIL: manifest start outside image bounds"; return 1; }
    in_range "$rela_end" "$img_start" "$img_end" \
        && [ "$((16#$rela_end))" -le "$((16#$img_end))" ] \
        || { echo "AUDIT FAIL: manifest end outside image bounds"; return 1; }

    # --- Check B: probe section inside the image, single occupant ---
    in_range "$probe_start" "$img_start" "$img_end" \
        || { echo "AUDIT FAIL: probe section start outside image bounds"; return 1; }
    [ "$((16#$probe_end))" -le "$((16#$img_end))" ] \
        || { echo "AUDIT FAIL: probe section end outside image bounds"; return 1; }
    probe_sec_ndx=$(sec_index ".data.kido_probe_linked" "$sections")
    [ -n "$probe_sec_ndx" ] || { echo "AUDIT FAIL: .data.kido_probe_linked absent"; return 1; }
    obj_count=$(awk -v ndx="$probe_sec_ndx" '$4 == "OBJECT" && $7 == ndx { c++ } END { print c+0 }' "$symtab")
    [ "$obj_count" -eq 1 ] \
        || { echo "AUDIT FAIL: probe section holds $obj_count OBJECT symbols (want 1)"; return 1; }

    # --- Check C: every dynamic relocation classified ---
    # "Covered" = patched by the walk at boot (applied) or deliberately
    # carved out (stays linked). Anything else fails the build.
    local text_addr text_size text_end
    text_addr=$(sec_addr ".text" "$sections")
    text_size=$(sec_size ".text" "$sections")
    for v in "$lit_start" "$lit_end" "$text_addr" "$text_size"; do
        [ -n "$v" ] || { echo "AUDIT FAIL: literal-pool/.text symbol absent from symtab"; return 1; }
    done
    text_end=$(printf '%x' $((16#$text_addr + 16#$text_size)))

    AUDIT_TOTAL=0; AUDIT_APPLIED=0; AUDIT_CARVED=0
    while IFS= read -r line; do
        case "$line" in [0-9a-f]*) ;; *) continue ;; esac  # data lines only
        off=$(echo "$line" | awk '{ print $1 }')
        type=$(echo "$line" | awk '{ print $3 }')
        [ "$type" = "R_AARCH64_RELATIVE" ] \
            || { echo "AUDIT FAIL: non-RELATIVE dynamic reloc: $type at $off"; return 1; }
        AUDIT_TOTAL=$((AUDIT_TOTAL + 1))
        if in_range "$off" "$rela_start" "$rela_end"; then
            echo "AUDIT FAIL: manifest self-target at $off"
            return 1
        elif in_range "$off" "$probe_start" "$probe_end"; then
            AUDIT_CARVED=$((AUDIT_CARVED + 1))      # probe constant: stays linked
        elif in_range "$off" "$lit_start" "$lit_end"; then
            AUDIT_CARVED=$((AUDIT_CARVED + 1))      # .S literal pool: stays linked;
                                                   # the .S adds delta manually
        elif in_range "$off" "$text_addr" "$text_end"; then
            echo "AUDIT FAIL: unexpected .text absolute at $off (outside the .S literal pool)"
            return 1
        else
            AUDIT_APPLIED=$((AUDIT_APPLIED + 1))    # .got/.data/etc: patched at boot
        fi
    done < "$relocs"

    [ "$AUDIT_TOTAL" -ge 1 ] \
        || { echo "AUDIT FAIL: no dynamic relocations (fail closed)"; return 1; }
    [ "$AUDIT_CARVED" -ge 1 ] \
        || { echo "AUDIT FAIL: carve-out empty (probe entry not manifest-visible)"; return 1; }

    # --- Check D: entry-object ABS* allowlist ---
    while IFS= read -r line; do
        case "$line" in [0-9a-f]*) ;; *) continue ;; esac
        type=$(echo "$line" | awk '{ print $3 }')
        case "$type" in R_AARCH64_ABS*) ;; *) continue ;; esac
        name=$(echo "$line" | awk '{ print $5 }')
        allowlisted "$name" \
            || { echo "AUDIT FAIL: entry object ABS reloc against non-allowlisted '$name'"; return 1; }
    done < "$objrelocs"

    echo "AUDIT PASS: total=$AUDIT_TOTAL applied=$AUDIT_APPLIED carved=$AUDIT_CARVED"
    return 0
}

# write_stamp <image> : emit modules/kido-reloc-audit-stamp.h.
write_stamp() {
    local img="$1"
    local stamp="$SCRIPT_DIR/../modules/kido-reloc-audit-stamp.h"
    local sha
    sha=$(sha256sum "$img" | awk '{ print $1 }')
    cat > "$stamp" <<EOF
/* GENERATED by scripts/kido-audit-abs-refs.sh --stamp on $(date -u +%F).
 * NEVER hand-write this file: its presence defines KIDO_RELOC_AUDIT_PASS
 * and flips kido_reloc_verify() from refuse-loud to relocated-and-fixed-
 * proceed. Audited image: $(basename "$img") sha256=$sha
 * manifest total=$AUDIT_TOTAL applied=$AUDIT_APPLIED carved=$AUDIT_CARVED. */
#ifndef KIDO_RELOC_AUDIT_STAMP_H
#define KIDO_RELOC_AUDIT_STAMP_H
#define KIDO_RELOC_AUDIT_PASS 1
#endif
EOF
    echo "stamp written: $stamp"
}

main() {
    local img="" obj="" stamp=0
    while [ $# -gt 0 ]; do
        case "$1" in
            --stamp) stamp=1; shift ;;
            *) if [ -z "$img" ]; then img="$1"; elif [ -z "$obj" ]; then obj="$1"; else
                   echo "usage: $0 <linked-image.elf> <kido-entry-arm64.o> [--stamp]"; return 2; fi
               shift ;;
        esac
    done
    [ -n "$img" ] && [ -n "$obj" ] \
        || { echo "usage: $0 <linked-image.elf> <kido-entry-arm64.o> [--stamp]"; return 2; }
    for f in "$img" "$obj"; do
        [ -f "$f" ] || { echo "AUDIT FAIL: not a file: $f"; return 1; }
    done
    command -v readelf >/dev/null \
        || { echo "AUDIT FAIL: readelf not found"; return 1; }

    local tmp
    tmp=$(mktemp -d)
    # Thin tool-invocation layer: the exact commands, documented.
    readelf -sW  "$img" > "$tmp/symtab"
    readelf -rW  "$img" > "$tmp/relocs"
    readelf -SW  "$img" > "$tmp/sections"
    readelf -rW  "$obj" > "$tmp/objrelocs"

    analyze "$tmp/symtab" "$tmp/relocs" "$tmp/sections" "$tmp/objrelocs"
    local rc=$?
    rm -rf "$tmp"
    if [ "$rc" -eq 0 ] && [ "$stamp" -eq 1 ]; then
        write_stamp "$img"
    fi
    return "$rc"
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    main "$@"
fi
