#!/bin/bash
# Copyright 2026 ANNE Media - https://anne.media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ============================================================================
# AM·OS Binary Hardening Audit
#
# Scans every .txz/.tgz in a production tree, extracts each package to a
# temporary directory, and verifies the ELF binaries inside against the
# OpenSSF-recommended mitigations:
#
#   PIE      Position-Independent Executable       Type: DYN
#   RELRO    Full RELRO (BIND_NOW, no lazy binding)  GNU_RELRO + BIND_NOW
#   CANARY   Stack protector                       __stack_chk_fail ref OR
#                                                  guard-load instruction
#   FORTIFY  Libc fortify wrappers                 __*_chk ref, or N/A if
#                                                  the binary has no
#                                                  fortifiable calls
#   NX       Non-executable stack                  GNU_STACK without E
#   CET      Intel CET (IBT + SHSTK)               GNU_PROPERTY note
#
# Per-binary checks yield one of three states:
#
#   1  present
#   0  absent   - a real gap
#   -  not applicable - the binary has no code that could carry it
#
# Per-package aggregate adds a fourth state:
#
#   ~  mixed - some binaries carry the mitigation, and one or more are
#      N/A by explicit exception in the FORTIFY, CANARY, or CET table.
#      Distinct from - (every binary N/A) and from a clean pass.
#
# Each package line also carries an inventory:
#
#   [N ELF: N ok, N gap, N exc] [N KO: N ok, N gap, N exc]
#
#   ok   binaries with no real gap (FORTIFY exceptions still count
#        as ok; they are N/A, not gaps)
#   gap  binaries with a real gap, whether accepted via a CET or
#        CANARY exception or unexplained
#   exc  binaries matched against any exception table
#
# A binary passes when it has no 0 after exceptions. N/A is a pass.
# A package passes when no binary has an unexplained 0.
#
# Kernel modules (.ko) are Type: REL relocatable objects. Only two of the
# six checks are meaningful for them: canary and CET. PIE/RELRO/FORTIFY/NX
# are reported as - (N/A). Kernel images (vmlinuz-*) are ordinary ELF
# executables and go through the normal userspace path.
#
# FORTIFY for kernel modules is a build-time property
# (CONFIG_FORTIFY_SOURCE). It leaves no trace in the module ELF: the
# kernel's fortify checks are compile-time (__compiletime_assert,
# -Werror=stringop-overflow), and the rare runtime helper (fortify_panic)
# only appears on the path the compiler could not prove safe. The F
# column is therefore shown as · for every .ko, and the meaningful
# signal is the kernel config line printed under each KO-bearing package.
#
# Architecture handling. Every check in this script is about x86_64 code
# generation. When a file whose e_machine is neither x86_64 nor i386
# reaches audit_elf, every column comes back as - (N/A). The host kernel
# rejects such files at execve on the e_machine field and dlopen rejects
# them for the same reason, so they are never executed on this system.
#
# Exception details live in AUDIT.TXT and are not reprinted on stdout.
# The summary carries the counts; the file is the audit trail.
#
# Parallelism. Packages are processed by a rolling pool of JOBS workers
# (default 4). The launcher uses the shell's own job table to count live
# workers, so a slow package never blocks the others and the pool never
# dispatches more than JOBS packages at once. Each result line is
# prefixed with [N/TOTAL], where N is the cumulative completion counter.
# Set JOBS=1 to force serial execution.
#
# Ctrl-C terminates the entire worker pool: SIGTERM is sent to the
# process group, a moment is allowed for graceful exit, and any
# survivors are force-killed before the script exits.
#
# Usage:
#   audit-hardening.sh [--tree DIR] [--package GLOB] [--json FILE]
#                      [--jobs N] [--quiet] [--no-color] [--include-repacks]
#
# Exit status: 0 if every binary passes, 1 if any fails.
# ============================================================================

set -o pipefail

TREE="/repo/amos64"
JSON_OUT=""
QUIET=0
NO_COLOR=0
INCLUDE_REPACKS=1
PACKAGE_FILTER=""
JOBS="${JOBS:-4}"

# ---------------------------------------------------------------------------
# Exception tables - see AUDIT.TXT for the file format and rationale.
#
# Four entry forms:
#   package_glob|binary_glob|reason              FORTIFY (F = N/A, not a gap)
#   KO_CET: package_glob|module_glob|reason      CET kernel module (T = gap)
#   CET_GAP: package_glob|binary_glob|reason     CET userspace binary (T = gap)
#   CANARY_GAP: package_glob|binary_glob|reason  Canary (C = gap)
#
# FORTIFY exceptions are N/A: the compiler correctly declined to emit a
# check. CET and CANARY exceptions are real gaps: the mitigation is
# genuinely absent and the omission is accepted.
# ---------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
AUDIT_FILE="$SCRIPT_DIR/AUDIT.TXT"

FORTIFY_EXCEPTIONS=()
KO_CET_EXCEPTIONS=()
CANARY_EXCEPTIONS=()

if [ -f "$AUDIT_FILE" ]; then
    while IFS= read -r line || [ -n "$line" ]; do
        line="${line#"${line%%[![:space:]]*}"}"
        line="${line%"${line##*[![:space:]]}"}"
        [ -z "$line" ] && continue
        case "$line" in \#*) continue ;; esac
        case "$line" in
            KO_CET:*|CET_GAP:*)
                rest="${line#*:}"
                rest="${rest#"${rest%%[![:space:]]*}"}"
                KO_CET_EXCEPTIONS+=("$rest")
                ;;
            CANARY_GAP:*)
                rest="${line#*:}"
                rest="${rest#"${rest%%[![:space:]]*}"}"
                CANARY_EXCEPTIONS+=("$rest")
                ;;
            *)
                FORTIFY_EXCEPTIONS+=("$line")
                ;;
        esac
    done < "$AUDIT_FILE"
else
    echo "warning: $AUDIT_FILE not found; no exceptions will be applied" >&2
fi

while [[ $# -gt 0 ]]; do
    case "$1" in
        --tree)             TREE="$2" ; shift 2 ;;
        --json)             JSON_OUT="$2" ; shift 2 ;;
        --jobs)             JOBS="$2" ; shift 2 ;;
        --quiet)            QUIET=1 ; shift ;;
        --no-color)         NO_COLOR=1 ; shift ;;
        --include-repacks)  INCLUDE_REPACKS=1 ; shift ;;
        --package)          PACKAGE_FILTER="$2" ; shift 2 ;;
        -h|--help)
            sed -n '2,110p' "$0" | sed 's/^# \{0,1\}//'
            exit 0
            ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

case "$JOBS" in
    ''|*[!0-9]*) echo "error: --jobs must be a positive integer (got: $JOBS)" >&2; exit 2 ;;
esac
[ "$JOBS" -ge 1 ] || { echo "error: --jobs must be at least 1" >&2; exit 2; }

if [ "$NO_COLOR" = "1" ] || [ ! -t 1 ]; then
    C_RESET=""; C_BOLD=""; C_DIM=""
    C_RED=""; C_GREEN=""; C_YELLOW=""; C_CYAN=""
else
    C_RESET=$'\033[0m'; C_BOLD=$'\033[1m'; C_DIM=$'\033[2m'
    C_RED=$'\033[31m'; C_GREEN=$'\033[32m'; C_YELLOW=$'\033[33m'; C_CYAN=$'\033[36m'
fi

die()  { echo "error: $*" >&2; exit 1; }
warn() { echo "warning: $*" >&2; }

RUNDIR=$(mktemp -d "${TMPDIR:-/tmp}/audit-hardening.XXXXXX")
STATEDIR="$RUNDIR/state"
COUNTER_FILE="$RUNDIR/counter"
mkdir -p "$STATEDIR"
echo 0 > "$COUNTER_FILE"

exec 8>"$RUNDIR/stdout.lock"

