//
//  kutils.m
//  Cyanide
//
//  Created by seo on 3/25/26.
//

#import "kutils.h"
#import "../LogTextView.h"
#import "krw.h"
#import "ksafe.h"
#import "kexploit_opa334.h"
#import "offsets.h"
#import <unistd.h>
#import <string.h>
#import <stdbool.h>
#import <sys/mount.h>
#import <Foundation/Foundation.h>

extern uint64_t rwSocketPcb;
extern bool gIsPACSupported;

uint64_t gSelfProc = 0;
uint64_t gSelfTask = 0;

void kutils_reset_self_cache(void) {
    gSelfProc = 0;
    gSelfTask = 0;
}

static bool kutils_is_kernel_ptr(uint64_t value) {
    if (!value)
        return false;
    if (VM_MIN_KERNEL_ADDRESS && VM_MAX_KERNEL_ADDRESS)
        return value >= VM_MIN_KERNEL_ADDRESS && value <= VM_MAX_KERNEL_ADDRESS;
    return (value & 0xffff000000000000ULL) == 0xffff000000000000ULL;
}

static bool kutils_is_kernel_or_smr_ptr(uint64_t value) {
    if (!value)
        return false;
    if (kutils_is_kernel_ptr(value))
        return true;
    if (VM_MIN_KERNEL_ADDRESS && VM_MAX_KERNEL_ADDRESS)
        return false;
    return (value & 0xffff000000000000ULL) == 0xffff000000000000ULL;
}

static uint64_t gKutilsLastIpcTask = 0;
static uint64_t gKutilsLastIpcSpace = 0;
static mach_port_name_t gKutilsLastIpcName = 0;
static uint64_t gKutilsLastIpcRawTable = 0;
static uint64_t gKutilsLastIpcTable = 0;

static bool kutils_verbose_logging(void) {
    // Was gated on getenv("KUTILS_VERBOSE"), which can never be set for a
    // sideloaded iOS app -- so these diagnostics had never once printed. They
    // are the only thing that says WHICH stage of the ipc walk failed, which is
    // exactly what is needed when init_remote_call reports
    // "failed to resolve dummy thread kobject". Use the app's own verbose flag.
    return log_verbose_enabled();
}

static void kutils_log_ipc_reject(const char *what,
                                  uint64_t task,
                                  uint64_t space,
                                  mach_port_name_t name,
                                  uint64_t value,
                                  uint64_t rawTable,
                                  uint64_t decodedTable) {
    static int rejectLogs = 0;
    if (rejectLogs++ >= 12 || !kutils_verbose_logging())
        return;

    printf("[kutils] ipc %s rejected task=%#llx space=%#llx port=0x%x value=%#llx rawTable=%#llx table=%#llx vm=[%#llx,%#llx] t1sz=0x%llx smr=0x%llx pac=%d\n",
           what,
           task,
           space,
           name,
           value,
           rawTable,
           decodedTable,
           VM_MIN_KERNEL_ADDRESS,
           VM_MAX_KERNEL_ADDRESS,
           t1sz_boot,
           smr_base,
           gIsPACSupported);
}

static void kutils_log_ipc_entry_dump(uint64_t entry) {
    static int dumpLogs = 0;
    if (dumpLogs++ >= 8 || !kutils_is_kernel_ptr(entry) || !kutils_verbose_logging())
        return;

    uint64_t raw0 = kread64(entry);
    uint64_t raw8 = kread64(entry + 8);
    uint64_t raw10 = kread64(entry + 0x10);
    uint64_t ptr0 = kread_ptr(entry);
    uint64_t ptr8 = kread_ptr(entry + 8);
    uint64_t ptr10 = kread_ptr(entry + 0x10);
    printf("[kutils] ipc entry dump entry=%#llx raw[0]=%#llx raw[8]=%#llx raw[10]=%#llx ptr[0]=%#llx ptr[8]=%#llx ptr[10]=%#llx\n",
           entry,
           raw0,
           raw8,
           raw10,
           ptr0,
           ptr8,
           ptr10);
}

static uint64_t kutils_find_pid_from_anchor(uint64_t anchorProc, pid_t pid, bool forward) {
    uint64_t proc = anchorProc;
    for (int i = 0; i < 4096 && kutils_is_kernel_ptr(proc); i++) {
        uint32_t curPid = kread32(proc + off_proc_p_pid);
        if (curPid == (uint32_t)pid)
            return proc;

        uint64_t next = kread64(proc + (forward ? off_proc_p_list_le_next : off_proc_p_list_le_prev));
        if (!kutils_is_kernel_ptr(next) || next == proc)
            break;
        proc = next;
    }
    return 0;
}

