mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-06 11:39:36 +08:00
Enforce VEX reserved-field and compatibility-width rules, correct BMI feature gating, and repair affected SIMD and x87 semantics. Serialize every locked x86 RMW path so an unaligned software update cannot race an overlapping aligned host atomic. Make CONFIG_WASM_X86 kernels use a 32 KiB shadow stack. Deep reference-SIMD frames could exceed the former 16 KiB allocation and later surface as SLUB or page-cache corruption. Capture x86 page-fault present bits before fault handling changes the mapping, and bump the kwemu contract to ABI 6. Add physical VEX encoding coverage, locked-atomic and mixed-ISA kernel workloads, a stack-bound instrumentation audit, and a disposable amd64 Alpine userland regression. Extend kernel matrix output to retain stdout separately from host stderr so native fault and RNG comparisons remain exact. The audit covers x64/i386 differential execution, atomics, UP/SMP and JIT/no-JIT kernel runs, and real amd64 SSH and Python userland checks. It retains the documented limits around scheduler placement, non-x86 hosts, browser coverage, and broader workload matrices.
150 lines
7.1 KiB
Python
150 lines
7.1 KiB
Python
#!/usr/bin/env python3
|
|
# SPDX-License-Identifier: GPL-2.0-or-later
|
|
# Copyright (C) 2026 Jeremy Su
|
|
"""Check the kernel's shadow-stack bounds through the x86 kwtest workload.
|
|
|
|
Instruments stack-pointer assignments in a named, lowered kernel with Binaryen.
|
|
Checks each task's actual stack allocation, including cold reference SIMD paths
|
|
whose frames can skip over the stack-end canary without touching it.
|
|
"""
|
|
import argparse
|
|
import bisect
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
|
|
|
|
def instrument(source, stack_offset):
|
|
functions = list(re.finditer(r'^ \(func (\S+)', source, re.M))
|
|
starts = [m.start() for m in functions]
|
|
# These entry points switch tasks or establish their first shadow stack.
|
|
switches = {'$wasm_arch_switch', '$ret_from_fork', '$kw_secondary_entry',
|
|
'$kw_secondary_resume', '$kw_resume', '$_start'}
|
|
positions = []
|
|
for match in re.finditer(r'\(global.set \$__stack_pointer\b', source):
|
|
owner = functions[bisect.bisect_right(starts, match.start()) - 1].group(1)
|
|
if owner in switches:
|
|
continue
|
|
depth = 0
|
|
for end in range(match.start(), len(source)):
|
|
if source[end] == '(':
|
|
depth += 1
|
|
elif source[end] == ')':
|
|
depth -= 1
|
|
if depth == 0:
|
|
positions.append(end + 1)
|
|
break
|
|
else:
|
|
raise RuntimeError('Unbalanced stack-pointer assignment')
|
|
if not positions:
|
|
raise RuntimeError('No named shadow-stack assignments found')
|
|
pieces, start = [], 0
|
|
for end in positions:
|
|
pieces += [source[start:end],
|
|
'\n(call $kw_stack_guard (global.get $__stack_pointer) (global.get $current))']
|
|
start = end
|
|
pieces.append(source[start:])
|
|
source = ''.join(pieces)
|
|
first_line = source.index('\n')
|
|
source = (source[:first_line] + '\n(import "env" "kw_stack_fail" '
|
|
'(func $kw_stack_fail (param i64 i64 i64)))' + source[first_line:])
|
|
helper = f'''
|
|
(func $kw_stack_guard (param $sp i64) (param $task i64) (local $base i64)
|
|
(if (i64.ne (local.get $task) (i64.const 0))
|
|
(then
|
|
(local.set $base (i64.load (i32.wrap_i64 (i64.add (local.get $task) (i64.const {stack_offset})))))
|
|
(if (i64.lt_u (local.get $sp) (local.get $base))
|
|
(then (call $kw_stack_fail (local.get $sp) (local.get $task) (local.get $base)) (unreachable))))))
|
|
'''
|
|
return source.rstrip()[:-1] + helper + ')\n', len(positions)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--cpus', type=int, default=1)
|
|
parser.add_argument('--no-jit', action='store_true')
|
|
parser.add_argument('--kernel', type=Path)
|
|
parser.add_argument('--initrd', type=Path)
|
|
parser.add_argument('--out', type=Path)
|
|
parser.add_argument('--program', action='append', choices=[
|
|
'kwtest-x86_64', 'isa-audit', 'fp-audit', 'x87-audit', 'x87-fp-audit'])
|
|
args = parser.parse_args()
|
|
if args.cpus < 1:
|
|
parser.error('--cpus must be positive')
|
|
root = Path(__file__).resolve().parent.parent
|
|
build = root / 'vendor/build'
|
|
kernel_dir = build / ('kernel-smp' if args.cpus > 1 else 'kernel')
|
|
kernel = (args.kernel or kernel_dir / 'vmlinux32.wasm').resolve()
|
|
initrd = (args.initrd or build / 'initramfs/base-test.cpio').resolve()
|
|
out = (args.out or build / f'x64-stack/{args.cpus}cpu-{"nojit" if args.no_jit else "jit"}').resolve()
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
programs = args.program or ['kwtest-x86_64', 'isa-audit', 'fp-audit', 'x87-audit', 'x87-fp-audit']
|
|
references, extra = {}, []
|
|
|
|
def newc(name, data, mode, ino):
|
|
name = (name + '\0').encode()
|
|
fields = [ino, mode, 0, 0, 1, 0, len(data), 0, 0, 0, 0, len(name), 0]
|
|
header = ('070701' + ''.join(f'{n:08x}' for n in fields)).encode() + name
|
|
return header + bytes(-len(header) % 4) + data + bytes(-len(data) % 4)
|
|
|
|
for program in programs:
|
|
if program == 'kwtest-x86_64':
|
|
continue
|
|
elf = root / 'zig-out/guest/x64' / (program + '.elf')
|
|
native = subprocess.run([str(elf)], capture_output=True, text=True, timeout=120, check=True)
|
|
if not native.stdout:
|
|
raise RuntimeError(f'Empty native reference for {program}')
|
|
references[program] = native.stdout.rstrip()
|
|
extra.append(newc('usr/bin/' + program, elf.read_bytes(), 0o100755, len(extra) + 1))
|
|
if extra:
|
|
archive = out / 'base-stack-test.cpio'
|
|
archive.write_bytes(initrd.read_bytes() + b''.join(extra) + newc('TRAILER!!!', b'', 0, len(extra) + 1))
|
|
initrd = archive
|
|
offsets = (kernel_dir / 'include/generated/asm-offsets.h').read_text()
|
|
stack_offset = int(re.search(r'#define TASK_STRUCT_STACK\s+(\d+)', offsets).group(1))
|
|
binaryen = root / 'vendor/toolchain/binaryen/bin'
|
|
original, checked = out / 'kernel.wat', out / 'checked.wat'
|
|
wasm = out / 'checked.wasm'
|
|
subprocess.run([str(binaryen / 'wasm-dis'), str(kernel), '-o', str(original)], check=True)
|
|
source, count = instrument(original.read_text(), stack_offset)
|
|
checked.write_text(source)
|
|
subprocess.run([str(binaryen / 'wasm-as'), str(checked), '--all-features',
|
|
'--disable-compact-imports', '-g', '-o', str(wasm)], check=True)
|
|
preload = out / 'preload.mjs'
|
|
preload.write_text('''// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Jeremy Su
|
|
Error.stackTraceLimit = 45;
|
|
const instantiate = WebAssembly.instantiate.bind(WebAssembly);
|
|
WebAssembly.instantiate = async function(module, imports) {
|
|
if (imports?.env) imports.env.kw_stack_fail = (sp, task, base) => {
|
|
throw new Error(`STACK_OVERFLOW sp=${sp.toString(16)} task=${task.toString(16)} base=${base.toString(16)} below=${base-sp}`);
|
|
};
|
|
return instantiate(module, imports);
|
|
};
|
|
''')
|
|
# The large text intermediates are reproducible; retain the checked module.
|
|
original.unlink()
|
|
checked.unlink()
|
|
for program in programs:
|
|
command = ['node', '--import', str(preload), 'js/cli.ts', '--kernel', str(wasm),
|
|
'--initrd', str(initrd), '--distro', 'none', '--cpus', str(args.cpus),
|
|
'--timeout', '180', '--append', f'console=hvc0 rdinit=/usr/bin/{program}']
|
|
if args.no_jit:
|
|
command.append('--no-jit')
|
|
run = subprocess.run(command, cwd=root, capture_output=True, text=True, timeout=240)
|
|
(out / f'{program}.stdout.log').write_text(run.stdout)
|
|
(out / f'{program}.stderr.log').write_text(run.stderr)
|
|
if program in references:
|
|
passed = (run.returncode == 253 and references[program] in run.stdout.replace('\r', '') and
|
|
re.search(r'Attempted to kill init! exitcode=0x0+(?:[^0-9a-fA-F]|$)', run.stdout))
|
|
else:
|
|
passed = run.returncode == 0 and 'kwtest: 0 failure(s)' in run.stdout
|
|
if not passed or re.search(r'STACK_OVERFLOW|\bFAIL\b|BUG:|WARNING:', run.stdout + run.stderr):
|
|
raise RuntimeError(f'Stack audit {program} failed (exit {run.returncode}); see {out}')
|
|
print(f'ok x64 stack: {program}', flush=True)
|
|
print(f'ok x64 stack: {count} assignments checked, cpus={args.cpus}, jit={not args.no_jit}')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|