on_signal() {
    trap '' INT TERM
    printf '\ninterrupted, terminating workers\n' >&2
    kill -TERM 0 2>/dev/null || true
    local i
    for i in 1 2 3 4 5; do
        local live
        live=$(jobs -rp 2>/dev/null | wc -l)
        [ "$live" -eq 0 ] && break
        sleep 0.2
    done
    local pids
    pids=$(jobs -rp 2>/dev/null)
    if [ -n "$pids" ]; then
        # shellcheck disable=SC2086
        kill -KILL $pids 2>/dev/null || true
    fi
    exit 130
}

on_exit() {
    rm -rf "$RUNDIR" 2>/dev/null || true
}

trap on_signal INT TERM
trap on_exit EXIT

glyphs() {
    local g=""
    for v in "$@"; do
        case "$v" in
            1)   g+="${C_GREEN}✓${C_RESET}" ;;
            0)   g+="${C_RED}✗${C_RESET}" ;;
            -)   g+="${C_DIM}·${C_RESET}" ;;
            "~") g+="${C_YELLOW}~${C_RESET}" ;;
            *)   g+="?" ;;
        esac
    done
    printf '%s' "$g"
}

if ! readelf -hW /bin/true >/dev/null 2>&1; then
    echo "error: readelf is broken on this system:" >&2
    readelf -hW /bin/true 2>&1 | head -3 >&2
    exit 2
fi

has_stack_buffers_disasm() {
    local disasm="$1"
    local window=0
    local re_sym='^[0-9a-f]+ <[^>]*>:'
    local re_lea='lea[[:space:]]+[^,]*(%rsp|%rbp)[^,]*,%(rdi|rsi|rdx|rcx|r8|r9|edi|esi|edx|ecx|r8d|r9d)([[:space:]]|$)'
    local re_callee='call[[:space:]].*<(read|pread|pread64|write|pwrite|pwrite64|recv|recvfrom|recvmsg|send|sendto|sendmsg|memcpy|memmove|memset|memcmp|strcpy|stpcpy|strncpy|strcat|strncat|sprintf|snprintf|vsprintf|vsnprintf|gets|fgets|fgets_unlocked|readlink|readlinkat|getcwd|getwd|getdomainname|gethostname|getlogin_r|ttyname_r|confstr|realpath|asprintf|vasprintf|dprintf|vdprintf|obstack_printf|obstack_vprintf)@'

    while IFS= read -r line; do
        if [[ "$line" =~ $re_sym ]]; then
            window=0
            continue
        fi
        if [ "$window" -gt 0 ]; then
            if [[ "$line" =~ $re_callee ]]; then
                return 0
            fi
            window=$((window - 1))
            continue
        fi
        if [[ "$line" =~ $re_lea ]]; then
            window=5
        fi
    done <<< "$disasm"
    return 1
}

is_glibc_own_binary() {
    local path="$1"
    local bn
    bn=$(basename "$path")

    case "$bn" in
        libcrypt.so.2*) return 1 ;;
    esac

    case "$path" in
        */gconv/*.so) return 0 ;;
    esac

    case "$bn" in
        libnss_*.so*) return 0 ;;
    esac

    case "$bn" in
        libc.so.*|libm.so.*|libpthread.so.*|librt.so.*|libdl.so.*|\
        libutil.so.*|libanl.so.*|libnsl.so.*|libresolv.so.*|\
        libBrokenLocale.so.*|libmvec.so.*|\
        libcrypt.so.1*|libpcprofile.so|libmemusage.so|\
        ld-linux-*.so.*|ld.so|ldconfig|sln|getconf|\
        XBS5_*|POSIX_V6_*|POSIX_V7_*|\
        sprof|pldd|pcprofiledump|sotruss-lib.so)
            return 0 ;;
    esac

    return 1
}

fortify_exception() {
    local pkg="$1" bin="$2"
    local entry p b reason
    for entry in "${FORTIFY_EXCEPTIONS[@]}"; do
        IFS='|' read -r p b reason <<< "$entry"
        [ -z "$p" ] && continue
        # shellcheck disable=SC2053
        if [[ "$pkg" == $p && "$bin" == $b ]]; then
            printf '%s' "$reason"
            return 0
        fi
    done
    return 1
}

cet_exception() {
    local pkg="$1" bin="$2"
    local entry p b reason
    for entry in "${KO_CET_EXCEPTIONS[@]}"; do
        IFS='|' read -r p b reason <<< "$entry"
        [ -z "$p" ] && continue
        # shellcheck disable=SC2053
        if [[ "$pkg" == $p && "$bin" == $b ]]; then
            printf '%s' "$reason"
            return 0
        fi
    done
    return 1
}

canary_exception() {
    local pkg="$1" bin="$2"
    local entry p b reason
    for entry in "${CANARY_EXCEPTIONS[@]}"; do
        IFS='|' read -r p b reason <<< "$entry"
        [ -z "$p" ] && continue
        # shellcheck disable=SC2053
        if [[ "$pkg" == $p && "$bin" == $b ]]; then
            printf '%s' "$reason"
            return 0
        fi
    done
    return 1
}

kernel_config_line() {
    local tmp="$1"
    local cfg
    cfg=$(find "$tmp" -maxdepth 4 -path '*/boot/config-*' -type f 2>/dev/null | head -1)
    [ -n "$cfg" ] || return 1

    local f s i h
    grep -q '^CONFIG_FORTIFY_SOURCE=y'        "$cfg" && f=y || f=n
    grep -q '^CONFIG_STACKPROTECTOR_STRONG=y' "$cfg" && s=y || s=n
    grep -q '^CONFIG_X86_KERNEL_IBT=y'        "$cfg" && i=y || i=n
    grep -q '^CONFIG_X86_USER_SHADOW_STACK=y' "$cfg" && h=y || h=n

    printf 'kernel config: FORTIFY=%s STACKPROTECTOR_STRONG=%s KERNEL_IBT=%s USER_SHADOW_STACK=%s' \
        "$f" "$s" "$i" "$h"
    return 0
}

