//
//  ksafe.m
//  Cyanide
//
//  Mapped-address safety gate for KRW reads.
//  READ-ONLY: every kernel access below is kread64; no writes anywhere.
//
//  Implementation: kernel_map entry snapshot — NOT a page-table walk.
//  On SPTM devices (T8140/A18) pmap page-table pages live in SPTM-owned
//  physical memory that the kernel's own static aperture deliberately does
//  NOT map; reading them is an instant "Unexpected fault in kernel static
//  region / physical aperture" panic (observed twice on iPhone17,2/22F76).
//  vm_map metadata, by contrast, is ordinary zone memory and always readable:
//  an address is treated as mapped when [addr, addr+len) lies inside some
//  vm_map_entry's [start, end) of kernel_map. The zone submap entry covers
//  the whole kalloc/zone band, so heap candidates are gated correctly; freed
//  pages inside an otherwise-backed zone range remain a small accepted race.
//

#import "ksafe.h"
#import "krw.h"
#import "kutils.h"
#import "offsets.h"
#import "kexploit_opa334.h"
#import "xpaci.h"
#import <mach/mach.h>
#import <stdio.h>
#import <stdlib.h>
#import <stdatomic.h>
#import <sched.h>
#import <pthread.h>
#import <time.h>

// vm_map layout on this build family (verified against live dumps):
//   +0x10 hdr.links.prev   +0x18 hdr.links.next
//   +0x20 hdr.links.start  +0x28 hdr.links.end
//   +0x30 nentries(u32) | page_shift(u32)
// vm_map_entry embeds vm_map_links at +0:
//   +0x00 prev  +0x08 next  +0x10 start  +0x18 end
#define KS_MAP_HDR_NEXT   0x18
#define KS_MAP_LINKS_ADDR 0x10   // &map->hdr.links == list terminator
#define KS_MAP_NENTRIES   0x30
#define KS_ENTRY_NEXT     0x08
#define KS_ENTRY_START    0x10
#define KS_ENTRY_END      0x18
#define KS_ENTRY_READ     0x20

#define KS_MAX_ENTRIES    16384

typedef struct { uint64_t start, end; } ks_range_t;
// Double buffer: kaddr_is_mapped reads g_ks_buf[g_ks_cur] while a refresh
// fills the other buffer, then switches g_ks_cur atomically. Readers pin the
// buffer they search (g_ks_readers), and a refresh only refills a buffer with
// no reader left in it: a reader stalled across two refreshes (>= 500 ms
// apart, but a preempted thread can take that long) would otherwise search a
// half-written table and could call an unmapped address mapped.
static ks_range_t g_ks_buf[2][KS_MAX_ENTRIES];
static uint32_t   g_ks_nbuf[2];
static _Atomic int g_ks_cur = 0;
static _Atomic uint32_t g_ks_readers[2];

// Pins the current buffer: returns its index; ks_unpin(index) when done.
// Re-checks after pinning: a refresh that switched buffers meanwhile may
// already be refilling the one we loaded, so move on to the new current one.
static int ks_pin(void)
{
    for (;;) {
        int cur = atomic_load(&g_ks_cur);
        atomic_fetch_add(&g_ks_readers[cur], 1);
        if (atomic_load(&g_ks_cur) == cur) return cur;
        atomic_fetch_sub(&g_ks_readers[cur], 1);
    }
}

static void ks_unpin(int cur)
{
    atomic_fetch_sub(&g_ks_readers[cur], 1);
}
static bool       g_ksafe_available = false;
static uint64_t   g_ks_map = 0;            // kernel_map, for refreshes
static pthread_mutex_t g_ks_refresh_lock = PTHREAD_MUTEX_INITIALIZER;
static uint64_t   g_ks_last_refresh_ns = 0;
// Completion time of the last SUCCESSFUL snapshot (bringup excluded). Lets a
// rate-limited caller tell "a fresh snapshot is already active" from "could
// not refresh" (ksafe_refresh_status).
static uint64_t   g_ks_last_ok_ns = 0;

bool ksafe_available(void) {
    return g_ksafe_available;
}

// A vm_map_entry is a zone element: kernel heap band, 16-byte aligned.
// This is the ONLY guard before dereferencing a chain pointer — a wild read
// outside the mapped heap bands panics the kernel.
static bool ks_is_heap_ptr(uint64_t p) {
    uint64_t band32 = p >> 32;
    return band32 >= 0xFFFFFFC0ULL && band32 <= 0xFFFFFFEFULL && (p & 0xF) == 0;
}