static uint64_t kutils_task_from_socket_thread(void) {
    if (!kutils_is_kernel_ptr(rwSocketPcb))
        return 0;

    uint64_t rwSocketAddr = kread64(rwSocketPcb + off_inpcb_inp_socket);
    if (!kutils_is_kernel_ptr(rwSocketAddr))
        return 0;

    uint64_t current_thread = kread64(rwSocketAddr + off_socket_so_background_thread);
    if (!kutils_is_kernel_ptr(current_thread))
        return 0;

    uint64_t current_thread_ro = kread64(current_thread + off_thread_t_tro);
    if (!kutils_is_kernel_ptr(current_thread_ro))
        return 0;

    uint64_t task = kread64(current_thread_ro + off_thread_ro_tro_task);
    return kutils_is_kernel_ptr(task) ? task : 0;
}

static uint64_t kutils_proc_from_socket_thread(void) {
    if (!kutils_is_kernel_ptr(rwSocketPcb))
        return 0;

    uint64_t rwSocketAddr = kread64(rwSocketPcb + off_inpcb_inp_socket);
    if (!kutils_is_kernel_ptr(rwSocketAddr))
        return 0;

    uint64_t current_thread = kread64(rwSocketAddr + off_socket_so_background_thread);
    if (!kutils_is_kernel_ptr(current_thread))
        return 0;

    uint64_t current_thread_ro = kread64(current_thread + off_thread_t_tro);
    if (!kutils_is_kernel_ptr(current_thread_ro))
        return 0;

    uint64_t proc = kread64(current_thread_ro + off_thread_ro_tro_proc);
    return kutils_is_kernel_ptr(proc) ? proc : 0;
}

bool kutils_recover_self_proc_from(uint64_t anchor_proc) {
    kutils_reset_self_cache();
    if (!kutils_is_kernel_ptr(anchor_proc)) {
        printf("[kutils] invalid proc recovery anchor: %#llx\n", anchor_proc);
        return false;
    }

    pid_t pid = getpid();
    uint64_t proc = kutils_find_pid_from_anchor(anchor_proc, pid, true);
    if (!proc)
        proc = kutils_find_pid_from_anchor(anchor_proc, pid, false);
    if (!proc) {
        printf("[kutils] could not recover self proc from anchor %#llx pid=%d\n",
               anchor_proc, pid);
        return false;
    }

    gSelfProc = proc;
    gSelfTask = proc_task(gSelfProc);
    if (!kutils_is_kernel_ptr(gSelfTask)) {
        printf("[kutils] recovered self proc but task is invalid proc=%#llx task=%#llx\n",
               gSelfProc, gSelfTask);
        kutils_reset_self_cache();
        return false;
    }

    return true;
}

uint64_t proc_self(void) {
    if(!gSelfProc)
        gSelfProc = kutils_proc_from_socket_thread();
    return gSelfProc;
}

uint64_t task_self(void) {
    if(!gSelfTask) {
        if (gSelfProc)
            gSelfTask = proc_task(gSelfProc);
        if (!kutils_is_kernel_ptr(gSelfTask))
            gSelfTask = kutils_task_from_socket_thread();
    }
    return gSelfTask;
}

uint64_t proc_find(pid_t pid) {
    // Round 13: one krwLock hold + one final repark for the whole allproc
    // walk (2 reads per proc; the round-9 per-op repark made every walk pay a
    // third syscall per read, and the fastkill path does several walks per
    // kill). Falls back to per-op locking when the batch can't take the lock
    // (sockets dead — the reads then fail safe exactly as before).
    bool batched = krw_batch_begin();
    uint64_t result = 0;
    uint64_t proc = proc_self();
    for (int i = 0; i < 4096 && kutils_is_kernel_ptr(proc); i++) {
        uint32_t curPid = kread32(proc + off_proc_p_pid);
        if (curPid == pid) {
            result = proc;
            goto done;
        }

        uint64_t next = kread64(proc + off_proc_p_list_le_next);
        if (!kutils_is_kernel_ptr(next) || next == proc) break;
        proc = next;
    }

    proc = proc_self();
    for (int i = 0; i < 4096 && kutils_is_kernel_ptr(proc); i++) {
        uint32_t curPid = kread32(proc + off_proc_p_pid);
        if (curPid == pid) {
            result = proc;
            goto done;
        }

        uint64_t prev = kread64(proc + off_proc_p_list_le_prev);
        if (!kutils_is_kernel_ptr(prev) || prev == proc) break;
        proc = prev;
    }

done:
    if (batched) krw_batch_end();
    return result;
}