audit_elf() {
    local b="$1"
    local pkg="$2"
    local hdr lw dyn props syms bn
    bn=$(basename "$b")
    hdr=$(readelf -hW  "$b" 2>/dev/null)

    if ! grep -qE 'Machine:.*(Advanced Micro Devices X86-64|Intel 80386)' <<< "$hdr"; then
        echo "- - - - - -"
        return
    fi

    lw=$(readelf -lW   "$b" 2>/dev/null)
    dyn=$(readelf -dW  "$b" 2>/dev/null)
    props=$(readelf -nW "$b" 2>/dev/null)
    syms=$(readelf -sW --dyn-syms "$b" 2>/dev/null)

    local pie=0 relro=0 canary=0 fortify=0 nx=0 cet=0

    grep -qE 'Type:[[:space:]]+DYN' <<< "$hdr" && pie=1

    grep -q GNU_RELRO <<< "$lw" && grep -q BIND_NOW <<< "$dyn" && relro=1

    local is_stub=0
    if grep -qE 'Type:[[:space:]]+DYN' <<< "$hdr"; then
        local text_hex text_size
        text_hex=$(objdump -h "$b" 2>/dev/null | awk '$2 == ".text" { print $3; exit }')
        if [ -n "$text_hex" ] && [[ "$text_hex" =~ ^[0-9a-fA-F]+$ ]]; then
            text_size=$((16#$text_hex))
            if [ "$text_size" -lt 4096 ]; then
                is_stub=1
            fi
        fi
    fi

    local is_go=0
    if readelf -SW "$b" 2>/dev/null | grep -q 'gopclntab'; then
        is_go=1
    fi

    if grep -qE '__stack_chk_fail(_local)?@' <<< "$syms"; then
        canary=1
    elif [ "$is_stub" = 1 ]; then
        canary=-
    elif [ "$is_go" = 1 ]; then
        canary=-
    else
        local disasm=""
        if command -v objdump >/dev/null 2>&1; then
            disasm=$(objdump -d --no-show-raw-insn "$b" 2>/dev/null)
        fi
        if [ -n "$disasm" ] && grep -qE '%fs:0x28|%gs:0x14' <<< "$disasm"; then
            canary=1
        elif [ -n "$disasm" ] && has_stack_buffers_disasm "$disasm"; then
            canary=0
        else
            canary=-
        fi
    fi

    if grep -qE '__[a-z0-9_]+_chk(@|$)|__open(_64)?_2(@|$)|__openat(_64)?_2(@|$)' <<< "$syms"; then
        fortify=1
    elif is_glibc_own_binary "$b"; then
        fortify=-
    elif fortify_exception "$pkg" "$bn" >/dev/null; then
        fortify=-
    elif awk '
        BEGIN {
            n = split("mempcpy memccpy stpcpy stpncpy strcpy strncpy strcat strncat sprintf snprintf vsprintf vsnprintf gets fgets fgets_unlocked asprintf vasprintf dprintf vdprintf obstack_printf obstack_vprintf read pread pread64 readlink readlinkat getcwd getwd getdomainname getlogin_r ttyname_r confstr realpath recv recvfrom", names, " ")
        }
        $4 == "FUNC" && $7 == "UND" {
            s = $8
            sub(/@.*/, "", s)
            for (i = 1; i <= n; i++) if (s == names[i]) { found = 1; exit }
        }
        END { exit !found }
    ' <<< "$syms"; then
        fortify=0
    else
        fortify=-
    fi

    local stack_line
    stack_line=$(grep GNU_STACK <<< "$lw")
    if [ -n "$stack_line" ] && ! grep -q ' RWE ' <<< "$stack_line"; then
        nx=1
    fi

    if awk '
        /Displaying notes found in:.*\.note\.gnu\.property/ { inprop = 1; next }
        /^[[:space:]]*$/ { inprop = 0 }
        inprop && /IBT/ && /SHSTK/ { found = 1; exit }
        END { exit !found }
    ' <<< "$props"; then
        cet=1
    fi

    echo "$pie $relro $canary $fortify $nx $cet"
}

audit_ko() {
    local b="$1"
    local props syms

    props=$(readelf -nW "$b" 2>/dev/null)
    syms=$(readelf -sW "$b" 2>/dev/null)

    local canary=0 cet=0

    if awk '
        /Displaying notes found in:.*\.note\.gnu\.property/ { inprop = 1; next }
        /^[[:space:]]*$/ { inprop = 0 }
        inprop && /IBT|SHSTK/ { found = 1; exit }
        END { exit !found }
    ' <<< "$props"; then
        cet=1
    fi

    if grep -qE '__stack_chk_fail' <<< "$syms"; then
        canary=1
    else
        local disasm=""
        if command -v objdump >/dev/null 2>&1; then
            disasm=$(objdump -d --no-show-raw-insn "$b" 2>/dev/null)
        fi
        if [ -n "$disasm" ] && grep -qE '%gs:0x28' <<< "$disasm"; then
            canary=1
        elif [ -n "$disasm" ] && has_stack_buffers_disasm "$disasm"; then
            canary=0
        else
            canary=-
        fi
    fi

    echo "- - $canary - - $cet"
}

worst_of() {
    local worst="-"
    for v in "$@"; do
        case "$v" in
            0) echo 0; return ;;
            1) worst=1 ;;
        esac
    done
    echo "$worst"
}

is_perfect() {
    for v in "$@"; do
        [ "$v" = 0 ] && return 1
    done
    return 0
}

write_counts() {
    local pkg_state="$1"
    mkdir -p "$pkg_state" 2>/dev/null || true
    {
        echo "PKGS_TOTAL $PKGS_TOTAL"
        echo "PKGS_AUDITED $PKGS_AUDITED"
        echo "PKGS_NO_ELF $PKGS_NO_ELF"
        echo "PKGS_PERFECT $PKGS_PERFECT"
        echo "PKGS_PARTIAL $PKGS_PARTIAL"
        echo "PKGS_ACCEPTED $PKGS_ACCEPTED"
        echo "REPACK_TOTAL $REPACK_TOTAL"
        echo "BINS_TOTAL $BINS_TOTAL"
        echo "BINS_PERFECT $BINS_PERFECT"
        echo "BINS_ACCEPTED_GAPS $BINS_ACCEPTED_GAPS"
        echo "BINS_GAPS $BINS_GAPS"
        echo "BINS_EXCEPTIONS $BINS_EXCEPTIONS"
        echo "ELF_BINS_TOTAL $ELF_BINS_TOTAL"
        echo "KO_BINS_TOTAL $KO_BINS_TOTAL"
        echo "ELF_CET_COUNT $ELF_CET_COUNT"
        echo "KO_CET_COUNT $KO_CET_COUNT"
        echo "CANARY_EXCEPTIONS_APPLIED $CANARY_EXCEPTIONS_APPLIED"
    } > "$pkg_state/counts"
}

print_result_line() {
    local bname="$1" glyph_str="$2" inv="$3" kconfig="$4"
    local n

    flock 8
    n=$(< "$COUNTER_FILE")
    n=$((n + 1))
    echo "$n" > "$COUNTER_FILE"
    printf '[%3d/%3d]  %-42s  %s  %s\n' \
        "$n" "$TOTAL_PKGS" "$bname" "$glyph_str" "$inv"
    if [ -n "$kconfig" ]; then
        printf '  %-42s  %-11s  %s\n' "" "" "${C_DIM}${kconfig}${C_RESET}"
    fi
    flock -u 8
}

print_skip_line() {
    local bname="$1" reason="$2"
    local n

    flock 8
    n=$(< "$COUNTER_FILE")
    n=$((n + 1))
    echo "$n" > "$COUNTER_FILE"
    printf '[%3d/%3d]  %-42s  %s\n' \
        "$n" "$TOTAL_PKGS" "$bname" "$reason"
    flock -u 8
}