static int ks_range_cmp(const void *a, const void *b) {
    uint64_t sa = ((const ks_range_t *)a)->start, sb = ((const ks_range_t *)b)->start;
    return (sa > sb) - (sa < sb);
}

// Walk kernel_map's circular entry list and collect [start, end) ranges.
// Every chain pointer is validated against the heap band BEFORE it is read;
// any corruption aborts the snapshot instead of dereferencing garbage.
static bool ks_snapshot_kernel_map(uint64_t map, ks_range_t *ranges, uint32_t *nOut) {
    uint32_t nentries = (uint32_t)(kread64(map + KS_MAP_NENTRIES) & 0xFFFFFFFF);
    uint64_t term = map + KS_MAP_LINKS_ADDR;
    uint64_t e    = xpaci(kread64(map + KS_MAP_HDR_NEXT));
    printf("[KSAFE] kmap snapshot: map=0x%llx nentries=%u first=0x%llx\n",
           map, nentries, e);
    if (!nentries || nentries > KS_MAX_ENTRIES) {
        printf("[KSAFE] kmap snapshot: implausible nentries=%u\n", nentries);
        return false;
    }
    if (!ks_is_heap_ptr(e)) {
        printf("[KSAFE] kmap snapshot: first entry 0x%llx not a heap ptr\n", e);
        return false;
    }

    uint8_t buf[KS_ENTRY_READ];
    uint32_t n = 0;
    for (uint32_t i = 0; i < nentries + 64; i++) {
        if (e == term) break;
        if (!ks_is_heap_ptr(e)) {
            printf("[KSAFE] kmap snapshot: chain broke at i=%u e=0x%llx\n", i, e);
            return false;
        }
        kreadbuf(e, buf, KS_ENTRY_READ);
        uint64_t next  = xpaci(*(uint64_t *)(buf + KS_ENTRY_NEXT));
        uint64_t start = *(uint64_t *)(buf + KS_ENTRY_START);
        uint64_t end   = *(uint64_t *)(buf + KS_ENTRY_END);
        if (end > start && n < KS_MAX_ENTRIES) {
            ranges[n].start = start;
            ranges[n].end   = end;
            n++;
        }
        e = next;
    }
    if (n < 16) {
        printf("[KSAFE] kmap snapshot: only %u ranges — implausible\n", n);
        return false;
    }
    qsort(ranges, n, sizeof(ks_range_t), ks_range_cmp);
    // Merge adjacent / overlapping entries: kernel_map can describe one
    // contiguous mapped region as several back-to-back entries, and an object
    // lying across such a seam failed "inside a single entry" although every
    // byte is mapped -- a false "not mapped" that made un-arms skip live
    // threads. Back-to-back mapped entries are mapped as a whole.
    uint32_t m = 0;
    for (uint32_t i = 1; i < n; i++) {
        if (ranges[i].start <= ranges[m].end) {
            if (ranges[i].end > ranges[m].end) ranges[m].end = ranges[i].end;
        } else {
            ranges[++m] = ranges[i];
        }
    }
    n = m + 1;
    *nOut = n;
    printf("[KSAFE] kmap snapshot: %u ranges, 0x%llx..0x%llx\n",
           n, ranges[0].start, ranges[n - 1].end);
    return true;
}

bool kaddr_is_mapped(uint64_t kvaddr, size_t len) {
    if (!g_ksafe_available) return false;
    if (len == 0) return true;
    if (kvaddr + len - 1 < kvaddr) return false;   // range overflows

    int cur = ks_pin();
    const ks_range_t *ranges = g_ks_buf[cur];
    // Binary search: the last range with start <= kvaddr.
    uint32_t lo = 0, hi = g_ks_nbuf[cur];
    while (lo < hi) {
        uint32_t mid = lo + (hi - lo) / 2;
        if (ranges[mid].start <= kvaddr) lo = mid + 1;
        else                             hi = mid;
    }
    bool mapped = false;
    if (lo > 0) {
        const ks_range_t *r = &ranges[lo - 1];
        mapped = kvaddr >= r->start && kvaddr + len <= r->end;
    }
    ks_unpin(cur);
    return mapped;
}