uint64_t proc_find_by_name(const char* name) {
    uint64_t proc = proc_self();
    for (int i = 0; i < 4096 && kutils_is_kernel_ptr(proc); i++) {
        char *p_name = proc_get_p_name(proc);
        if(p_name != NULL && strcmp(p_name, name) == 0)
            return proc;

        uint64_t next = kread64(proc + off_proc_p_list_le_next);
        if (!kutils_is_kernel_ptr(next) || next == proc) break;
        proc = next;
    }
    
    proc = proc_self();
    for (int i = 0; i < 4096 && kutils_is_kernel_ptr(proc); i++) {
        char *p_name = proc_get_p_name(proc);
        if(p_name != NULL && strcmp(p_name, name) == 0)
            return proc;

        uint64_t prev = kread64(proc + off_proc_p_list_le_prev);
        if (!kutils_is_kernel_ptr(prev) || prev == proc) break;
        proc = prev;
    }
    
    return 0;
}

// Thread-local: the Process Viewer poll (background queue) and the kill
// path's protected-comm check (main queue) both resolve names concurrently —
// a shared static buffer let one overwrite the other between the read and the
// caller's copy-out, so the protection check could see another process's
// name. One spare byte keeps a full 32-char p_name NUL-terminated.
static __thread char proc_name[33];
char* proc_get_p_name(uint64_t proc) {
    if(!kutils_is_kernel_ptr(proc))   return NULL;
    // A canonical pointer is not proof the struct is still mapped: a reaped
    // proc's zone page can be trimmed. Gate the name range with the kernel_map
    // snapshot; the callers treat NULL as "unknown", never as a name.
    if (ksafe_available() &&
        !kaddr_is_mapped(proc + off_proc_p_name, 32)) return NULL;
    memset(proc_name, 0, sizeof(proc_name));
    kreadbuf(proc + off_proc_p_name, proc_name, 32);
    return proc_name;
}

uint64_t proc_task(uint64_t proc)
{
    if (!kutils_is_kernel_ptr(proc))
        return 0;
    uint64_t p_proc_ro = kread64(proc + off_proc_p_proc_ro);
    if (!kutils_is_kernel_ptr(p_proc_ro))
        return 0;
    uint64_t pr_task = kread64(p_proc_ro + off_proc_ro_pr_task);
    return pr_task;
}

static uint64_t ipc_entry_lookup_for_task(uint64_t task, uint64_t space, mach_port_name_t name)
{
    if (!kutils_is_kernel_ptr(space))
        return 0;

    // New format in iOS 16.1
    uint64_t rawTable = kread_ptr(space + off_ipc_space_is_table);
    uint64_t table = kread_smrptr(space + off_ipc_space_is_table);
    gKutilsLastIpcTask = task;
    gKutilsLastIpcSpace = space;
    gKutilsLastIpcName = name;
    gKutilsLastIpcRawTable = rawTable;
    gKutilsLastIpcTable = table;
    // Temporary FIX:
    // It seems like only problem occured when arm64 devices (especially iPad 7/17.0)
    // When tried running without below if code block, it still works fine on iPhone SE2/17.0, SE3/18.6.2
    // If code blocks running on iPad M4/26.0.x, it occured problems.
    if(!gIsPACSupported) {
        table |= 0xFFFFFF8000000000ULL;
        table = kalloc_array_decode(table);
        gKutilsLastIpcTable = table;
    }
    if (!kutils_is_kernel_or_smr_ptr(table)) {
        kutils_log_ipc_reject("table", task, space, name, table, rawTable, table);
        return 0;
    }

    uint64_t entry = table + (sizeof_ipc_entry * (name >> 8));
    if (!kutils_is_kernel_or_smr_ptr(entry)) {
        kutils_log_ipc_reject("entry", task, space, name, entry, rawTable, table);
        return 0;
    }
    return entry;
}

uint64_t ipc_entry_lookup(uint64_t space, mach_port_name_t name)
{
    return ipc_entry_lookup_for_task(0, space, name);
}

uint64_t task_get_ipc_port_table_entry(uint64_t task, mach_port_t port)
{
    if (!kutils_is_kernel_ptr(task))
        return 0;

    uint64_t itk_space = kread_ptr(task + off_task_itk_space);
    if (!kutils_is_kernel_ptr(itk_space))
        return 0;

    return ipc_entry_lookup_for_task(task, itk_space, port);
}
    
