diff --git a/overlay/include/linux/kemu.h b/overlay/include/linux/kemu.h index dea45c4..01da5d4 100644 --- a/overlay/include/linux/kemu.h +++ b/overlay/include/linux/kemu.h @@ -42,6 +42,8 @@ void kemu_exit_to_user(struct pt_regs *regs); /* Signal delivery and syscall restart for kemu tasks. */ void kemu_do_signal(struct pt_regs *regs); +/* syscall_rollback() on a kemu task (current): guest x0 gets orig_x0 back. */ +void kemu_syscall_rollback(struct task_struct *task); /* mm / task lifecycle. */ int kemu_dup_mm(struct mm_struct *oldmm, struct mm_struct *mm); @@ -60,6 +62,13 @@ long kemu_arch_ptrace(struct task_struct *child, long request, unsigned long addr, unsigned long data); void kemu_user_step(struct task_struct *child, bool on); +/* ipc/sem.c: semctl on a kernel struct (kemu marshals the user layout, + * whose x86_64 and arm64 forms differ). Called from kemu and defined in + * ipc/sem.c, which reuses the static semctl_stat/semctl_down helpers. */ +struct semid64_ds; +int kemu_semctl_stat(int semid, int cmd, struct semid64_ds *out); +int kemu_semctl_set(int semid, int cmd, struct semid64_ds *in); + /* mm / proc */ void kemu_unmapped(struct mm_struct *mm, unsigned long start, unsigned long end); bool kemu_vma_hidden(struct vm_area_struct *vma); diff --git a/overlay/kernel/kemu/abi.c b/overlay/kernel/kemu/abi.c index 08f00d9..e9d24b7 100644 --- a/overlay/kernel/kemu/abi.c +++ b/overlay/kernel/kemu/abi.c @@ -18,6 +18,9 @@ #include #include #include +#include +#include +#include #include "kemu_internal.h" @@ -28,6 +31,7 @@ asmlinkage long __x64_sys_open_by_handle_at(const struct pt_regs *regs); asmlinkage long __x64_sys_fanotify_init(const struct pt_regs *regs); asmlinkage long __x64_sys_newuname(const struct pt_regs *regs); asmlinkage long __x64_sys_clone(const struct pt_regs *regs); +asmlinkage long __x64_sys_semctl(const struct pt_regs *regs); asmlinkage long __x64_sys_epoll_pwait(const struct pt_regs *regs); asmlinkage long __x64_sys_epoll_pwait2(const struct pt_regs *regs); int do_sys_openat2(int dfd, const char __user *filename, struct open_how *how); @@ -101,8 +105,13 @@ long kemu_sys_openat2(struct pt_regs *regs) err = copy_struct_from_user(&how, sizeof(how), uhow, usize); if (err) return err; + /* Audit logs the guest's (arm64) flags, under AUDIT_ARCH_AARCH64. */ + audit_openat2_how(&how); /* Bits outside the translated set are validated by the core. */ how.flags = (how.flags & ~(u64)U32_MAX) | kemu_oflags_to_host((u32)how.flags); + /* O_LARGEFILE is forced on 64-bit (non-O_PATH), as in native openat2. */ + if (!(how.flags & O_PATH) && force_o_largefile()) + how.flags |= O_LARGEFILE; return do_sys_openat2((int)kemu_reg(regs, di), (const char __user *)kemu_reg(regs, si), &how); } @@ -295,3 +304,85 @@ long kemu_sys_clone(struct pt_regs *regs) swap(kemu_reg(regs, r10), kemu_reg(regs, r8)); return __x64_sys_clone(regs); } + +/* ---- semctl ---- + * + * The x86_64 semid64_ds inserts two padding words (__unused1/__unused2) + * that asm-generic (arm64) doesn't, so its layout is 104 bytes where the + * guest's is 88. Only IPC_STAT/SEM_STAT/SEM_STAT_ANY (out) and IPC_SET (in) + * carry the struct; every other command is layout-agnostic and passes + * through. cmd never has the IPC_64 bit here (the entry fixes the version), + * matching the native switch; anything else falls through to the native + * handler, which rejects it exactly as arm64 would. + */ +struct kemu_ipc64_perm { + s32 key; + u32 uid, gid, cuid, cgid; + u32 mode; + u16 seq, __pad2; + u64 __unused1, __unused2; +}; + +struct kemu_semid64_ds { + struct kemu_ipc64_perm sem_perm; + s64 sem_otime; + s64 sem_ctime; + u64 sem_nsems; + u64 __unused3; + u64 __unused4; +}; +static_assert(sizeof(struct kemu_semid64_ds) == 88); +static_assert(sizeof(struct kemu_ipc64_perm) == sizeof(struct ipc64_perm)); + +/* Copy the shared fields between the native and guest layouts. */ +static void kemu_semid_to_guest(const struct semid64_ds *k, struct kemu_semid64_ds *g) +{ + memset(g, 0, sizeof(*g)); + memcpy(&g->sem_perm, &k->sem_perm, sizeof(g->sem_perm)); + g->sem_otime = k->sem_otime; + g->sem_ctime = k->sem_ctime; + g->sem_nsems = k->sem_nsems; +} + +static void kemu_semid_from_guest(const struct kemu_semid64_ds *g, struct semid64_ds *k) +{ + memset(k, 0, sizeof(*k)); + memcpy(&k->sem_perm, &g->sem_perm, sizeof(g->sem_perm)); + k->sem_otime = g->sem_otime; + k->sem_ctime = g->sem_ctime; + k->sem_nsems = g->sem_nsems; +} + +long kemu_sys_semctl(struct pt_regs *regs) +{ + int semid = (int)kemu_reg(regs, di); + int cmd = (int)kemu_reg(regs, dx); + void __user *p = (void __user *)kemu_reg(regs, r10); + struct kemu_semid64_ds g; + struct semid64_ds k; + int err; + + /* As ksys_semctl(): the stat/set helpers would mask a negative id + * into a valid index. */ + if (semid < 0) + return -EINVAL; + switch (cmd) { + case IPC_STAT: + case SEM_STAT: + case SEM_STAT_ANY: + err = kemu_semctl_stat(semid, cmd, &k); + if (err < 0) + return err; + kemu_semid_to_guest(&k, &g); + if (copy_to_user(p, &g, sizeof(g))) + return -EFAULT; + return err; /* SEM_STAT* returns the semid */ + case IPC_SET: + if (copy_from_user(&g, p, sizeof(g))) + return -EFAULT; + kemu_semid_from_guest(&g, &k); + return kemu_semctl_set(semid, cmd, &k); + default: + return __x64_sys_semctl(regs); + } +} diff --git a/overlay/kernel/kemu/core.c b/overlay/kernel/kemu/core.c index c8709e8..8db526b 100644 --- a/overlay/kernel/kemu/core.c +++ b/overlay/kernel/kemu/core.c @@ -484,7 +484,8 @@ int kemu_dup_mm(struct mm_struct *oldmm, struct mm_struct *mm) km->vdso_base = okm->vdso_base; err = -ENOMEM; km->chunks[0] = vzalloc(KEMU_STUBS_SIZE); - km->table = vmalloc(KEMU_TABLE_SIZE); + /* Zeroed: the whole table is mapped, but only part of it is written. */ + km->table = vzalloc(KEMU_TABLE_SIZE); if (!km->chunks[0] || !km->table) goto out_unlock; memcpy(km->chunks[0], okm->chunks[0], KEMU_STUBS_SIZE); diff --git a/overlay/kernel/kemu/jit.c b/overlay/kernel/kemu/jit.c index 61a8b1f..db6c64a 100644 --- a/overlay/kernel/kemu/jit.c +++ b/overlay/kernel/kemu/jit.c @@ -101,12 +101,19 @@ static void kemu_inval_free(struct kemu_mm *km); static void kemu_chunk_free(struct kemu_mm *km, int c) { - vfree(km->chunks[c]); - kvfree(km->blockmap[c]); - km->chunks[c] = NULL; - km->blockmap[c] = NULL; + void *mem = km->chunks[c]; + unsigned long *bm = km->blockmap[c]; + + WRITE_ONCE(km->chunks[c], NULL); + WRITE_ONCE(km->blockmap[c], NULL); km->chunk_used[c] = 0; - km->chunk_retired[c] = 0; + /* + * kemu_materialize() reads chunk_retired locklessly and then trusts + * the pointers of a live (0) chunk: clear them first. + */ + smp_store_release(&km->chunk_retired[c], 0); + vfree(mem); + kvfree(bm); } void kemu_jit_free(struct kemu_mm *km) @@ -468,7 +475,11 @@ static int kemu_chunk_new(struct kemu_mm *km) kemu_jit_flush(km); return -EAGAIN; } - mem = __vmalloc(KEMU_CHUNK_SIZE, GFP_KERNEL_ACCOUNT); + /* + * Zeroed: kemu_code_fault() maps every page of a live chunk, including + * the unused tail and the padding between blocks. + */ + mem = __vmalloc(KEMU_CHUNK_SIZE, GFP_KERNEL_ACCOUNT | __GFP_ZERO); bm = kvzalloc(BITS_TO_LONGS(KEMU_BLOCKMAP_BITS) * sizeof(long), GFP_KERNEL_ACCOUNT); if (!mem || !bm) { @@ -480,7 +491,8 @@ static int kemu_chunk_new(struct kemu_mm *km) km->blockmap[c] = bm; km->chunk_used[c] = 0; km->chunk_retired[c] = 0; - WRITE_ONCE(km->chunks[c], mem); + /* Publish the blockmap with the chunk (kemu_materialize is lockless). */ + smp_store_release(&km->chunks[c], mem); up_write(&km->chunk_sem); km->cur_chunk = c; return 0; @@ -499,14 +511,17 @@ static u8 *kemu_find_block(struct kemu_mm *km, unsigned long off, size_t *len) u64 gpc; u32 main; size_t sz; - u8 *blk; + u8 *chunk, *blk; - if (c == 0 || c >= KEMU_MAX_CHUNKS || !km->chunks[c] || in >= km->chunk_used[c]) + if (c == 0 || c >= KEMU_MAX_CHUNKS) + return NULL; + chunk = smp_load_acquire(&km->chunks[c]); + if (!chunk || in >= km->chunk_used[c]) return NULL; bit = find_last_bit(km->blockmap[c], in / KEMU_BLOCK_ALIGN + 1); if (bit > in / KEMU_BLOCK_ALIGN) return NULL; - blk = km->chunks[c] + bit * KEMU_BLOCK_ALIGN; + blk = chunk + bit * KEMU_BLOCK_ALIGN; sz = kemu_rs_block_info(blk, km->chunk_used[c] - bit * KEMU_BLOCK_ALIGN, &gpc, &main); if (!sz || in >= bit * KEMU_BLOCK_ALIGN + sz) return NULL; @@ -733,13 +748,23 @@ void kemu_materialize(struct pt_regs *regs) kemu_rs_recover_stub(kemu_stub_info(km, ip - km->code_base), &h, &kt->shadow); } else if (ip >= km->code_base && ip < km->code_base + KEMU_CODE_SIZE) { + u64 retired; + off = ip - km->code_base; - blk = kemu_find_block(km, off, &len); + c = off >> KEMU_CHUNK_SHIFT; + /* + * A chunk retired in an epoch this thread has already + * acknowledged is not pinned by it (kemu_min_epoch_seen), so + * another thread's kemu_reclaim() may free it under us. Correct + * code never runs there: acknowledging an epoch resets the host + * return stack. Only a forged return address gets here. + */ + retired = smp_load_acquire(&km->chunk_retired[c]); + blk = retired && retired <= kt->epoch_seen ? NULL : kemu_find_block(km, off, &len); if (!blk || !kemu_rs_recover(blk, len, ((u8 *)km->chunks[off >> KEMU_CHUNK_SHIFT] + (off & (KEMU_CHUNK_SIZE - 1))) - blk, &h, &kt->shadow)) { - c = off >> KEMU_CHUNK_SHIFT; pr_warn_ratelimited("kemu: %s[%d]: cannot recover state at %lx (chunk %lu %s retired %llu used %x; epoch %llu seen %llu flags %lx)\n", current->comm, task_pid_nr(current), ip, c, km->chunks[c] ? "live" : "freed", km->chunk_retired[c], @@ -996,7 +1021,7 @@ int kemu_jit_dup(struct kemu_mm *okm, struct kemu_mm *km) for (c = 1; c < KEMU_MAX_CHUNKS; c++) { if (!okm->chunks[c] || okm->chunk_retired[c]) continue; - km->chunks[c] = __vmalloc(KEMU_CHUNK_SIZE, GFP_KERNEL_ACCOUNT); + km->chunks[c] = __vmalloc(KEMU_CHUNK_SIZE, GFP_KERNEL_ACCOUNT | __GFP_ZERO); km->blockmap[c] = kvmalloc(BITS_TO_LONGS(KEMU_BLOCKMAP_BITS) * sizeof(long), GFP_KERNEL_ACCOUNT); if (!km->chunks[c] || !km->blockmap[c]) diff --git a/overlay/kernel/kemu/kemu_internal.h b/overlay/kernel/kemu/kemu_internal.h index 3d1c0bc..303efdb 100644 --- a/overlay/kernel/kemu/kemu_internal.h +++ b/overlay/kernel/kemu/kemu_internal.h @@ -166,6 +166,7 @@ struct kemu_pgvec { #define KEMU_TF_KSTATE BIT(2) /* state page authoritative (in kernel) */ #define KEMU_TF_STEP BIT(3) /* ptrace single-step */ #define KEMU_TF_STEP_SVC BIT(4) /* trap after the stepped svc */ +#define KEMU_TF_ROLLBACK BIT(5) /* syscall_rollback() undid this svc */ struct kemu_thread { struct task_struct *task; @@ -251,6 +252,7 @@ long kemu_sys_epoll_pwait(struct pt_regs *regs); long kemu_sys_epoll_pwait2(struct pt_regs *regs); long kemu_sys_uname(struct pt_regs *regs); long kemu_sys_clone(struct pt_regs *regs); +long kemu_sys_semctl(struct pt_regs *regs); /* env.c: host services for the Rust core. */ int kemu_c_read(u64 addr, void *buf, size_t len); diff --git a/overlay/kernel/kemu/ptrace.c b/overlay/kernel/kemu/ptrace.c index 5518a18..23f3509 100644 --- a/overlay/kernel/kemu/ptrace.c +++ b/overlay/kernel/kemu/ptrace.c @@ -16,12 +16,21 @@ #define KEMU_PSR_NZCV 0xf0000000ULL +/* + * User workers (e.g. vhost) in a kemu thread group have no kemu state but + * are still visited with the group's regset view, e.g. by core dumps. + * Their arm64 registers read as zero and can't be written. + */ + /* arm64 user_pt_regs: x0-x30, sp, pc, pstate. */ static int kemu_gpr_get(struct task_struct *target, const struct user_regset *regset, struct membuf to) { - struct kemu_cpu *cpu = target->kemu->cpu; + struct kemu_cpu *cpu; + if (!target->kemu) + return membuf_zero(&to, to.left); + cpu = target->kemu->cpu; membuf_write(&to, cpu->x, sizeof(cpu->x)); membuf_store(&to, cpu->sp); membuf_store(&to, cpu->pc); @@ -52,6 +61,8 @@ static int kemu_gpr_set(struct task_struct *target, const struct user_regset *re u64 r[34]; int err; + if (!target->kemu) + return -EIO; memcpy(r, kt->cpu->x, sizeof(kt->cpu->x)); r[31] = kt->cpu->sp; r[32] = kt->cpu->pc; @@ -75,9 +86,12 @@ static int kemu_gpr_set(struct task_struct *target, const struct user_regset *re static int kemu_fpr_get(struct task_struct *target, const struct user_regset *regset, struct membuf to) { - struct kemu_cpu *cpu = target->kemu->cpu; + struct kemu_cpu *cpu; u32 rsv[2] = { 0, 0 }; + if (!target->kemu) + return membuf_zero(&to, to.left); + cpu = target->kemu->cpu; membuf_write(&to, cpu->v, sizeof(cpu->v)); membuf_store(&to, cpu->fpsr); membuf_store(&to, cpu->fpcr); @@ -88,13 +102,16 @@ static int kemu_fpr_set(struct task_struct *target, const struct user_regset *re unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { - struct kemu_cpu *cpu = target->kemu->cpu; + struct kemu_cpu *cpu; struct { u64 v[32][2]; u32 fpsr, fpcr, rsv[2]; } f; int err; + if (!target->kemu) + return -EIO; + cpu = target->kemu->cpu; memcpy(f.v, cpu->v, sizeof(f.v)); f.fpsr = cpu->fpsr; f.fpcr = cpu->fpcr; @@ -111,6 +128,8 @@ static int kemu_fpr_set(struct task_struct *target, const struct user_regset *re static int kemu_tls_get(struct task_struct *target, const struct user_regset *regset, struct membuf to) { + if (!target->kemu) + return membuf_zero(&to, to.left); return membuf_store(&to, target->kemu->cpu->tpidr); } @@ -118,9 +137,13 @@ static int kemu_tls_set(struct task_struct *target, const struct user_regset *re unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { - u64 tls = target->kemu->cpu->tpidr; - int err = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &tls, 0, sizeof(tls)); + u64 tls; + int err; + if (!target->kemu) + return -EIO; + tls = target->kemu->cpu->tpidr; + err = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &tls, 0, sizeof(tls)); if (!err) target->kemu->cpu->tpidr = tls; return err; @@ -129,9 +152,12 @@ static int kemu_tls_set(struct task_struct *target, const struct user_regset *re static int kemu_syscall_get(struct task_struct *target, const struct user_regset *regset, struct membuf to) { - int nr = (target->kemu->flags & KEMU_TF_IN_SVC) ? - (int)kemu_reg(task_pt_regs(target), orig_ax) : -1; + int nr; + if (!target->kemu) + return membuf_zero(&to, to.left); + nr = (target->kemu->flags & KEMU_TF_IN_SVC) ? + (int)kemu_reg(task_pt_regs(target), orig_ax) : -1; return membuf_store(&to, nr); } @@ -139,10 +165,13 @@ static int kemu_syscall_set(struct task_struct *target, const struct user_regset unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { - int nr = (target->kemu->flags & KEMU_TF_IN_SVC) ? - (int)kemu_reg(task_pt_regs(target), orig_ax) : -1; - int err = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &nr, 0, sizeof(nr)); + int nr, err; + if (!target->kemu) + return -EIO; + nr = (target->kemu->flags & KEMU_TF_IN_SVC) ? + (int)kemu_reg(task_pt_regs(target), orig_ax) : -1; + err = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &nr, 0, sizeof(nr)); if (err) return err; if (target->kemu->flags & KEMU_TF_IN_SVC) @@ -222,6 +251,8 @@ void kemu_user_step(struct task_struct *child, bool on) { struct kemu_thread *kt = child->kemu; + if (!kt) + return; if (on) kt->flags |= KEMU_TF_STEP; else diff --git a/overlay/kernel/kemu/syscall.c b/overlay/kernel/kemu/syscall.c index 00b7b1c..cabf214 100644 --- a/overlay/kernel/kemu/syscall.c +++ b/overlay/kernel/kemu/syscall.c @@ -57,10 +57,23 @@ static long kemu_dispatch(struct pt_regs *regs, long nr) return kemu_syscall_table(regs, nr); } +/* + * syscall_rollback() hook (seccomp RET_TRAP/RET_KILL, syscall user + * dispatch): always on current, inside its syscall. + */ +void kemu_syscall_rollback(struct task_struct *task) +{ + struct kemu_thread *kt = task->kemu; + + if (kt->flags & KEMU_TF_IN_SVC) + kt->flags |= KEMU_TF_ROLLBACK; +} + /* KEMU_OP_SVC: a guest `svc #0`. The guest PC already points past it. */ void kemu_svc(struct pt_regs *regs) { struct kemu_thread *kt = current->kemu; + struct mm_struct *old_mm = current->mm; struct kemu_cpu *cpu = kt->cpu; u64 next_pc; long nr; @@ -69,22 +82,42 @@ void kemu_svc(struct pt_regs *regs) next_pc = cpu->pc; kemu_load_syscall_view(regs, cpu); kt->orig_x0 = kemu_reg(regs, di); - kt->flags |= KEMU_TF_IN_SVC; + kt->flags = (kt->flags & ~KEMU_TF_ROLLBACK) | KEMU_TF_IN_SVC; nr = kemu_syscall_enter(regs); kemu_store_syscall_args(regs, cpu); if (nr != -1) kemu_reg(regs, ax) = kemu_dispatch(regs, nr); + + /* + * A successful execve frees this thread's kemu state and its state + * page (kemu_exec_release + the old mm's teardown). The new kemu_thread + * can reuse the same slab object, so compare the mm too before touching + * anything behind @kt or @cpu. + */ + if (current->kemu != kt || current->mm != old_mm) + return; + if (kemu_debug >= 2) pr_info("kemu: %s[%d] sys %ld(%lx, %lx, %lx, %lx) = %lx pc %llx\n", current->comm, task_pid_nr(current), nr, kemu_reg(regs, di), kemu_reg(regs, si), kemu_reg(regs, dx), kemu_reg(regs, r10), kemu_reg(regs, ax), cpu->pc); - /* exec may have replaced (or dropped) the kemu state. */ - if (current->kemu != kt) - return; - if (kt->flags & KEMU_TF_IN_SVC) - WRITE_ONCE(kt->cpu->x[0], kemu_reg(regs, ax)); + /* + * Guest x0 gets the return value, except when seccomp/syscall-user- + * dispatch rolled the syscall back (RET_TRAP, RET_KILL). x86 rollback + * writes orig_ax (here the arm64 syscall nr) into ax, but arm64 restores + * orig_x0; a SIGSYS broker (Chromium, Firefox) reads orig_x0 from the + * frame. syscall_rollback() flags the rollback: a skip that sets a + * return value (RET_ERRNO, a user-notification reply) can leave ax + * equal to orig_ax too, and must still be written. + */ + if (kt->flags & KEMU_TF_IN_SVC) { + if (kt->flags & KEMU_TF_ROLLBACK) + WRITE_ONCE(kt->cpu->x[0], kt->orig_x0); + else + WRITE_ONCE(kt->cpu->x[0], kemu_reg(regs, ax)); + } /* The guest PC changed (e.g. rt_sigreturn): resume at dispatch. */ if (READ_ONCE(cpu->pc) != next_pc) kemu_redirect(kt); diff --git a/overlay/kernel/kemu/syscall_table.h b/overlay/kernel/kemu/syscall_table.h index 164dd1b..8c31ded 100644 --- a/overlay/kernel/kemu/syscall_table.h +++ b/overlay/kernel/kemu/syscall_table.h @@ -207,7 +207,6 @@ asmlinkage long __x64_sys_renameat(const struct pt_regs *regs); asmlinkage long __x64_sys_renameat2(const struct pt_regs *regs); asmlinkage long __x64_sys_request_key(const struct pt_regs *regs); asmlinkage long __x64_sys_restart_syscall(const struct pt_regs *regs); -asmlinkage long __x64_sys_rseq(const struct pt_regs *regs); asmlinkage long __x64_sys_rt_sigaction(const struct pt_regs *regs); asmlinkage long __x64_sys_rt_sigpending(const struct pt_regs *regs); asmlinkage long __x64_sys_rt_sigprocmask(const struct pt_regs *regs); @@ -228,7 +227,6 @@ asmlinkage long __x64_sys_sched_setparam(const struct pt_regs *regs); asmlinkage long __x64_sys_sched_setscheduler(const struct pt_regs *regs); asmlinkage long __x64_sys_sched_yield(const struct pt_regs *regs); asmlinkage long __x64_sys_seccomp(const struct pt_regs *regs); -asmlinkage long __x64_sys_semctl(const struct pt_regs *regs); asmlinkage long __x64_sys_semget(const struct pt_regs *regs); asmlinkage long __x64_sys_semop(const struct pt_regs *regs); asmlinkage long __x64_sys_semtimedop(const struct pt_regs *regs); @@ -320,6 +318,7 @@ long kemu_sys_openat(struct pt_regs *regs); long kemu_sys_openat2(struct pt_regs *regs); long kemu_sys_pipe2(struct pt_regs *regs); long kemu_sys_rt_sigreturn(struct pt_regs *regs); +long kemu_sys_semctl(struct pt_regs *regs); long kemu_sys_uname(struct pt_regs *regs); #define KEMU_NR_SYSCALLS 470 @@ -516,7 +515,7 @@ static long kemu_syscall_table(struct pt_regs *regs, unsigned long nr) case 188: return __x64_sys_msgrcv(regs); /* msgrcv */ case 189: return __x64_sys_msgsnd(regs); /* msgsnd */ case 190: return __x64_sys_semget(regs); /* semget */ - case 191: return __x64_sys_semctl(regs); /* semctl */ + case 191: return kemu_sys_semctl(regs); /* semctl */ case 192: return __x64_sys_semtimedop(regs); /* semtimedop */ case 193: return __x64_sys_semop(regs); /* semop */ case 194: return __x64_sys_shmget(regs); /* shmget */ @@ -602,7 +601,6 @@ static long kemu_syscall_table(struct pt_regs *regs, unsigned long nr) case 290: return __x64_sys_pkey_free(regs); /* pkey_free */ case 291: return __x64_sys_statx(regs); /* statx */ case 292: return __x64_sys_io_pgetevents(regs); /* io_pgetevents */ - case 293: return __x64_sys_rseq(regs); /* rseq */ case 294: return __x64_sys_kexec_file_load(regs); /* kexec_file_load */ case 424: return __x64_sys_pidfd_send_signal(regs); /* pidfd_send_signal */ case 428: return __x64_sys_open_tree(regs); /* open_tree */ @@ -652,6 +650,7 @@ static long kemu_syscall_table(struct pt_regs *regs, unsigned long nr) } /* arm64 syscalls without an x86_64 entry point, or disabled (ENOSYS): */ +/* 293 rseq (disabled) */ /* 425 io_uring_setup (disabled) */ /* 426 io_uring_enter (disabled) */ /* 427 io_uring_register (disabled) */ diff --git a/overlay/rust/kemu_core/src/interp.rs b/overlay/rust/kemu_core/src/interp.rs index 08a6980..4855099 100644 --- a/overlay/rust/kemu_core/src/interp.rs +++ b/overlay/rust/kemu_core/src/interp.rs @@ -14,7 +14,9 @@ use crate::sysregs; /// Reason the interpreter returned to its caller. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Exit { - /// Instruction budget exhausted. `pc` points at the next instruction. + /// Instruction budget exhausted. `pc` points at the next instruction, + /// which may be one that gave up before completing (a contended + /// atomic) and must simply be executed again. Budget, /// `SVC` executed. `pc` already advanced past the `svc`. Svc, diff --git a/overlay/rust/kemu_core/src/interp/mem.rs b/overlay/rust/kemu_core/src/interp/mem.rs index 3f9e6a7..88d5ee0 100644 --- a/overlay/rust/kemu_core/src/interp/mem.rs +++ b/overlay/rust/kemu_core/src/interp/mem.rs @@ -6,6 +6,10 @@ use crate::decode::{Index, Insn, Order, RmwOp}; use crate::env::{Access, Env, Fault}; use crate::state::CpuState; +/// Attempts of an LSE read-modify-write before the instruction is handed +/// back unexecuted (`Exit::Budget` with `pc` unchanged). +pub(crate) const ATOMIC_RETRIES: u32 = 64; + /// Read `size` (log2 bytes) from guest memory, zero-extended into u64. fn load_mem(env: &mut dyn DynEnv, addr: u64, size: u8) -> Result { Ok(match size { @@ -343,8 +347,12 @@ pub(super) fn exec_atomic(cpu: &mut CpuState, env: &mut E, insn: Insn) - return Step::Exit(Exit::Fault(Fault { addr, access: Access::Write, align: true })); } let operand = cpu.xr(rs); - // Read-modify-write via a cmpxchg loop on `size` bytes. - loop { + // Read-modify-write via a cmpxchg loop on `size` bytes. Other + // threads can make every attempt fail; after a bounded number of + // retries give up with nothing committed and `pc` still at this + // instruction, so the host gets a preemption/signal point and the + // instruction is restarted from scratch. + for _ in 0..ATOMIC_RETRIES { let old = match load_mem(env, addr, size) { Ok(v) => v, Err(f) => return Step::Exit(Exit::Fault(f)), @@ -367,10 +375,10 @@ pub(super) fn exec_atomic(cpu: &mut CpuState, env: &mut E, insn: Insn) - if got == truncsz(old, size) { // Return the pre-op value (zero-extended) to rt (unless XZR). cpu.set_xr(rt, truncsz(old, size)); - break; + return Step::Next; } } - Step::Next + Step::Exit(Exit::Budget) } else { Step::Exit(Exit::Undefined(0)) } diff --git a/overlay/rust/kemu_core/src/interp/tests.rs b/overlay/rust/kemu_core/src/interp/tests.rs index ed13c10..e0ee8ed 100644 --- a/overlay/rust/kemu_core/src/interp/tests.rs +++ b/overlay/rust/kemu_core/src/interp/tests.rs @@ -418,3 +418,56 @@ fn recover_cached_vectors() { assert!(bodies >= 2 && (!enabled || helpers > 0) && exits > 0, "enabled={enabled} bodies={bodies} helpers={helpers} exits={exits}"); } } + +/// Env whose cmpxchg never succeeds: models an atomic word another CPU keeps +/// changing between our load and our store. +struct ContendedEnv { + mem: std::vec::Vec, + base: u64, + attempts: u32, +} +impl Env for ContendedEnv { + fn fetch(&mut self, pc: u64) -> Result { self.read_u32(pc) } + fn read_u8(&mut self, a: u64) -> Result { + let i = (a - self.base) as usize; + self.mem.get(i).copied().ok_or(Fault { addr: a, access: crate::env::Access::Read, align: false }) + } + fn read_u16(&mut self, a: u64) -> Result { Ok(u16::from_le_bytes([self.read_u8(a)?, self.read_u8(a+1)?])) } + fn read_u32(&mut self, a: u64) -> Result { let mut b=[0u8;4]; for (i,x) in b.iter_mut().enumerate(){*x=self.read_u8(a+i as u64)?;} Ok(u32::from_le_bytes(b)) } + fn read_u64(&mut self, a: u64) -> Result { let mut b=[0u8;8]; for (i,x) in b.iter_mut().enumerate(){*x=self.read_u8(a+i as u64)?;} Ok(u64::from_le_bytes(b)) } + fn write_u8(&mut self, a: u64, v: u8) -> Result<(), Fault> { let i=(a-self.base) as usize; self.mem[i]=v; Ok(()) } + fn write_u16(&mut self, a: u64, v: u16) -> Result<(), Fault> { for (i,b) in v.to_le_bytes().iter().enumerate(){self.write_u8(a+i as u64,*b)?;} Ok(()) } + fn write_u32(&mut self, a: u64, v: u32) -> Result<(), Fault> { for (i,b) in v.to_le_bytes().iter().enumerate(){self.write_u8(a+i as u64,*b)?;} Ok(()) } + fn write_u64(&mut self, a: u64, v: u64) -> Result<(), Fault> { for (i,b) in v.to_le_bytes().iter().enumerate(){self.write_u8(a+i as u64,*b)?;} Ok(()) } + fn cmpxchg(&mut self, a: u64, size: u32, _e: [u64;2], _n: [u64;2]) -> Result<[u64;2], Fault> { + // Always report an "old" value that differs from what was expected, + // so the RMW never commits. + self.attempts += 1; + let cur = match size { 1 => self.read_u8(a)? as u64, 2 => self.read_u16(a)? as u64, 4 => self.read_u32(a)? as u64, _ => self.read_u64(a)? }; + Ok([cur ^ 1, 0]) + } + fn cntvct(&mut self) -> u64 { 0 } + fn cntfrq(&mut self) -> u64 { 1 } + fn random(&mut self) -> Option { None } +} + +/// #12: a perpetually-contended LSE atomic must not spin forever in the +/// kernel. The interpreter gives up after a bounded number of tries, +/// returning Exit::Budget with pc left on the instruction so it restarts. +#[test] +fn contended_atomic_is_bounded() { + // ldadd x0, x1, [x2] (0xf8200041 decodes to Insn::Atomic Add) + let base = 0x2000; + let mut mem = std::vec![0u8; 0x1000]; + mem[..4].copy_from_slice(&0xf820_0041u32.to_le_bytes()); + let mut env = ContendedEnv { mem, base, attempts: 0 }; + let mut cpu = CpuState::new(); + cpu.pc = base; + cpu.x[0] = 1; // addend + cpu.x[2] = base + 0x100; // aligned data address + let (e, n) = run(&mut cpu, &mut env, 1000); + assert_eq!(e, Exit::Budget, "contended atomic should yield, not loop"); + assert_eq!(cpu.pc, base, "pc must stay on the atomic for restart"); + assert_eq!(n, 0, "the atomic did not retire"); + assert!(env.attempts <= super::mem::ATOMIC_RETRIES, "retries not bounded: {}", env.attempts); +} diff --git a/overlay/rust/kemu_core/src/jit/t1.rs b/overlay/rust/kemu_core/src/jit/t1.rs index 65a3d70..5311eff 100644 --- a/overlay/rust/kemu_core/src/jit/t1.rs +++ b/overlay/rust/kemu_core/src/jit/t1.rs @@ -21,12 +21,14 @@ use crate::decode::{ self, BfOp, CselOp, Dp1Op, Dp2Op, Ext, Index, Insn, LogicOp, MulOp, Order, RmwOp, Shift as AShift, }; -use crate::env::{Env, Fault}; +use crate::env::{Access, Env, Fault}; mod crypto; pub use crypto::HostCrypto; mod fp; mod vector; +#[cfg(all(test, feature = "std"))] +mod regression; pub const MAX_INSNS: usize = 64; @@ -167,7 +169,22 @@ impl Scratch { /// Instruction fetch for the translator: records the page, and the word as /// a dependency in relocatable mode. +/// +/// In relocatable mode a word is read from guest memory at most once per +/// translation; later fetches of the same PC (flag look-ahead into exit +/// targets) reuse the recorded value. The shared cache validates a block +/// against these records only, so no decision may depend on a re-read that +/// could differ (another thread rewriting the word mid-translation). fn fetch(env: &mut E, s: &mut Scratch, rec: bool, pc: u64) -> Result { + if rec { + if let Some(d) = s.deps.iter().take(s.ndeps as usize).find(|d| d.pc == pc) { + return if d.ok != 0 { + Ok(d.word) + } else { + Err(Fault { addr: pc, access: Access::Exec, align: false }) + }; + } + } let r = env.fetch(pc); s.record_page(pc); if rec { diff --git a/overlay/rust/kemu_core/src/jit/t1/regression.rs b/overlay/rust/kemu_core/src/jit/t1/regression.rs new file mode 100644 index 0000000..250c016 --- /dev/null +++ b/overlay/rust/kemu_core/src/jit/t1/regression.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0 +//! Regression tests for translator/interpreter fixes (kemu audit 2026-10). +//! std-only (needs a Vec-backed environment and boxing). +#![cfg(all(test, feature = "std"))] + +extern crate std; +use std::{boxed::Box, vec, vec::Vec}; + +use crate::env::{Access, Env, Fault}; +use crate::jit::stubs::{gen_stubs, ExitMode, StubAddrs}; +use crate::jit::t1; + +const PC0: u64 = 0x40_0000; + +fn stub_addrs() -> StubAddrs { + let mut page = vec![0u8; 4096]; + let so = gen_stubs(&mut page, ExitMode::Syscall, 0x7f00_0000_0000, 0xfff8).unwrap(); + so.addrs(0x7e00_0000_0000) +} + +/// Environment whose word at PC0+4 flips from `first` to `second` after the +/// first fetch (a second thread rewriting guest text mid-translation). +struct Racy { + words: Vec, + flip_at: u64, + first: u32, + second: u32, + seen: bool, +} + +impl Env for Racy { + fn fetch(&mut self, pc: u64) -> Result { + if pc == self.flip_at { + let w = if self.seen { self.second } else { self.first }; + self.seen = true; + return Ok(w); + } + let i = pc.wrapping_sub(PC0) / 4; + self.words + .get(i as usize) + .copied() + .ok_or(Fault { addr: pc, access: Access::Exec, align: false }) + } + fn read_u8(&mut self, a: u64) -> Result { Err(f(a)) } + fn read_u16(&mut self, a: u64) -> Result { Err(f(a)) } + fn read_u32(&mut self, a: u64) -> Result { Err(f(a)) } + fn read_u64(&mut self, a: u64) -> Result { Err(f(a)) } + fn write_u8(&mut self, a: u64, _: u8) -> Result<(), Fault> { Err(f(a)) } + fn write_u16(&mut self, a: u64, _: u16) -> Result<(), Fault> { Err(f(a)) } + fn write_u32(&mut self, a: u64, _: u32) -> Result<(), Fault> { Err(f(a)) } + fn write_u64(&mut self, a: u64, _: u64) -> Result<(), Fault> { Err(f(a)) } + fn cmpxchg(&mut self, a: u64, _: u32, _: [u64; 2], _: [u64; 2]) -> Result<[u64; 2], Fault> { Err(f(a)) } + fn cntvct(&mut self) -> u64 { 0 } + fn cntfrq(&mut self) -> u64 { 1 } + fn random(&mut self) -> Option { None } +} + +fn f(a: u64) -> Fault { + Fault { addr: a, access: Access::Read, align: false } +} + +fn xlate(env: &mut Racy) -> (Vec, Vec) { + let cfg = t1::Cfg { stubs: stub_addrs(), code_uaddr: 0x7e00_0010_0000, reloc: true, tbi: false, vector_cache: true, crypto: t1::HostCrypto::default() }; + let mut s = Box::new(t1::Scratch::new()); + let mut out = vec![0u8; 1 << 16]; + let r = t1::translate(env, PC0, &mut out, &cfg, &mut s).unwrap(); + out.truncate(r.size); + let mut blob = vec![0u8; s.xcache_blob_size().unwrap()]; + s.xcache_blob(PC0, 1 << 20, &mut blob).unwrap(); + (out, blob) +} + +/// #2: a relocatable translation must read each guest word at most once, so +/// its flag look-ahead can't be steered by a racing writer into producing a +/// block whose dependency records (what the shared cache re-validates) don't +/// match the code that was emitted. +#[test] +fn xcache_fetch_is_memoized_against_a_racing_writer() { + // subs x0,x0,#1 ; b.eq +0x100 (reads NZCV) ; b -4 (back edge). + // The look-ahead into the b.eq target re-reads PC0+4. + let words = vec![0xf100_0400, 0x5400_0800, 0x17ff_ffff]; + let base = Racy { words: words.clone(), flip_at: PC0 + 4, first: 0x5400_0800, second: 0x5400_0800, seen: false }; + let racy = Racy { words, flip_at: PC0 + 4, first: 0x5400_0800, second: 0xf100_003f /* cmp x1,#0 */, seen: false }; + let (hc, hb) = xlate(&mut { base }); + let (rc, rb) = xlate(&mut { racy }); + assert_eq!(hb, rb, "dependency records diverge under a racing writer"); + assert_eq!(hc, rc, "emitted code diverges under a racing writer"); +} diff --git a/patches/0006-kemu-syscall-arch.patch b/patches/0006-kemu-syscall-arch.patch index aa018d2..daf30cb 100644 --- a/patches/0006-kemu-syscall-arch.patch +++ b/patches/0006-kemu-syscall-arch.patch @@ -1,5 +1,5 @@ diff --git a/arch/x86/include/asm/syscall.h b/arch/x86/include/asm/syscall.h -index c10dbb74c..6df5e99fa 100644 +index c10dbb74c..8c9172ffb 100644 --- a/arch/x86/include/asm/syscall.h +++ b/arch/x86/include/asm/syscall.h @@ -11,6 +11,7 @@ @@ -10,7 +10,18 @@ index c10dbb74c..6df5e99fa 100644 #include #include #include /* for TS_COMPAT */ -@@ -111,6 +112,10 @@ static inline void syscall_set_arguments(struct task_struct *task, +@@ -48,6 +49,10 @@ static inline void syscall_set_nr(struct task_struct *task, + static inline void syscall_rollback(struct task_struct *task, + struct pt_regs *regs) + { ++#ifdef CONFIG_KEMU ++ if (task_is_kemu(task)) ++ kemu_syscall_rollback(task); ++#endif + regs->ax = regs->orig_ax; + } + +@@ -166,6 +171,10 @@ static inline void syscall_set_arguments(struct task_struct *task, static inline int syscall_get_arch(struct task_struct *task) { @@ -18,6 +29,6 @@ index c10dbb74c..6df5e99fa 100644 + if (task_is_kemu(task)) + return AUDIT_ARCH_AARCH64; +#endif - return AUDIT_ARCH_I386; - } - + /* x32 tasks should be considered AUDIT_ARCH_X86_64. */ + return (IS_ENABLED(CONFIG_IA32_EMULATION) && + task->thread_info.status & TS_COMPAT) diff --git a/patches/0013-kemu-seccomp.patch b/patches/0013-kemu-seccomp.patch new file mode 100644 index 0000000..a27b55d --- /dev/null +++ b/patches/0013-kemu-seccomp.patch @@ -0,0 +1,52 @@ +diff --git a/kernel/seccomp.c b/kernel/seccomp.c +index 25f62867a..519ab3e3f 100644 +--- a/kernel/seccomp.c ++++ b/kernel/seccomp.c +@@ -18,6 +18,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -370,6 +371,16 @@ static inline bool seccomp_cache_check_allow(const struct seccomp_filter *sfilte + int syscall_nr = sd->nr; + const struct action_cache *cache = &sfilter->cache; + ++#ifdef CONFIG_KEMU ++ /* ++ * kemu tasks present arm64 syscall numbers under AUDIT_ARCH_AARCH64. ++ * The cache bitmaps are built from the x86 (native/compat) tables, so ++ * they must never be consulted: run the full filter instead. ++ */ ++ if (task_is_kemu(current)) ++ return false; ++#endif ++ + #ifndef SECCOMP_ARCH_COMPAT + /* A native-only architecture doesn't need to check sd->arch. */ + return seccomp_cache_check_allow_bitmap(cache->allow_native, +@@ -1064,12 +1075,22 @@ static const int mode1_syscalls[] = { + -1, /* negative terminated */ + }; + ++#ifdef CONFIG_KEMU ++/* arm64 read(63)/write(64)/exit(93)/rt_sigreturn(139), negative terminated. */ ++static const int kemu_mode1_syscalls[] = { 63, 64, 93, 139, -1 }; ++#endif ++ + static void __secure_computing_strict(int this_syscall) + { + const int *allowed_syscalls = mode1_syscalls; + #ifdef CONFIG_COMPAT + if (in_compat_syscall()) + allowed_syscalls = get_compat_mode1_syscalls(); ++#endif ++#ifdef CONFIG_KEMU ++ /* kemu tasks are never compat, so this does not collide with the above. */ ++ if (task_is_kemu(current)) ++ allowed_syscalls = kemu_mode1_syscalls; + #endif + do { + if (*allowed_syscalls == this_syscall) diff --git a/patches/0014-kemu-ipc.patch b/patches/0014-kemu-ipc.patch new file mode 100644 index 0000000..ba8b5ba --- /dev/null +++ b/patches/0014-kemu-ipc.patch @@ -0,0 +1,36 @@ +diff --git a/ipc/sem.c b/ipc/sem.c +index 0f06e4bd4..162da0158 100644 +--- a/ipc/sem.c ++++ b/ipc/sem.c +@@ -89,6 +89,7 @@ + #include + + #include ++#include + #include "util.h" + + /* One semaphore structure for each semaphore in the system. */ +@@ -1707,6 +1708,23 @@ SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg) + return ksys_semctl(semid, semnum, cmd, arg, IPC_64); + } + ++#ifdef CONFIG_KEMU ++/* ++ * kemu marshals semid64_ds itself (the x86_64 layout has two extra padding ++ * words the arm64/asm-generic layout lacks), so it needs the IPC_STAT and ++ * IPC_SET work on a kernel struct rather than a user buffer. ++ */ ++int kemu_semctl_stat(int semid, int cmd, struct semid64_ds *out) ++{ ++ return semctl_stat(current->nsproxy->ipc_ns, semid, cmd, out); ++} ++ ++int kemu_semctl_set(int semid, int cmd, struct semid64_ds *in) ++{ ++ return semctl_down(current->nsproxy->ipc_ns, semid, cmd, in); ++} ++#endif ++ + #ifdef CONFIG_ARCH_WANT_IPC_PARSE_VERSION + long ksys_old_semctl(int semid, int semnum, int cmd, unsigned long arg) + { diff --git a/scripts/export-patches.sh b/scripts/export-patches.sh index 02fdac8..5e3fccf 100755 --- a/scripts/export-patches.sh +++ b/scripts/export-patches.sh @@ -27,6 +27,8 @@ emit kemu-x86-fault arch/x86/mm/fault.c arch/x86/kernel/traps.c emit kemu-mm mm/vma.c mm/mprotect.c mm/mremap.c mm/mmap.c mm/memory.c emit kemu-proc fs/proc/ arch/x86/kernel/cpu/proc.c fs/coredump.c emit kemu-ptrace kernel/ptrace.c arch/x86/kernel/ptrace.c arch/x86/kernel/step.c +emit kemu-seccomp kernel/seccomp.c +emit kemu-ipc ipc/sem.c emit kemu-rseq kernel/rseq.c emit kemu-perf kernel/events/ arch/x86/events/ # Anything else touched must be listed above. diff --git a/scripts/gen-syscalls.py b/scripts/gen-syscalls.py index 378c260..af06e1c 100755 --- a/scripts/gen-syscalls.py +++ b/scripts/gen-syscalls.py @@ -12,13 +12,17 @@ overrides = { "rt_sigreturn", "clone", "uname", "newfstatat", "fstat", "epoll_ctl", "epoll_pwait", "epoll_pwait2", "openat", "openat2", - "fcntl", "pipe2", "open_by_handle_at", "fanotify_init", + "fcntl", "pipe2", "open_by_handle_at", "fanotify_init", "semctl", } -# Not offered to guests (ENOSYS; programs fall back): io_uring reads and -# writes native structs (e.g. struct epoll_event for IORING_OP_EPOLL_CTL) -# behind kemu's back, so the guest ABI can't be guaranteed. -disabled = {"io_uring_setup", "io_uring_enter", "io_uring_register"} +# Not offered to guests (ENOSYS; programs fall back): +# - io_uring reads and writes native structs (e.g. struct epoll_event for +# IORING_OP_EPOLL_CTL) behind kemu's back, so the guest ABI can't be +# guaranteed. +# - rseq compares the host (code-cache) PC against the guest rseq_cs range, +# so critical sections never abort and a crafted abort_ip would redirect +# host execution; it is unimplemented (DESIGN ยง11.2 is aspirational here). +disabled = {"io_uring_setup", "io_uring_enter", "io_uring_register", "rseq"} syms = set() for line in open(sysmap): diff --git a/tests/kernel/abi b/tests/kernel/abi index 711e2cd..e0f38f3 100755 Binary files a/tests/kernel/abi and b/tests/kernel/abi differ diff --git a/tests/kernel/abi.c b/tests/kernel/abi.c index 96dbece..6ef0655 100644 --- a/tests/kernel/abi.c +++ b/tests/kernel/abi.c @@ -24,14 +24,26 @@ #include #include #include +#include +#include #include #include #include +#include +#include #include #include +#include +#include +#include +#include static int failures; +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#endif + #define CHECK(name, cond, ...) do { \ if (cond) printf("PASS %s\n", name); \ else { failures++; printf("FAIL %s: ", name); printf(__VA_ARGS__); printf("\n"); } \ @@ -322,6 +334,170 @@ static void test_misc(void) CHECK("cntvct", cnt2 >= cnt1 && frq > 1000000, "cnt %lu %lu frq %lu", cnt1, cnt2, frq); } +/* ---- ABI fixes (kemu audit 2026-10) ---- */ + +/* + * semctl IPC_STAT must use the arm64 semid64_ds layout (88 bytes), not the + * x86_64 one (104): the x86 handler would write 16 bytes past the buffer + * and land the ctime in sem_nsems. + */ +static void test_semctl(void) +{ + union semun { int val; struct semid_ds *buf; unsigned short *array; } arg; + struct { struct semid_ds ds; unsigned long canary; } s; + int id = semget(IPC_PRIVATE, 3, IPC_CREAT | 0600); + + if (id < 0) { + CHECK("semctl-stat", 0, "semget errno %d", errno); + return; + } + s.canary = 0xfeedface; + arg.buf = &s.ds; + int r = semctl(id, 0, IPC_STAT, arg); + CHECK("semctl-stat", r == 0 && s.ds.sem_nsems == 3 && s.canary == 0xfeedface, + "r %d nsems %lu canary %lx", r, (unsigned long)s.ds.sem_nsems, s.canary); + /* A negative id is EINVAL before anything else, as native: not a + * masked index (INT_MIN -> set 0) or an EFAULT from the bad buffer. */ + arg.buf = (struct semid_ds *)1; + errno = 0; + r = semctl(-1, 0, IPC_SET, arg); + CHECK("semctl-negative-set", r == -1 && errno == EINVAL, "r %d errno %d", r, errno); + arg.buf = &s.ds; + errno = 0; + r = semctl(INT_MIN, 0, SEM_STAT_ANY, arg); + CHECK("semctl-negative-stat", r == -1 && errno == EINVAL, "r %d errno %d", r, errno); + semctl(id, 0, IPC_RMID); +} + +/* + * openat2 must force O_LARGEFILE on 64-bit like native: without it a write + * past 2 GiB fails with EFBIG. + */ +static void test_openat2(void) +{ + struct open_how how = { .flags = O_RDWR | O_CREAT | O_TRUNC, .mode = 0600 }; + int fd = syscall(__NR_openat2, AT_FDCWD, "/tmp/kemu-of2", &how, sizeof(how)); + + if (fd < 0) { + CHECK("openat2-largefile", 0, "openat2 errno %d", errno); + return; + } + off_t big = (off_t)3 << 30; /* 3 GiB */ + ssize_t w = pwrite(fd, "x", 1, big); + CHECK("openat2-largefile", w == 1, "pwrite %zd errno %d", w, errno); + close(fd); + unlink("/tmp/kemu-of2"); +} + +/* + * seccomp/audit must see AUDIT_ARCH_AARCH64 with arm64 syscall numbers. A + * filter that matches arch==AARCH64 && nr==getpid returns errno 42; if the + * arch were reported as x86_64 the match would fail and getpid would run. + */ +static void test_seccomp_arch(void) +{ + struct sock_filter prog[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_AARCH64, 0, 3), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 172 /* arm64 getpid */, 0, 1), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | 42), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + struct sock_fprog fp = { .len = ARRAY_SIZE(prog), .filter = prog }; + pid_t p = fork(); + + if (p == 0) { + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || + syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, 0, &fp)) + _exit(100 + (errno & 0x7f)); + long r = syscall(172); /* getpid */ + _exit(r == -1 && errno == 42 ? 0 : 1); + } + int st; + waitpid(p, &st, 0); + CHECK("seccomp-arch", WIFEXITED(st) && WEXITSTATUS(st) == 0, + "exit %d (100+=setup errno)", WIFEXITED(st) ? WEXITSTATUS(st) : -1); +} + +/* SECCOMP_MODE_STRICT must allow arm64 read/write/exit/rt_sigreturn. */ +static void test_seccomp_strict(void) +{ + pid_t p = fork(); + + if (p == 0) { + if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, 0, 0, 0)) + _exit(2); + char c = 'k'; + write(2, &c, 0); /* zero-length write: just the syscall */ + /* Strict mode allows exit but not exit_group (glibc's _exit). */ + syscall(__NR_exit, 0); + } + int st; + waitpid(p, &st, 0); + /* Killed by SIGKILL (wrong allow-list) vs clean exit 0. */ + CHECK("seccomp-strict", WIFEXITED(st) && WEXITSTATUS(st) == 0, + "%s %d", WIFSIGNALED(st) ? "signal" : "exit", + WIFSIGNALED(st) ? WTERMSIG(st) : WEXITSTATUS(st)); +} + +/* + * x0 after a seccomp-skipped syscall: the return value it set, even when + * that equals the syscall number (RET_ERRNO|0 on io_setup, nr 0, returns + * 0); but the original x0 after a rollback (RET_TRAP), where SIGSYS sees + * the registers as they were at the svc. + */ +static volatile unsigned long sys_x0; +static void on_sys(int sig, siginfo_t *si, void *ucv) +{ + sys_x0 = ((ucontext_t *)ucv)->uc_mcontext.regs[0]; +} + +static void test_seccomp_x0(void) +{ + struct sock_filter prog[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_AARCH64, 0, 5), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0 /* arm64 io_setup */, 0, 1), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 172 /* arm64 getpid */, 0, 1), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRAP), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + struct sock_fprog fp = { .len = ARRAY_SIZE(prog), .filter = prog }; + struct sigaction sa = { .sa_sigaction = on_sys, .sa_flags = SA_SIGINFO }; + pid_t p = fork(); + + if (p == 0) { + unsigned long ctx = 0; + + sigaction(SIGSYS, &sa, NULL); + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || + syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, 0, &fp)) + _exit(100 + (errno & 0x7f)); + long r = syscall(0, 1234, &ctx); /* io_setup */ + if (r != 0) + _exit(r == 1234 ? 2 : 3); + syscall(172, 0x5eedUL); /* getpid -> SIGSYS */ + _exit(sys_x0 == 0x5eed ? 0 : 4); + } + int st; + waitpid(p, &st, 0); + CHECK("seccomp-x0", WIFEXITED(st) && WEXITSTATUS(st) == 0, + "exit %d (2: errno-0 return replaced by x0, 4: SIGSYS x0, 100+: setup)", + WIFEXITED(st) ? WEXITSTATUS(st) : -1); +} + +static void test_abi_fixes(void) +{ + test_semctl(); + test_openat2(); + test_seccomp_arch(); + test_seccomp_strict(); + test_seccomp_x0(); +} + int main(int argc, char **argv) { if (argc > 1 && !strcmp(argv[1], "child")) { @@ -336,6 +512,7 @@ int main(int argc, char **argv) test_epoll(); test_ptrace(); test_misc(); + test_abi_fixes(); printf("%s: %d failures\n", failures ? "FAILED" : "ALL PASSED", failures); return failures != 0; }