void ksafe_bringup(void) {
    if (g_ksafe_available) {
        printf("[KSAFE] already available, ignoring\n");
        return;
    }
    if (!kexploit_krw_ready()) {
        printf("[KSAFE] FAIL: KRW not ready\n");
        return;
    }

    // kernel_map through known struct offsets: pid0 proc -> proc_ro -> task
    // -> map. All heap objects, readable with the plain primitive.
    uint64_t kproc = proc_find(0);
    if (!is_kaddr_valid(kproc)) {
        printf("[KSAFE] kernel proc not found\n");
        return;
    }
    uint64_t ktask = xpaci(proc_task(kproc));
    if (!is_kaddr_valid(ktask)) {
        printf("[KSAFE] kernel task not found\n");
        return;
    }
    uint64_t map = task_get_vm_map(ktask);
    if (!is_kaddr_valid(map)) {
        printf("[KSAFE] kernel vm_map not found\n");
        return;
    }

    if (ks_snapshot_kernel_map(map, g_ks_buf[0], &g_ks_nbuf[0])) {
        g_ks_map = map;
        atomic_store_explicit(&g_ks_cur, 0, memory_order_release);
        g_ksafe_available = true;
        printf("[KSAFE] available: kernel_map entry snapshot active\n");
    } else {
        printf("[KSAFE] snapshot FAILED, mapped-check unavailable\n");
    }
}

bool ksafe_refresh(void) {
    // The bool API means "a fresh snapshot is now active", which includes a
    // successful snapshot taken inside the 500 ms rate window (RECENT). Only
    // FAILED means nothing usable was available. Review P3.
    return ksafe_refresh_status() != KSAFE_REFRESH_FAILED;
}

ksafe_refresh_status_t ksafe_refresh_status(void) {
    if (!g_ksafe_available || !g_ks_map) return KSAFE_REFRESH_FAILED;
    if (!kexploit_krw_ready()) return KSAFE_REFRESH_FAILED;
    pthread_mutex_lock(&g_ks_refresh_lock);
    uint64_t now = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
    if (g_ks_last_refresh_ns && now - g_ks_last_refresh_ns < 500000000ULL) {
        // Rate-limited. Only a SUCCESSFUL snapshot completed inside the same
        // window counts as fresh; a failed/skipped attempt does not.
        bool recent = g_ks_last_ok_ns && now - g_ks_last_ok_ns < 500000000ULL;
        pthread_mutex_unlock(&g_ks_refresh_lock);
        return recent ? KSAFE_REFRESH_RECENT : KSAFE_REFRESH_FAILED;
    }
    g_ks_last_refresh_ns = now;
    int next = 1 - atomic_load(&g_ks_cur);
    // Wait (briefly) for readers still searching the buffer about to be
    // refilled. Lookups take microseconds; if one is stuck, keep the current
    // snapshot rather than block a KRW path.
    for (int spins = 0; atomic_load(&g_ks_readers[next]) != 0; spins++) {
        if (clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) - now > 50000000ULL) {
            printf("[KSAFE] refresh skipped: a lookup is still reading the old snapshot\n");
            pthread_mutex_unlock(&g_ks_refresh_lock);
            return KSAFE_REFRESH_FAILED;
        }
        sched_yield();
    }
    uint32_t n = 0;
    bool ok = ks_snapshot_kernel_map(g_ks_map, g_ks_buf[next], &n);
    if (ok) {
        g_ks_nbuf[next] = n;
        atomic_store(&g_ks_cur, next);
        g_ks_last_ok_ns = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
        printf("[KSAFE] snapshot refreshed\n");
    } else {
        printf("[KSAFE] refresh failed — keeping the previous snapshot\n");
    }
    pthread_mutex_unlock(&g_ks_refresh_lock);
    return ok ? KSAFE_REFRESH_DONE : KSAFE_REFRESH_FAILED;
}

void ksafe_describe(uint64_t kvaddr, size_t len) {
    if (!g_ksafe_available) { printf("[KSAFE] describe 0x%llx: unavailable\n", kvaddr); return; }
    int cur = ks_pin();
    const ks_range_t *ranges = g_ks_buf[cur];
    uint32_t lo = 0, hi = g_ks_nbuf[cur];
    while (lo < hi) {
        uint32_t mid = lo + (hi - lo) / 2;
        if (ranges[mid].start <= kvaddr) lo = mid + 1;
        else                             hi = mid;
    }
    if (lo == 0) { printf("[KSAFE] describe 0x%llx+0x%zx: below every range\n", kvaddr, len); ks_unpin(cur); return; }
    const ks_range_t *r = &ranges[lo - 1];
    printf("[KSAFE] describe 0x%llx+0x%zx: nearest range 0x%llx..0x%llx%s (of %u)\n",
           kvaddr, len, r->start, r->end,
           kvaddr >= r->end ? " (starts after it)" : " (runs past its end)", g_ks_nbuf[cur]);
    ks_unpin(cur);
}