uint64_t task_get_ipc_port_object(uint64_t task, mach_port_t port)
{
    uint64_t entry = task_get_ipc_port_table_entry(task, port);
    if (!kutils_is_kernel_or_smr_ptr(entry)) {
        uint64_t space = 0;
        uint64_t rawTable = 0;
        uint64_t table = 0;
        if (gKutilsLastIpcTask == task && gKutilsLastIpcName == port) {
            space = gKutilsLastIpcSpace;
            rawTable = gKutilsLastIpcRawTable;
            table = gKutilsLastIpcTable;
        }
        kutils_log_ipc_reject("entry", task, space, port, entry, rawTable, table);
        return 0;
    }

    uint64_t objectAddr = entry + off_ipc_entry_ie_object;
    if (!kutils_is_kernel_ptr(objectAddr)) {
        kutils_log_ipc_reject("object address", task, 0, port, objectAddr, entry, 0);
        return 0;
    }

    uint64_t object = kread_ptr(objectAddr);
    if (!kutils_is_kernel_ptr(object)) {
        kutils_log_ipc_entry_dump(entry);
        kutils_log_ipc_reject("object", task, 0, port, object, entry, kalloc_array_decode(object));
        return 0;
    }
    return object;
}

uint64_t task_get_ipc_port_kobject(uint64_t task, mach_port_t port)
{
    uint64_t object = task_get_ipc_port_object(task, port);
    if (!kutils_is_kernel_ptr(object))
        return 0;

    uint64_t kobject = kread_ptr(object + off_ipc_port_ip_kobject);
    if (!kutils_is_kernel_ptr(kobject)) {
        kutils_log_ipc_reject("kobject", task, 0, port, kobject, object, kalloc_array_decode(kobject));
        return 0;
    }
    return kobject;
}

uint64_t task_get_vm_map(uint64_t task_ptr)
{
    if (!kutils_is_kernel_ptr(task_ptr))
        return 0;
    return kread_ptr(task_ptr + off_task_map);
}

uint64_t thread_get_t_tro(uint64_t thread) {
    if (!kutils_is_kernel_ptr(thread))
        return 0;
    // Round 16: boot-snapshot map gate. Threads die mid-walk; a kread of a
    // freed thread struct on a trimmed zone page faults the kernel
    // synchronously (copy_validate class) — the VA-range check alone cannot
    // see that. Returns 0 (= dead thread) for never-committed windows; the
    // freed-after-snapshot residual is accepted (µs window, zone-GC timing).
    if (ksafe_available() && !kaddr_is_mapped(thread, off_thread_t_tro + 8))
        return 0;
    return kread64(thread + off_thread_t_tro);
}

// from pe_main.js
// Round 21 (T3): _save variant hands the caller the ORIGINAL flags so every
// teardown path can put the remote task's task_exc_guard back. This is a
// TASK-LEVEL mutation of the hijacked task (launchd): leaving DELIVER set
// after our ports die makes a future real guard violation try to deliver an
// exception into dead ports — an undeliverable exception wedges the faulting
// launchd thread in mach_msg_rpc_from_kernel (the panic-1/3 shape).
int disable_excguard_kill_save(uint64_t task, uint32_t *origOut) {
    if (!kutils_is_kernel_ptr(task) || !off_task_task_exc_guard)
        return -1;

    uint64_t addr = task + off_task_task_exc_guard;
    uint32_t before = kread32(addr);
    if (before & 0xffff0000U) {
        printf("[kutils] refusing task_exc_guard write task=%#llx off=%#x value=%#x\n",
               task, off_task_task_exc_guard, before);
        return -1;
    }
    if (origOut) *origOut = before;

    // in mach_port_guard_ast, the victim would crash if these are on.
    uint32_t excGuard = before;
    excGuard &= ~(TASK_EXC_GUARD_MP_CORPSE | TASK_EXC_GUARD_MP_FATAL);
    excGuard |= TASK_EXC_GUARD_MP_DELIVER;
    kwrite32(addr, excGuard);

    uint32_t verify = kread32(addr);
    if ((verify & (TASK_EXC_GUARD_MP_CORPSE | TASK_EXC_GUARD_MP_FATAL)) ||
        !(verify & TASK_EXC_GUARD_MP_DELIVER)) {
        printf("[kutils] task_exc_guard verify failed task=%#llx off=%#x before=%#x after=%#x\n",
               task, off_task_task_exc_guard, before, verify);
        // The write may have partially landed — best-effort revert NOW, while
        // the caller still knows the original value, rather than leaving a
        // half-patched launchd behind a failed init.
        kwrite32(addr, before);
        uint32_t reverify = kread32(addr);
        printf("[kutils] task_exc_guard revert after failed verify: %#x (%s)\n",
               reverify, reverify == before ? "OK" : "FAILED");
        return -1;
    }

    return 0;
}