audit_one_package() {
    local txz="$1"
    local pkg_state="$2"

    mkdir -p "$pkg_state" 2>/dev/null || true

    local txz_base
    txz_base=$(basename "$txz")

    local PKGS_TOTAL=0
    local PKGS_AUDITED=0
    local PKGS_NO_ELF=0
    local PKGS_PERFECT=0
    local PKGS_PARTIAL=0
    local PKGS_ACCEPTED=0
    local REPACK_TOTAL=0
    local BINS_TOTAL=0
    local BINS_PERFECT=0
    local BINS_ACCEPTED_GAPS=0
    local BINS_GAPS=0
    local BINS_EXCEPTIONS=0
    local ELF_BINS_TOTAL=0
    local KO_BINS_TOTAL=0
    local ELF_CET_COUNT=0
    local KO_CET_COUNT=0
    local CANARY_EXCEPTIONS_APPLIED=0

    case "$txz_base" in
        aaa_libraries-*)
            if [ "$INCLUDE_REPACKS" = "1" ]; then
                REPACK_TOTAL=$((REPACK_TOTAL + 1))
            else
                if [ "$QUIET" = "0" ]; then
                    print_skip_line "$txz_base" \
                        "${C_DIM}REPACK: excluded (use --include-repacks)${C_RESET}"
                fi
                write_counts "$pkg_state"
                return 0
            fi
            ;;
    esac

    local tmp
    tmp=$(mktemp -d -p "$RUNDIR")
    if ! tar xf "$txz" -C "$tmp" 2>/dev/null; then
        rm -rf "$tmp"
        warn "could not extract $txz_base; skipping"
        write_counts "$pkg_state"
        return 0
    fi

    PKGS_TOTAL=$((PKGS_TOTAL + 1))

    local -a elfs=()
    mapfile -t elfs < <(
        find "$tmp" -type f ! -name '*.ko' \
             \( -executable -o -name '*.so' -o -name '*.so.*' \
                -o -name '*.node' \) -print0 2>/dev/null \
          | xargs -0 -r file 2>/dev/null \
          | awk -F: '/ELF/{print $1}'
    )

    local -a kos=()
    while IFS= read -r -d '' ko; do
        if [ "$(readelf -hW "$ko" 2>/dev/null | awk '/Type:/ {print $2}')" = "REL" ]; then
            kos+=("$ko")
        fi
    done < <(find "$tmp" -type f -name '*.ko' -print0 2>/dev/null)

    if [ ${#elfs[@]} -eq 0 ] && [ ${#kos[@]} -eq 0 ]; then
        rm -rf "$tmp"
        PKGS_NO_ELF=$((PKGS_NO_ELF + 1))
        write_counts "$pkg_state"
        if [ "$QUIET" = "0" ]; then
            print_result_line "$txz_base" \
                "${C_DIM}······${C_RESET}" \
                "${C_DIM}(no ELF content)${C_RESET}" ""
        fi
        return 0
    fi

    PKGS_AUDITED=$((PKGS_AUDITED + 1))

    local pkg_kconfig_line=""
    if [ ${#kos[@]} -gt 0 ]; then
        pkg_kconfig_line=$(kernel_config_line "$tmp") || pkg_kconfig_line=""
    fi

    local -a p_pie=() p_relro=() p_canary=() p_fortify=() p_nx=() p_cet=()
    local -a pkg_bad_list=()
    local pkg_had_exception=0
    local pkg_exception_count=0
    local pkg_cet_exception_count=0
    local pkg_canary_exception_count=0
    local pkg_elf_exc_binaries=0
    local pkg_ko_exc_binaries=0
    local pkg_elf_count=${#elfs[@]}
    local pkg_ko_count=${#kos[@]}
    local pkg_gap_count=0
    local pkg_elf_gap_count=0
    local pkg_ko_gap_count=0
    local pkg_ko_ok_count=0

    local b
    for b in "${elfs[@]}"; do
        BINS_TOTAL=$((BINS_TOTAL + 1))
        ELF_BINS_TOTAL=$((ELF_BINS_TOTAL + 1))
        local pie relro canary fortify nx cet
        read -r pie relro canary fortify nx cet <<< "$(audit_elf "$b" "$txz_base")"

        local binary_exc=0
        local gap_exception=0

        if reason=$(fortify_exception "$txz_base" "$(basename "$b")"); then
            binary_exc=1
            pkg_had_exception=1
            pkg_exception_count=$((pkg_exception_count + 1))
            BINS_EXCEPTIONS=$((BINS_EXCEPTIONS + 1))
        fi

        if [ "$cet" = "0" ]; then
            if reason=$(cet_exception "$txz_base" "$(basename "$b")"); then
                cet=-
                gap_exception=1
                binary_exc=1
                pkg_had_exception=1
                pkg_cet_exception_count=$((pkg_cet_exception_count + 1))
                ELF_CET_COUNT=$((ELF_CET_COUNT + 1))
            fi
        fi

        if [ "$canary" = "0" ]; then
            if reason=$(canary_exception "$txz_base" "$(basename "$b")"); then
                canary=-
                gap_exception=1
                binary_exc=1
                pkg_had_exception=1
                pkg_canary_exception_count=$((pkg_canary_exception_count + 1))
                CANARY_EXCEPTIONS_APPLIED=$((CANARY_EXCEPTIONS_APPLIED + 1))
            fi
        fi

        [ "$binary_exc" = "1" ] && pkg_elf_exc_binaries=$((pkg_elf_exc_binaries + 1))

        p_pie+=("$pie"); p_relro+=("$relro"); p_canary+=("$canary")
        p_fortify+=("$fortify"); p_nx+=("$nx"); p_cet+=("$cet")

        if ! is_perfect "$pie" "$relro" "$canary" "$fortify" "$nx" "$cet"; then
            pkg_gap_count=$((pkg_gap_count + 1))
            pkg_elf_gap_count=$((pkg_elf_gap_count + 1))
            BINS_GAPS=$((BINS_GAPS + 1))
            pkg_bad_list+=("$(basename "$b"): P=$pie R=$relro C=$canary F=$fortify N=$nx T=$cet")
        elif [ "$gap_exception" = "1" ]; then
            pkg_gap_count=$((pkg_gap_count + 1))
            pkg_elf_gap_count=$((pkg_elf_gap_count + 1))
            BINS_ACCEPTED_GAPS=$((BINS_ACCEPTED_GAPS + 1))
        else
            BINS_PERFECT=$((BINS_PERFECT + 1))
        fi
    done

    for b in "${kos[@]}"; do
        BINS_TOTAL=$((BINS_TOTAL + 1))
        KO_BINS_TOTAL=$((KO_BINS_TOTAL + 1))
        local pie relro canary fortify nx cet
        read -r pie relro canary fortify nx cet <<< "$(audit_ko "$b")"

        local binary_exc=0
        local gap_exception=0

        if [ "$cet" = "0" ]; then
            if reason=$(cet_exception "$txz_base" "$(basename "$b")"); then
                cet=-
                gap_exception=1
                binary_exc=1
                pkg_had_exception=1
                pkg_cet_exception_count=$((pkg_cet_exception_count + 1))
                KO_CET_COUNT=$((KO_CET_COUNT + 1))
            fi
        fi

        if [ "$canary" = "0" ]; then
            if reason=$(canary_exception "$txz_base" "$(basename "$b")"); then
                canary=-
                gap_exception=1
                binary_exc=1
                pkg_had_exception=1
                pkg_canary_exception_count=$((pkg_canary_exception_count + 1))
                CANARY_EXCEPTIONS_APPLIED=$((CANARY_EXCEPTIONS_APPLIED + 1))
            fi
        fi

        [ "$binary_exc" = "1" ] && pkg_ko_exc_binaries=$((pkg_ko_exc_binaries + 1))

        p_pie+=("$pie"); p_relro+=("$relro"); p_canary+=("$canary")
        p_fortify+=("$fortify"); p_nx+=("$nx"); p_cet+=("$cet")

        if ! is_perfect "$pie" "$relro" "$canary" "$fortify" "$nx" "$cet"; then
            pkg_gap_count=$((pkg_gap_count + 1))
            pkg_ko_gap_count=$((pkg_ko_gap_count + 1))
            BINS_GAPS=$((BINS_GAPS + 1))
            pkg_bad_list+=("KO $(basename "$b"): P=$pie R=$relro C=$canary F=$fortify N=$nx T=$cet")
        elif [ "$gap_exception" = "1" ]; then
            pkg_gap_count=$((pkg_gap_count + 1))
            pkg_ko_gap_count=$((pkg_ko_gap_count + 1))
            BINS_ACCEPTED_GAPS=$((BINS_ACCEPTED_GAPS + 1))
        else
            BINS_PERFECT=$((BINS_PERFECT + 1))
            pkg_ko_ok_count=$((pkg_ko_ok_count + 1))
        fi
    done

    local pkg_pie pkg_relro pkg_canary pkg_fortify pkg_nx pkg_cet
    pkg_pie=$(worst_of   "${p_pie[@]}")
    pkg_relro=$(worst_of "${p_relro[@]}")
    pkg_canary=$(worst_of "${p_canary[@]}")
    pkg_fortify=$(worst_of "${p_fortify[@]}")
    pkg_nx=$(worst_of   "${p_nx[@]}")
    pkg_cet=$(worst_of  "${p_cet[@]}")

    if [ "$pkg_fortify" != "0" ] && [ "$pkg_exception_count" -gt 0 ]; then
        pkg_fortify="~"
    fi
    if [ "$pkg_cet" != "0" ] && [ "$pkg_cet_exception_count" -gt 0 ]; then
        pkg_cet="~"
    fi
    if [ "$pkg_canary" != "0" ] && [ "$pkg_canary_exception_count" -gt 0 ]; then
        pkg_canary="~"
    fi

    local pkg_elf_ok=$((pkg_elf_count - pkg_elf_gap_count))
    local inv="[$pkg_elf_count ELF: $pkg_elf_ok ok, $pkg_elf_gap_count gap, $pkg_elf_exc_binaries exc]"
    if [ "$pkg_ko_count" -gt 0 ]; then
        inv="$inv [$pkg_ko_count KO: $pkg_ko_ok_count ok, $pkg_ko_gap_count gap, $pkg_ko_exc_binaries exc]"
    fi

    local glyph_str
    glyph_str=$(glyphs "$pkg_pie" "$pkg_relro" "$pkg_canary" "$pkg_fortify" "$pkg_nx" "$pkg_cet")

    if is_perfect "$pkg_pie" "$pkg_relro" "$pkg_canary" "$pkg_fortify" "$pkg_nx" "$pkg_cet"; then
        if [ "$pkg_had_exception" = "1" ]; then
            PKGS_ACCEPTED=$((PKGS_ACCEPTED + 1))
        else
            PKGS_PERFECT=$((PKGS_PERFECT + 1))
        fi
    else
        PKGS_PARTIAL=$((PKGS_PARTIAL + 1))
        local f
        for f in "${pkg_bad_list[@]}"; do
            echo "$(basename "$txz")  $f" >> "$pkg_state/fails"
        done
    fi

    if [ "$QUIET" = "0" ]; then
        print_result_line "$(basename "$txz")" "$glyph_str" "$inv" "$pkg_kconfig_line"
    fi

    rm -rf "$tmp"
    write_counts "$pkg_state"
}

# ---------------------------------------------------------------------------
# audit_annode_bundle ZIP_PATH PKG_STATE
#
# Audits the annode distribution bundle. Unlike the txz packages, this is
# a zip containing anne-node.jar which in turn contains native shared
# objects. The bundle is treated as a package for reporting and counting
# purposes, but it is not built by makepkg and is not signed the same
# way. Exception lookups use "anne-node.jar" as the package name, so an
# exception entry in AUDIT.TXT matches with a glob like:
#
#   anne-node.jar|libshabal.so|reason here
#
# Extraction is two passes: unzip the outer container to obtain
# anne-node.jar, then unzip the jar into a directory tree. The jar is a
# zip, so the same unzip tool handles both.
# ---------------------------------------------------------------------------
audit_annode_bundle() {
    local zip_path="$1"
    local pkg_state="$2"

    mkdir -p "$pkg_state" 2>/dev/null || true

    local display_name="annode (anne-node.jar)"
    local pkg_name="anne-node.jar"

    # Same counter set as audit_one_package, local to this worker.
    local PKGS_TOTAL=0
    local PKGS_AUDITED=0
    local PKGS_NO_ELF=0
    local PKGS_PERFECT=0
    local PKGS_PARTIAL=0
    local PKGS_ACCEPTED=0
    local REPACK_TOTAL=0
    local BINS_TOTAL=0
    local BINS_PERFECT=0
    local BINS_ACCEPTED_GAPS=0
    local BINS_GAPS=0
    local BINS_EXCEPTIONS=0
    local ELF_BINS_TOTAL=0
    local KO_BINS_TOTAL=0
    local ELF_CET_COUNT=0
    local KO_CET_COUNT=0
    local CANARY_EXCEPTIONS_APPLIED=0

    if [ ! -f "$zip_path" ]; then
        warn "annode bundle not found: $zip_path"
        write_counts "$pkg_state"
        return 0
    fi

    local tmp
    tmp=$(mktemp -d -p "$RUNDIR")

    # First pass: extract anne-node.jar from the outer zip.
    if ! unzip -q -o "$zip_path" anne-node.jar -d "$tmp" 2>/dev/null; then
        rm -rf "$tmp"
        warn "could not extract anne-node.jar from $zip_path"
        if [ "$QUIET" = "0" ]; then
            print_result_line "$display_name" \
                "${C_RED}✗✗✗✗✗✗${C_RESET}" \
                "${C_RED}(extraction failed)${C_RESET}" ""
        fi
        write_counts "$pkg_state"
        return 0
    fi

    local jar_path="$tmp/anne-node.jar"
    if [ ! -f "$jar_path" ]; then
        rm -rf "$tmp"
        warn "anne-node.jar not found inside $zip_path"
        if [ "$QUIET" = "0" ]; then
            print_result_line "$display_name" \
                "${C_RED}✗✗✗✗✗✗${C_RESET}" \
                "${C_RED}(jar missing)${C_RESET}" ""
        fi
        write_counts "$pkg_state"
        return 0
    fi

    # Second pass: extract the jar contents into a subdirectory.
    mkdir -p "$tmp/jar"
    if ! unzip -q -o "$jar_path" -d "$tmp/jar" 2>/dev/null; then
        rm -rf "$tmp"
        warn "could not extract $jar_path"
        if [ "$QUIET" = "0" ]; then
            print_result_line "$display_name" \
                "${C_RED}✗✗✗✗✗✗${C_RESET}" \
                "${C_RED}(jar extraction failed)${C_RESET}" ""
        fi
        write_counts "$pkg_state"
        return 0
    fi

    PKGS_TOTAL=$((PKGS_TOTAL + 1))

    # --- ELF detection inside the extracted jar tree ----------------------
    local -a elfs=()
    mapfile -t elfs < <(
        find "$tmp/jar" -type f ! -name '*.ko' \
             \( -executable -o -name '*.so' -o -name '*.so.*' \
                -o -name '*.node' \) -print0 2>/dev/null \
          | xargs -0 -r file 2>/dev/null \
          | awk -F: '/ELF/{print $1}'
    )

    local -a kos=()
    while IFS= read -r -d '' ko; do
        if [ "$(readelf -hW "$ko" 2>/dev/null | awk '/Type:/ {print $2}')" = "REL" ]; then
            kos+=("$ko")
        fi
    done < <(find "$tmp/jar" -type f -name '*.ko' -print0 2>/dev/null)

    if [ ${#elfs[@]} -eq 0 ] && [ ${#kos[@]} -eq 0 ]; then
        rm -rf "$tmp"
        PKGS_NO_ELF=$((PKGS_NO_ELF + 1))
        write_counts "$pkg_state"
        if [ "$QUIET" = "0" ]; then
            print_result_line "$display_name" \
                "${C_DIM}······${C_RESET}" \
                "${C_DIM}(no ELF content)${C_RESET}" ""
        fi
        return 0
    fi

    PKGS_AUDITED=$((PKGS_AUDITED + 1))

    local pkg_kconfig_line=""
    if [ ${#kos[@]} -gt 0 ]; then
        pkg_kconfig_line=$(kernel_config_line "$tmp/jar") || pkg_kconfig_line=""
    fi

    local -a p_pie=() p_relro=() p_canary=() p_fortify=() p_nx=() p_cet=()
    local -a pkg_bad_list=()
    local pkg_had_exception=0
    local pkg_exception_count=0
    local pkg_cet_exception_count=0
    local pkg_canary_exception_count=0
    local pkg_elf_exc_binaries=0
    local pkg_ko_exc_binaries=0
    local pkg_elf_count=${#elfs[@]}
    local pkg_ko_count=${#kos[@]}
    local pkg_gap_count=0
    local pkg_elf_gap_count=0
    local pkg_ko_gap_count=0
    local pkg_ko_ok_count=0

    local b
    for b in "${elfs[@]}"; do
        BINS_TOTAL=$((BINS_TOTAL + 1))
        ELF_BINS_TOTAL=$((ELF_BINS_TOTAL + 1))
        local pie relro canary fortify nx cet
        read -r pie relro canary fortify nx cet <<< "$(audit_elf "$b" "$pkg_name")"

        local binary_exc=0
        local gap_exception=0

        if reason=$(fortify_exception "$pkg_name" "$(basename "$b")"); then
            binary_exc=1
            pkg_had_exception=1
            pkg_exception_count=$((pkg_exception_count + 1))
            BINS_EXCEPTIONS=$((BINS_EXCEPTIONS + 1))
        fi

        if [ "$cet" = "0" ]; then
            if reason=$(cet_exception "$pkg_name" "$(basename "$b")"); then
                cet=-
                gap_exception=1
                binary_exc=1
                pkg_had_exception=1
                pkg_cet_exception_count=$((pkg_cet_exception_count + 1))
                ELF_CET_COUNT=$((ELF_CET_COUNT + 1))
            fi
        fi

        if [ "$canary" = "0" ]; then
            if reason=$(canary_exception "$pkg_name" "$(basename "$b")"); then
                canary=-
                gap_exception=1
                binary_exc=1
                pkg_had_exception=1
                pkg_canary_exception_count=$((pkg_canary_exception_count + 1))
                CANARY_EXCEPTIONS_APPLIED=$((CANARY_EXCEPTIONS_APPLIED + 1))
            fi
        fi

        [ "$binary_exc" = "1" ] && pkg_elf_exc_binaries=$((pkg_elf_exc_binaries + 1))

        p_pie+=("$pie"); p_relro+=("$relro"); p_canary+=("$canary")
        p_fortify+=("$fortify"); p_nx+=("$nx"); p_cet+=("$cet")

        if ! is_perfect "$pie" "$relro" "$canary" "$fortify" "$nx" "$cet"; then
            pkg_gap_count=$((pkg_gap_count + 1))
            pkg_elf_gap_count=$((pkg_elf_gap_count + 1))
            BINS_GAPS=$((BINS_GAPS + 1))
            pkg_bad_list+=("$(basename "$b"): P=$pie R=$relro C=$canary F=$fortify N=$nx T=$cet")
        elif [ "$gap_exception" = "1" ]; then
            pkg_gap_count=$((pkg_gap_count + 1))
            pkg_elf_gap_count=$((pkg_elf_gap_count + 1))
            BINS_ACCEPTED_GAPS=$((BINS_ACCEPTED_GAPS + 1))
        else
            BINS_PERFECT=$((BINS_PERFECT + 1))
        fi
    done

    for b in "${kos[@]}"; do
        BINS_TOTAL=$((BINS_TOTAL + 1))
        KO_BINS_TOTAL=$((KO_BINS_TOTAL + 1))
        local pie relro canary fortify nx cet
        read -r pie relro canary fortify nx cet <<< "$(audit_ko "$b")"

        local binary_exc=0
        local gap_exception=0

        if [ "$cet" = "0" ]; then
            if reason=$(cet_exception "$pkg_name" "$(basename "$b")"); then
                cet=-
                gap_exception=1
                binary_exc=1
                pkg_had_exception=1
                pkg_cet_exception_count=$((pkg_cet_exception_count + 1))
                KO_CET_COUNT=$((KO_CET_COUNT + 1))
            fi
        fi

        if [ "$canary" = "0" ]; then
            if reason=$(canary_exception "$pkg_name" "$(basename "$b")"); then
                canary=-
                gap_exception=1
                binary_exc=1
                pkg_had_exception=1
                pkg_canary_exception_count=$((pkg_canary_exception_count + 1))
                CANARY_EXCEPTIONS_APPLIED=$((CANARY_EXCEPTIONS_APPLIED + 1))
            fi
        fi

        [ "$binary_exc" = "1" ] && pkg_ko_exc_binaries=$((pkg_ko_exc_binaries + 1))

        p_pie+=("$pie"); p_relro+=("$relro"); p_canary+=("$canary")
        p_fortify+=("$fortify"); p_nx+=("$nx"); p_cet+=("$cet")

        if ! is_perfect "$pie" "$relro" "$canary" "$fortify" "$nx" "$cet"; then
            pkg_gap_count=$((pkg_gap_count + 1))
            pkg_ko_gap_count=$((pkg_ko_gap_count + 1))
            BINS_GAPS=$((BINS_GAPS + 1))
            pkg_bad_list+=("KO $(basename "$b"): P=$pie R=$relro C=$canary F=$fortify N=$nx T=$cet")
        elif [ "$gap_exception" = "1" ]; then
            pkg_gap_count=$((pkg_gap_count + 1))
            pkg_ko_gap_count=$((pkg_ko_gap_count + 1))
            BINS_ACCEPTED_GAPS=$((BINS_ACCEPTED_GAPS + 1))
        else
            BINS_PERFECT=$((BINS_PERFECT + 1))
            pkg_ko_ok_count=$((pkg_ko_ok_count + 1))
        fi
    done

    local pkg_pie pkg_relro pkg_canary pkg_fortify pkg_nx pkg_cet
    pkg_pie=$(worst_of   "${p_pie[@]}")
    pkg_relro=$(worst_of "${p_relro[@]}")
    pkg_canary=$(worst_of "${p_canary[@]}")
    pkg_fortify=$(worst_of "${p_fortify[@]}")
    pkg_nx=$(worst_of   "${p_nx[@]}")
    pkg_cet=$(worst_of  "${p_cet[@]}")

    if [ "$pkg_fortify" != "0" ] && [ "$pkg_exception_count" -gt 0 ]; then
        pkg_fortify="~"
    fi
    if [ "$pkg_cet" != "0" ] && [ "$pkg_cet_exception_count" -gt 0 ]; then
        pkg_cet="~"
    fi
    if [ "$pkg_canary" != "0" ] && [ "$pkg_canary_exception_count" -gt 0 ]; then
        pkg_canary="~"
    fi

    local pkg_elf_ok=$((pkg_elf_count - pkg_elf_gap_count))
    local inv="[$pkg_elf_count ELF: $pkg_elf_ok ok, $pkg_elf_gap_count gap, $pkg_elf_exc_binaries exc]"
    if [ "$pkg_ko_count" -gt 0 ]; then
        inv="$inv [$pkg_ko_count KO: $pkg_ko_ok_count ok, $pkg_ko_gap_count gap, $pkg_ko_exc_binaries exc]"
    fi

    local glyph_str
    glyph_str=$(glyphs "$pkg_pie" "$pkg_relro" "$pkg_canary" "$pkg_fortify" "$pkg_nx" "$pkg_cet")

    if is_perfect "$pkg_pie" "$pkg_relro" "$pkg_canary" "$pkg_fortify" "$pkg_nx" "$pkg_cet"; then
        if [ "$pkg_had_exception" = "1" ]; then
            PKGS_ACCEPTED=$((PKGS_ACCEPTED + 1))
        else
            PKGS_PERFECT=$((PKGS_PERFECT + 1))
        fi
    else
        PKGS_PARTIAL=$((PKGS_PARTIAL + 1))
        local f
        for f in "${pkg_bad_list[@]}"; do
            echo "$display_name  $f" >> "$pkg_state/fails"
        done
    fi

    if [ "$QUIET" = "0" ]; then
        print_result_line "$display_name" "$glyph_str" "$inv" "$pkg_kconfig_line"
    fi

    rm -rf "$tmp"
    write_counts "$pkg_state"
}

[ -d "$TREE" ] || die "tree not found: $TREE"

mapfile -t PACKAGES < <(find "$TREE" -maxdepth 2 -type f \
    \( -name '*.txz' -o -name '*.tgz' \) | sort)

if [ -n "$PACKAGE_FILTER" ]; then
    FILTERED=()
    for p in "${PACKAGES[@]}"; do
        [ -f "$p" ] || continue
        # shellcheck disable=SC2053
        [[ "$(basename "$p")" == $PACKAGE_FILTER ]] && FILTERED+=("$p")
    done
    PACKAGES=("${FILTERED[@]}")
fi

ANNODE_ZIP="$TREE/z/annode/anne-node.zip"
if [ -f "$ANNODE_ZIP" ] && [ -z "$PACKAGE_FILTER" ]; then
    HAVE_ANNODE=1
else
    HAVE_ANNODE=0
fi

TOTAL_PKGS=$(( ${#PACKAGES[@]} + HAVE_ANNODE ))

if [ "$QUIET" = "0" ]; then
    echo
    echo "${C_BOLD}AM·OS Binary Hardening Audit${C_RESET}"
    echo "${C_DIM}tree: $TREE${C_RESET}"
    if [ -n "$PACKAGE_FILTER" ]; then
        echo "${C_DIM}filter: $PACKAGE_FILTER${C_RESET}"
    fi
    echo "${C_DIM}jobs: $JOBS   packages: $TOTAL_PKGS${C_RESET}"
    echo "${C_DIM}$(date '+%Y-%m-%d %H:%M:%S')${C_RESET}"
    echo
    printf '  %-12s  %-42s  %-11s  %s\n' "PROGRESS" "PACKAGE" "P R C F N T" "INVENTORY"
    printf '  %s  %s  %s  %s\n' \
        "$(printf '%0.s-' {1..12})" \
        "$(printf '%0.s-' {1..42})" \
        "$(printf '%0.s-' {1..11})" \
        "$(printf '%0.s-' {1..32})"
    echo
    echo "${C_BOLD}Legend${C_RESET}"
    echo "  ${C_DIM}P${C_RESET} PIE   ${C_DIM}R${C_RESET} Full RELRO   ${C_DIM}C${C_RESET} Canary"
    echo "  ${C_DIM}F${C_RESET} FORTIFY   ${C_DIM}N${C_RESET} NX stack   ${C_DIM}T${C_RESET} CET (IBT/SHSTK)"
    echo
    echo "  ${C_GREEN}✓${C_RESET} present   ${C_YELLOW}~${C_RESET} audited, exception documented   ${C_RED}✗${C_RESET} absent, unexplained   ${C_DIM}·${C_RESET} N/A (no code to harden)"
    echo
    echo "  ${C_DIM}INVENTORY${C_RESET}  [N ELF: N ok, N gap, N exc] [N KO: N ok, N gap, N exc]"
    echo "    ${C_DIM}N${C_RESET} total binaries   ${C_DIM}ok${C_RESET} binaries with no real gap"
    echo "    ${C_DIM}gap${C_RESET} binaries with a real gap (accepted or unexplained)"
    echo "    ${C_DIM}exc${C_RESET} binaries matched against an exception table"
    echo "    ${C_DIM}KO${C_RESET} kernel modules; only canary and CET are meaningful, the other four show as ·"
    echo
    echo "  ${C_DIM}FORTIFY exceptions are N/A (compiler declined to emit a check);${C_RESET}"
    echo "  ${C_DIM}those binaries count as ok. CET and CANARY exceptions are real${C_RESET}"
    echo "  ${C_DIM}gaps (mitigation absent, omission accepted); those count as gap.${C_RESET}"
    echo
    echo "  ${C_DIM}KO rows: FORTIFY is a kernel-build property (CONFIG_FORTIFY_SOURCE);${C_RESET}"
    echo "  ${C_DIM}it is not visible in a module's ELF, so F is shown as · for every .ko.${C_RESET}"
    echo "  ${C_DIM}The config line printed under each KO-bearing package is the actual signal.${C_RESET}"
    echo
    echo "  ${C_DIM}Result lines appear in completion order with a [N/TOTAL] counter.${C_RESET}"
    echo "  ${C_DIM}Ctrl-C terminates the worker pool.${C_RESET}"
    echo
fi

# The annode bundle is a special case: a zip containing anne-node.jar
# which contains native libraries. It is audited alongside the txz
# packages and counted as one package. It is skipped when a --package
# filter is active, since filters are meant to narrow to specific
# txz packages.
ANNODE_ZIP="$TREE/z/annode/anne-node.zip"
if [ -f "$ANNODE_ZIP" ] && [ -z "$PACKAGE_FILTER" ]; then
    HAVE_ANNODE=1
else
    HAVE_ANNODE=0
fi

# Recompute TOTAL_PKGS to include the bundle if it will be audited.
TOTAL_PKGS=$(( ${#PACKAGES[@]} + HAVE_ANNODE ))

idx=0

if [ "$HAVE_ANNODE" = "1" ]; then
    idx=$((idx + 1))
    printf -v state_name '%05d' "$idx"
    pkg_state="$STATEDIR/$state_name"
    mkdir -p "$pkg_state"
    : > "$pkg_state/fails"

    audit_annode_bundle "$ANNODE_ZIP" "$pkg_state" &

    while [ "$(jobs -rp | wc -l)" -ge "$JOBS" ]; do
        wait -n || true
    done
fi

for txz in "${PACKAGES[@]}"; do
    [ -f "$txz" ] || continue

    idx=$((idx + 1))
    printf -v state_name '%05d' "$idx"
    pkg_state="$STATEDIR/$state_name"
    mkdir -p "$pkg_state"
    : > "$pkg_state/fails"

    audit_one_package "$txz" "$pkg_state" &

    while [ "$(jobs -rp | wc -l)" -ge "$JOBS" ]; do
        wait -n || true
    done
done
wait

PKGS_TOTAL=0
PKGS_AUDITED=0
PKGS_NO_ELF=0
PKGS_PERFECT=0
PKGS_PARTIAL=0
PKGS_ACCEPTED=0
REPACK_TOTAL=0
BINS_TOTAL=0
BINS_PERFECT=0
BINS_ACCEPTED_GAPS=0
BINS_GAPS=0
BINS_EXCEPTIONS=0
ELF_BINS_TOTAL=0
KO_BINS_TOTAL=0
ELF_CET_COUNT=0
KO_CET_COUNT=0
CANARY_EXCEPTIONS_APPLIED=0

for state in "$STATEDIR"/*/counts; do
    [ -f "$state" ] || continue
    while read -r key val; do
        case "$key" in
            PKGS_TOTAL)                 PKGS_TOTAL=$((PKGS_TOTAL + val)) ;;
            PKGS_AUDITED)               PKGS_AUDITED=$((PKGS_AUDITED + val)) ;;
            PKGS_NO_ELF)                PKGS_NO_ELF=$((PKGS_NO_ELF + val)) ;;
            PKGS_PERFECT)               PKGS_PERFECT=$((PKGS_PERFECT + val)) ;;
            PKGS_PARTIAL)               PKGS_PARTIAL=$((PKGS_PARTIAL + val)) ;;
            PKGS_ACCEPTED)              PKGS_ACCEPTED=$((PKGS_ACCEPTED + val)) ;;
            REPACK_TOTAL)               REPACK_TOTAL=$((REPACK_TOTAL + val)) ;;
            BINS_TOTAL)                 BINS_TOTAL=$((BINS_TOTAL + val)) ;;
            BINS_PERFECT)               BINS_PERFECT=$((BINS_PERFECT + val)) ;;
            BINS_ACCEPTED_GAPS)         BINS_ACCEPTED_GAPS=$((BINS_ACCEPTED_GAPS + val)) ;;
            BINS_GAPS)                  BINS_GAPS=$((BINS_GAPS + val)) ;;
            BINS_EXCEPTIONS)            BINS_EXCEPTIONS=$((BINS_EXCEPTIONS + val)) ;;
            ELF_BINS_TOTAL)             ELF_BINS_TOTAL=$((ELF_BINS_TOTAL + val)) ;;
            KO_BINS_TOTAL)              KO_BINS_TOTAL=$((KO_BINS_TOTAL + val)) ;;
            ELF_CET_COUNT)              ELF_CET_COUNT=$((ELF_CET_COUNT + val)) ;;
            KO_CET_COUNT)               KO_CET_COUNT=$((KO_CET_COUNT + val)) ;;
            CANARY_EXCEPTIONS_APPLIED)  CANARY_EXCEPTIONS_APPLIED=$((CANARY_EXCEPTIONS_APPLIED + val)) ;;
        esac
    done < "$state"
done

FAIL_LINES=()
for pkg_dir in $(printf '%s\n' "$STATEDIR"/*/ | sort); do
    [ -f "${pkg_dir}fails" ] || continue
    while IFS= read -r line; do
        [ -n "$line" ] && FAIL_LINES+=("$line")
    done < "${pkg_dir}fails"
done

PKGS_PASSING=$(( PKGS_PERFECT + PKGS_ACCEPTED ))

PCT_BINS=0
[ "$BINS_TOTAL" -gt 0 ] && PCT_BINS=$(( BINS_PERFECT * 100 / BINS_TOTAL ))
PCT_PKGS=0
[ "$PKGS_AUDITED" -gt 0 ] && PCT_PKGS=$(( PKGS_PASSING * 100 / PKGS_AUDITED ))

echo
echo "${C_BOLD}Summary${C_RESET}"
if [ "$INCLUDE_REPACKS" = "1" ] && [ "$REPACK_TOTAL" -gt 0 ]; then
    printf '  %-26s %s\n' "repack packages included:" "$REPACK_TOTAL"
elif [ "$INCLUDE_REPACKS" = "0" ]; then
    printf '  %-26s %s%s%s\n' "repack packages skipped:" "$C_DIM" "$REPACK_TOTAL" "$C_RESET"
fi
printf '  %-26s %s\n' "packages scanned:" "$PKGS_TOTAL"
printf '  %-26s %s  %s(have at least one ELF or KO)%s\n' \
    "  audited:" "$PKGS_AUDITED" "$C_DIM" "$C_RESET"
if [ "$PKGS_NO_ELF" -gt 0 ]; then
    printf '  %-26s %s  %s(metapackages, script-only)%s\n' \
        "  no ELF content:" "$PKGS_NO_ELF" "$C_DIM" "$C_RESET"
fi
printf '  %-26s %s  %s(no exception applied)%s\n' \
    "  no exceptions:" "$PKGS_PERFECT" "$C_DIM" "$C_RESET"
printf '  %-26s %s  %s(reason in AUDIT.TXT)%s\n' \
    "  documented exceptions:" "$PKGS_ACCEPTED" "$C_DIM" "$C_RESET"
printf '  %-26s %s / %s\n' "  unexplained gaps:" "$PKGS_PARTIAL" "$PKGS_AUDITED"
printf '  %-26s %s\n' "binaries scanned (ELF + KO):" "$BINS_TOTAL"
printf '  %-26s %s  %s(%s ELF + %s KO)%s\n' \
    "  of which:" "" \
    "$C_DIM" "$ELF_BINS_TOTAL" "$KO_BINS_TOTAL" "$C_RESET"
printf '  %-26s %s / %s  (%s%%)\n' \
    "  no exceptions:" \
    "$BINS_PERFECT" "$BINS_TOTAL" "$PCT_BINS"
printf '  %-26s %s / %s\n' "  accepted gaps:" "$BINS_ACCEPTED_GAPS" "$BINS_TOTAL"
printf '  %-26s %s / %s\n' "  unexplained gaps:" "$BINS_GAPS" "$BINS_TOTAL"
printf '  %-26s %s  %s(N/A, not gaps)%s\n' \
    "FORTIFY exceptions applied:" \
    "$BINS_EXCEPTIONS" \
    "$C_DIM" "$C_RESET"
printf '  %-26s %s  %s(real gaps, reason in AUDIT.TXT)%s\n' \
    "CANARY accepted gaps:" \
    "$CANARY_EXCEPTIONS_APPLIED" \
    "$C_DIM" "$C_RESET"
printf '  %-26s %s  %s(real gaps, reason in AUDIT.TXT)%s\n' \
    "CET accepted gaps:" \
    "$(( ELF_CET_COUNT + KO_CET_COUNT ))" \
    "$C_DIM" "$C_RESET"
printf '  %-26s %s  %s(userspace binaries, excluded from ISO)%s\n' \
    "  ELF:" \
    "$ELF_CET_COUNT" \
    "$C_DIM" "$C_RESET"
printf '  %-26s %s  %s(kernel modules, .S input, blacklisted)%s\n' \
    "  KO:" \
    "$KO_CET_COUNT" \
    "$C_DIM" "$C_RESET"
if [ "$(( CANARY_EXCEPTIONS_APPLIED + ELF_CET_COUNT + KO_CET_COUNT ))" -gt "$BINS_ACCEPTED_GAPS" ]; then
    printf '  %-26s %s  %s(some binaries appear in more than one category above)%s\n' \
        "  gap categories:" "" "$C_DIM" "$C_RESET"
fi
echo

if [ ${#FAIL_LINES[@]} -gt 0 ] && [ "$QUIET" = "0" ]; then
    echo "${C_BOLD}Binaries with unexplained gaps (✗ on one or more checks)${C_RESET}"
    for l in "${FAIL_LINES[@]}"; do
        echo "  $l"
    done
    echo
fi

if [ "$QUIET" = "0" ] && [ $(( BINS_EXCEPTIONS + CANARY_EXCEPTIONS_APPLIED + ELF_CET_COUNT + KO_CET_COUNT )) -gt 0 ]; then
    echo "${C_DIM}Exception details: $AUDIT_FILE${C_RESET}"
    echo
fi

if [ -n "$JSON_OUT" ]; then
    cat > "$JSON_OUT" <<EOF
{
  "generated": "$(date -u '+%Y-%m-%dT%H:%M:%SZ')",
  "tree": "$TREE",
  "package_filter": "$PACKAGE_FILTER",
  "jobs": $JOBS,
  "packages_total": $PKGS_TOTAL,
  "packages_audited": $PKGS_AUDITED,
  "packages_no_elf": $PKGS_NO_ELF,
  "packages_perfect": $PKGS_PERFECT,
  "packages_partial": $PKGS_PARTIAL,
  "packages_accepted": $PKGS_ACCEPTED,
  "packages_passing": $PKGS_PASSING,
  "repack_packages": $REPACK_TOTAL,
  "repack_included": $INCLUDE_REPACKS,
  "binaries_total": $BINS_TOTAL,
  "elf_bins_total": $ELF_BINS_TOTAL,
  "ko_bins_total": $KO_BINS_TOTAL,
  "binaries_no_gaps": $BINS_PERFECT,
  "binaries_accepted_gaps": $BINS_ACCEPTED_GAPS,
  "binaries_unexplained_gaps": $BINS_GAPS,
  "binaries_with_exceptions": $(( BINS_EXCEPTIONS + CANARY_EXCEPTIONS_APPLIED + ELF_CET_COUNT + KO_CET_COUNT )),
  "fortify_exceptions_applied": $BINS_EXCEPTIONS,
  "canary_exceptions_applied": $CANARY_EXCEPTIONS_APPLIED,
  "cet_accepted_gaps": $(( ELF_CET_COUNT + KO_CET_COUNT )),
  "cet_accepted_gaps_elf": $ELF_CET_COUNT,
  "cet_accepted_gaps_ko": $KO_CET_COUNT,
  "packages_pct": $PCT_PKGS,
  "binaries_pct": $PCT_BINS
}
EOF
    echo "JSON: $JSON_OUT"
fi

[ "$PKGS_PARTIAL" -eq 0 ]