int disable_excguard_kill(uint64_t task) {
    return disable_excguard_kill_save(task, NULL);
}

// Round 21 (T3): write the ORIGINAL task_exc_guard flags back, with readback
// verification. Called from every RemoteCall teardown path (destroy, abandon,
// init-failure). Safe to call only with live KRW — the caller gates that.
int restore_excguard_kill(uint64_t task, uint32_t origFlags) {
    if (!kutils_is_kernel_ptr(task) || !off_task_task_exc_guard)
        return -1;
    if (origFlags & 0xffff0000U) {
        printf("[kutils] refusing task_exc_guard restore task=%#llx value=%#x (implausible)\n",
               task, origFlags);
        return -1;
    }

    uint64_t addr = task + off_task_task_exc_guard;
    uint32_t before = kread32(addr);
    kwrite32(addr, origFlags);
    uint32_t verify = kread32(addr);
    if (verify != origFlags) {
        printf("[kutils] task_exc_guard restore FAILED task=%#llx off=%#x current=%#x wanted=%#x after=%#x\n",
               task, off_task_task_exc_guard, before, origFlags, verify);
        return -1;
    }
    printf("[kutils] task_exc_guard restored task=%#llx %#x -> %#x\n",
           task, before, origFlags);
    return 0;
}

uint64_t thread_get_task(uint64_t thread)
{
    uint64_t tro = thread_get_t_tro(thread);
    if (!kutils_is_kernel_ptr(tro))
        return 0;
    // Round 16: the tro (thread_ro) is a separate zone allocation that dies
    // with the thread — same trimmed-page fault class as the thread struct
    // itself. Boot-snapshot map gate before dereferencing it.
    if (ksafe_available() && !kaddr_is_mapped(tro, off_thread_ro_tro_task + 8))
        return 0;
    return kread64(tro + off_thread_ro_tro_task);
}

uint16_t thread_get_options(uint64_t thread)
{
    return kread16(thread + off_thread_options);
}

void thread_set_options(uint64_t thread, uint16_t options) {
    kwrite16(thread + off_thread_options, options);
}

void thread_set_mutex(uint64_t thread, uint32_t ctid) {
    kwrite32(thread + off_thread_mutex_lck_mtx_data, ctid);
}

uint32_t thread_get_mutex(uint64_t thread) {
    return kread32(thread + off_thread_mutex_lck_mtx_data);
}

uint64_t thread_get_kstackptr(uint64_t thread) {
    return kread_ptr(thread + off_thread_machine_kstackptr);
}

uint64_t thread_get_jop_pid(uint64_t thread) {
    return kread64(thread + off_thread_machine_jop_pid);
}

uint64_t thread_get_rop_pid(uint64_t thread) {
    return kread64(thread + off_thread_machine_rop_pid);
}

uint64_t proc_get_cred_label(uint64_t proc) {
    uint64_t p_proc_ro = kread64(proc + off_proc_p_proc_ro);
    uint64_t ucred = kread64(p_proc_ro + off_proc_ro_p_ucred);
    uint64_t label = kread_ptr(ucred + off_ucred_cr_label);
    return label;
}

uint64_t amfi_cslot_get(uint64_t label) {
    return kread64(label + off_label_l_perpolicy_amfi);
}

uint64_t label_get_sandbox(uint64_t label) {
    return kread64(label + off_label_l_perpolicy_sandbox);
}

// from Darksword's libs/TaskRop/Task.js - static #kallocArrayDecodeAddr(ptr)
uint64_t kalloc_array_decode(uint64_t ptr)
{
    //xnu-10002.61.3/osfmk/kern/kalloc.c:2047
    uint64_t shift = 64 - t1sz_boot - 1;
    uint64_t zone_mask = 1ULL << shift;

    if (ptr & zone_mask) {
        ptr &= ~0x1FULL;
    } else {
        ptr &= ~0x3FFFULL;
        ptr |= zone_mask;
    }
    return ptr;
}

const char* get_bootManifestHash(void) {
    struct statfs fs;
    if (statfs("/usr/standalone/firmware", &fs) == 0) {
        NSString *mountedPath = [NSString stringWithUTF8String:fs.f_mntfromname];
        NSArray<NSString *> *components = [mountedPath componentsSeparatedByString:@"/"];
        if ([components count] > 3) {
            NSString *substring = components[3];
            return substring.UTF8String;
        }
    }
    return NULL;
}
