feat(drivers): integrate Linux wait and static registry services

This commit is contained in:
Tyler Smith committed 2026-10-24 17:31:41 +00:00
1 parent a0b55178eb
commit 86355b2f8f
42 files changed
+6392 -30

No files matched your search

Generated
+2
View File
@@ -1602,6 +1602,8 @@ version = "0.1.0"
dependencies = [
"aes",
"cc",
"libc",
"object",
"sha2",
"subtle",
"triomphe",
+4
View File
@@ -40,6 +40,10 @@ zeroize = { version = "1.9", default-features = false }
triomphe = { version = "=0.1.16", default-features = false }
[build-dependencies]
# Reuse retained shared-input/object/digest versions; no new crate fetch.
libc = "0.2"
object = { version = "0.37", default-features = false, features = ["read"] }
sha2 = { version = "0.10", default-features = false }
cc = { version = "1", optional = true }
[[test]]
+496
View File
@@ -0,0 +1,496 @@
// SPDX-License-Identifier: MIT
//! Bounded descriptor-relative build inputs, shared by source selection and
//! original-object registration capture. No compiler or source is executed.
//! Resolve explicitly selected root aliases once; never follow links below.
//! Final rechecks refuse observed changes, not atomic cross-file/ABA snapshots.
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, ffi::OsString, fs::File, path::{Component, Path, PathBuf}};
pub type Hash = [u8; 32];
pub type Result<T> = std::result::Result<T, String>;
macro_rules! require { ($condition:expr, $($message:tt)*) => { if !$condition { return Err(format!($($message)*)); } }; }
pub fn hex(hash: &Hash) -> String { hash.iter().map(|byte| format!("{byte:02x}")).collect() }
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct RootId(usize);
impl RootId { pub fn index(self) -> usize { self.0 } }
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct Key(usize);
impl Key { pub fn index(self) -> usize { self.0 } }
#[derive(Clone, Copy, Debug)]
pub struct Limits { pub max_unique_files: usize, pub max_unique_bytes: u64, pub max_roots: usize, pub max_directory_entries: usize }
pub struct Request<'a> { pub root: RootId, pub relative: &'a Path, pub expected_sha256: Option<Hash>, pub max_bytes: u64 }
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Identity {
pub device: i128, pub inode: u128, pub mode: u64, pub bytes: u64,
pub mtime_secs: i128, pub mtime_nanos: i128, pub ctime_secs: i128, pub ctime_nanos: i128,
}
impl Identity { fn same_object(&self, other: &Self) -> bool { self.device == other.device && self.inode == other.inode } }
#[derive(Clone, Debug)]
pub struct Binding { pub key: Key, pub path: PathBuf, pub bytes: u64, pub sha256: Hash, pub identity: Identity }
#[derive(Clone, Debug)]
pub struct RootBinding { pub root: RootId, pub path: PathBuf, pub identity: Identity }
#[derive(Clone, Debug, Default)]
pub struct Stats { pub unique_files: usize, pub unique_bytes: u64, pub bytes_hashed: u64, pub bytes_returned: u64, pub metadata_cache_hits: u64 }
#[derive(Debug)]
pub struct Bindings { pub files: Vec<Binding>, pub roots: Vec<RootBinding>, pub stats: Stats }
#[derive(Clone)]
struct Record { root: RootId, relative: PathBuf, path: PathBuf, expected: Option<Hash>, max_bytes: u64, observed: Option<Binding> }
struct DirectoryGuard { root: RootId, relative: Option<PathBuf>, identity: Identity, names: Option<Vec<OsString>> }
/// A logical path is validated without resolving below-root symlinks or '..'.
/// Per-component opens later enforce the corresponding filesystem boundary.
pub fn validate_relative(path: &Path) -> Result<()> {
require!(!path.as_os_str().is_empty() && !path.is_absolute(), "expected nonempty relative input path");
require!(path.as_os_str().len() <= 16 * 1024, "relative input path exceeds finite bound");
for component in path.components() { require!(matches!(component, Component::Normal(_)), "noncanonical relative input path: {}", path.display()); }
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
use std::os::unix::ffi::OsStrExt;
require!(path.as_os_str().as_bytes().split(|byte| *byte == b'/').all(|part| !part.is_empty() && part != b"." && part != b".." && !part.contains(&0)), "invalid relative input components");
}
Ok(())
}
pub struct Inputs {
limits: Limits, roots: Vec<platform::Root>, records: Vec<Record>, paths: BTreeMap<PathBuf, Key>,
directories: BTreeMap<PathBuf, DirectoryGuard>, stats: Stats,
}
impl Inputs {
pub fn new(limits: Limits) -> Result<Self> {
require!(platform::SUPPORTED, "safe build inputs require Linux/macOS no-follow descriptor operations");
require!(limits.max_unique_files > 0 && limits.max_unique_bytes > 0 && limits.max_unique_bytes < u64::MAX && limits.max_roots > 0 && limits.max_directory_entries > 0, "nonzero finite input limits required");
Ok(Self { limits, roots: Vec::new(), records: Vec::new(), paths: BTreeMap::new(), directories: BTreeMap::new(), stats: Stats::default() })
}
pub fn add_root(&mut self, selected: &Path) -> Result<RootId> {
let root = platform::Root::new(selected)?;
if let Some(index) = self.roots.iter().position(|known| known.path == root.path) {
require!(self.roots[index].identity.same_object(&root.identity), "selected root identity changed");
return Ok(RootId(index));
}
require!(self.roots.len() < self.limits.max_roots, "input root count exceeds bound");
let id = RootId(self.roots.len()); self.roots.push(root); Ok(id)
}
fn root(&self, root: RootId) -> Result<&platform::Root> { self.roots.get(root.0).ok_or_else(|| "unknown input root".to_owned()) }
pub fn root_path(&self, root: RootId) -> Result<&Path> { Ok(&self.root(root)?.path) }
/// Preflight all intended uses before content access. Same absolute lexical
/// path shares one record, one expected pin and the tightest role cap.
/// Return request-order keys including duplicates. Errors commit nothing.
pub fn prepare(&mut self, requests: &[Request<'_>]) -> Result<Vec<Key>> {
let mut records = self.records.clone(); let mut paths = self.paths.clone(); let mut keys = Vec::new();
for request in requests {
validate_relative(request.relative)?;
require!(request.max_bytes > 0 && request.max_bytes <= self.limits.max_unique_bytes, "invalid per-role input cap");
let path = self.root(request.root)?.path.join(request.relative);
let key = if let Some(key) = paths.get(&path).copied() {
let record = &mut records[key.0];
if let (Some(old), Some(new)) = (record.expected, request.expected_sha256) { require!(old == new, "conflicting expected hashes for {}", path.display()); }
if let Some(expected) = request.expected_sha256 {
if let Some(observed) = &record.observed { require!(observed.sha256 == expected, "late expected hash conflicts with captured input"); }
record.expected = Some(expected);
}
record.max_bytes = record.max_bytes.min(request.max_bytes);
if let Some(observed) = &record.observed { require!(observed.bytes <= record.max_bytes, "captured input exceeds tightened role cap"); }
key
} else {
require!(records.len() < self.limits.max_unique_files, "unique prepared input count exceeds bound");
let key = Key(records.len()); paths.insert(path.clone(), key);
records.push(Record { root: request.root, relative: request.relative.to_owned(), path, expected: request.expected_sha256, max_bytes: request.max_bytes, observed: None }); key
};
keys.push(key);
}
self.records = records; self.paths = paths; Ok(keys)
}
fn capture(&mut self, key: Key, bytes: bool) -> Result<(Binding, Option<Vec<u8>>)> {
self.capture_with(key, bytes, &mut |_| Ok(()))
}
fn capture_with(&mut self, key: Key, bytes: bool, hook: &mut impl FnMut(platform::Step) -> Result<()>) -> Result<(Binding, Option<Vec<u8>>)> {
let record = self.records.get(key.0).cloned().ok_or_else(|| "unprepared input key".to_owned())?;
let cached = record.observed.as_ref();
let hash = bytes || cached.is_none();
let cap = if cached.is_none() { record.max_bytes.min(self.limits.max_unique_bytes.saturating_sub(self.stats.unique_bytes)) } else { record.max_bytes };
let captured = self.root(record.root)?.capture(&record.relative, cap, hash, bytes, hook)?;
if let Some(previous) = cached { require!(previous.identity == captured.identity, "input identity changed: {}", record.path.display()); }
if let Some(digest) = captured.sha256 {
if let Some(expected) = record.expected { require!(digest == expected, "input hash mismatch: {}", record.path.display()); }
if let Some(previous) = cached { require!(digest == previous.sha256, "input bytes changed: {}", record.path.display()); }
self.stats.bytes_hashed = self.stats.bytes_hashed.checked_add(captured.identity.bytes).ok_or("hash byte counter exhausted")?;
} else {
self.stats.metadata_cache_hits = self.stats.metadata_cache_hits.checked_add(1).ok_or("input cache counter exhausted")?;
}
let digest = captured.sha256.or_else(|| cached.map(|value| value.sha256)).ok_or("missing input digest")?;
let binding = Binding { key, path: record.path, bytes: captured.identity.bytes, sha256: digest, identity: captured.identity };
if cached.is_none() {
self.stats.unique_bytes = self.stats.unique_bytes.checked_add(binding.bytes).ok_or("unique byte counter exhausted")?;
self.stats.unique_files += 1;
self.records[key.0].observed = Some(binding.clone());
}
if let Some(value) = &captured.bytes { self.stats.bytes_returned = self.stats.bytes_returned.checked_add(u64::try_from(value.len()).map_err(|e| e.to_string())?).ok_or("returned byte counter exhausted")?; }
Ok((binding, captured.bytes))
}
/// Hash-only first use. Repeats reopen safely and check identity/cap without
/// copying or rehashing a compiler/common header for every translation unit.
pub fn verify(&mut self, key: Key) -> Result<Binding> { Ok(self.capture(key, false)?.0) }
/// Temporary actual bytes for a parser/object scanner; not retained here.
pub fn read(&mut self, key: Key) -> Result<Vec<u8>> { self.capture(key, true)?.1.ok_or_else(|| "missing captured bytes".to_owned()) }
/// Explicit caller-owned source-provenance directory capability. None is
/// the selected root. Below-root directories are no-follow and guarded.
pub fn directory(&mut self, root: RootId, relative: Option<&Path>) -> Result<File> {
if let Some(path) = relative { validate_relative(path)?; }
let selected = self.root(root)?; let file = selected.directory(relative)?;
if let Some(relative) = relative {
let identity = platform::identity(&file)?; let path = selected.path.join(relative);
if let Some(guard) = self.directories.get(&path) { require!(guard.identity == identity, "input directory identity changed"); }
else { require!(self.directories.len() < self.limits.max_unique_files, "directory guard count exceeds bound"); self.directories.insert(path, DirectoryGuard { root, relative: Some(relative.to_owned()), identity, names: None }); }
}
Ok(file)
}
pub fn names(&mut self, root: RootId, relative: &Path) -> Result<Vec<OsString>> {
validate_relative(relative)?;
let selected = self.root(root)?; let path = selected.path.join(relative);
let (identity, names) = selected.names(relative, self.limits.max_directory_entries)?;
if let Some(guard) = self.directories.get_mut(&path) {
require!(guard.identity == identity && guard.names.as_ref().is_none_or(|old| *old == names), "input directory/listing changed");
guard.names = Some(names.clone());
} else {
require!(self.directories.len() < self.limits.max_unique_files, "directory guard count exceeds bound");
self.directories.insert(path, DirectoryGuard { root, relative: Some(relative.to_owned()), identity, names: Some(names.clone()) });
}
Ok(names)
}
/// Fresh streamed hash once per unique observed file, all roots/listings
/// rechecked. Consuming closes reader-owned descriptors on success or error.
pub fn finish(mut self) -> Result<Bindings> {
for root in &self.roots { root.check()?; }
let mut files = Vec::new();
for record in &self.records {
let Some(binding) = &record.observed else { continue; };
let captured = self.root(record.root)?.capture(&record.relative, record.max_bytes, true, false, &mut |_| Ok(()))?;
require!(captured.identity == binding.identity && captured.sha256 == Some(binding.sha256), "input changed before publication: {}", record.path.display());
self.stats.bytes_hashed = self.stats.bytes_hashed.checked_add(binding.bytes).ok_or("hash byte counter exhausted")?;
files.push(binding.clone());
}
for guard in self.directories.values() {
if let Some(names) = &guard.names {
let (identity, current) = self.root(guard.root)?.names(guard.relative.as_deref().ok_or("missing listing path")?, self.limits.max_directory_entries)?;
require!(identity == guard.identity && current == *names, "input directory/listing changed before publication");
} else {
let current = self.root(guard.root)?.directory(guard.relative.as_deref())?;
require!(platform::identity(&current)? == guard.identity, "input directory changed before publication");
}
}
for root in &self.roots { root.check()?; }
let roots = self.roots.iter().enumerate().map(|(index, root)| RootBinding { root: RootId(index), path: root.path.clone(), identity: root.identity.clone() }).collect();
Ok(Bindings { files, roots, stats: self.stats })
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
mod platform {
use super::*;
use std::{ffi::{CStr, CString, OsStr}, io::{self, Read}, mem::MaybeUninit,
os::{fd::{AsRawFd, FromRawFd, IntoRawFd, RawFd}, unix::ffi::{OsStrExt, OsStringExt}}};
pub(super) const SUPPORTED: bool = true;
const DIRECTORY: i32 = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC;
const INPUT: i32 = libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC | libc::O_NOCTTY;
fn os<T>(value: io::Result<T>) -> Result<T> { value.map_err(|error| error.to_string()) }
fn convert(value: &libc::stat) -> Result<Identity> {
Ok(Identity { device: i128::from(value.st_dev), inode: u128::from(value.st_ino), mode: u64::from(value.st_mode),
bytes: u64::try_from(value.st_size).map_err(|_| "negative input size")?, mtime_secs: i128::from(value.st_mtime),
mtime_nanos: i128::from(value.st_mtime_nsec), ctime_secs: i128::from(value.st_ctime), ctime_nanos: i128::from(value.st_ctime_nsec) })
}
pub(super) fn identity(file: &File) -> Result<Identity> {
let mut value = MaybeUninit::<libc::stat>::uninit();
// SAFETY: live File owns fd; exact stat output storage is writable.
require!(unsafe { libc::fstat(file.as_raw_fd(), value.as_mut_ptr()) } == 0, "descriptor stat: {}", io::Error::last_os_error());
// SAFETY: successful fstat initialized all stat fields used by convert.
convert(unsafe { &value.assume_init() })
}
fn directory_mode(value: &Identity) -> bool { value.mode & u64::from(libc::S_IFMT) == u64::from(libc::S_IFDIR) }
fn regular(value: &Identity) -> bool { value.mode & u64::from(libc::S_IFMT) == u64::from(libc::S_IFREG) }
fn component(value: &OsStr) -> Result<CString> { CString::new(value.as_bytes()).map_err(|error| format!("invalid input component: {error}")) }
fn open_at(parent: RawFd, name: &OsStr, flags: i32) -> Result<File> {
let name = component(name)?;
// SAFETY: live retained parent, terminated name, no creation vararg.
let fd = unsafe { libc::openat(parent, name.as_ptr(), flags) };
require!(fd >= 0, "no-follow open {:?}: {}", name, io::Error::last_os_error());
// SAFETY: successful openat uniquely transfers descriptor ownership.
Ok(unsafe { File::from_raw_fd(fd) })
}
fn absolute(path: &Path) -> Result<File> {
require!(path.is_absolute(), "input root must be absolute");
// SAFETY: terminated literal and no O_CREAT vararg.
let fd = unsafe { libc::open(c"/".as_ptr(), DIRECTORY) };
require!(fd >= 0, "filesystem root open: {}", io::Error::last_os_error());
// SAFETY: successful open produced exactly this owned descriptor.
let mut parent = unsafe { File::from_raw_fd(fd) };
for part in path.components() {
match part { Component::RootDir => {}, Component::Normal(name) => parent = open_at(parent.as_raw_fd(), name, DIRECTORY)?, _ => return Err("noncanonical absolute root".into()) }
}
Ok(parent)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum Step { BeforeDirectory(usize), BeforeFinalOpen, BeforeRead, AfterRead }
pub(super) struct Capture { pub identity: Identity, pub sha256: Option<Hash>, pub bytes: Option<Vec<u8>> }
pub(super) struct Root { pub path: PathBuf, pub identity: Identity, directory: File }
impl Root {
pub fn new(selected: &Path) -> Result<Self> {
let path = os(selected.canonicalize())?; let directory = absolute(&path)?; let identity = identity(&directory)?;
require!(directory_mode(&identity), "selected root is not a directory"); Ok(Self { path, identity, directory })
}
pub fn check(&self) -> Result<()> { let current = absolute(&self.path)?; require!(self.identity.same_object(&identity(&current)?), "selected input root changed"); Ok(()) }
fn walk(&self, path: Option<&Path>, hook: &mut impl FnMut(Step) -> Result<()>) -> Result<File> {
let mut parent = os(self.directory.try_clone())?;
if let Some(path) = path {
validate_relative(path)?;
for (index, part) in path.components().enumerate() {
hook(Step::BeforeDirectory(index))?;
let Component::Normal(part) = part else { return Err("invalid input directory component".into()); };
parent = open_at(parent.as_raw_fd(), part, DIRECTORY)?;
}
}
Ok(parent)
}
pub fn directory(&self, relative: Option<&Path>) -> Result<File> { self.walk(relative, &mut |_| Ok(())) }
pub fn capture(&self, relative: &Path, limit: u64, hash: bool, retain: bool, hook: &mut impl FnMut(Step) -> Result<()>) -> Result<Capture> {
validate_relative(relative)?;
let parent_path = relative.parent().filter(|path| !path.as_os_str().is_empty());
let parent = self.walk(parent_path, hook)?;
let name = relative.file_name().ok_or("input filename missing")?; let encoded = component(name)?;
let mut metadata = MaybeUninit::<libc::stat>::uninit();
// SAFETY: live retained parent, terminated name, writable stat storage.
require!(unsafe { libc::fstatat(parent.as_raw_fd(), encoded.as_ptr(), metadata.as_mut_ptr(), libc::AT_SYMLINK_NOFOLLOW) } == 0, "no-follow input stat {}: {}", relative.display(), io::Error::last_os_error());
// SAFETY: successful fstatat initialized stat fields used below.
let before_path = convert(unsafe { &metadata.assume_init() })?;
require!(regular(&before_path) && before_path.bytes <= limit, "nonregular/symlink/oversized input: {}", relative.display());
hook(Step::BeforeFinalOpen)?;
let mut input = open_at(parent.as_raw_fd(), name, INPUT)?; let before = identity(&input)?;
require!(regular(&before) && before == before_path, "input changed during safe open: {}", relative.display());
if !hash { return Ok(Capture { identity: before, sha256: None, bytes: None }); }
hook(Step::BeforeRead)?;
let mut digest = Sha256::new(); let mut bytes = retain.then(Vec::new); let mut size = 0u64; let mut buffer = [0u8; 64 * 1024];
loop {
let remaining = limit.checked_add(1).and_then(|bound| bound.checked_sub(size)).ok_or("input limit overflow")?;
let count = usize::try_from(remaining.min(u64::try_from(buffer.len()).map_err(|e| e.to_string())?)).map_err(|e| e.to_string())?;
let read = os(input.read(&mut buffer[..count]))?; if read == 0 { break; }
size = size.checked_add(u64::try_from(read).map_err(|e| e.to_string())?).ok_or("input size overflow")?;
require!(size <= limit, "input grew beyond byte bound"); digest.update(&buffer[..read]);
if let Some(bytes) = &mut bytes { bytes.try_reserve(read).map_err(|error| error.to_string())?; bytes.extend_from_slice(&buffer[..read]); }
}
hook(Step::AfterRead)?;
let after = identity(&input)?;
require!(before == after && size == before.bytes, "input changed during bounded capture");
Ok(Capture { identity: after, sha256: Some(digest.finalize().into()), bytes })
}
pub fn names(&self, relative: &Path, limit: usize) -> Result<(Identity, Vec<OsString>)> {
let parent = self.directory(Some(relative))?; let before = identity(&parent)?; let fd = parent.into_raw_fd();
// SAFETY: unique directory descriptor transfers to DIR only on success.
let pointer = unsafe { libc::fdopendir(fd) };
if pointer.is_null() {
let error = io::Error::last_os_error();
// SAFETY: failed fdopendir did not consume this unique fd.
unsafe { libc::close(fd) }; return Err(error.to_string());
}
let directory = Directory(pointer); let mut names = Vec::new();
loop {
// SAFETY: supported platform's thread-local errno cell.
unsafe { *errno() = 0 };
// SAFETY: unique live DIR remains retained through iteration.
let entry = unsafe { libc::readdir(directory.0) };
if entry.is_null() {
// SAFETY: the supported errno accessor supplies this calling
// thread's live, nonnull errno cell; only read its readdir status.
require!(unsafe { *errno() } == 0, "input directory enumeration failed"); break;
}
// SAFETY: readdir supplies a terminated name until the next call.
let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }.to_bytes();
if matches!(name, b"." | b"..") { continue; }
require!(names.len() < limit, "input directory entry count exceeds bound");
names.push(OsString::from_vec(name.to_vec()));
}
// SAFETY: live DIR uniquely retains the borrowed descriptor through
// the following fstat; no File takes ownership of that descriptor.
let descriptor = unsafe { libc::dirfd(directory.0) };
let mut metadata = MaybeUninit::<libc::stat>::uninit();
// SAFETY: retained descriptor and writable exact stat storage.
require!(unsafe { libc::fstat(descriptor, metadata.as_mut_ptr()) } == 0, "directory stat failed");
// SAFETY: successful fstat initialized fields read by convert.
let after = convert(unsafe { &metadata.assume_init() })?;
require!(before == after, "input directory changed during enumeration");
names.sort(); require!(names.windows(2).all(|pair| pair[0] != pair[1]), "duplicate directory names"); Ok((after, names))
}
}
struct Directory(*mut libc::DIR);
impl Drop for Directory {
fn drop(&mut self) {
// SAFETY: unique successful fdopendir owner closes DIR and fd once.
unsafe { libc::closedir(self.0) };
}
}
#[cfg(target_os = "linux")]
unsafe fn errno() -> *mut i32 {
// SAFETY: Linux libc supplies the calling thread's live errno cell;
// obtaining its pointer requires no caller-owned storage or arguments.
unsafe { libc::__errno_location() }
}
#[cfg(target_os = "macos")]
unsafe fn errno() -> *mut i32 {
// SAFETY: macOS libc supplies the calling thread's live errno cell;
// obtaining its pointer requires no caller-owned storage or arguments.
unsafe { libc::__error() }
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
mod platform {
use super::*;
pub(super) const SUPPORTED: bool = false;
pub(super) struct Root { pub path: PathBuf, pub identity: Identity }
pub(super) enum Step {}
pub(super) struct Capture { pub identity: Identity, pub sha256: Option<Hash>, pub bytes: Option<Vec<u8>> }
fn unsupported<T>() -> Result<T> { Err("safe no-follow input operations unsupported on this host".into()) }
impl Root {
pub fn new(_: &Path) -> Result<Self> { unsupported() }
pub fn check(&self) -> Result<()> { unsupported() }
pub fn directory(&self, _: Option<&Path>) -> Result<File> { unsupported() }
pub fn names(&self, _: &Path, _: usize) -> Result<(Identity, Vec<OsString>)> { unsupported() }
pub fn capture(&self, _: &Path, _: u64, _: bool, _: bool, _: &mut impl FnMut(Step) -> Result<()>) -> Result<Capture> { unsupported() }
}
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests {
use super::*;
use platform::Step;
use std::{ffi::CString, fs, os::unix::{ffi::OsStrExt, fs::symlink}};
fn limits() -> Limits { Limits { max_unique_files: 32, max_unique_bytes: 1024, max_roots: 4, max_directory_entries: 32 } }
fn fixture() -> (tempfile::TempDir, Inputs, RootId) {
let directory = tempfile::tempdir().unwrap(); let mut inputs = Inputs::new(limits()).unwrap();
let root = inputs.add_root(directory.path()).unwrap(); (directory, inputs, root)
}
fn key(inputs: &mut Inputs, root: RootId, path: &str, expected: Option<Hash>, max_bytes: u64) -> Key {
inputs.prepare(&[Request { root, relative: Path::new(path), expected_sha256: expected, max_bytes }]).unwrap()[0]
}
fn digest(bytes: &[u8]) -> Hash { Sha256::digest(bytes).into() }
fn fifo(path: &Path) {
let name = CString::new(path.as_os_str().as_bytes()).unwrap();
// SAFETY: terminated private fixture path; creates its own named pipe.
assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0);
}
#[test]
fn preflight_is_transactional_conflicting_pins_and_role_caps_cannot_downgrade() {
let (directory, mut inputs, root) = fixture(); fs::write(directory.path().join("one"), b"original").unwrap();
let hash = digest(b"original"); let first = key(&mut inputs, root, "one", Some(hash), 8);
assert!(inputs.prepare(&[
Request { root, relative: Path::new("two"), expected_sha256: None, max_bytes: 8 },
Request { root, relative: Path::new("one"), expected_sha256: Some(digest(b"modified")), max_bytes: 8 },
]).is_err());
assert_eq!(inputs.records.len(), 1); assert_eq!(inputs.stats.bytes_hashed, 0);
assert_eq!(key(&mut inputs, root, "one", None, 16), first);
assert_eq!(inputs.records[first.0].expected, Some(hash)); assert_eq!(inputs.records[first.0].max_bytes, 8);
inputs.verify(first).unwrap();
assert!(inputs.prepare(&[Request { root, relative: Path::new("one"), expected_sha256: None, max_bytes: 7 }]).is_err());
assert_eq!(inputs.records[first.0].max_bytes, 8);
assert!(inputs.prepare(&[Request { root, relative: Path::new("bad/../one"), expected_sha256: None, max_bytes: 8 }]).is_err());
assert!(validate_relative(Path::new("bad/./one")).is_err()); assert!(validate_relative(Path::new("bad//one")).is_err());
}
#[test]
fn hash_only_cache_counts_unique_inputs_and_final_rehash_without_retaining_bytes() {
let (directory, mut inputs, root) = fixture(); fs::write(directory.path().join("compiler"), b"compiler").unwrap();
let compiler = key(&mut inputs, root, "compiler", Some(digest(b"compiler")), 512);
for _ in 0..774 { assert_eq!(inputs.verify(compiler).unwrap().bytes, 8); }
assert_eq!(inputs.stats.bytes_hashed, 8); assert_eq!(inputs.stats.bytes_returned, 0);
assert_eq!(inputs.stats.metadata_cache_hits, 773); assert_eq!(inputs.stats.unique_files, 1);
let finished = inputs.finish().unwrap(); assert_eq!(finished.files.len(), 1);
assert_eq!(finished.stats.bytes_hashed, 16); assert_eq!(finished.stats.unique_bytes, 8);
assert_eq!(finished.stats.bytes_returned, 0);
}
#[test]
fn overlapping_explicit_roots_deduplicate_and_temporary_object_bytes_are_accounted() {
let (directory, mut inputs, root) = fixture(); fs::create_dir(directory.path().join("objects")).unwrap();
fs::write(directory.path().join("objects/one.o"), b"object").unwrap();
let child = inputs.add_root(&directory.path().join("objects")).unwrap();
let keys = inputs.prepare(&[
Request { root, relative: Path::new("objects/one.o"), expected_sha256: Some(digest(b"object")), max_bytes: 16 },
Request { root: child, relative: Path::new("one.o"), expected_sha256: Some(digest(b"object")), max_bytes: 6 },
]).unwrap(); assert_eq!(keys[0], keys[1]);
assert_eq!(inputs.read(keys[0]).unwrap(), b"object"); inputs.verify(keys[1]).unwrap();
let finished = inputs.finish().unwrap(); assert_eq!(finished.files.len(), 1); assert_eq!(finished.roots.len(), 2);
assert_eq!(finished.stats.unique_bytes, 6); assert_eq!(finished.stats.bytes_hashed, 12); assert_eq!(finished.stats.bytes_returned, 6);
}
#[test]
fn nonregular_inputs_aliases_and_bounds_refuse_without_a_blocking_pipe_open() {
let (directory, mut inputs, root) = fixture(); fs::write(directory.path().join("one"), b"original").unwrap();
fifo(&directory.path().join("pipe")); symlink("one", directory.path().join("alias")).unwrap();
for path in ["pipe", "alias"] { let selected = key(&mut inputs, root, path, None, 8); assert!(inputs.read(selected).is_err()); }
let selected = key(&mut inputs, root, "one", None, 7); assert!(inputs.read(selected).is_err());
let capability = inputs.directory(root, None).unwrap(); drop(inputs);
assert_eq!(platform::identity(&capability).unwrap().mode & u64::from(libc::S_IFMT), u64::from(libc::S_IFDIR));
}
#[test]
fn final_symlink_fifo_and_same_byte_inode_swaps_refuse_before_data_read() {
for swap in 0..3 {
let (directory, mut inputs, root) = fixture(); let path = directory.path().join("one"); fs::write(&path, b"original").unwrap();
let outside = tempfile::tempdir().unwrap(); let secret = outside.path().join("secret"); fs::write(&secret, b"outside").unwrap();
let replacement = directory.path().join("replacement"); fs::write(&replacement, b"original").unwrap();
let selected = key(&mut inputs, root, "one", None, 8); let mut reads = 0;
let result = inputs.capture_with(selected, true, &mut |step| {
if step == Step::BeforeFinalOpen {
match swap {
0 => { fs::remove_file(&path).map_err(|error| error.to_string())?; symlink(&secret, &path).map_err(|error| error.to_string())?; },
1 => { fs::remove_file(&path).map_err(|error| error.to_string())?; fifo(&path); },
_ => fs::rename(&replacement, &path).map_err(|error| error.to_string())?,
}
}
if step == Step::BeforeRead { reads += 1; } Ok(())
}); assert!(result.is_err()); assert_eq!(reads, 0); assert_eq!(inputs.stats.unique_files, 0);
}
}
#[test]
fn intermediate_symlink_race_never_reads_outside_selected_root() {
let (directory, mut inputs, root) = fixture(); let nested = directory.path().join("dir"); fs::create_dir(&nested).unwrap();
fs::write(nested.join("one"), b"original").unwrap(); let outside = tempfile::tempdir().unwrap(); fs::write(outside.path().join("one"), b"outside").unwrap();
let selected = key(&mut inputs, root, "dir/one", None, 8); let mut reads = 0;
assert!(inputs.capture_with(selected, true, &mut |step| {
if step == Step::BeforeDirectory(0) { fs::rename(&nested, directory.path().join("held")).map_err(|error| error.to_string())?; symlink(outside.path(), &nested).map_err(|error| error.to_string())?; }
if step == Step::BeforeRead { reads += 1; } Ok(())
}).is_err()); assert_eq!(reads, 0);
}
#[test]
fn opened_parent_is_anchored_but_rename_is_refused_before_publication() {
let (directory, mut inputs, root) = fixture(); let nested = directory.path().join("dir"); fs::create_dir(&nested).unwrap(); fs::write(nested.join("one"), b"original").unwrap();
let selected = key(&mut inputs, root, "dir/one", None, 8);
let (_, bytes) = inputs.capture_with(selected, true, &mut |step| {
if step == Step::BeforeFinalOpen { fs::rename(&nested, directory.path().join("held")).map_err(|error| error.to_string())?; fs::create_dir(&nested).map_err(|error| error.to_string())?; fs::write(nested.join("one"), b"outside").map_err(|error| error.to_string())?; } Ok(())
}).unwrap(); assert_eq!(bytes.unwrap(), b"original"); assert!(inputs.finish().is_err());
}
#[test]
fn file_growth_after_stat_and_metadata_change_after_read_refuse() {
for growth in [true, false] {
let (directory, mut inputs, root) = fixture(); let path = directory.path().join("one"); fs::write(&path, b"original").unwrap(); let selected = key(&mut inputs, root, "one", None, 8);
assert!(inputs.capture_with(selected, true, &mut |step| {
if growth && step == Step::BeforeRead { fs::write(&path, b"too-large").map_err(|error| error.to_string())?; }
if !growth && step == Step::AfterRead { fs::write(&path, b"modified").map_err(|error| error.to_string())?; File::open(&path).and_then(|file| file.set_modified(std::time::SystemTime::UNIX_EPOCH)).map_err(|error| error.to_string())?; } Ok(())
}).is_err());
}
}
#[test]
fn aggregate_and_unique_file_limits_refuse_and_expected_mismatch_does_not_cache() {
let directory = tempfile::tempdir().unwrap(); for path in ["one", "two"] { fs::write(directory.path().join(path), b"data").unwrap(); }
let mut inputs = Inputs::new(Limits { max_unique_bytes: 7, max_unique_files: 2, ..limits() }).unwrap(); let root = inputs.add_root(directory.path()).unwrap();
let first = key(&mut inputs, root, "one", None, 4); let second = key(&mut inputs, root, "two", None, 4); inputs.verify(first).unwrap(); assert!(inputs.verify(second).is_err());
assert!(inputs.prepare(&[Request { root, relative: Path::new("three"), expected_sha256: None, max_bytes: 1 }]).is_err());
let mut inputs = Inputs::new(limits()).unwrap(); let root = inputs.add_root(directory.path()).unwrap(); let selected = key(&mut inputs, root, "one", Some(digest(b"else")), 4);
assert!(inputs.verify(selected).is_err()); assert!(inputs.records[selected.0].observed.is_none());
}
#[test]
fn same_byte_replacement_changed_root_and_listing_are_final_failures() {
let (directory, mut inputs, root) = fixture(); let path = directory.path().join("one"); fs::write(&path, b"original").unwrap(); let selected = key(&mut inputs, root, "one", None, 8); inputs.verify(selected).unwrap();
let replacement = directory.path().join("replacement"); fs::write(&replacement, b"original").unwrap(); fs::rename(replacement, path).unwrap(); assert!(inputs.finish().is_err());
let parent = tempfile::tempdir().unwrap(); let selected = parent.path().join("selected"); fs::create_dir(&selected).unwrap(); let mut inputs = Inputs::new(limits()).unwrap(); inputs.add_root(&selected).unwrap();
fs::rename(&selected, parent.path().join("held")).unwrap(); fs::create_dir(&selected).unwrap(); assert!(inputs.finish().is_err());
let (directory, mut inputs, root) = fixture(); let patches = directory.path().join("patches"); fs::create_dir(&patches).unwrap(); fs::write(patches.join("one.patch"), b"one").unwrap();
assert_eq!(inputs.names(root, Path::new("patches")).unwrap(), [OsString::from("one.patch")]);
symlink(&patches, directory.path().join("alias")).unwrap(); assert!(inputs.names(root, Path::new("alias")).is_err());
fs::write(patches.join("two.patch"), b"two").unwrap(); File::open(&patches).unwrap().set_modified(std::time::SystemTime::UNIX_EPOCH).unwrap(); assert!(inputs.finish().is_err());
}
}
@@ -0,0 +1,651 @@
// SPDX-License-Identifier: MIT
//! Actual selected-object registration manifest. No source-body scan or linking.
//! Requires the already retained object 0.37 and sha2 0.10 build dependencies.
use object::{Architecture, BinaryFormat, Object, ObjectKind, ObjectSection, ObjectSymbol,
RelocationKind, RelocationTarget, SectionKind, SymbolKind};
use super::inputs::{self, Inputs, Key, Limits, Request, RootId};
use sha2::{Digest, Sha256};
use std::{collections::{BTreeMap, BTreeSet}, fmt::Write as _, path::PathBuf};
type Result<T> = std::result::Result<T, String>;
const PREFIX: &str = "stela_linux_reg__";
const ABI: u32 = 1;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TargetAbi { ElfSysv, MachOSysv, CoffWin64Lp64 }
impl TargetAbi {
fn format(self) -> BinaryFormat {
match self { Self::ElfSysv => BinaryFormat::Elf, Self::MachOSysv => BinaryFormat::MachO,
Self::CoffWin64Lp64 => BinaryFormat::Coff }
}
}
#[derive(Clone, Debug)]
pub struct Input { pub root: usize, pub relative: PathBuf, pub sha256: inputs::Hash }
#[derive(Clone, Debug)]
pub struct InputRoot { pub label: String, pub selected: PathBuf }
#[derive(Clone, Copy, Debug)]
pub struct RoleLimits {
pub cohort_bytes: u64, pub source_bytes: u64, pub compiler_bytes: u64,
pub dependency_bytes: u64, pub object_bytes: u64,
}
#[derive(Clone, Copy)]
enum Role { Cohort, Source, Compiler, Dependency, Object }
impl RoleLimits {
fn cap(self, role: Role) -> u64 {
match role { Role::Cohort => self.cohort_bytes, Role::Source => self.source_bytes,
Role::Compiler => self.compiler_bytes, Role::Dependency => self.dependency_bytes,
Role::Object => self.object_bytes }
}
}
struct UnitKeys { source: Key, compiler: Key, dependencies: Vec<Key>, object: Key }
/* Explicit roots are reviewed directory capabilities, never inferred from an
* input's parent or widened to the entire filesystem. The shared reader owns
* canonicalization, conflicting pins, limits, safe opens and final rechecks. */
fn prepare_inputs(plan: &Plan) -> Result<(Inputs, Vec<RootId>, Key, Vec<UnitKeys>)> {
let mut owner = Inputs::new(plan.input_limits)?;
let mut roots = Vec::new();
for root in &plan.roots {
let id = owner.add_root(&root.selected)?;
if owner.root_path(id)?.parent().is_none() { return Err("filesystem-wide input root is not an authorized plan capability".into()); }
roots.push(id);
}
let mut uses = vec![(&plan.cohort,Role::Cohort)];
for unit in &plan.units {
uses.push((&unit.source,Role::Source)); uses.push((&unit.compiler,Role::Compiler));
for dependency in &unit.dependencies { uses.push((dependency,Role::Dependency)); }
uses.push((&unit.object,Role::Object));
}
let mut requests = Vec::new();
for (input,role) in uses {
requests.push(Request { root: *roots.get(input.root).ok_or("input references unknown reviewed root")?,
relative: &input.relative, expected_sha256: Some(input.sha256), max_bytes: plan.role_limits.cap(role) });
}
// All expected hashes/role caps are preflighted together before content.
let keys = owner.prepare(&requests)?;
let mut keys = keys.into_iter();
let cohort = keys.next().ok_or("missing prepared cohort key")?;
let mut units = Vec::new();
for unit in &plan.units {
let source = keys.next().ok_or("missing prepared source key")?;
let compiler = keys.next().ok_or("missing prepared compiler key")?;
let mut dependencies = Vec::new();
for _ in &unit.dependencies { dependencies.push(keys.next().ok_or("missing prepared dependency key")?); }
let object = keys.next().ok_or("missing prepared object key")?;
units.push(UnitKeys { source, compiler, dependencies, object });
}
if keys.next().is_some() { return Err("unexpected prepared input keys".into()); }
Ok((owner,roots,cohort,units))
}
#[derive(Clone, Debug)]
pub struct Group {
pub token: String, pub ordinal: u32, pub module_name: String,
pub module_file: String, pub provenance: String,
}
#[derive(Clone, Debug)]
pub struct Unit {
pub token: String, pub ordinal: u32, pub group_token: String,
pub source: Input, pub source_label: String, pub provenance: String,
pub object: Input,
/// Exact compiler executable identity, hashed separately from arguments.
pub compiler: Input,
/// Exact ordered argv used for THIS source occurrence (no shell string).
pub options: Vec<String>,
/// Complete captured include/config/generated-header dependency closure.
pub dependencies: Vec<Input>,
}
#[derive(Clone, Debug)]
pub struct Plan {
pub roots: Vec<InputRoot>, pub input_limits: Limits, pub role_limits: RoleLimits,
pub domain_token: String, pub domain_ordinal: u32, pub target: TargetAbi,
pub target_triple: String, pub image_symbol: String,
/// Hash of the separately reviewed selected-source/Kbuild plan.
pub cohort: Input,
/// Explicit Kbuild order, including units which emit no registrations.
pub groups: Vec<Group>, pub units: Vec<Unit>,
}
#[derive(Debug)]
pub struct Manifest { pub c_source: String, pub receipt: String, pub records: usize }
#[derive(Clone, Debug)]
struct Record { symbol: String, code: char, sequence: u32 }
fn digest(bytes: &[u8]) -> [u8; 32] { Sha256::digest(bytes).into() }
fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() }
fn token(s: &str) -> bool {
let mut bytes = s.bytes();
bytes.next().is_some_and(|b| b.is_ascii_alphabetic()) && bytes.all(|b| b.is_ascii_alphanumeric())
}
fn identifier(s: &str) -> bool {
let mut bytes = s.bytes();
bytes.next().is_some_and(|b| b == b'_' || b.is_ascii_alphabetic()) &&
bytes.all(|b| b == b'_' || b.is_ascii_alphanumeric())
}
/* The exported owner root occupies a disjoint reviewed C identifier family.
* C keywords and plain array names cannot satisfy this shape. Actual generated
* names are checked independently too, including future namespace extensions. */
fn image_namespace(name: &str) -> Result<()> {
let middle = name.strip_prefix("stela_linux_").and_then(|s| s.strip_suffix("_image"));
if !identifier(name) || !middle.is_some_and(|s| identifier(s) &&
s.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)) {
return Err("image symbol requires stela_linux_<identifier>_image namespace".into());
}
Ok(())
}
fn image_collision(image: &str, generated: &str) -> Result<()> {
if image == generated { return Err(format!("image symbol collides with generated identifier: {generated}")); }
Ok(())
}
fn validate_image_name(plan: &Plan) -> Result<()> {
image_namespace(&plan.image_symbol)?;
for name in ["inits","exits","parameters","infos","devices","setups","groups","units"] {
image_collision(&plan.image_symbol,name)?;
}
for group in &plan.groups {
image_collision(&plan.image_symbol,&group_symbol(&plan.domain_token,&group.token))?;
}
for unit in &plan.units {
image_collision(&plan.image_symbol,&unit_symbol(&plan.domain_token,&unit.token))?;
image_collision(&plan.image_symbol,&format!("stela_linux_capture__{}__{}",plan.domain_token,unit.token))?;
}
Ok(())
}
fn text(s: &str) -> bool { !s.is_empty() && !s.contains('\0') }
fn c_string(s: &str) -> String {
let mut out = String::from("\"");
for b in s.bytes() {
match b { b'"' => out.push_str("\\\""), b'\\' => out.push_str("\\\\"),
0x20..=0x7e => out.push(char::from(b)), _ => write!(out, "\\{b:03o}").unwrap() }
}
out.push('"'); out
}
fn json_string(s: &str) -> String {
let mut out = String::from("\"");
for ch in s.chars() {
match ch { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"),
c if c <= '\u{1f}' => write!(out, "\\u{:04x}", u32::from(c)).unwrap(),
c => out.push(c) }
}
out.push('"'); out
}
fn group_symbol(domain: &str, group: &str) -> String { format!("stela_linux_group__{domain}__{group}") }
fn unit_symbol(domain: &str, unit: &str) -> String { format!("stela_linux_unit__{domain}__{unit}") }
fn logical_name(name: &str, format: BinaryFormat) -> &str {
if format == BinaryFormat::MachO { name.strip_prefix('_').unwrap_or(name) } else { name }
}
fn parse_record(name: &str, domain: &str, unit: &str) -> Result<Record> {
let suffix = name.strip_prefix(PREFIX).ok_or_else(|| format!("invalid registration prefix: {name}"))?;
let fields: Vec<_> = suffix.split("__").collect();
if fields.len() != 4 || fields[0] != domain || fields[1] != unit ||
!token(fields[0]) || !token(fields[1]) { return Err(format!("wrong/malformed registration identity: {name}")); }
let code = match fields[2] { "i"=>'i', "m"=>'m', "x"=>'x', "e"=>'e', "p"=>'p',
"s"=>'s', "a"=>'a', "f"=>'f', "d"=>'d', "c"=>'c',
_ => return Err(format!("unknown registration kind: {name}")) };
let sequence: u32 = fields[3].parse().map_err(|_| format!("invalid counter: {name}"))?;
if fields[3] != sequence.to_string() { return Err(format!("noncanonical counter: {name}")); }
Ok(Record { symbol: name.to_owned(), code, sequence })
}
fn record_type(code: char) -> &'static str {
match code { 'i'|'m'|'c' => "stela_linux_init_record", 'x'|'e' => "stela_linux_exit_record",
'p' => "stela_linux_parameter_record", 's'|'a' => "stela_linux_setup_record",
'f' => "stela_linux_info_record", 'd' => "stela_linux_device_record", _ => unreachable!() }
}
fn record_kind(code: char) -> u16 {
match code { 'i'=>1, 'm'=>2, 'x'=>3, 'e'=>4, 'p'=>5, 's'=>6, 'a'=>7, 'f'=>8, 'd'=>9, 'c'=>10, _=>unreachable!() }
}
fn validate_header(bytes: &[u8], record: &Record, ordinal: u32) -> Result<()> {
let abi = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
let kind = u16::from_le_bytes(bytes[4..6].try_into().unwrap());
let level = i8::from_le_bytes([bytes[6]]); let flags = bytes[7];
let unit = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
let seq = u32::from_le_bytes(bytes[12..16].try_into().unwrap());
let level_ok = match record.code { 'i' => (-3..=7).contains(&level) && level != -1,
'm' => level == 6, 'c' => level == -4, 'p' => (-1..=7).contains(&level), _ => level == -1 };
let flags_ok = flags == 0 || (record.code == 'i' && (1..=7).contains(&level) && flags == 1);
if abi != ABI || kind != record_kind(record.code) || unit != ordinal || seq != record.sequence ||
!level_ok || !flags_ok { return Err(format!("record prefix disagrees with selected ABI: {}", record.symbol)); }
Ok(())
}
fn scan(plan: &Plan, unit: &Unit, bytes: &[u8]) -> Result<Vec<Record>> {
let file = object::File::parse(bytes).map_err(|e| format!("{}: ordinary object required: {e}", unit.object.relative.display()))?;
if file.format() != plan.target.format() || file.kind() != ObjectKind::Relocatable ||
file.architecture() != Architecture::X86_64 || !file.is_little_endian() || !file.is_64() {
return Err(format!("{}: wrong target/relocatable LP64 object format", unit.object.relative.display()));
}
if file.symbol_table().is_none() { return Err("object lacks a registration-inspectable symbol table".into()); }
for section in file.sections() {
let name = section.name().map_err(|e| e.to_string())?;
if name.starts_with(".gnu.lto_") || name.starts_with(".llvm.lto") ||
matches!(name, ".llvmbc" | ".llvmcmd" | "__bitcode" | "__bundle") {
return Err(format!("LTO/embedded bitcode not admitted: {name}"));
}
}
let anchor_name = format!("stela_linux_capture__{}__{}", plan.domain_token, unit.token);
let mut anchor_count = 0;
for symbol in file.symbols() {
let Ok(raw) = symbol.name() else { continue; };
if logical_name(raw,file.format()) != anchor_name { continue; }
anchor_count += 1;
if !symbol.is_definition() || !symbol.is_global() || symbol.is_weak() || symbol.is_common() ||
symbol.kind() != SymbolKind::Data || (symbol.size() != 0 && symbol.size() != 8) {
return Err("capture anchor must be a strong pointer data definition".into());
}
let section = file.section_by_index(symbol.section_index().ok_or("missing anchor section")?).map_err(|e|e.to_string())?;
let offset = symbol.address().checked_sub(section.address()).ok_or("invalid anchor address")?;
if symbol.address() % 8 != 0 || section.align() < 8 ||
!matches!(section.kind(),SectionKind::Data | SectionKind::ReadOnlyData | SectionKind::ReadOnlyDataWithRel) {
return Err("capture anchor requires ordinary aligned initialized data".into());
}
let data = section.data().map_err(|e|e.to_string())?;
let start = usize::try_from(offset).map_err(|e|e.to_string())?;
let end = start.checked_add(8).ok_or("anchor extent overflow")?;
if data.get(start..end).ok_or("truncated capture anchor")?.iter().any(|b| *b != 0) {
return Err("capture anchor has a nonzero implicit addend".into());
}
let mut references = 0;
for (address, relocation) in section.relocations() {
if address != offset { continue; }
let RelocationTarget::Symbol(index) = relocation.target() else { return Err("anchor must reference actual unit symbol".into()); };
let target = file.symbol_by_index(index).map_err(|e|e.to_string())?;
if relocation.kind() != RelocationKind::Absolute || relocation.size() != 64 || relocation.addend() != 0 ||
logical_name(target.name().map_err(|e|e.to_string())?,file.format()) != unit_symbol(&plan.domain_token,&unit.token) {
return Err("capture anchor references wrong unit/ABI".into());
}
references += 1;
}
if references != 1 { return Err("capture anchor requires exactly one unit relocation".into()); }
}
if anchor_count != 1 { return Err("exactly one per-TU capture anchor required; missing opt-in header".into()); }
let mut records = Vec::new(); let mut sequences = BTreeSet::new(); let mut names = BTreeSet::new();
for symbol in file.symbols() {
let raw = symbol.name_bytes().map_err(|e| e.to_string())?;
let mut reserved = raw;
while let Some(rest) = reserved.strip_prefix(b"_") { reserved = rest; }
if !reserved.starts_with(b"stela_linux_reg_") && reserved != b"stela_linux_reg" { continue; }
let raw_name = std::str::from_utf8(raw).map_err(|e| e.to_string())?;
let decorated = if file.format() == BinaryFormat::MachO { "_stela_linux_reg__" } else { PREFIX };
if !raw_name.starts_with(decorated) { return Err(format!("malformed platform registration symbol: {raw_name}")); }
let name = logical_name(raw_name, file.format());
let record = parse_record(name, &plan.domain_token, &unit.token)?;
if symbol.is_undefined() || symbol.is_common() || symbol.is_weak() || !symbol.is_global() ||
!symbol.is_definition() || symbol.kind() != SymbolKind::Data {
return Err(format!("registration must be a strong external data definition: {name}"));
}
if !names.insert(name.to_owned()) || !sequences.insert(record.sequence) {
return Err(format!("duplicate registration symbol/counter: {name}"));
}
let index = symbol.section_index().ok_or_else(|| format!("missing data section: {name}"))?;
let section = file.section_by_index(index).map_err(|e| e.to_string())?;
if !matches!(section.kind(), SectionKind::Data | SectionKind::ReadOnlyData | SectionKind::ReadOnlyDataWithRel) {
return Err(format!("registration not in ordinary initialized data: {name}"));
}
let size = if record.code == 'd' { 56 } else { 48 };
if symbol.size() != 0 && symbol.size() != size { return Err(format!("wrong registration object size: {name}")); }
if symbol.address() % 8 != 0 || section.align() < 8 { return Err(format!("unaligned registration: {name}")); }
let offset = symbol.address().checked_sub(section.address()).ok_or_else(|| format!("invalid record address: {name}"))?;
let data = section.data().map_err(|e| e.to_string())?;
let start = usize::try_from(offset).map_err(|e| e.to_string())?;
let end = start.checked_add(usize::try_from(size).unwrap()).ok_or("record extent overflow")?;
let record_bytes = data.get(start..end).ok_or_else(|| format!("truncated record data: {name}"))?;
validate_header(record_bytes, &record, unit.ordinal)?;
for (address, _) in section.relocations() {
if address >= offset && address < offset + size &&
![16,24,32,40].contains(&(address-offset)) {
return Err(format!("relocation corrupts fixed record bytes: {name}"));
}
}
for (slot, expected) in [(16, group_symbol(&plan.domain_token, &unit.group_token)),
(24, unit_symbol(&plan.domain_token, &unit.token))] {
let slot_index = usize::try_from(slot).unwrap();
if record_bytes[slot_index..slot_index+8].iter().any(|b| *b != 0) {
return Err(format!("identity has a nonzero implicit addend: {name}+{slot}"));
}
let mut seen = false;
for (address, relocation) in section.relocations() {
if address != offset + slot { continue; }
if seen || relocation.kind() != RelocationKind::Absolute || relocation.size() != 64 || relocation.addend() != 0 {
return Err(format!("malformed identity relocation: {name}+{slot}"));
}
let RelocationTarget::Symbol(target) = relocation.target() else {
return Err(format!("identity must reference actual manifest symbol: {name}+{slot}"));
};
let target = file.symbol_by_index(target).map_err(|e| e.to_string())?;
if logical_name(target.name().map_err(|e| e.to_string())?, file.format()) != expected {
return Err(format!("wrong group/unit identity: {name}+{slot}"));
}
seen = true;
}
if !seen { return Err(format!("missing strong identity relocation: {name}+{slot}")); }
}
records.push(record);
}
records.sort_by_key(|record| record.sequence);
Ok(records)
}
fn validate_plan(plan: &Plan) -> Result<()> {
validate_image_name(plan)?;
if plan.target == TargetAbi::CoffWin64Lp64 && plan.target_triple != "x86_64-pc-cygwin" {
return Err("LP64 COFF requires reviewed x86_64-pc-cygwin target".into());
}
if !token(&plan.domain_token) || !identifier(&plan.image_symbol) || !text(&plan.target_triple) || plan.units.is_empty() {
return Err("explicit nonempty domain/target/image/source cohort required".into());
}
let mut root_labels = BTreeSet::new();
if plan.roots.is_empty() || plan.roots.iter().any(|r| !text(&r.label) || !root_labels.insert(&r.label)) {
return Err("explicit uniquely labeled reviewed input roots required".into());
}
let mut group_tokens = BTreeSet::new(); let mut group_ordinals = BTreeSet::new();
for group in &plan.groups {
if !token(&group.token) || !text(&group.module_name) || !text(&group.module_file) || !text(&group.provenance) ||
group.module_name == "stela-linux" || !group_tokens.insert(&group.token) || !group_ordinals.insert(group.ordinal) {
return Err("invalid/duplicate Kbuild group or forbidden fallback module".into());
}
}
let groups: BTreeMap<_,_> = plan.groups.iter().map(|g| (g.token.as_str(),g)).collect();
let mut unit_tokens = BTreeSet::new(); let mut unit_ordinals = BTreeSet::new(); let mut object_paths = BTreeSet::new();
let mut used_groups = BTreeSet::new();
for unit in &plan.units {
let group = groups.get(unit.group_token.as_str()).ok_or("unit references missing Kbuild group")?;
if !token(&unit.token) || !text(&unit.source_label) || !text(&unit.provenance) ||
!unit_tokens.insert(&unit.token) || !unit_ordinals.insert(unit.ordinal) || !object_paths.insert((unit.object.root,&unit.object.relative)) {
return Err("invalid/duplicate TU occurrence, ordinal or actual object".into());
}
used_groups.insert(&unit.group_token);
let definitions = [format!("-DSTELA_LINUX_REG_DOMAIN={}",plan.domain_token),
format!("-DSTELA_LINUX_REG_UNIT={}",unit.token), format!("-DSTELA_LINUX_REG_UNIT_ORDINAL={}",unit.ordinal),
format!("-DSTELA_LINUX_REG_GROUP_SYMBOL={}",group_symbol(&plan.domain_token,&unit.group_token)),
format!("-DKBUILD_MODNAME={}",c_string(&group.module_name)), format!("-DKBUILD_MODFILE={}",c_string(&group.module_file))];
for definition in &definitions {
if unit.options.iter().filter(|s| *s == definition).count() != 1 { return Err(format!("missing/duplicate exact capture definition: {definition}")); }
let key = definition.split('=').next().unwrap();
if unit.options.iter().filter(|s| s.split('=').next() == Some(key)).count() != 1 {
return Err(format!("conflicting compiler definition: {key}"));
}
}
if unit.options.iter().any(|s| s == "-flto" || s.starts_with("-flto=") || s.contains('\0')) {
return Err("LTO/NUL compiler options refused".into());
}
if unit.dependencies.is_empty() { return Err("complete captured dependency closure required".into()); }
}
if used_groups.len() != plan.groups.len() { return Err("orphan build group".into()); }
Ok(())
}
/// Genuine compiler-produced object cases, explicitly supplied by the hosted
/// integration harness. Missing inputs fail; no environment-based silent skip.
#[derive(Debug)]
pub struct QualificationCase {
pub plan: Plan,
pub expected_records: Option<usize>,
pub expected_error: Option<String>,
}
fn qualification_shape(cases: &[QualificationCase]) -> Result<()> {
if cases.is_empty() { return Err("real-object qualification cases required".into()); }
for case in cases {
match (case.expected_records,&case.expected_error) {
(Some(_),None) => (),
(None,Some(needle)) if !needle.trim().is_empty() => (),
_ => return Err("qualification requires exactly one count or nonempty error pattern".into()),
}
}
Ok(())
}
pub fn qualify(cases: &[QualificationCase]) -> Result<()> {
// Validate the ENTIRE list before any generator/file access, so an invalid
// later expectation cannot run earlier cases or pass on unrelated failure.
qualification_shape(cases)?;
for case in cases {
match (generate(&case.plan), case.expected_records, &case.expected_error) {
(Ok(manifest), Some(expected), None) if manifest.records == expected => (),
(Err(error), None, Some(expected)) if error.contains(expected) => (),
(result, _, _) => return Err(format!("qualification expectation mismatch: {result:?}")),
}
}
Ok(())
}
fn receipt_input(out: &mut String, label: &str, input: &Input, key: Key, unit: Option<&str>) -> Result<()> {
let relative = input.relative.to_str().ok_or("receipt path must be UTF-8")?;
writeln!(out,"{{\"role\":{},\"unit\":{},\"selected_root\":{},\"relative\":{},\"key\":{},\"sha256\":{}}}",
json_string(label),unit.map(json_string).unwrap_or_else(|| "null".to_owned()),
input.root,json_string(relative),key.index(),json_string(&hex(&input.sha256))).unwrap(); Ok(())
}
fn identity_json(identity: &inputs::Identity) -> String {
format!("{{\"device\":{},\"inode\":{},\"mode\":{},\"bytes\":{},\"mtime_secs\":{},\"mtime_nanos\":{},\"ctime_secs\":{},\"ctime_nanos\":{}}}",
identity.device,identity.inode,identity.mode,identity.bytes,identity.mtime_secs,identity.mtime_nanos,identity.ctime_secs,identity.ctime_nanos)
}
fn receipt_bindings(out: &mut String, bindings: &inputs::Bindings) -> Result<()> {
for root in &bindings.roots {
writeln!(out,"{{\"final_root\":{},\"path\":{},\"identity\":{}}}",root.root.index(),
json_string(root.path.to_str().ok_or("root receipt path must be UTF-8")?),identity_json(&root.identity)).unwrap();
}
for binding in &bindings.files {
writeln!(out,"{{\"final_input\":{},\"path\":{},\"bytes\":{},\"sha256\":{},\"identity\":{}}}",binding.key.index(),
json_string(binding.path.to_str().ok_or("input receipt path must be UTF-8")?),binding.bytes,
json_string(&hex(&binding.sha256)),identity_json(&binding.identity)).unwrap();
}
let stats = &bindings.stats;
writeln!(out,"{{\"input_stats\":{{\"unique_files\":{},\"unique_bytes\":{},\"bytes_hashed\":{},\"bytes_returned\":{},\"metadata_cache_hits\":{}}}}}",
stats.unique_files,stats.unique_bytes,stats.bytes_hashed,stats.bytes_returned,stats.metadata_cache_hits).unwrap();
Ok(())
}
/// Pure generation after bounded reads. Caller writes outputs only after all
/// validation succeeds, then compiles C with the SAME target and reviewed ABI.
/// Root reachability is NOT independent ALL-selected-object link qualification.
pub fn generate(plan: &Plan) -> Result<Manifest> {
validate_plan(plan)?;
let (mut inputs,roots,cohort_key,unit_keys) = prepare_inputs(plan)?;
inputs.verify(cohort_key)?;
let mut receipt = String::new();
writeln!(receipt,"{{\"schema\":1,\"target_abi\":{},\"target_triple\":{},\"domain\":{},\"domain_ordinal\":{},\"image_symbol\":{}}}",
json_string(&format!("{:?}",plan.target)),json_string(&plan.target_triple),json_string(&plan.domain_token),plan.domain_ordinal,json_string(&plan.image_symbol)).unwrap();
writeln!(receipt,"{{\"input_limits\":{{\"max_unique_files\":{},\"max_unique_bytes\":{},\"max_roots\":{},\"max_directory_entries\":{}}}}}",
plan.input_limits.max_unique_files,plan.input_limits.max_unique_bytes,
plan.input_limits.max_roots,plan.input_limits.max_directory_entries).unwrap();
writeln!(receipt,"{{\"role_limits\":{{\"cohort_bytes\":{},\"source_bytes\":{},\"compiler_bytes\":{},\"dependency_bytes\":{},\"object_bytes\":{}}}}}",
plan.role_limits.cohort_bytes,plan.role_limits.source_bytes,plan.role_limits.compiler_bytes,
plan.role_limits.dependency_bytes,plan.role_limits.object_bytes).unwrap();
receipt_input(&mut receipt,"reviewed_cohort",&plan.cohort,cohort_key,None)?;
for (index,(root,id)) in plan.roots.iter().zip(&roots).enumerate() {
writeln!(receipt,"{{\"selected_root\":{},\"binding_root\":{},\"label\":{},\"selected_path\":{}}}",index,id.index(),
json_string(&root.label),json_string(root.selected.to_str().ok_or("selected root path must be UTF-8")?)).unwrap();
}
let mut observed = Vec::new(); let mut names = BTreeSet::new();
for (unit,keys) in plan.units.iter().zip(&unit_keys) {
// Compiler and common headers retain hashes/identity only. Repeated
// verify calls enforce each role without compiler-sized byte caches.
inputs.verify(keys.source)?; inputs.verify(keys.compiler)?;
receipt_input(&mut receipt,"source",&unit.source,keys.source,Some(&unit.token))?;
receipt_input(&mut receipt,"compiler",&unit.compiler,keys.compiler,Some(&unit.token))?;
for (dependency,key) in unit.dependencies.iter().zip(&keys.dependencies) {
inputs.verify(*key)?; receipt_input(&mut receipt,"dependency",dependency,*key,Some(&unit.token))?;
}
let records = {
let bytes = inputs.read(keys.object)?;
receipt_input(&mut receipt,"object",&unit.object,keys.object,Some(&unit.token))?;
scan(plan,unit,&bytes)?
}; // The actual object buffer is released before the next TU.
let argv = unit.options.iter().map(|v| json_string(v)).collect::<Vec<_>>().join(",");
writeln!(receipt,"{{\"unit\":{},\"ordinal\":{},\"group\":{},\"source_label\":{},\"provenance\":{},\"argv\":[{}],\"registrations\":{}}}",
json_string(&unit.token),unit.ordinal,json_string(&unit.group_token),json_string(&unit.source_label),json_string(&unit.provenance),argv,records.len()).unwrap();
for record in &records {
image_collision(&plan.image_symbol,&record.symbol)?;
if !names.insert(record.symbol.clone()) { return Err(format!("duplicate cohort registration: {}",record.symbol)); }
writeln!(receipt,"{{\"registration\":{},\"unit\":{},\"sequence\":{},\"type\":{}}}",json_string(&record.symbol),json_string(&unit.token),record.sequence,json_string(record_type(record.code))).unwrap();
}
observed.extend(records);
}
let mut c = String::from("/* Generated from actual selected objects; do not edit. */\n#include <stela/registry.h>\n");
for group in &plan.groups {
writeln!(c,"const struct stela_linux_build_group {} = {{ {}U, {}U, {}U, 0, {}, {}, {} }};",
group_symbol(&plan.domain_token,&group.token),ABI,plan.domain_ordinal,group.ordinal,
c_string(&group.module_name),c_string(&group.module_file),c_string(&group.provenance)).unwrap();
writeln!(receipt,"{{\"group\":{},\"ordinal\":{},\"module_name\":{},\"module_file\":{},\"provenance\":{}}}",json_string(&group.token),group.ordinal,json_string(&group.module_name),json_string(&group.module_file),json_string(&group.provenance)).unwrap();
}
for unit in &plan.units {
writeln!(c,"const struct stela_linux_build_unit {} = {{ {}U, {}U, &{}, {}, {} }};",
unit_symbol(&plan.domain_token,&unit.token),ABI,unit.ordinal,group_symbol(&plan.domain_token,&unit.group_token),
c_string(&unit.source_label),c_string(&unit.provenance)).unwrap();
}
for record in &observed { writeln!(c,"extern const struct {} {};",record_type(record.code),record.symbol).unwrap(); }
let sets = [("inits","imc","stela_linux_init_record"),("exits","xe","stela_linux_exit_record"),
("parameters","p","stela_linux_parameter_record"),("infos","f","stela_linux_info_record"),
("devices","d","stela_linux_device_record"),("setups","sa","stela_linux_setup_record")];
let mut counts = Vec::new();
for (name,codes,ty) in sets {
let records: Vec<_> = observed.iter().filter(|r| codes.contains(r.code)).collect();
counts.push(records.len());
if records.is_empty() { continue; }
writeln!(c,"static const struct {ty} *const {name}[] = {{").unwrap();
for record in records { writeln!(c," &{},",record.symbol).unwrap(); }
c.push_str("};\n");
}
c.push_str("static const struct stela_linux_build_group *const groups[] = {\n");
for group in &plan.groups { writeln!(c," &{},",group_symbol(&plan.domain_token,&group.token)).unwrap(); }
c.push_str("};\nstatic const struct stela_linux_build_unit *const units[] = {\n");
for unit in &plan.units { writeln!(c," &{},",unit_symbol(&plan.domain_token,&unit.token)).unwrap(); }
writeln!(c,"}};\nconst struct stela_linux_registry_image {} = {{ {}U, 0,",plan.image_symbol,ABI).unwrap();
for ((name,_,_),count) in sets.iter().zip(counts) { writeln!(c," {}, {count},",if count == 0 { "0" } else { name }).unwrap(); }
writeln!(c," groups, {}, units, {}\n}};",plan.groups.len(),plan.units.len()).unwrap();
writeln!(receipt,"{{\"generated_c_sha256\":{},\"whole_selected_object_link\":\"UNRUN\",\"runtime\":\"UNRUN\"}}",json_string(&hex(&digest(c.as_bytes())))).unwrap();
// Consuming final validation rehashes each UNIQUE consumed file once,
// checks roots/identities and closes all retained reader descriptors.
// No output is returned or published if these final checks refuse.
let bindings = inputs.finish()?;
receipt_bindings(&mut receipt,&bindings)?;
Ok(Manifest { c_source: c, receipt, records: observed.len() })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registration_identity_is_canonical_and_tu_scoped() {
let record = parse_record("stela_linux_reg__D1__U2__p__17","D1","U2").unwrap();
assert_eq!((record.code,record.sequence),('p',17));
for bad in ["stela_linux_reg__D1__U3__p__17","stela_linux_reg__D1__U2__p__017",
"stela_linux_reg__D1__U2__p__4294967296","stela_linux_reg__D1__U2__z__0",
"stela_linux_reg__D1__U2__p__0__extra"] { assert!(parse_record(bad,"D1","U2").is_err()); }
}
#[test]
fn string_encoders_keep_c_bytes_and_json_controls_unambiguous() {
assert_eq!(c_string("a\n0\"\\"),"\"a\\0120\\\"\\\\\"");
assert_eq!(json_string("a\n\"\\"),"\"a\\u000a\\\"\\\\\"");
}
fn policy_plan() -> Plan {
let input = Input { root: 0, relative: PathBuf::from("unused"), sha256: [0;32] };
Plan {
roots: vec![InputRoot { label: "reviewed".into(), selected: PathBuf::from("never-opened") }],
input_limits: Limits { max_unique_files: 32, max_unique_bytes: 1024*1024*1024,
max_roots: 2, max_directory_entries: 32 },
// Explicit compiler cap admits the known ~290-MB retained tool;
// small fixtures exercise accounting without allocating that size.
role_limits: RoleLimits { cohort_bytes: 1024, source_bytes: 1024,
compiler_bytes: 512*1024*1024, dependency_bytes: 1024, object_bytes: 1024 },
domain_token: "Fixture".into(), domain_ordinal: 1, target: TargetAbi::ElfSysv,
target_triple: "x86_64-unknown-linux-gnu".into(), image_symbol: "stela_linux_fixture_image".into(),
cohort: input.clone(),
groups: vec![Group { token: "image".into(), ordinal: 1, module_name: "fixture".into(),
module_file: "fixtures/fixture".into(), provenance: "authored policy fixture".into() }],
units: vec![Unit { token: "image".into(), ordinal: 1, group_token: "image".into(),
source: input.clone(), source_label: "fixture.c".into(), provenance: "authored policy fixture".into(),
object: input.clone(), compiler: input.clone(), options: Vec::new(), dependencies: vec![input] }],
}
}
#[test]
fn image_names_reject_keywords_arrays_and_generated_identities() {
for allowed in ["stela_linux_fixture_image","stela_linux_video_fixture_image"] {
assert!(image_namespace(allowed).is_ok());
}
let mut plan = policy_plan();
for forbidden in ["for","struct","_Generic","inits","exits","parameters","infos",
"devices","setups","groups","units","stela_linux__image","stela_linux_9bad_image",
"stela_linux_bad-image","stela_linux_fixture_image;", "stela_linux_fixture_image\n"] {
plan.image_symbol = forbidden.into();
assert!(validate_image_name(&plan).is_err(),"accepted {forbidden}");
}
for collision in [group_symbol("Fixture","image"),unit_symbol("Fixture","image"),
"stela_linux_capture__Fixture__image".into()] {
assert!(image_namespace(&collision).is_ok());
plan.image_symbol = collision;
assert!(validate_image_name(&plan).unwrap_err().contains("collides"));
}
let record = "stela_linux_reg__Fixture__image__i__0";
assert!(image_collision(record,record).is_err());
}
#[test]
fn all_qualification_expectations_are_checked_before_generation() {
for (count,error) in [(None,None),(Some(0),Some("bad")),(None,Some("")),(None,Some(" \t\n"))] {
let cases = [
QualificationCase { plan: policy_plan(), expected_records: Some(0), expected_error: None },
QualificationCase { plan: policy_plan(), expected_records: count, expected_error: error.map(str::to_owned) },
];
// The first deliberately incomplete plan would fail generation;
// reaching that error would prove whole-list preflight was lost.
assert_eq!(qualify(&cases).unwrap_err(),
"qualification requires exactly one count or nonempty error pattern");
}
assert!(qualification_shape(&[]).is_err());
assert!(qualification_shape(&[
QualificationCase { plan: policy_plan(), expected_records: Some(0), expected_error: None },
QualificationCase { plan: policy_plan(), expected_records: None, expected_error: Some("hash mismatch".into()) },
]).is_ok());
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
struct FixtureDirectory(PathBuf);
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl FixtureDirectory {
fn new() -> Self {
use std::{fs::DirBuilder, os::unix::fs::DirBuilderExt,
sync::atomic::{AtomicUsize,Ordering}};
static NEXT: AtomicUsize = AtomicUsize::new(0);
let parent = std::env::temp_dir();
for _ in 0..16 {
let path = parent.join(format!("stela-registry-input-{}-{}",std::process::id(),NEXT.fetch_add(1,Ordering::Relaxed)));
match DirBuilder::new().mode(0o700).create(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("fixture directory: {error}"),
}
}
panic!("fixture directory collision bound exhausted");
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl Drop for FixtureDirectory {
fn drop(&mut self) {
if let Err(error) = std::fs::remove_dir_all(&self.0) {
if !std::thread::panicking() { panic!("fixture directory cleanup: {error}"); }
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn shared_input_verification_deduplicates_roles_without_compiler_bytes() {
let directory = FixtureDirectory::new();
std::fs::write(directory.0.join("shared"),b"abc").unwrap();
let mut plan = policy_plan(); plan.roots[0].selected = directory.0.clone();
let shared = Input { root: 0, relative: PathBuf::from("shared"), sha256: digest(b"abc") };
plan.cohort = shared.clone(); plan.units[0].source = shared.clone();
plan.units[0].compiler = shared.clone(); plan.units[0].dependencies = vec![shared];
let (mut owner,_,cohort,units) = prepare_inputs(&plan).unwrap();
assert_eq!(cohort,units[0].source); assert_eq!(cohort,units[0].compiler);
assert_eq!(cohort,units[0].dependencies[0]);
owner.verify(cohort).unwrap();
for _ in 0..100 { owner.verify(units[0].compiler).unwrap(); }
let bindings = owner.finish().unwrap();
assert_eq!(bindings.stats.unique_files,1);
assert_eq!(bindings.stats.unique_bytes,3);
assert_eq!(bindings.stats.bytes_returned,0);
assert_eq!(bindings.stats.bytes_hashed,6); // one initial + one final pass
assert_eq!(bindings.stats.metadata_cache_hits,100);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn conflicting_role_pins_refuse_before_any_file_content_is_read() {
let directory = FixtureDirectory::new();
let mut plan = policy_plan(); plan.roots[0].selected = directory.0.clone();
// The shared file intentionally does not exist: conflict refusal must
// precede reading it, not accidentally pass on an unrelated I/O error.
let shared = Input { root: 0, relative: PathBuf::from("absent"), sha256: [1;32] };
plan.cohort = shared.clone(); plan.units[0].compiler = Input { sha256: [2;32], ..shared };
let error = match prepare_inputs(&plan) { Err(error) => error, Ok(_) => panic!("conflicting pins accepted") };
assert!(error.contains("conflicting expected hashes"),"wrong refusal: {error}");
}
}
+16 -1
View File
@@ -215,6 +215,8 @@ impl Linux {
PathBuf::from(format!("{LINUX}/lib/kobject.c")),
PathBuf::from(format!("{LINUX}/lib/kobject_uevent.c")),
PathBuf::from(format!("{LINUX}/lib/ctype.c")),
PathBuf::from(format!("{LINUX}/kernel/locking/mutex.c")),
PathBuf::from(format!("{LINUX}/kernel/sched/wait_support.c")),
];
for source in &upstream {
println!("cargo:rerun-if-changed={}", source.display());
@@ -247,12 +249,17 @@ impl Linux {
.files([
format!("{COMPAT}/kernel/trees.c"),
format!("{COMPAT}/stela/task_test.c"),
format!("{COMPAT}/stela/mutex_test.c"),
])
.objects(helper_objects)
.compile("linux-task-fixture");
}
if let Some(host) = hosted() {
let services = [PathBuf::from(format!("{COMPAT}/stela/test.c"))];
let services = [
PathBuf::from(format!("{COMPAT}/stela/test.c")),
PathBuf::from(format!("{COMPAT}/stela/registry_test_host.c")),
PathBuf::from(format!("{COMPAT}/stela/taint_test_host.c")),
];
let services = archive(&host, "linux-host", &services);
let mut kernel_build = host;
linux.apply(&mut kernel_build, None, &[], None);
@@ -278,6 +285,10 @@ impl Linux {
"linux_trees",
"crate::gpu::linux::task::tests::run_trees_child()",
);
tests.add_rust(
"linux_mutex_wait",
"crate::gpu::linux::task::tests::run_mutex_child()",
);
}
let Some(mut build) = hosted() else {
return;
@@ -299,6 +310,10 @@ impl Linux {
("linux_slab", "slab.c", "STELA_LINUX_SLAB_TEST"),
("linux_cache", "cache.c", "STELA_LINUX_CACHE_TEST"),
("linux_params", "params.c", "STELA_LINUX_PARAMS_TEST"),
("linux_params_parser", "params.c", "STELA_LINUX_PARAMS_PARSER_TEST"),
("linux_registry", "registry.c", "STELA_LINUX_REGISTRY_TEST"),
("linux_taint", "taint.c", "STELA_LINUX_TAINT_TEST"),
("linux_entry_generation", "linux.c", "STELA_LINUX_ENTRY_GENERATION_TEST"),
("linux_firmware", "firmware.c", "STELA_LINUX_FIRMWARE_TEST"),
("linux_crc", "crc.c", "STELA_LINUX_CRC_TEST"),
("linux_find_bit", "find_bit.c", "STELA_LINUX_FIND_BIT_TEST"),
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: MIT
/* The execution Stela gives Linux code: one owner at a time, on one context
* that nothing preempts or interrupts. */
#include <linux/bug.h>
#include <linux/irqflags.h>
#include <linux/bottom_half.h>
#include <linux/processor.h>
@@ -15,6 +16,9 @@ const struct stela_linux_owner stela_linux_bare = {.services = &no_services};
static bool running;
static const struct stela_linux_owner *owner;
/* Logical entry identity. A qualified task switch preserves this generation;
* a complete exit/reenter always issues a fresh one, even for the same owner. */
static u64 entry_serial, entry_generation;
/* No interrupt reaches Linux code. This is only its simulated local state. */
static unsigned long irq_flags = ARCH_IRQ_ENABLED;
/* Linux headers keep actual nested atomic/read-side state here. */
@@ -25,15 +29,18 @@ struct thread_info stela_thread_info;
void stela_linux_lease_snapshot(struct stela_linux_lease *lease)
{
bool entered = __atomic_load_n(&running, __ATOMIC_ACQUIRE);
if (entered != (owner != NULL))
if (entered != (owner != NULL) || entered != (entry_generation != 0))
__builtin_trap();
*lease = (struct stela_linux_lease){.owner = owner, .irq_flags = irq_flags};
*lease = (struct stela_linux_lease){.owner = owner, .irq_flags = irq_flags,
.generation = entry_generation};
}
bool stela_linux_lease_matches(const struct stela_linux_lease *lease)
{
return __atomic_load_n(&running, __ATOMIC_ACQUIRE) == (lease->owner != NULL) &&
owner == lease->owner && irq_flags == lease->irq_flags;
owner == lease->owner && irq_flags == lease->irq_flags &&
entry_generation == lease->generation &&
(lease->owner != NULL) == (lease->generation != 0);
}
void stela_linux_lease_suspend(const struct stela_linux_lease *lease)
@@ -41,6 +48,7 @@ void stela_linux_lease_suspend(const struct stela_linux_lease *lease)
if (!stela_linux_lease_matches(lease))
__builtin_trap();
owner = NULL;
entry_generation = 0;
irq_flags = ARCH_IRQ_ENABLED;
if (lease->owner)
__atomic_store_n(&running, false, __ATOMIC_RELEASE);
@@ -48,7 +56,13 @@ void stela_linux_lease_suspend(const struct stela_linux_lease *lease)
bool stela_linux_lease_resume(const struct stela_linux_lease *lease)
{
if (owner || irq_flags != ARCH_IRQ_ENABLED)
/* Validate the saved continuation before ANY mutation. The internal task
* state machine additionally owns resume-once/actual-owner authority. */
if ((lease->owner != NULL) != (lease->generation != 0) ||
lease->generation > entry_serial ||
(lease->irq_flags != ARCH_IRQ_ENABLED && lease->irq_flags != ARCH_IRQ_DISABLED) ||
(!lease->owner && lease->irq_flags != ARCH_IRQ_ENABLED) || owner || entry_generation ||
irq_flags != ARCH_IRQ_ENABLED)
return false;
if (!lease->owner)
return !__atomic_load_n(&running, __ATOMIC_ACQUIRE);
@@ -57,6 +71,7 @@ bool stela_linux_lease_resume(const struct stela_linux_lease *lease)
__ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
return false;
owner = lease->owner;
entry_generation = lease->generation;
irq_flags = lease->irq_flags;
return true;
}
@@ -69,9 +84,12 @@ bool stela_linux_try_enter(const struct stela_linux_owner *next)
if (!__atomic_compare_exchange_n(&running, &expected, true, false,
__ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
return false;
if (owner || preempt_count() || irq_flags != ARCH_IRQ_ENABLED)
if (owner || entry_generation || preempt_count() || irq_flags != ARCH_IRQ_ENABLED)
__builtin_trap();
if (entry_serial == ~(u64)0)
__builtin_trap(); /* Never wrap/reissue a logical entry identity. */
owner = next;
entry_generation = ++entry_serial;
return true;
}
@@ -90,6 +108,7 @@ void stela_linux_exit(void)
if (!stela_linux_quiescent())
__builtin_trap();
owner = NULL;
entry_generation = 0;
__atomic_store_n(&running, false, __ATOMIC_RELEASE);
}
@@ -111,9 +130,20 @@ void stela_linux_unsupported(const char *operation)
void stela_linux_warn(const char *file, int line, const char *condition, unsigned int flags)
{
const struct stela_linux_owner *current_owner = stela_linux_owner();
(void)flags;
if (current_owner->services->warn)
current_owner->services->warn(current_owner->context, file, line, condition);
/* Same taint encoding consumed by original BUG_GET_TAINT. */
add_taint(flags >> 8, LOCKDEP_STILL_OK);
}
/* A terminal selected-domain stop, not Linux panic/reboot/crash dumping. */
void stela_linux_fatal(const char *message)
{
const struct stela_linux_owner *current_owner = stela_linux_owner();
if (current_owner->services->log)
current_owner->services->log(current_owner->context, LOGLEVEL_EMERG, message);
/* A returning logger cannot turn this failure into a successful return. */
__builtin_trap();
}
unsigned long arch_local_save_flags(void)
@@ -163,3 +193,55 @@ void __local_bh_enable_ip(unsigned long ip, unsigned int count)
__builtin_trap();
enable_bh(count);
}
#ifdef STELA_LINUX_ENTRY_GENERATION_TEST
#include <stela/test.h>
static void exhaust_generation(void)
{
entry_serial = ~(u64)0;
stela_linux_enter(&stela_linux_bare);
}
int main(void)
{
struct stela_linux_lease taskless, first, same, other, restored;
stela_linux_lease_snapshot(&taskless);
assert(!taskless.owner && !taskless.generation && stela_linux_lease_matches(&taskless));
stela_linux_enter(&stela_linux_bare);
stela_linux_lease_snapshot(&first);
assert(first.owner == &stela_linux_bare && first.generation);
stela_linux_exit();
assert(!stela_linux_lease_matches(&first));
stela_linux_enter(&stela_linux_bare);
stela_linux_lease_snapshot(&same);
assert(same.generation > first.generation && !stela_linux_lease_matches(&first));
/* A task switch is continuation, unlike exit: an intervening owner gets a
* fresh serial, then resume restores the exact saved logical entry. */
stela_linux_lease_suspend(&same);
stela_linux_lease_snapshot(&taskless);
assert(!taskless.owner && !taskless.generation);
const struct stela_linux_services services = {};
const struct stela_linux_owner different = {.services=&services,.context=&other};
stela_linux_enter(&different);
stela_linux_lease_snapshot(&other);
assert(other.owner==&different && other.generation > same.generation);
stela_linux_exit();
struct stela_linux_lease invalid = same;
invalid.generation=0;
assert(!stela_linux_lease_resume(&invalid) && stela_linux_lease_matches(&taskless));
invalid=taskless; invalid.generation=first.generation;
assert(!stela_linux_lease_resume(&invalid) && stela_linux_lease_matches(&taskless));
invalid=same; invalid.generation=~(u64)0;
assert(!stela_linux_lease_resume(&invalid) && stela_linux_lease_matches(&taskless));
assert(stela_linux_lease_resume(&same));
stela_linux_lease_snapshot(&restored);
assert(restored.owner==same.owner && restored.generation==same.generation &&
stela_linux_lease_matches(&same) && !stela_linux_lease_matches(&other));
assert(!stela_linux_lease_resume(&other) && stela_linux_lease_matches(&same));
stela_linux_exit();
assert(stela_test_traps(exhaust_generation));
stela_linux_lease_snapshot(&taskless);
assert(!taskless.owner && !taskless.generation);
printf("Linux entry generation: real entry identity, task continuation and no wrap fixtures passed\n");
return 0;
}
#endif
@@ -1,9 +1,9 @@
// SPDX-License-Identifier: GPL-2.0-or-later
/* Bounded module-parameter operations for the entered serialized Linux owner.
// SPDX-License-Identifier: GPL-2.0-only
/* Shared module-parameter grammar and operations for the entered serialized Linux owner.
* Behavioral reference: Linux 7.2.12 kernel/params.c, Copyright (C) 2001
* Rusty Russell, and lib/kstrtox.c. Keep the public operation ABI and use
* Stela's canonical parser/formatter/heap. No sysfs, module loader, security
* dispatch or pre-allocator command-line lifetime is supplied by this unit. */
* Stela's canonical parser/formatter/heap. No sysfs, module loader, LSM
* implementation or pre-allocator command-line lifetime is supplied by this unit. */
#include <asm/page.h>
#include <linux/errno.h>
#include <linux/kstrtox.h>
@@ -15,6 +15,254 @@
#include <linux/string.h>
#include <stela/linux.h>
/* Shared grammar and dispatch projected from Linux 7.2.12 kernel/params.c,
* Copyright (C) 2001 Rusty Russell, and lib/cmdline.c (GPL-2.0-only).
* Pinned input identities and verbatim oracle ranges accompany this proposal.
* Existing typed operations below remain unchanged. */
#include <linux/ctype.h>
#include <linux/err.h>
#include <linux/irqflags.h>
#include <linux/panic.h>
#include <linux/security.h>
#include <stela/params.h>
static char dash2underscore(char c)
{
if (c == '-')
return '_';
return c;
}
bool parameqn(const char *a, const char *b, size_t n)
{
size_t i;
for (i = 0; i < n; i++) {
if (dash2underscore(a[i]) != dash2underscore(b[i]))
return false;
}
return true;
}
bool parameq(const char *a, const char *b)
{
return parameqn(a, b, strlen(a)+1);
}
/*
* Parse a string to get a param value pair.
* You can use " around spaces, but can't escape ".
* Hyphens and underscores equivalent in parameter names.
*/
char *next_arg(char *args, char **param, char **val)
{
unsigned int i, equals = 0;
int in_quote = 0, quoted = 0;
if (*args == '"') {
args++;
in_quote = 1;
quoted = 1;
}
for (i = 0; args[i]; i++) {
if (isspace(args[i]) && !in_quote)
break;
if (equals == 0) {
if (args[i] == '=')
equals = i;
}
if (args[i] == '"')
in_quote = !in_quote;
}
*param = args;
if (!equals)
*val = NULL;
else {
args[equals] = '\0';
*val = args + equals + 1;
/* Don't include quotes in value. */
if (**val == '"') {
(*val)++;
if (args[i-1] == '"')
args[i-1] = '\0';
}
}
if (quoted && i > 0 && args[i-1] == '"')
args[i-1] = '\0';
if (args[i]) {
args[i] = '\0';
args += i + 1;
} else
args += i;
/* Chew up trailing spaces. */
return skip_spaces(args);
}
/* The public contiguous ABI and registry view share one dispatch core. The
* accessor never copies descriptors: custom setters see the original kp. */
struct parameter_view {
const struct kernel_param *contiguous;
const struct kernel_param *const *pointers;
unsigned int count;
};
static const struct kernel_param *parameter_at(const struct parameter_view *view,
unsigned int index)
{
return view->pointers ? view->pointers[index] : &view->contiguous[index];
}
static int observe_parameter(const struct stela_linux_param_observer *observer,
enum stela_linux_param_event event,
const struct kernel_param *kp, char *param, char *val,
int result, int *observer_error)
{
if (!observer || !observer->observe)
return 0;
int error = observer->observe(observer->context, event, kp, param, val, result);
if (error) {
*observer_error = error < 0 ? error : -EPROTO;
return *observer_error;
}
return 0;
}
static int parse_parameter(char *param, char *val, const char *doing,
const struct parameter_view *view, s16 min_level,
s16 max_level, void *arg, parse_unknown_fn unknown,
const struct stela_linux_param_observer *observer,
int *observer_error)
{
for (unsigned int i = 0; i < view->count; i++) {
const struct kernel_param *kp = parameter_at(view, i);
/* Invalid owned manifests must not turn into a NULL call. Public
* Linux callers retain their valid-descriptor input contract. */
if (!kp || !kp->name || !kp->ops)
return -EINVAL;
if (!parameq(param, kp->name))
continue;
if (kp->level < min_level || kp->level > max_level)
return 0;
if (!val && !(kp->ops->flags & KERNEL_PARAM_OPS_FL_NOARG))
return -EINVAL;
if ((kp->ops->flags & ~KERNEL_PARAM_OPS_FL_NOARG) ||
(kp->flags & ~(KERNEL_PARAM_FL_HWPARAM | KERNEL_PARAM_FL_UNSAFE))) {
pr_err("%s: unsupported parameter flags for '%s'\n", doing, param);
return -EOPNOTSUPP;
}
if (!kp->ops->set)
return -EPERM;
int error = observe_parameter(observer, STELA_LINUX_PARAM_BEFORE_SET,
kp, param, val, 0, observer_error);
if (error)
return error;
pr_debug("handling %s with %p\n", param, kp->ops->set);
kernel_param_lock(kp->mod);
/* Preserve security-first ordering and real shared taint effects. */
if ((kp->flags & KERNEL_PARAM_FL_HWPARAM) &&
security_locked_down(LOCKDOWN_MODULE_PARAMETERS)) {
error = -EPERM;
} else {
if (kp->flags & KERNEL_PARAM_FL_UNSAFE) {
pr_notice("Setting dangerous option %s - tainting kernel\n", kp->name);
add_taint(TAINT_USER, LOCKDEP_STILL_OK);
}
error = kp->ops->set(val, kp);
}
kernel_param_unlock(kp->mod);
int fault = observe_parameter(observer, STELA_LINUX_PARAM_AFTER_SET,
kp, param, val, error, observer_error);
return fault ? fault : error;
}
if (unknown) {
int error = observe_parameter(observer, STELA_LINUX_PARAM_BEFORE_UNKNOWN,
NULL, param, val, 0, observer_error);
if (error)
return error;
pr_debug("doing %s: %s='%s'\n", doing, param, val);
error = unknown(param, val, doing, arg);
int fault = observe_parameter(observer, STELA_LINUX_PARAM_AFTER_UNKNOWN,
NULL, param, val, error, observer_error);
return fault ? fault : error;
}
pr_debug("Unknown argument '%s'\n", param);
return -ENOENT;
}
static struct stela_linux_params_result parse_parameter_args(
const char *doing, char *args, const struct parameter_view *view,
s16 min_level, s16 max_level, void *arg, parse_unknown_fn unknown,
const struct stela_linux_param_observer *observer)
{
(void)stela_linux_owner();
struct stela_linux_params_result result = {0};
char *param, *val;
args = skip_spaces(args);
if (*args)
pr_debug("doing %s, parsing ARGS: '%s'\n", doing, args);
while (*args) {
args = next_arg(args, &param, &val);
if (!val && !strcmp(param, "--")) {
if (!result.result)
result.result = args;
return result;
}
int irq_was_disabled = irqs_disabled();
int ret = parse_parameter(param, val, doing, view, min_level, max_level,
arg, unknown, observer, &result.observer_error);
/* A broken callback boundary is terminal, distinct from a source
* parameter error. No warning/log callback runs in a changed owner. */
if (result.observer_error) {
result.result = ERR_PTR(result.observer_error);
return result;
}
if (irq_was_disabled && !irqs_disabled())
pr_warn("%s: option '%s' enabled irq's!\n", doing, param);
switch (ret) {
case 0:
continue;
case -ENOENT:
pr_err("%s: Unknown parameter `%s'\n", doing, param);
break;
case -ENOSPC:
pr_err("%s: `%s' too large for parameter `%s'\n", doing, val ?: "", param);
break;
default:
pr_err("%s: `%s' invalid for parameter `%s'\n", doing, val ?: "", param);
break;
}
result.result = ERR_PTR(ret);
}
return result;
}
char *parse_args(const char *doing, char *args, const struct kernel_param *params,
unsigned int num, s16 min_level, s16 max_level, void *arg,
parse_unknown_fn unknown)
{
const struct parameter_view view = {.contiguous = params, .count = num};
return parse_parameter_args(doing, args, &view, min_level, max_level,
arg, unknown, NULL).result;
}
struct stela_linux_params_result stela_linux_parse_args_view(
const char *doing, char *args, const struct kernel_param *const *params,
unsigned int num, s16 min_level, s16 max_level, void *arg,
parse_unknown_fn unknown, const struct stela_linux_param_observer *observer)
{
(void)stela_linux_owner();
if (num && !params)
return (struct stela_linux_params_result){.result = ERR_PTR(-EINVAL)};
const struct parameter_view view = {.pointers = params, .count = num};
return parse_parameter_args(doing, args, &view, min_level, max_level,
arg, unknown, observer);
}
#define PARAM_STRING_LIMIT 1024UL
/* The public getter contract supplies a full page, including its terminator. */
@@ -596,3 +844,7 @@ int main(void)
return 0;
}
#endif
#ifdef STELA_LINUX_PARAMS_PARSER_TEST
#include <stela/params-parser-test.h>
#endif
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,28 @@
// SPDX-License-Identifier: GPL-2.0
// SPDX-License-Identifier: GPL-2.0-only
/* Owned common string helpers following Linux
* cc9de5d4b5ab6459f5774946aa3195ad51236fa8 lib/string.c and
* lib/string_helpers.c. Their original GPL notices remain with those sources.
* Existing MIT kernel/string.c is unchanged. */
#include <linux/ctype.h>
#include <linux/string.h>
/* skip_spaces is an exact bounded projection from the pinned original
* lib/string_helpers.c, Copyright 31 August 2008 James Bottomley;
* Copyright (C) 2013, Intel Corporation. No dynamic module export table. */
/**
* skip_spaces - Removes leading whitespace from @str.
* @str: The string to be stripped.
*
* Returns a pointer to the first non-whitespace character in @str.
*/
char *skip_spaces(const char *str)
{
while (isspace(*str))
++str;
return (char *)str;
}
int strncmp(const char *left, const char *right, size_t count)
{
for (size_t i = 0; i < count; i++) {
@@ -54,8 +72,41 @@ char *strreplace(char *string, char old, char replacement)
#ifdef STELA_LINUX_STRING_HELPERS_TEST
#include <stela/test.h>
/* The expected set is transcribed from pinned lib/ctype.c, not derived
* from isspace here: bytes 9..13, 32 and 160 carry its _S bit. This includes
* Linux's single-byte NBSP, without host locale or Unicode decoding. */
static void leading_whitespace(void)
{
char *(*volatile skip)(const char *) = skip_spaces;
for (unsigned int byte = 0; byte < 256; byte++) {
struct { u8 before; char text[3]; u8 after; } guarded = {
.before = 0x61, .text = {(char)byte, 'X', 0}, .after = 0xc8,
};
char saved[sizeof(guarded.text)];
memcpy(saved, guarded.text, sizeof(saved));
bool whitespace = (byte >= 9 && byte <= 13) || byte == 32 || byte == 160;
assert(skip(guarded.text) == guarded.text + whitespace);
assert(guarded.before == 0x61 && guarded.after == 0xc8);
assert(!memcmp(saved, guarded.text, sizeof(saved)));
}
static const char mixed[] = {'\t', '\n', '\v', '\f', '\r', ' ', (char)0xa0, '!', 0};
assert(skip(mixed) == mixed + 7);
char only[] = {' ', (char)0xa0, '\t', '\n', '\v', '\f', '\r', 0};
char only_saved[sizeof(only)];
memcpy(only_saved, only, sizeof(only));
assert(skip(only) == only + sizeof(only) - 1);
assert(!memcmp(only, only_saved, sizeof(only)));
static const char empty[] = "";
assert(skip(empty) == empty);
static const char embedded[] = {' ', 0, '\t', 'X', 0};
assert(skip(embedded) == embedded + 1);
static const char utf8_nbsp[] = {(char)0xc2, (char)0xa0, 'X', 0};
assert(skip(utf8_nbsp) == utf8_nbsp);
}
int main(void)
{
leading_whitespace();
/* Exercise the actual implementation, not compiler-folded libc calls. */
int (*volatile compare)(const char *, const char *, size_t) = strncmp;
char *(*volatile find)(const char *, int) = strchr;
@@ -0,0 +1,199 @@
// SPDX-License-Identifier: GPL-2.0-only
/* Selected Linux taint service, derived from Linux kernel/panic.c and
* lib/debug_locks.c at cc9de5d4b5ab6459f5774946aa3195ad51236fa8.
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
*
* Shared image state, serialized by the entered Linux owner. This is not the
* Linux panic/reboot/SMP implementation. Taint-triggered fatal stops report to
* that owner and trap; neither owner exit nor registry retirement resets state.
*/
#include <linux/bitops.h>
#include <linux/build_bug.h>
#include <linux/debug_locks.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kconfig.h>
#include <linux/kstrtox.h>
#include <linux/panic.h>
#include <linux/printk.h>
#include <linux/sprintf.h>
#include <linux/string.h>
#include <linux/string_choices.h>
#include <stela/linux.h>
static unsigned long tainted_mask =
IS_ENABLED(CONFIG_RANDSTRUCT) ? (1UL << TAINT_RANDSTRUCT) : 0;
unsigned long panic_on_taint;
bool panic_on_taint_nousertaint;
/* __debug_locks_off in the original header exchanges this even !LOCKDEP. */
int debug_locks __read_mostly = 1;
int debug_locks_silent __read_mostly;
#define TAINT_FLAG(taint, _c_true, _c_false) \
[ TAINT_##taint ] = { \
.c_true = _c_true, .c_false = _c_false, \
.desc = #taint, \
}
/*
* NOTE: if you modify the taint_flags or TAINT_FLAGS_COUNT,
* please also modify tools/debugging/kernel-chktaint and
* Documentation/admin-guide/tainted-kernels.rst, including its
* small shell script that prints the TAINT_FLAGS_COUNT bits of
* /proc/sys/kernel/tainted.
*
* Also, update INIT_TAINT_BUF_MAX below.
*/
const struct taint_flag taint_flags[TAINT_FLAGS_COUNT] = {
TAINT_FLAG(PROPRIETARY_MODULE, 'P', 'G'),
TAINT_FLAG(FORCED_MODULE, 'F', ' '),
TAINT_FLAG(CPU_OUT_OF_SPEC, 'S', ' '),
TAINT_FLAG(FORCED_RMMOD, 'R', ' '),
TAINT_FLAG(MACHINE_CHECK, 'M', ' '),
TAINT_FLAG(BAD_PAGE, 'B', ' '),
TAINT_FLAG(USER, 'U', ' '),
TAINT_FLAG(DIE, 'D', ' '),
TAINT_FLAG(OVERRIDDEN_ACPI_TABLE, 'A', ' '),
TAINT_FLAG(WARN, 'W', ' '),
TAINT_FLAG(CRAP, 'C', ' '),
TAINT_FLAG(FIRMWARE_WORKAROUND, 'I', ' '),
TAINT_FLAG(OOT_MODULE, 'O', ' '),
TAINT_FLAG(UNSIGNED_MODULE, 'E', ' '),
TAINT_FLAG(SOFTLOCKUP, 'L', ' '),
TAINT_FLAG(LIVEPATCH, 'K', ' '),
TAINT_FLAG(AUX, 'X', ' '),
TAINT_FLAG(RANDSTRUCT, 'T', ' '),
TAINT_FLAG(TEST, 'N', ' '),
TAINT_FLAG(FWCTL, 'J', ' '),
};
#undef TAINT_FLAG
/* All 20 verbose descriptions need 328 bytes including NUL. Keep the
* original bootstrap bound permanently, without importing alloc_taint_buf. */
#define STELA_TAINT_BUFFER_SIZE 350
static_assert(sizeof("Tainted: ")
+ sizeof("PROPRIETARY_MODULE") - 1 + 4
+ sizeof("FORCED_MODULE") - 1 + 4
+ sizeof("CPU_OUT_OF_SPEC") - 1 + 4
+ sizeof("FORCED_RMMOD") - 1 + 4
+ sizeof("MACHINE_CHECK") - 1 + 4
+ sizeof("BAD_PAGE") - 1 + 4
+ sizeof("USER") - 1 + 4
+ sizeof("DIE") - 1 + 4
+ sizeof("OVERRIDDEN_ACPI_TABLE") - 1 + 4
+ sizeof("WARN") - 1 + 4
+ sizeof("CRAP") - 1 + 4
+ sizeof("FIRMWARE_WORKAROUND") - 1 + 4
+ sizeof("OOT_MODULE") - 1 + 4
+ sizeof("UNSIGNED_MODULE") - 1 + 4
+ sizeof("SOFTLOCKUP") - 1 + 4
+ sizeof("LIVEPATCH") - 1 + 4
+ sizeof("AUX") - 1 + 4
+ sizeof("RANDSTRUCT") - 1 + 4
+ sizeof("TEST") - 1 + 4
+ sizeof("FWCTL") - 1 + 4
+ 2 * (TAINT_FLAGS_COUNT - 1) <= STELA_TAINT_BUFFER_SIZE);
static char taint_buffer[STELA_TAINT_BUFFER_SIZE];
static void valid_flag(unsigned flag)
{
if (flag >= TAINT_FLAGS_COUNT)
stela_linux_fatal("Linux taint flag out of range");
}
static const char *format_taint(bool verbose)
{
(void)stela_linux_owner();
static_assert(TAINT_FLAGS_COUNT == 20);
if (!tainted_mask) {
memcpy(taint_buffer, "Not tainted", sizeof("Not tainted"));
return taint_buffer;
}
size_t used = (size_t)scnprintf(taint_buffer, sizeof(taint_buffer), "Tainted: ");
const char *sep = "";
for (unsigned i = 0; i < TAINT_FLAGS_COUNT; i++) {
const struct taint_flag *t = &taint_flags[i];
bool is_set = test_bit(i, &tainted_mask);
char c = is_set ? t->c_true : t->c_false;
if (verbose) {
if (!is_set)
continue;
used += (size_t)scnprintf(taint_buffer + used, sizeof(taint_buffer) - used,
"%s[%c]=%s", sep, c, t->desc);
sep = ", ";
} else {
taint_buffer[used++] = c;
taint_buffer[used] = '\0';
}
}
return taint_buffer;
}
const char *print_tainted(void)
{
return format_taint(false);
}
const char *print_tainted_verbose(void)
{
return format_taint(true);
}
int test_taint(unsigned flag)
{
(void)stela_linux_owner();
valid_flag(flag);
return test_bit(flag, &tainted_mask);
}
unsigned long get_taint(void)
{
(void)stela_linux_owner();
return tainted_mask;
}
void add_taint(unsigned flag, enum lockdep_ok lockdep_ok)
{
(void)stela_linux_owner();
valid_flag(flag);
if (lockdep_ok == LOCKDEP_NOW_UNRELIABLE && __debug_locks_off())
pr_warn("Disabling lock debugging due to kernel taint\n");
set_bit(flag, &tainted_mask);
if (tainted_mask & panic_on_taint) {
panic_on_taint = 0;
stela_linux_fatal("panic_on_taint set ...");
}
}
static int __init panic_on_taint_setup(char *s)
{
char *taint_str;
if (!s)
return -EINVAL;
taint_str = strsep(&s, ",");
if (kstrtoul(taint_str, 16, &panic_on_taint))
return -EINVAL;
/* make sure panic_on_taint doesn't hold out-of-range TAINT flags */
panic_on_taint &= TAINT_FLAGS_MAX;
if (!panic_on_taint)
return -EINVAL;
if (s && !strcmp(s, "nousertaint"))
panic_on_taint_nousertaint = true;
pr_info("panic_on_taint: bitmask=0x%lx nousertaint_mode=%s\n",
panic_on_taint, str_enabled_disabled(panic_on_taint_nousertaint));
return 0;
}
early_param("panic_on_taint", panic_on_taint_setup);
#ifdef STELA_LINUX_TAINT_TEST
#include <stela/taint_test.h>
#endif
@@ -3,10 +3,13 @@
* This implements identity/lease transitions, not a substitute Linux scheduler. */
#include <linux/errno.h>
#include <linux/irqflags.h>
#include <linux/limits.h>
#include <linux/preempt.h>
#include <linux/refcount.h>
#include <linux/sched.h>
#include <linux/sched/task_stack.h>
#include <linux/sched/task.h>
#include <linux/sched/signal.h>
#include <linux/string.h>
#include <stela/linux.h>
#include <stela/page.h>
@@ -15,6 +18,19 @@
static_assert(CONFIG_THREAD_INFO_IN_TASK == 1);
static_assert(!IS_ENABLED(CONFIG_SMP));
static_assert(!IS_ENABLED(CONFIG_PREEMPT_RT));
static_assert(!IS_ENABLED(CONFIG_MUTEX_SPIN_ON_OWNER));
static_assert(!IS_ENABLED(CONFIG_SCHED_PROXY_EXEC));
static_assert(!IS_ENABLED(CONFIG_DEBUG_LOCK_ALLOC));
static_assert(!IS_ENABLED(CONFIG_DEBUG_MUTEXES));
static_assert(!IS_ENABLED(CONFIG_DEBUG_WW_MUTEX_SLOWPATH));
static_assert(!IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY_BUILD));
static_assert(!IS_ENABLED(CONFIG_PREEMPT_DYNAMIC));
/* I2C's required RT/PI extension is separate; no partial RT field enablement. */
static_assert(!IS_ENABLED(CONFIG_RT_MUTEXES));
static_assert(!IS_ENABLED(CONFIG_BLOCK));
static_assert(!IS_ENABLED(CONFIG_TASK_DELAY_ACCT));
static_assert(!IS_ENABLED(CONFIG_PSI));
static_assert(!IS_ENABLED(CONFIG_SCHEDSTATS));
static_assert(sizeof(struct stela_linux_task_context) == 64);
static_assert(offsetof(struct stela_linux_task_context, sequence) == 16);
static_assert(offsetof(struct stela_linux_task_context, stack_pointer) == 56);
@@ -31,6 +47,7 @@ struct stela_linux_task {
struct stela_linux_lease lease;
int prepared_count;
bool attached, active, suspended, prepared;
bool io_blocked, load_blocked, finalizing;
};
/* The real same-CPU Runtime owns publication. This does not authorize C entry
@@ -112,16 +129,57 @@ struct task_struct *stela_linux_current(void)
return &task->linux_task;
}
static bool quiet(const struct stela_linux_task *task)
/* Only admitted same-CPU C code and IF=0 switch hooks access these counters.
* They describe actual committed sleepers, not token nesting or all Linux rq
* statistics. A native CPU-idle/accounting consumer remains unbound. */
static unsigned int waiting_io, waiting_load;
static void block_account(struct stela_linux_task *task, unsigned int state)
{
if (task->io_blocked || task->load_blocked || task->linux_task.is_blocked)
__builtin_trap();
bool io = task->linux_task.in_iowait;
bool load = !!(state & TASK_UNINTERRUPTIBLE);
if ((io && waiting_io == UINT_MAX) || (load && waiting_load == UINT_MAX))
__builtin_trap();
task->io_blocked = io;
task->load_blocked = load;
task->linux_task.sched_contributes_to_load = load;
waiting_io += io;
waiting_load += load;
task->linux_task.is_blocked = 1;
task->linux_task.on_rq = 0;
}
static void wake_account(struct stela_linux_task *task)
{
if ((task->io_blocked && !waiting_io) || (task->load_blocked && !waiting_load))
__builtin_trap();
waiting_io -= task->io_blocked;
waiting_load -= task->load_blocked;
task->io_blocked = false;
task->load_blocked = false;
task->linux_task.is_blocked = 0;
}
static bool quiet_except_usage(const struct stela_linux_task *task)
{
return !task->linux_task.thread_info.preempt_count && !task->linux_task.thread_info.flags &&
READ_ONCE(task->linux_task.__state) == TASK_RUNNING &&
task->linux_task.flags == PF_KTHREAD && !task->linux_task.blocked_on &&
!task->linux_task.blocked_donor && !task->linux_task.wake_q.next &&
refcount_read(&task->linux_task.usage) == 1 &&
!task->linux_task.in_iowait && !task->linux_task.is_blocked &&
!task->io_blocked && !task->load_blocked &&
sigisemptyset(&task->linux_task.pending.signal) &&
list_empty(&task->linux_task.pending.list) &&
refcount_read(&task->linux_task.stack_refcount) == 1;
}
static bool quiet(const struct stela_linux_task *task)
{
return quiet_except_usage(task) && refcount_read(&task->linux_task.usage) == 1;
}
struct stela_linux_task *stela_linux_task_allocate(void)
{
struct stela_linux_task *task = stela_linux_heap_alloc(sizeof(*task), __alignof__(*task));
@@ -129,6 +187,14 @@ struct stela_linux_task *stela_linux_task_allocate(void)
return NULL;
task->linux_task.thread_info.task = &task->linux_task;
task->linux_task.flags = PF_KTHREAD;
/* Equal-priority normal kernel continuations; zero prio would falsely
* describe an RT task when a later separately admitted profile reads it. */
task->linux_task.policy = SCHED_NORMAL;
task->linux_task.prio = DEFAULT_PRIO;
task->linux_task.static_prio = DEFAULT_PRIO;
task->linux_task.normal_prio = DEFAULT_PRIO;
INIT_LIST_HEAD(&task->linux_task.pending.list);
sigemptyset(&task->linux_task.pending.signal);
refcount_set(&task->linux_task.usage, 1);
refcount_set(&task->linux_task.stack_refcount, 1);
raw_spin_lock_init(&task->linux_task.pi_lock);
@@ -144,7 +210,7 @@ int stela_linux_task_attach(struct stela_linux_task *task,
struct stela_linux_lease lease;
stela_linux_lease_snapshot(&lease);
if (!task || task->attached || !quiet(task) || !view_valid(view, true) ||
!actual_stack(view) || !ops || !ops->is_current || !binding ||
!actual_stack(view) || !ops || !ops->is_current || !ops->wake_target || !binding ||
__atomic_load_n(&active, __ATOMIC_ACQUIRE) || lease.owner ||
lease.irq_flags != ARCH_IRQ_ENABLED || stela_thread_info.preempt_count ||
stela_thread_info.flags)
@@ -158,6 +224,8 @@ int stela_linux_task_attach(struct stela_linux_task *task,
task->binding = binding;
task->attached = true;
task->active = true;
task->linux_task.on_cpu = 1;
task->linux_task.on_rq = 1;
__atomic_store_n(&active, task, __ATOMIC_RELEASE);
return 0;
}
@@ -222,7 +290,7 @@ static bool prepared_here(struct stela_linux_task *task)
{
return task->prepared && task->scope && !task->suspended &&
task->linux_task.thread_info.preempt_count == task->prepared_count &&
!task->linux_task.thread_info.flags &&
!(task->linux_task.thread_info.flags & ~_TIF_SIGPENDING) &&
task->lease.owner && task->lease.irq_flags == ARCH_IRQ_ENABLED &&
stela_linux_lease_matches(&task->lease);
}
@@ -257,6 +325,9 @@ int stela_linux_task_leave(struct stela_linux_task *task,
/* Every refusal above is mutation-free. No callbacks, allocator, final
* release or Rust owner borrow crosses this committed IF=0 transition. */
task->lease = lease;
if (reason == 1)
block_account(task, READ_ONCE(task->linux_task.__state));
task->linux_task.on_cpu = 0;
stela_linux_lease_suspend(&lease);
task->active = false;
task->suspended = true;
@@ -282,7 +353,14 @@ int stela_linux_task_arrive(struct stela_linux_task *task,
}
if (!stela_linux_lease_resume(&task->lease))
return -EBUSY;
/* Also resolves a real Runtime spurious/IRQ pending wake which never
* entered C wake_up_process. Actual !SMP/!PROXY switch exclusion owns
* this target before current publication; no Linux ISR/task can race. */
WRITE_ONCE(task->linux_task.blocked_on, NULL);
wake_account(task);
task->context = *view;
task->linux_task.on_cpu = 1;
task->linux_task.on_rq = 1;
task->suspended = false;
task->active = true;
/* A genuine resume makes this sleeper runnable. Original lock/wait code
@@ -304,6 +382,8 @@ int stela_linux_task_complete(struct stela_linux_task *task,
return -EBUSY;
task->lease = lease;
task->context.sequence = 0;
task->linux_task.on_cpu = 0;
task->linux_task.on_rq = 0;
task->active = false;
__atomic_store_n(&active, NULL, __ATOMIC_RELEASE);
return 0;
@@ -334,9 +414,32 @@ void stela_linux_task_release(struct stela_linux_task *task)
if (!task || task->attached || task->active || task->suspended || task->scope ||
task->prepared || !quiet(task))
__builtin_trap();
/* Consume the actual retained baseline only after independent detach and
* unique Rust metadata ownership; extra public C refs must already end. */
task->finalizing = true;
if (!refcount_dec_and_test(&task->linux_task.usage))
__builtin_trap();
__put_task_struct(&task->linux_task);
}
void __put_task_struct(struct task_struct *linux_task)
{
struct stela_linux_task *task = container_of(linux_task, struct stela_linux_task, linux_task);
if (!task->finalizing || task->attached || task->active || task->suspended || task->scope ||
task->prepared || task->context.sequence || !quiet_except_usage(task) ||
refcount_read(&linux_task->usage))
__builtin_trap();
stela_linux_heap_free(task, sizeof(*task), __alignof__(*task));
}
void __put_task_struct_rcu_cb(struct rcu_head *head)
{
/* Original put_task_struct reaches this only at final refcount zero.
* An active task's baseline is borrowed and cannot legally be put by a
* caller that did not own it. The real finalizer validates that lifetime. */
__put_task_struct(container_of(head, struct task_struct, rcu));
}
static int finish_prepared(struct stela_linux_task *task, int result)
{
if (!live_here(task, &task->context) || !prepared_here(task))
@@ -352,6 +455,14 @@ int stela_linux_task_park(bool scheduler_preempt_disabled)
int error = prepare(task, scheduler_preempt_disabled ? 1 : 0);
if (error)
return error;
/* Same selected scheduler effect as try_to_block_task: a signal posted
* by a process PREPARE retirement callback must not be lost. Native IRQ
* views only publish generic pending wake, never mutate Linux sigsets. */
smp_mb();
if (signal_pending_state(READ_ONCE(task->linux_task.__state), &task->linux_task)) {
clear_task_blocked_on(&task->linux_task, NULL);
WRITE_ONCE(task->linux_task.__state, TASK_RUNNING);
}
int result = task->scope_ops->park(task->scope);
if (result > 1)
__builtin_trap();
@@ -369,3 +480,113 @@ int stela_linux_task_yield(void)
__builtin_trap();
return finish_prepared(task, result);
}
/* The whole original mutex uses precisely this scheduler boundary. Invalid
* outer atomic/read-side nesting is a contract violation, not busy polling. */
void schedule_preempt_disabled(void)
{
if (preempt_count() != 1 || stela_linux_task_park(true) < 0)
__builtin_trap();
}
static int wake_state(struct task_struct *linux_task, unsigned int state)
{
(void)current_record();
(void)stela_linux_owner();
/* Original API borrowed lifetime: a task ref, live waiter/lock scope or
* other real producer lease retains this actual job. A numeric extra
* reference is not universal ownership proof. The caller supplies that
* lifetime; positive usage only rejects an already-dead object. */
if (!refcount_read(&linux_task->usage))
__builtin_trap();
struct stela_linux_task *task = container_of(linux_task, struct stela_linux_task, linux_task);
if (!task->attached || !task->context.sequence || !task->ops)
__builtin_trap();
guard(raw_spinlock_irqsave)(&linux_task->pi_lock);
/* Full wake barrier pairs with original set_current_state before the
* genuine predicate/park. No preemptive Linux ISR can enter this port. */
smp_mb();
if (!(READ_ONCE(linux_task->__state) & state))
return 0;
/* Publish the generation-safe signal before changing C state. Failure
* under a held live ref is corruption and must not lose a wake. */
if (task->ops->wake_target(task->binding, task->context.sequence))
__builtin_trap();
clear_task_blocked_on(linux_task, NULL);
wake_account(task);
linux_task->on_rq = 1;
WRITE_ONCE(linux_task->__state, TASK_RUNNING);
return 1;
}
int wake_up_process(struct task_struct *task)
{
return wake_state(task, TASK_NORMAL);
}
int wake_up_state(struct task_struct *task, unsigned int state)
{
return wake_state(task, state);
}
static int wait_signal(unsigned int kind)
{
switch (kind) {
case 1: return SIGUSR1;
case 2: return SIGKILL;
default: return 0;
}
}
int stela_linux_task_signal(struct stela_linux_task *task, u64 expected_sequence,
unsigned int kind)
{
(void)stela_linux_current();
/* Metadata is separately retained by TargetTask. Inspect only generation
* until it matches; stale handles cannot inspect a future job's state. */
if (!expected_sequence || task->context.sequence != expected_sequence)
return -ESTALE;
int signal_number = wait_signal(kind);
if (!signal_number)
return -EINVAL;
if (!task->attached)
return -ESTALE;
get_task_struct(&task->linux_task);
sigaddset(&task->linux_task.pending.signal, signal_number);
set_tsk_thread_flag(&task->linux_task, TIF_SIGPENDING);
unsigned int state = TASK_INTERRUPTIBLE | (kind == 2 ? TASK_WAKEKILL : 0U);
(void)wake_up_state(&task->linux_task, state);
put_task_struct(&task->linux_task);
return 0;
}
int stela_linux_task_ack_signal(unsigned int kind)
{
struct task_struct *task = stela_linux_current();
int signal_number = wait_signal(kind);
if (!signal_number)
return -EINVAL;
sigdelset(&task->pending.signal, signal_number);
if (sigisemptyset(&task->pending.signal))
clear_tsk_thread_flag(task, TIF_SIGPENDING);
return 0;
}
unsigned int stela_linux_task_pending_signals(void)
{
struct task_struct *task = stela_linux_current();
return (sigismember(&task->pending.signal, SIGUSR1) ? 1U : 0U) |
(sigismember(&task->pending.signal, SIGKILL) ? 2U : 0U);
}
unsigned int stela_linux_task_waiting_io(void)
{
(void)stela_linux_current();
return waiting_io;
}
unsigned int stela_linux_task_waiting_load(void)
{
(void)stela_linux_current();
return waiting_load;
}
@@ -15,6 +15,7 @@
* access, are bound by the adapter that owns the device. A NULL log or warn
* discards those reports and a NULL firmware has no images; a service reached
* without its callback, or outside enter and exit, traps. */
#include <linux/compiler_attributes.h>
#include <linux/types.h>
struct stela_linux_services {
@@ -60,6 +61,9 @@ void stela_linux_rcu_finish(void);
const struct stela_linux_owner *stela_linux_owner(void);
/* Report an operation Stela does not provide yet to the running owner. */
void stela_linux_unsupported(const char *operation);
/* Emit an emergency report through the entered owner, then unconditionally
* trap. No graceful return; this does not implement Linux panic machinery. */
__noreturn void stela_linux_fatal(const char *message);
/* Platform memory behind Linux's allocators: Stela's global heap in its
* images, libc in hosted test programs. Zeroed and aligned to align, a power
@@ -1,19 +1,20 @@
/* SPDX-License-Identifier: MIT */
#ifndef STELA_MODULE_H
#define STELA_MODULE_H
/* Module registration in Stela's images, which load no modules and run no
* initcalls: a built-in driver's init and exit functions and its device
* tables are registered nowhere. Linux would put them in initcall sections,
* which reference every function a driver's init reaches, and alias its
* device tables, which Mach-O hosts reject. An adapter that compiles a
* module's registration includes this first; macros expand where they are
* used, so the module's own sources then register nothing. */
/* Partial helper builds erase module registration as before. Explicitly
* selected built-in cohorts opt into typed capture after original Linux
* declarations, retaining their actual callbacks and descriptor identities. */
#include <linux/module.h>
#if defined(STELA_LINUX_CAPTURE_REGISTRATIONS)
#include <stela/registration.h>
#else
#undef module_init
#define module_init(fn)
#undef module_exit
#define module_exit(fn)
#undef MODULE_DEVICE_TABLE
#define MODULE_DEVICE_TABLE(type, name)
#endif /* explicit registry opt-in versus partial helper builds */
#endif
@@ -0,0 +1,435 @@
// SPDX-License-Identifier: MIT
/* Callable whole-original-mutex fixtures. Each role runs on a distinct actual
* Runtime stack with original task metadata and an entered owner. Checkpoints
* enqueue real continuations or post a retained expected-job cancellation;
* no fixture writes lock internals or grants ownership to a sleeper. */
#include <linux/atomic.h>
#include <linux/errno.h>
#include <linux/irqflags.h>
#include <linux/mutex.h>
#include <linux/preempt.h>
#include <linux/rcupdate.h>
#include <linux/sched.h>
#include <linux/sched/signal.h>
#include <linux/sched/task.h>
#include <linux/sched/wake_q.h>
#include <linux/string.h>
#include <linux/ww_mutex.h>
#include <stela/linux.h>
#include <stela/task.h>
#include <stela/test.h>
struct stela_mutex_test_call {
u32 scenario, role;
void *context;
void (*checkpoint)(void *context, u32 event);
};
void stela_linux_mutex_test_run(void *opaque);
static struct mutex lock, auxiliary;
static struct ww_mutex first, second, extra;
static DEFINE_WD_CLASS(die_class);
static DEFINE_WW_CLASS(wound_class);
static struct task_struct *tasks[4];
static unsigned int attempted, finished, acquired, arrivals[3], winners[3];
static unsigned int payload, deadlocks, reused, reuse_finished;
static struct rcu_head signal_retirement;
static const struct stela_mutex_test_call *retirement_call;
static void checkpoint(const struct stela_mutex_test_call *call, u32 event)
{
call->checkpoint(call->context, event);
}
static void until(const unsigned int *value, unsigned int expected)
{
unsigned int yields = 0;
while (READ_ONCE(*value) != expected) {
/* A bounded number of genuine coroutine switches, not CPU polling. */
assert(yields++ < 64);
assert(!stela_linux_task_yield());
}
}
static void current_valid(void)
{
unsigned long pointer;
asm volatile("mov %%rsp, %0" : "=r"(pointer));
assert(current->flags == PF_KTHREAD);
assert(current->policy == SCHED_NORMAL);
assert(current->prio == DEFAULT_PRIO && current->normal_prio == DEFAULT_PRIO);
assert(current->static_prio == DEFAULT_PRIO);
assert(pointer >= (unsigned long)current->stack);
assert(pointer - (unsigned long)current->stack < THREAD_SIZE);
assert(!preempt_count() && !irqs_disabled());
assert(current->on_cpu == 1 && current->on_rq == 1 && !current->is_blocked);
assert(!stela_linux_task_pending_signals());
}
static void wrong_baseline_put(void)
{
/* The borrowed baseline is not a caller-owned get_task_struct reference. */
put_task_struct(current);
rcu_barrier();
}
static void wake_queue_and_refs(void)
{
DEFINE_WAKE_Q(queue);
struct task_struct *self = current;
assert(refcount_read(&self->usage) == 1);
wake_q_add(&queue, self);
assert(refcount_read(&self->usage) == 2);
wake_q_add(&queue, self);
assert(refcount_read(&self->usage) == 2);
get_task_struct(self);
wake_q_add_safe(&queue, self); /* duplicate consumes this real extra ref */
assert(refcount_read(&self->usage) == 2);
wake_up_q(&queue);
assert(refcount_read(&self->usage) == 1 && !self->wake_q.next);
wake_q_init(&queue); /* original wake_up_q does not reinitialize the head */
get_task_struct(self);
wake_q_add_safe(&queue, self); /* newly queued transfers the owned ref */
assert(refcount_read(&self->usage) == 2);
wake_up_q(&queue);
assert(refcount_read(&self->usage) == 1 && !self->wake_q.next);
assert(!wake_up_state(self, TASK_NORMAL));
assert(stela_test_traps(wrong_baseline_put));
assert(refcount_read(&self->usage) == 1);
}
static void uncontended(const struct stela_mutex_test_call *call)
{
atomic_t users = ATOMIC_INIT(2);
assert(!mutex_is_locked(&lock));
assert(!mutex_get_owner(&lock));
assert(mutex_trylock(&lock));
assert(mutex_get_owner(&lock) == (unsigned long)current);
assert(!mutex_trylock(&lock));
mutex_unlock(&lock);
assert(!atomic_dec_and_mutex_lock(&users, &lock));
assert(atomic_read(&users) == 1 && !mutex_is_locked(&lock));
assert(atomic_dec_and_mutex_lock(&users, &lock));
assert(!atomic_read(&users) && mutex_is_locked(&lock));
mutex_unlock(&lock);
ww_mutex_init(&extra, &wound_class);
assert(ww_mutex_trylock(&extra, NULL));
assert(!ww_mutex_trylock(&extra, NULL));
ww_mutex_unlock(&extra);
assert(!ww_mutex_lock(&extra, NULL));
ww_mutex_unlock(&extra);
assert(!ww_mutex_lock_interruptible(&extra, NULL));
ww_mutex_unlock(&extra);
ww_mutex_destroy(&extra);
/* Available IO locks restore the exact nested token without ever being
* accounted as blocked. This checks behavior absent a scheduler switch. */
mutex_lock_io(&lock);
assert(!current->in_iowait);
mutex_unlock(&lock);
int token = io_schedule_prepare();
assert(!token && current->in_iowait);
mutex_lock_io(&lock);
assert(current->in_iowait);
mutex_unlock(&lock);
io_schedule_finish(token);
assert(!current->in_iowait);
assert(!stela_linux_task_waiting_io() && !stela_linux_task_waiting_load());
/* Pending signals cannot defeat an available fastpath acquisition.
* Both bits are delivered by retained TargetTask, never fixture writes. */
checkpoint(call, 7);
assert(stela_linux_task_pending_signals() == 1);
assert(!mutex_lock_interruptible(&lock));
mutex_unlock(&lock);
assert(!mutex_lock_killable(&lock));
mutex_unlock(&lock);
checkpoint(call, 8);
assert(stela_linux_task_pending_signals() == 3);
assert(!mutex_lock_interruptible(&lock));
mutex_unlock(&lock);
assert(!mutex_lock_killable(&lock));
mutex_unlock(&lock);
assert(!stela_linux_task_ack_signal(1));
assert(!stela_linux_task_ack_signal(2));
assert(!stela_linux_task_pending_signals());
wake_queue_and_refs();
}
static void post_during_prepare(struct rcu_head *head)
{
assert(head == &signal_retirement && retirement_call);
assert(current == tasks[1]);
/* Original process retirement has real softirq/preempt accounting. The
* Rust checkpoint only tries its uncontended metadata lock and uses
* bounded atomic/refcount operations; it never allocates or parks. */
assert(preempt_count() == (int)SOFTIRQ_OFFSET && !irqs_disabled());
checkpoint(retirement_call, 4);
}
static void reset(unsigned int scenario)
{
assert(!attempted || finished == attempted);
memset(tasks, 0, sizeof(tasks));
memset(arrivals, 0, sizeof(arrivals));
memset(winners, 0, sizeof(winners));
attempted = finished = acquired = payload = deadlocks = reused = reuse_finished = 0;
retirement_call = NULL;
mutex_init(&lock);
mutex_init(&auxiliary);
struct ww_class *class = scenario == 7 ? &die_class : &wound_class;
ww_mutex_init(&first, class);
ww_mutex_init(&second, class);
}
static void acknowledge_all(void)
{
unsigned int pending = stela_linux_task_pending_signals();
if (pending & 1)
assert(!stela_linux_task_ack_signal(1));
if (pending & 2)
assert(!stela_linux_task_ack_signal(2));
assert(!stela_linux_task_pending_signals());
}
static void ordinary_worker(const struct stela_mutex_test_call *call)
{
unsigned int role = call->role, scenario = call->scenario;
assert(role >= 1 && role <= 3 && current != tasks[0]);
for (unsigned int i = 0; i < 4; i++)
assert(!tasks[i] || tasks[i] != current);
tasks[role] = current;
assert(!mutex_trylock(&lock));
arrivals[attempted++] = role;
int result = 0;
if (scenario == 5) {
retirement_call = call;
call_rcu(&signal_retirement, post_during_prepare);
}
switch (scenario) {
case 1:
case 5:
case 6:
result = mutex_lock_interruptible(&lock);
break;
case 2:
result = mutex_lock_killable(&lock);
break;
case 4:
case 10: {
int outer = io_schedule_prepare();
int inner = io_schedule_prepare();
assert(!outer && inner == 1 && current->in_iowait);
io_schedule_finish(inner);
assert(current->in_iowait);
io_schedule_finish(outer);
assert(!current->in_iowait);
mutex_lock_io(&lock);
assert(!current->in_iowait);
break;
}
default:
mutex_lock(&lock);
break;
}
if (scenario == 1 || scenario == 2 || scenario == 5) {
assert(result == -EINTR && !current->blocked_on);
assert(mutex_get_owner(&lock) == (unsigned long)tasks[0]);
assert(stela_linux_task_pending_signals() == (scenario == 2 ? 3U : 1U));
} else {
assert(!result && mutex_get_owner(&lock) == (unsigned long)current);
assert(payload == 42);
winners[acquired++] = role;
mutex_unlock(&lock);
}
acknowledge_all();
assert(!preempt_count() && !current->blocked_on);
assert(!current->in_iowait && current->__state == TASK_RUNNING);
finished++;
}
static void ordinary_owner(const struct stela_mutex_test_call *call)
{
unsigned int scenario = call->scenario, workers = scenario ? 1 : 3;
uncontended(call);
mutex_lock(&lock);
tasks[0] = current;
checkpoint(call, 1);
until(&attempted, workers);
assert(!acquired && mutex_get_owner(&lock) == (unsigned long)current);
if (scenario == 1 || scenario == 2 || scenario == 3 || scenario == 4 || scenario == 6 || scenario == 10) {
assert(stela_linux_task_waiting_load() == (scenario == 1 || scenario == 6 ? 0U : 1U));
assert(stela_linux_task_waiting_io() == (scenario == 4 || scenario == 10 ? 1U : 0U));
}
if (scenario == 1 || scenario == 2 || scenario == 3 || scenario == 4)
checkpoint(call, 2);
if (scenario == 2 || scenario == 3 || scenario == 4) {
/* Nonfatal cancellation does not wake killable/uninterruptible IO. */
assert(!stela_linux_task_yield());
assert(!finished && stela_linux_task_waiting_load() == 1);
if (scenario == 2) {
checkpoint(call, 3);
} else {
/* Lock-scoped borrowed waiter is valid at baseline usage one. */
assert(refcount_read(&tasks[1]->usage) == 1);
assert(wake_up_process(tasks[1]) == 1);
assert(!tasks[1]->blocked_on && !tasks[1]->is_blocked);
assert(tasks[1]->on_rq == 1 && !tasks[1]->on_cpu);
assert(!stela_linux_task_waiting_load());
assert(!stela_linux_task_yield());
assert(!finished && stela_linux_task_waiting_load() == 1);
assert(stela_linux_task_waiting_io() == (scenario == 4 || scenario == 10 ? 1U : 0U));
}
}
if (scenario == 10) {
/* Only a generation-gated generic IRQ wake view is invoked. It does
* not touch C state/accounting. Arrival must resolve them once on
* the real resumed stack before the original waiter rechecks. */
assert(tasks[1]->blocked_on == &lock && tasks[1]->is_blocked);
checkpoint(call, 10);
assert(tasks[1]->blocked_on == &lock && tasks[1]->is_blocked);
assert(stela_linux_task_waiting_io() == 1);
assert(!stela_linux_task_yield());
assert(!finished && stela_linux_task_waiting_io() == 1);
assert(stela_linux_task_waiting_load() == 1);
}
if (scenario == 6) {
/* A genuine spurious resume requests original HANDOFF; cancellation
* then loses to original unlock/PICKUP before the waiter runs. */
assert(wake_up_process(tasks[1]) == 1);
assert(!stela_linux_task_yield());
assert(atomic_long_read(&lock.owner) & 2UL);
checkpoint(call, 2);
}
if (scenario == 1 || scenario == 2 || scenario == 5) {
until(&finished, 1);
assert(!acquired && !lock.first_waiter);
}
payload = 42;
mutex_unlock(&lock);
if (scenario == 6)
assert(atomic_long_read(&lock.owner) & 4UL);
until(&finished, workers);
assert(!stela_linux_task_waiting_io() && !stela_linux_task_waiting_load());
if (!scenario) {
assert(acquired == 3);
for (unsigned int i = 0; i < 3; i++)
assert(winners[i] == arrivals[i]);
checkpoint(call, 5); /* old target after actual completion */
checkpoint(call, 6); /* same Notify continuation, new real job */
until(&reused, 1);
checkpoint(call, 5); /* old target while the future job is live */
until(&reuse_finished, 1);
}
assert(!mutex_is_locked(&lock) && !lock.first_waiter);
}
static void ww_worker(const struct stela_mutex_test_call *call)
{
struct ww_acquire_ctx context;
unsigned int scenario = call->scenario;
struct ww_class *class = scenario == 7 ? &die_class : &wound_class;
tasks[1] = current;
ww_acquire_init(&context, class);
assert(context.task == current && !context.acquired);
if (scenario != 9) {
assert(!ww_mutex_lock(&second, &context));
assert(context.acquired == 1);
}
attempted++;
int error = ww_mutex_lock_interruptible(&first, &context);
if (scenario == 9) {
assert(error == -EINTR && !context.acquired);
assert(stela_linux_task_pending_signals() == 1);
acknowledge_all();
} else {
assert(error == -EDEADLK && context.acquired == 1);
if (scenario == 8)
assert(context.wounded);
deadlocks++;
ww_mutex_unlock(&second);
assert(!context.acquired);
ww_mutex_lock_slow(&first, &context);
assert(context.acquired == 1 && !context.wounded);
assert(ww_mutex_trylock(&second, &context));
assert(context.acquired == 2);
ww_acquire_done(&context);
ww_mutex_unlock(&second);
ww_mutex_unlock(&first);
}
assert(!context.acquired && !current->blocked_on);
ww_acquire_fini(&context);
finished++;
}
static void ww_owner(const struct stela_mutex_test_call *call)
{
struct ww_acquire_ctx context;
struct ww_class *class = call->scenario == 7 ? &die_class : &wound_class;
ww_acquire_init(&context, class); /* older than worker's actual context */
assert(!ww_mutex_lock(&first, &context));
assert(ww_mutex_lock(&first, &context) == -EALREADY);
tasks[0] = current;
checkpoint(call, 1);
until(&attempted, 1);
if (call->scenario == 9) {
checkpoint(call, 2);
until(&finished, 1);
assert(!deadlocks && context.acquired == 1);
} else {
if (call->scenario == 7)
until(&deadlocks, 1);
else
assert(!deadlocks && !finished);
/* Wound/wait: this older task blocks on second, original wake_q
* wounds the younger owner sleeping on first, and genuine wake/
* backoff releases second so this original lock call can resume. */
assert(!ww_mutex_lock(&second, &context));
assert(deadlocks == 1 && context.acquired == 2);
ww_mutex_unlock(&second);
}
ww_acquire_done(&context);
ww_mutex_unlock(&first);
assert(!context.acquired);
ww_acquire_fini(&context);
until(&finished, 1);
assert(!mutex_is_locked(&first.base) && !mutex_is_locked(&second.base));
}
void stela_linux_mutex_test_run(void *opaque)
{
const struct stela_mutex_test_call *call = opaque;
const struct stela_linux_services services = {};
const struct stela_linux_owner owner = {.services = &services};
stela_linux_enter(&owner);
current_valid();
assert(call && call->scenario <= 10 && call->role <= 4);
if (!call->role) {
reset(call->scenario);
if (call->scenario < 7 || call->scenario == 10)
ordinary_owner(call);
else
ww_owner(call);
} else if (call->role == 4) {
assert(!call->scenario && current == tasks[1]);
mutex_lock(&auxiliary);
reused++;
assert(!stela_linux_task_yield());
assert(!stela_linux_task_pending_signals());
mutex_unlock(&auxiliary);
reuse_finished++;
} else if (call->scenario < 7 || call->scenario == 10) {
ordinary_worker(call);
} else {
assert(call->role == 1);
ww_worker(call);
}
assert(!current->blocked_on && !preempt_count());
assert(!stela_linux_task_pending_signals());
assert(stela_linux_quiescent());
/* A real extra original C ref refuses scope completion, then releases.
* The enclosing Rust wrapper subsequently performs the actual scope end. */
struct task_struct *self = current;
get_task_struct(self);
stela_linux_exit();
assert(stela_linux_task_scope_end((struct stela_linux_task *)self) == -EBUSY);
put_task_struct(self);
}
@@ -0,0 +1,384 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Included only by params.c's dedicated hosted parser fixture. The oracle
* functions below are retained Linux source bytes, not another implementation. */
#include <stela/test.h>
char *source_next_arg(char *args, char **param, char **val);
#define dash2underscore source_dash2underscore
#define parameqn source_parameqn
#define parameq source_parameq
#define param_check_unsafe source_param_check_unsafe
#define parse_one source_parse_one
#define parse_args source_parse_args
#define next_arg source_next_arg
#include <stela/params-reference.h>
#undef next_arg
#undef parse_args
#undef parse_one
#undef param_check_unsafe
#undef parameq
#undef parameqn
#undef dash2underscore
#define TOKEN_BYTES 512
#define TRACE_ENTRIES 32
struct parser_call {
const struct kernel_param *kp;
bool null_value;
bool tainted;
char name[48];
char value[80];
};
struct parser_capture {
char bytes[TOKEN_BYTES];
char diagnostics[2048];
size_t diagnostic_length;
struct parser_call calls[TRACE_ENTRIES];
unsigned int count;
unsigned int setters;
unsigned int unknowns;
unsigned int mutations;
int result_kind;
long result_value;
};
static struct parser_capture *active_capture;
static void parser_log(void *context, int level, const char *message)
{
struct parser_capture *capture = context;
assert(capture == active_capture);
/* Retain both severity and complete formatted diagnostic bytes. */
int added = scnprintf(capture->diagnostics + capture->diagnostic_length,
sizeof(capture->diagnostics) - capture->diagnostic_length,
"%d:%s", level, message);
assert(added > 0 && capture->diagnostic_length + added < sizeof(capture->diagnostics) - 1);
capture->diagnostic_length += added;
}
static struct parser_call *parser_trace(const struct kernel_param *kp, const char *name,
const char *value)
{
assert(active_capture->count < TRACE_ENTRIES);
struct parser_call *call = &active_capture->calls[active_capture->count++];
call->kp = kp;
call->null_value = !value;
call->tainted = !!(get_taint() & (1UL << TAINT_USER));
assert(strlen(name) < sizeof(call->name));
strcpy(call->name, name);
if (value) {
assert(strlen(value) < sizeof(call->value));
strcpy(call->value, value);
}
return call;
}
static int parser_set(const char *value, const struct kernel_param *kp)
{
parser_trace(kp, kp->name, value);
active_capture->setters++;
/* A custom setter can mutate before returning an error. No rollback. */
active_capture->mutations++;
if (kp->flags & KERNEL_PARAM_FL_UNSAFE)
assert(get_taint() & (1UL << TAINT_USER));
if (!value)
return 0;
if (!strcmp(value, "bad"))
return -EINVAL;
if (!strcmp(value, "large"))
return -ENOSPC;
if (!strcmp(value, "range"))
return -ERANGE;
return 0;
}
static int parser_unknown(char *param, char *val, const char *doing, void *arg)
{
assert(arg == active_capture && !strcmp(doing, "fixture"));
parser_trace(NULL, param, val);
active_capture->unknowns++;
if (val && !strcmp(param, "repair"))
param[strlen(param)] = '=';
if (!strcmp(param, "consume"))
return 0;
if (!strcmp(param, "large"))
return -ENOSPC;
if (!strcmp(param, "range"))
return -ERANGE;
return -ENOENT;
}
static const struct kernel_param_ops parser_ops = {.set = parser_set};
static const struct kernel_param_ops noarg_ops = {
.flags = KERNEL_PARAM_OPS_FL_NOARG, .set = parser_set,
};
/* Shared exact addresses used by all three executions. A duplicate public
* name tests original first-match filtering, including no setup fallback. */
static const struct kernel_param parser_parameters[] = {
{.name = "x", .ops = &parser_ops, .level = -1},
{.name = "has_dash", .ops = &parser_ops, .level = -1},
{.name = "switch", .ops = &noarg_ops, .level = -1},
{.name = "shadow", .ops = &parser_ops, .level = 5},
{.name = "shadow", .ops = &parser_ops, .level = -1},
{.name = "unsafe", .ops = &parser_ops, .level = -1, .flags = KERNEL_PARAM_FL_UNSAFE},
{.name = "hardware", .ops = &parser_ops, .level = -1,
.flags = KERNEL_PARAM_FL_HWPARAM | KERNEL_PARAM_FL_UNSAFE},
};
static void parser_result(struct parser_capture *capture, char *result)
{
unsigned long address = (unsigned long)result;
unsigned long base = (unsigned long)capture->bytes;
if (!result) {
capture->result_kind = 0;
} else if (address >= base && address < base + sizeof(capture->bytes)) {
capture->result_kind = 1;
capture->result_value = address - base;
} else {
capture->result_kind = 2;
capture->result_value = (long)result;
}
}
static void parser_run(struct parser_capture *capture, const char *command, unsigned int path,
s16 min, s16 max, bool with_unknown)
{
memset(capture, 0, sizeof(*capture));
memset(capture->bytes, 0x92, sizeof(capture->bytes));
assert(strlen(command) < sizeof(capture->bytes));
strcpy(capture->bytes, command);
active_capture = capture;
const struct stela_linux_services services = {.log = parser_log};
const struct stela_linux_owner owner = {.services = &services, .context = capture};
stela_linux_enter(&owner);
parse_unknown_fn unknown = with_unknown ? parser_unknown : NULL;
char *result;
if (!path) {
result = source_parse_args("fixture", capture->bytes, parser_parameters,
ARRAY_SIZE(parser_parameters), min, max, capture, unknown);
} else if (path == 1) {
result = parse_args("fixture", capture->bytes, parser_parameters,
ARRAY_SIZE(parser_parameters), min, max, capture, unknown);
} else {
const struct kernel_param *view[ARRAY_SIZE(parser_parameters)];
for (size_t i = 0; i < ARRAY_SIZE(view); i++)
view[i] = &parser_parameters[i];
struct stela_linux_params_result parsed = stela_linux_parse_args_view(
"fixture", capture->bytes, view, ARRAY_SIZE(view), min, max,
capture, unknown, NULL);
assert(!parsed.observer_error);
result = parsed.result;
}
parser_result(capture, result);
stela_linux_exit();
active_capture = NULL;
}
/* Run before any canonical case seeds TAINT_USER: missing required values
* and filtered levels must leave the real bit clear; a failing unsafe setter
* must see both the original notice and the taint already committed. */
static void unsafe_dispatch_order(void)
{
struct parser_capture capture = {0};
active_capture = &capture;
const struct stela_linux_services services = {.log = parser_log};
const struct stela_linux_owner owner = {.services = &services, .context = &capture};
const struct kernel_param *view[] = {&parser_parameters[5]};
stela_linux_enter(&owner);
assert(!(get_taint() & (1UL << TAINT_USER)));
strcpy(capture.bytes, "unsafe");
struct stela_linux_params_result parsed = stela_linux_parse_args_view(
"fixture", capture.bytes, view, 1, -1, -1, NULL, NULL, NULL);
assert(parsed.result == ERR_PTR(-EINVAL) && !parsed.observer_error);
assert(!capture.setters && !(get_taint() & (1UL << TAINT_USER)));
memset(&capture, 0, sizeof(capture));
strcpy(capture.bytes, "unsafe=filtered");
parsed = stela_linux_parse_args_view("fixture", capture.bytes, view, 1, 0, 7, NULL, NULL, NULL);
assert(!parsed.result && !parsed.observer_error && !capture.setters);
assert(!capture.diagnostic_length && !(get_taint() & (1UL << TAINT_USER)));
memset(&capture, 0, sizeof(capture));
strcpy(capture.bytes, "unsafe=bad");
parsed = stela_linux_parse_args_view("fixture", capture.bytes, view, 1, -1, -1, NULL, NULL, NULL);
assert(parsed.result == ERR_PTR(-EINVAL) && !parsed.observer_error);
assert(capture.setters == 1 && capture.calls[0].tainted);
assert(!strncmp(capture.diagnostics,
"5:Setting dangerous option unsafe - tainting kernel\n",
strlen("5:Setting dangerous option unsafe - tainting kernel\n")));
assert(get_taint() & (1UL << TAINT_USER)); /* Failed set never rolls back. */
stela_linux_exit();
active_capture = NULL;
}
static void canonical_parser_differential(void)
{
const struct {
const char *command;
s16 min, max;
bool unknown;
int error;
unsigned int setters, unknowns;
const char *tail;
} cases[] = {
{"", -1, -1, false, 0, 0, 0, NULL},
{" \t\n\r\v\f", -1, -1, false, 0, 0, 0, NULL},
{"x=one", -1, -1, false, 0, 1, 0, NULL},
{"x=one x=two", -1, -1, false, 0, 2, 0, NULL},
{"x", -1, -1, false, -EINVAL, 0, 0, NULL},
{"x=", -1, -1, false, 0, 1, 0, NULL},
{"switch", -1, -1, false, 0, 1, 0, NULL},
{"switch= switch=false", -1, -1, false, 0, 2, 0, NULL},
{"has-dash=a has_dash=b", -1, -1, false, 0, 2, 0, NULL},
{"X=case", -1, -1, false, -ENOENT, 0, 0, NULL},
{"x=\"two words\"", -1, -1, false, 0, 1, 0, NULL},
{"\"x=two words\"", -1, -1, false, 0, 1, 0, NULL},
{"x=\"unterminated space", -1, -1, false, 0, 1, 0, NULL},
{"x=a=b=c", -1, -1, false, 0, 1, 0, NULL},
{"x=\"\"", -1, -1, false, 0, 1, 0, NULL},
{"\"switch\"", -1, -1, false, 0, 1, 0, NULL},
{"=odd", -1, -1, true, -ENOENT, 0, 1, NULL},
{"x=one,two", -1, -1, false, 0, 1, 0, NULL},
{"shadow=value", -1, -1, true, 0, 0, 0, NULL},
{"shadow", -1, -1, true, 0, 0, 0, NULL},
{"shadow=value", 5, 5, false, 0, 1, 0, NULL},
{"shadow=value x=ignored", -1, 5, false, 0, 2, 0, NULL},
{"unknown=value", -1, -1, false, -ENOENT, 0, 0, NULL},
{"repair=abc", -1, -1, true, -ENOENT, 0, 1, NULL},
{"unknown=\"two words\"", -1, -1, true, -ENOENT, 0, 1, NULL},
{"\"consume=two words\" consume", -1, -1, true, 0, 0, 2, NULL},
{"x=bad x=valid", -1, -1, false, -EINVAL, 2, 0, NULL},
{"x=bad x=large x=range x=valid", -1, -1, false, -ERANGE, 4, 0, NULL},
{"range=q large=foo consume=ok", -1, -1, true, -ENOSPC, 0, 3, NULL},
{"-- untouched=x tail", -1, -1, false, 0, 0, 0, "untouched=x tail"},
{"x=one -- x=untouched", -1, -1, false, 0, 1, 0, "x=untouched"},
{"x=bad -- x=untouched", -1, -1, false, -EINVAL, 1, 0, NULL},
{"--=value x=one", -1, -1, true, -ENOENT, 1, 1, NULL},
{"unsafe", -1, -1, false, -EINVAL, 0, 0, NULL},
{"unsafe=bad x=valid", -1, -1, false, -EINVAL, 2, 0, NULL},
{"hardware=value", -1, -1, false, 0, 1, 0, NULL},
{"unsafe=ignored", 0, 7, false, 0, 0, 0, NULL},
};
/* TAINT_USER is monotonic. Seed the real shared state before canonical
* comparisons so the reference and both paths have identical inputs. */
stela_linux_enter(&stela_linux_bare);
add_taint(TAINT_USER, LOCKDEP_STILL_OK);
stela_linux_exit();
for (size_t i = 0; i < ARRAY_SIZE(cases); i++) {
struct parser_capture oracle, actual;
parser_run(&oracle, cases[i].command, 0, cases[i].min, cases[i].max, cases[i].unknown);
assert(oracle.setters == cases[i].setters && oracle.unknowns == cases[i].unknowns);
assert(oracle.mutations == oracle.setters);
if (cases[i].error) {
assert(oracle.result_kind == 2 && oracle.result_value == cases[i].error);
} else if (cases[i].tail) {
assert(oracle.result_kind == 1);
assert(!strcmp(oracle.bytes + oracle.result_value, cases[i].tail));
} else {
assert(!oracle.result_kind);
}
for (unsigned int path = 1; path <= 2; path++) {
parser_run(&actual, cases[i].command, path, cases[i].min, cases[i].max, cases[i].unknown);
/* Every byte was initialized, including trace padding and token
* suffix poison. Equal counts alone cannot pass this oracle. */
assert(!memcmp(&oracle, &actual, sizeof(oracle)));
}
}
assert(parameq("hyphen-name", "hyphen_name"));
assert(!parameq("hyphen", "hyphen_more"));
assert(parameqn("hyphen-nameSUFFIX", "hyphen_name", 11));
assert(!parameqn("hyphen-NAME", "hyphen_name", 11));
}
struct parser_observer_state {
enum stela_linux_param_event fail_event;
int failure;
unsigned int before, after;
int last_result;
};
static int parser_observe(void *context, enum stela_linux_param_event event,
const struct kernel_param *kp, char *param, char *val, int result)
{
struct parser_observer_state *state = context;
assert(param && val && !strcmp(val, "bad"));
if (event == STELA_LINUX_PARAM_BEFORE_SET || event == STELA_LINUX_PARAM_AFTER_SET)
assert(kp == &parser_parameters[0]);
else
assert(!kp);
if (event == STELA_LINUX_PARAM_BEFORE_SET || event == STELA_LINUX_PARAM_BEFORE_UNKNOWN) {
state->before++;
assert(!result && !active_capture->count);
} else {
state->after++;
state->last_result = result;
assert(active_capture->count == 1);
}
return event == state->fail_event ? state->failure : 0;
}
static void observer_terminal_failures(void)
{
for (unsigned int event = 0; event < 4; event++) {
for (unsigned int positive = 0; positive < 2; positive++) {
struct parser_capture capture = {0};
active_capture = &capture;
strcpy(capture.bytes, event < 2 ? "x=bad x=later" : "range=bad x=later");
const struct stela_linux_services services = {.log = parser_log};
const struct stela_linux_owner owner = {.services = &services, .context = &capture};
stela_linux_enter(&owner);
const struct kernel_param *view[] = {&parser_parameters[0]};
struct parser_observer_state state = {.fail_event = event,
.failure = positive ? 1 : -EOWNERDEAD};
const struct stela_linux_param_observer observer = {
.observe = parser_observe, .context = &state,
};
struct stela_linux_params_result parsed = stela_linux_parse_args_view(
"fixture", capture.bytes, view, ARRAY_SIZE(view), -1, -1,
&capture, parser_unknown, &observer);
int expected = positive ? -EPROTO : -EOWNERDEAD;
assert(parsed.observer_error == expected && parsed.result == ERR_PTR(expected));
bool after = event == STELA_LINUX_PARAM_AFTER_SET || event == STELA_LINUX_PARAM_AFTER_UNKNOWN;
assert(state.before == 1 && state.after == after);
assert(capture.count == after && capture.mutations == (after && event < 2));
if (after)
assert(state.last_result == (event < 2 ? -EINVAL : -ERANGE));
assert(strstr(capture.bytes + (event < 2 ? 6 : 10), "x=later"));
assert(!capture.diagnostic_length); /* terminal before error logger */
stela_linux_exit();
active_capture = NULL;
}
}
}
static void explicit_dispatch_extensions(void)
{
const struct kernel_param_ops readonly = {0};
const struct kernel_param_ops future_ops = {.flags = 2, .set = parser_set};
struct kernel_param parameter = {.name = "extension", .ops = &readonly, .level = -1};
const struct kernel_param *view[] = {&parameter, &parser_parameters[0]};
const struct kernel_param_ops *operations[] = {&readonly, &future_ops, &parser_ops};
const int errors[] = {-EPERM, -EOPNOTSUPP, -EOPNOTSUPP};
for (unsigned int i = 0; i < ARRAY_SIZE(operations); i++) {
struct parser_capture capture = {0};
active_capture = &capture;
strcpy(capture.bytes, "extension=value x=later");
parameter.ops = operations[i];
parameter.flags = i == 2 ? 0x80 : 0;
const struct stela_linux_services services = {.log = parser_log};
const struct stela_linux_owner owner = {.services = &services, .context = &capture};
stela_linux_enter(&owner);
struct stela_linux_params_result parsed = stela_linux_parse_args_view(
"fixture", capture.bytes, view, ARRAY_SIZE(view), -1, -1, NULL, NULL, NULL);
assert(!parsed.observer_error && parsed.result == ERR_PTR(errors[i]));
assert(capture.setters == 1 && capture.calls[0].kp == &parser_parameters[0]);
stela_linux_exit();
active_capture = NULL;
}
}
int main(void)
{
unsafe_dispatch_order();
canonical_parser_differential();
observer_terminal_failures();
explicit_dispatch_extensions();
printf("Linux parser: retained-source differential, exact descriptors and terminal observers passed\n");
return 0;
}
@@ -0,0 +1,192 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/* Verbatim bounded projections: Linux kernel/params.c Copyright (C) 2001
* Rusty Russell; lib/cmdline.c code/copyrights from init/main.c and
* arch/i386/kernel/setup.c. See source-projection.json for exact ranges. */
static char dash2underscore(char c)
{
if (c == '-')
return '_';
return c;
}
bool parameqn(const char *a, const char *b, size_t n)
{
size_t i;
for (i = 0; i < n; i++) {
if (dash2underscore(a[i]) != dash2underscore(b[i]))
return false;
}
return true;
}
bool parameq(const char *a, const char *b)
{
return parameqn(a, b, strlen(a)+1);
}
static bool param_check_unsafe(const struct kernel_param *kp)
{
if (kp->flags & KERNEL_PARAM_FL_HWPARAM &&
security_locked_down(LOCKDOWN_MODULE_PARAMETERS))
return false;
if (kp->flags & KERNEL_PARAM_FL_UNSAFE) {
pr_notice("Setting dangerous option %s - tainting kernel\n",
kp->name);
add_taint(TAINT_USER, LOCKDEP_STILL_OK);
}
return true;
}
static int parse_one(char *param,
char *val,
const char *doing,
const struct kernel_param *params,
unsigned num_params,
s16 min_level,
s16 max_level,
void *arg, parse_unknown_fn handle_unknown)
{
unsigned int i;
int err;
/* Find parameter */
for (i = 0; i < num_params; i++) {
if (parameq(param, params[i].name)) {
if (params[i].level < min_level
|| params[i].level > max_level)
return 0;
/* No one handled NULL, so do it here. */
if (!val &&
!(params[i].ops->flags & KERNEL_PARAM_OPS_FL_NOARG))
return -EINVAL;
pr_debug("handling %s with %p\n", param,
params[i].ops->set);
kernel_param_lock(params[i].mod);
if (param_check_unsafe(&params[i]))
err = params[i].ops->set(val, &params[i]);
else
err = -EPERM;
kernel_param_unlock(params[i].mod);
return err;
}
}
if (handle_unknown) {
pr_debug("doing %s: %s='%s'\n", doing, param, val);
return handle_unknown(param, val, doing, arg);
}
pr_debug("Unknown argument '%s'\n", param);
return -ENOENT;
}
/* Args looks like "foo=bar,bar2 baz=fuz wiz". */
char *parse_args(const char *doing,
char *args,
const struct kernel_param *params,
unsigned int num,
s16 min_level,
s16 max_level,
void *arg, parse_unknown_fn unknown)
{
char *param, *val, *err = NULL;
/* Chew leading spaces */
args = skip_spaces(args);
if (*args)
pr_debug("doing %s, parsing ARGS: '%s'\n", doing, args);
while (*args) {
int ret;
int irq_was_disabled;
args = next_arg(args, &param, &val);
/* Stop at -- */
if (!val && strcmp(param, "--") == 0)
return err ?: args;
irq_was_disabled = irqs_disabled();
ret = parse_one(param, val, doing, params, num,
min_level, max_level, arg, unknown);
if (irq_was_disabled && !irqs_disabled())
pr_warn("%s: option '%s' enabled irq's!\n",
doing, param);
switch (ret) {
case 0:
continue;
case -ENOENT:
pr_err("%s: Unknown parameter `%s'\n", doing, param);
break;
case -ENOSPC:
pr_err("%s: `%s' too large for parameter `%s'\n",
doing, val ?: "", param);
break;
default:
pr_err("%s: `%s' invalid for parameter `%s'\n",
doing, val ?: "", param);
break;
}
err = ERR_PTR(ret);
}
return err;
}
/*
* Parse a string to get a param value pair.
* You can use " around spaces, but can't escape ".
* Hyphens and underscores equivalent in parameter names.
*/
char *next_arg(char *args, char **param, char **val)
{
unsigned int i, equals = 0;
int in_quote = 0, quoted = 0;
if (*args == '"') {
args++;
in_quote = 1;
quoted = 1;
}
for (i = 0; args[i]; i++) {
if (isspace(args[i]) && !in_quote)
break;
if (equals == 0) {
if (args[i] == '=')
equals = i;
}
if (args[i] == '"')
in_quote = !in_quote;
}
*param = args;
if (!equals)
*val = NULL;
else {
args[equals] = '\0';
*val = args + equals + 1;
/* Don't include quotes in value. */
if (**val == '"') {
(*val)++;
if (args[i-1] == '"')
args[i-1] = '\0';
}
}
if (quoted && i > 0 && args[i-1] == '"')
args[i-1] = '\0';
if (args[i]) {
args[i] = '\0';
args += i + 1;
} else
args += i;
/* Chew up trailing spaces. */
return skip_spaces(args);
}
@@ -0,0 +1,42 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_PARAMS_H
#define STELA_PARAMS_H
#include <linux/moduleparam.h>
/* Each entry runs under the existing entered, serialized Linux owner.
* The caller supplies owned writable token bytes with the lifetime of EVERY
* consumer, including a custom setter retaining a value pointer. The registry
* view uses a checked-quiescent owner and its observer enforces that boundary
* before and after callbacks; no observer/context is retained. */
enum stela_linux_param_event {
STELA_LINUX_PARAM_BEFORE_SET,
STELA_LINUX_PARAM_AFTER_SET,
STELA_LINUX_PARAM_BEFORE_UNKNOWN,
STELA_LINUX_PARAM_AFTER_UNKNOWN,
};
struct stela_linux_param_observer {
/* Borrowed for this parse call only. BEFORE result is zero. AFTER is
* delivered even after a setter/unknown error. A negative return is a
* terminal context failure: stop immediately without parsing another
* token, and keep all prior effects. A positive observer return is an
* observer contract violation reported as -EPROTO. Unknown has kp=NULL.
* BEFORE_SET precedes HWPARAM/UNSAFE/security/taint effects as well as
* the actual setter. No callback occurs for a filtered or rejected kp. */
int (*observe)(void *context, enum stela_linux_param_event event,
const struct kernel_param *kp, char *param, char *val, int result);
void *context;
};
struct stela_linux_params_result {
/* Source parse_args convention: NULL, -- tail, or ERR_PTR(last error).
* On terminal observer failure this is ERR_PTR(observer_error). */
char *result;
int observer_error;
};
struct stela_linux_params_result stela_linux_parse_args_view(
const char *doing, char *args, const struct kernel_param *const *params,
unsigned int num, s16 min_level, s16 max_level, void *arg,
parse_unknown_fn unknown, const struct stela_linux_param_observer *observer);
#endif
@@ -0,0 +1,161 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/* Registration emission is projected from Linux init.h/moduleparam.h/module.h
* at cc9de5d4b5ab6459f5774946aa3195ad51236fa8. Callback bodies are untouched.
* Opt in AFTER original declarations and BEFORE the selected original TU.
* Existing partial helper builds must not force this header. */
#ifndef STELA_LINUX_REGISTRATION_H
#define STELA_LINUX_REGISTRATION_H
#ifdef __cplusplus
#error "static registry capture requires a C translation unit"
#endif
#include <linux/module.h>
#include <stela/registry.h>
#if defined(MODULE) || defined(CONFIG_MODULES)
#error "static registry requires actual built-in Linux semantics"
#endif
#if !defined(STELA_LINUX_REG_DOMAIN) || !defined(STELA_LINUX_REG_UNIT) || \
!defined(STELA_LINUX_REG_UNIT_ORDINAL) || !defined(STELA_LINUX_REG_GROUP_SYMBOL)
#error "registration requires explicit reviewed domain, TU and Kbuild group"
#endif
/* The manifest scanner enforces ASCII letter/alphanumeric domain/TU tokens.
* One __COUNTER__ argument is expanded once before it is pasted/reused. */
#define STELA_REG_NAME_I(domain, unit, kind, seq) \
stela_linux_reg__##domain##__##unit##__##kind##__##seq
#define STELA_REG_NAME_II(domain, unit, kind, seq) \
STELA_REG_NAME_I(domain, unit, kind, seq)
#define STELA_REG_NAME(kind, seq) \
STELA_REG_NAME_II(STELA_LINUX_REG_DOMAIN, STELA_LINUX_REG_UNIT, kind, seq)
#define STELA_REG_TEXT_I(domain, unit, seq) stela_linux_info__##domain##__##unit##__##seq
#define STELA_REG_TEXT_II(domain, unit, seq) STELA_REG_TEXT_I(domain, unit, seq)
#define STELA_REG_TEXT(seq) STELA_REG_TEXT_II(STELA_LINUX_REG_DOMAIN, STELA_LINUX_REG_UNIT, seq)
#define STELA_REG_UNIT_I(domain, unit) stela_linux_unit__##domain##__##unit
#define STELA_REG_UNIT_II(domain, unit) STELA_REG_UNIT_I(domain, unit)
#define STELA_REG_UNIT STELA_REG_UNIT_II(STELA_LINUX_REG_DOMAIN, STELA_LINUX_REG_UNIT)
extern const struct stela_linux_build_group STELA_LINUX_REG_GROUP_SYMBOL;
extern const struct stela_linux_build_unit STELA_REG_UNIT;
#define STELA_REG_CAPTURE_I(domain, unit) stela_linux_capture__##domain##__##unit
#define STELA_REG_CAPTURE_II(domain, unit) STELA_REG_CAPTURE_I(domain, unit)
/* Proves capture was included even for selected units with no registrations. */
const struct stela_linux_build_unit *const
STELA_REG_CAPTURE_II(STELA_LINUX_REG_DOMAIN, STELA_LINUX_REG_UNIT) __used = &STELA_REG_UNIT;
#define STELA_REG_HEADER(kind, lev, fl, seq) \
{ STELA_LINUX_REGISTRY_ABI, kind, lev, fl, STELA_LINUX_REG_UNIT_ORDINAL, seq }
#define STELA_REG_CONTEXT &STELA_LINUX_REG_GROUP_SYMBOL, &STELA_REG_UNIT
#define STELA_REG_INIT_I(fn, kind, lev, fl, code, seq) \
const struct stela_linux_init_record STELA_REG_NAME(code, seq) __used = { \
STELA_REG_HEADER(kind, lev, fl, seq), STELA_REG_CONTEXT, __stringify(fn), fn }
#define STELA_REG_INIT(fn, kind, lev, fl, code, seq) \
STELA_REG_INIT_I(fn, kind, lev, fl, code, seq)
#define STELA_REG_EXIT_I(fn, kind, code, seq) \
const struct stela_linux_exit_record STELA_REG_NAME(code, seq) __used = { \
STELA_REG_HEADER(kind, -1, 0, seq), STELA_REG_CONTEXT, __stringify(fn), fn }
#define STELA_REG_EXIT(fn, kind, code, seq) STELA_REG_EXIT_I(fn, kind, code, seq)
/* Preserve the actual IDs supported by original __define_initcall. */
#define STELA_REG_LEVEL_early STELA_LINUX_REG_EARLY_LEVEL
#define STELA_REG_LEVEL_rootfs STELA_LINUX_REG_ROOTFS_LEVEL
#define STELA_REG_SYNC_early 0
#define STELA_REG_SYNC_rootfs 0
#define STELA_REG_LEVEL_0 0
#define STELA_REG_SYNC_0 0
#define STELA_REG_LEVEL_1 1
#define STELA_REG_SYNC_1 0
#define STELA_REG_LEVEL_1s 1
#define STELA_REG_SYNC_1s STELA_LINUX_REG_SYNC
#define STELA_REG_LEVEL_2 2
#define STELA_REG_SYNC_2 0
#define STELA_REG_LEVEL_2s 2
#define STELA_REG_SYNC_2s STELA_LINUX_REG_SYNC
#define STELA_REG_LEVEL_3 3
#define STELA_REG_SYNC_3 0
#define STELA_REG_LEVEL_3s 3
#define STELA_REG_SYNC_3s STELA_LINUX_REG_SYNC
#define STELA_REG_LEVEL_4 4
#define STELA_REG_SYNC_4 0
#define STELA_REG_LEVEL_4s 4
#define STELA_REG_SYNC_4s STELA_LINUX_REG_SYNC
#define STELA_REG_LEVEL_5 5
#define STELA_REG_SYNC_5 0
#define STELA_REG_LEVEL_5s 5
#define STELA_REG_SYNC_5s STELA_LINUX_REG_SYNC
#define STELA_REG_LEVEL_6 6
#define STELA_REG_SYNC_6 0
#define STELA_REG_LEVEL_6s 6
#define STELA_REG_SYNC_6s STELA_LINUX_REG_SYNC
#define STELA_REG_LEVEL_7 7
#define STELA_REG_SYNC_7 0
#define STELA_REG_LEVEL_7s 7
#define STELA_REG_SYNC_7s STELA_LINUX_REG_SYNC
#undef __define_initcall
#define __define_initcall(fn, id) \
STELA_REG_INIT(fn, STELA_LINUX_REG_INIT, STELA_REG_LEVEL_##id, \
STELA_REG_SYNC_##id, i, __COUNTER__);
#undef module_init
#define module_init(fn) \
STELA_REG_INIT(fn, STELA_LINUX_REG_MODULE_INIT, 6, 0, m, __COUNTER__);
#undef __exitcall
#define __exitcall(fn) STELA_REG_EXIT(fn, STELA_LINUX_REG_EXIT, x, __COUNTER__)
#undef module_exit
#define module_exit(fn) STELA_REG_EXIT(fn, STELA_LINUX_REG_MODULE_EXIT, e, __COUNTER__);
#undef console_initcall
#define console_initcall(fn) \
STELA_REG_INIT(fn, STELA_LINUX_REG_CONSOLE, STELA_LINUX_REG_CONSOLE_LEVEL, \
0, c, __COUNTER__);
/* Exact original kernel_param declaration, including its symbol identity.
* Only platform section emission is replaced, then a sidecar roots it. */
#define STELA_REG_PARAM_I(prefix, name, ops, arg, perm, level, flags, seq) \
static_assert(sizeof("" prefix) - 1 <= __MODULE_NAME_LEN); \
static const char __param_str_##name[] = prefix #name; \
static struct kernel_param __moduleparam_const __param_##name \
__used __aligned(__alignof__(struct kernel_param)) = { \
__param_str_##name, THIS_MODULE, ops, VERIFY_OCTAL_PERMISSIONS(perm), \
level, flags, { arg } }; \
const struct stela_linux_parameter_record STELA_REG_NAME(p, seq) __used = { \
STELA_REG_HEADER(STELA_LINUX_REG_PARAMETER, level, 0, seq), STELA_REG_CONTEXT, \
__param_str_##name, &__param_##name }
#define STELA_REG_PARAM(prefix, name, ops, arg, perm, level, flags, seq) \
STELA_REG_PARAM_I(prefix, name, ops, arg, perm, level, flags, seq)
#undef __module_param_call
#define __module_param_call(prefix, name, ops, arg, perm, level, flags) \
STELA_REG_PARAM(prefix, name, ops, arg, perm, level, flags, __COUNTER__)
/* The setup target may genuinely be NULL for an obsolete option. */
#define STELA_REG_SETUP_KIND_0 STELA_LINUX_REG_SETUP
#define STELA_REG_SETUP_KIND_1 STELA_LINUX_REG_EARLY
#define STELA_REG_SETUP_CODE_0 s
#define STELA_REG_SETUP_CODE_1 a
#define STELA_REG_SETUP_I(str, fn, early, seq) \
const struct stela_linux_setup_record \
STELA_REG_NAME(STELA_REG_SETUP_CODE_##early, seq) __used = { \
STELA_REG_HEADER(STELA_REG_SETUP_KIND_##early, -1, 0, seq), \
STELA_REG_CONTEXT, str, fn }
#define STELA_REG_SETUP(str, fn, early, seq) STELA_REG_SETUP_I(str, fn, early, seq)
#undef __setup_param
#define __setup_param(str, unique_id, fn, early) \
STELA_REG_SETUP(str, fn, early, __COUNTER__)
#define STELA_REG_INFO_I(tag, info, seq) \
static_assert(sizeof(info) - 1 == __builtin_strlen(info), \
"MODULE_INFO(" #tag ", ...) contains embedded NUL byte"); \
static const char STELA_REG_TEXT(seq)[] __used __aligned(1) = \
__MODULE_INFO_PREFIX __stringify(tag) "=" info; \
const struct stela_linux_info_record STELA_REG_NAME(f, seq) __used = { \
STELA_REG_HEADER(STELA_LINUX_REG_INFO, -1, 0, seq), STELA_REG_CONTEXT, \
__stringify(tag), STELA_REG_TEXT(seq) }
#define STELA_REG_INFO(tag, info, seq) STELA_REG_INFO_I(tag, info, seq)
#undef MODULE_INFO
#define MODULE_INFO(tag, info) STELA_REG_INFO(tag, info, __COUNTER__)
/* Original declaration's type and address are compiler-checked here. This
* metadata does not register a driver or manufacture any matching IDs. */
#define STELA_REG_DEVICE_I(type, name, seq) \
const struct stela_linux_device_record STELA_REG_NAME(d, seq) __used = { \
STELA_REG_HEADER(STELA_LINUX_REG_DEVICE, -1, 0, seq), STELA_REG_CONTEXT, \
__stringify(type), &(name), sizeof(name) }
#define STELA_REG_DEVICE(type, name, seq) STELA_REG_DEVICE_I(type, name, seq)
#undef MODULE_DEVICE_TABLE
#define MODULE_DEVICE_TABLE(type, name) STELA_REG_DEVICE(type, name, __COUNTER__)
#endif
@@ -0,0 +1,177 @@
/* SPDX-License-Identifier: MIT */
#ifndef STELA_LINUX_REGISTRY_H
#define STELA_LINUX_REGISTRY_H
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/stddef.h>
/* Ordinary target C ABI, LP64 x86-64 only. Immutable descriptors/code/strings
* must remain pinned for the image lifetime. A public C pointer is not an
* untrusted serialized input; the producer proves complete readable objects. */
#define STELA_LINUX_REGISTRY_ABI 1U
#define STELA_LINUX_REG_SYNC 1U
#define STELA_LINUX_REG_EARLY_LEVEL (-2)
#define STELA_LINUX_REG_ROOTFS_LEVEL (-3)
#define STELA_LINUX_REG_CONSOLE_LEVEL (-4)
enum stela_linux_registration_kind {
STELA_LINUX_REG_INIT = 1, STELA_LINUX_REG_MODULE_INIT,
STELA_LINUX_REG_EXIT, STELA_LINUX_REG_MODULE_EXIT,
STELA_LINUX_REG_PARAMETER, STELA_LINUX_REG_SETUP, STELA_LINUX_REG_EARLY,
STELA_LINUX_REG_INFO, STELA_LINUX_REG_DEVICE, STELA_LINUX_REG_CONSOLE,
};
struct stela_linux_build_group {
u32 abi_version, domain_ordinal, group_ordinal, reserved;
const char *module_name, *module_file, *provenance;
};
struct stela_linux_build_unit {
u32 abi_version, ordinal;
const struct stela_linux_build_group *group;
const char *source_path, *provenance;
};
struct stela_linux_registration_header {
u32 abi_version;
u16 kind;
s8 level;
u8 flags;
u32 unit_ordinal, emission_sequence;
};
#define STELA_LINUX_RECORD_FIELDS \
struct stela_linux_registration_header header; \
const struct stela_linux_build_group *group; \
const struct stela_linux_build_unit *unit
struct stela_linux_init_record {
STELA_LINUX_RECORD_FIELDS;
const char *label;
initcall_t target;
};
struct stela_linux_exit_record {
STELA_LINUX_RECORD_FIELDS;
const char *label;
exitcall_t target;
};
struct stela_linux_parameter_record {
STELA_LINUX_RECORD_FIELDS;
const char *label;
const struct kernel_param *target;
};
struct stela_linux_setup_record {
STELA_LINUX_RECORD_FIELDS;
const char *label;
int (*target)(char *);
};
struct stela_linux_info_record {
STELA_LINUX_RECORD_FIELDS;
const char *tag, *text;
};
struct stela_linux_device_record {
STELA_LINUX_RECORD_FIELDS;
const char *type;
const void *table;
size_t size;
};
#undef STELA_LINUX_RECORD_FIELDS
/* Arrays retain reviewed selected-TU/link order then emission sequence, never
* filesystem order. The group/unit arrays cover ALL selected objects including
* those without registration records. The normal root extracts record owners;
* separate ALL-object linkage is still a mandatory qualification. */
struct stela_linux_registry_image {
u32 abi_version, reserved;
const struct stela_linux_init_record *const *inits;
size_t init_count;
const struct stela_linux_exit_record *const *exits;
size_t exit_count;
const struct stela_linux_parameter_record *const *parameters;
size_t parameter_count;
const struct stela_linux_info_record *const *infos;
size_t info_count;
const struct stela_linux_device_record *const *devices;
size_t device_count;
const struct stela_linux_setup_record *const *setups;
size_t setup_count;
const struct stela_linux_build_group *const *groups;
size_t group_count;
const struct stela_linux_build_unit *const *units;
size_t unit_count;
};
enum stela_linux_registry_stage {
STELA_LINUX_STAGE_CONSOLE, STELA_LINUX_STAGE_EARLY,
STELA_LINUX_STAGE_PURE, STELA_LINUX_STAGE_CORE, STELA_LINUX_STAGE_POSTCORE,
STELA_LINUX_STAGE_ARCH, STELA_LINUX_STAGE_SUBSYS, STELA_LINUX_STAGE_FS,
STELA_LINUX_STAGE_DEVICE, STELA_LINUX_STAGE_LATE, STELA_LINUX_STAGE_DONE,
};
enum stela_linux_registration_state {
STELA_LINUX_RECORD_NOT_RUN, STELA_LINUX_RECORD_RUNNING,
STELA_LINUX_RECORD_ZERO, STELA_LINUX_RECORD_POSITIVE,
STELA_LINUX_RECORD_NEGATIVE,
};
struct stela_linux_registration_status {
u32 state, kind, unit_ordinal, emission_sequence;
s32 returned;
s32 level;
u64 invocations, warnings, consumed;
};
struct stela_linux_registry_report {
u64 invocations, returned_zero, returned_positive, returned_negative;
u64 warnings, consumed, unhandled;
s32 last_error;
u32 next_stage, terminal;
};
struct stela_linux_registry_unknown_options {
int (*unhandled_option)(void *context, char *complete_option);
void *context;
};
struct stela_linux_registry_retirement {
/* Exact complete image/group membership, not a single device idle query.
* The callback actually stops/drains all consumers; no production authority
* is created by this API. Borrowed only until this call returns. */
const struct stela_linux_registry_image *image;
const struct stela_linux_build_group *const *groups;
size_t group_count;
int (*drain_all_consumers)(void *context);
void *context;
};
struct stela_linux_registry;
/* Original next_arg uses unsigned token indices: length <= UINT_MAX; larger
* inputs fail E2BIG before reading token bytes or invoking any callback. */
int stela_linux_registry_begin(const struct stela_linux_registry_image *,
const char *bytes, size_t length, struct stela_linux_registry **out);
int stela_linux_registry_early_parameters(struct stela_linux_registry *,
struct stela_linux_registry_report *);
int stela_linux_registry_initial_parameters(struct stela_linux_registry *,
const struct stela_linux_registry_unknown_options *, struct stela_linux_registry_report *);
int stela_linux_registry_run_stage(struct stela_linux_registry *, unsigned int,
struct stela_linux_registry_report *);
/* Stable status index: init, exit, parameter, info, device, setup arrays. */
int stela_linux_registry_status(const struct stela_linux_registry *, size_t,
struct stela_linux_registration_status *);
/* Original NULL/tail/ERR_PTR result from an already-attempted pass0..9.
* A tail borrows the registry token storage until successful retirement. */
int stela_linux_registry_parse_result(const struct stela_linux_registry *, unsigned int, char **);
int stela_linux_registry_retire(struct stela_linux_registry **,
const struct stela_linux_registry_retirement *);
static_assert(sizeof(void *) == 8 && sizeof(size_t) == 8 && sizeof(long) == 8 && sizeof(int) == 4);
static_assert(sizeof(initcall_t) == 8 && sizeof(exitcall_t) == 8);
static_assert(sizeof(struct stela_linux_registration_header) == 16);
static_assert(offsetof(struct stela_linux_registration_header, level) == 6);
static_assert(offsetof(struct stela_linux_registration_header, unit_ordinal) == 8);
#define STELA_LINUX_RECORD_LAYOUT(type, last, bytes) \
static_assert(offsetof(struct type, group) == 16); \
static_assert(offsetof(struct type, unit) == 24); \
static_assert(offsetof(struct type, last) == 40); \
static_assert(sizeof(struct type) == bytes && __alignof__(struct type) == 8)
STELA_LINUX_RECORD_LAYOUT(stela_linux_init_record, target, 48);
STELA_LINUX_RECORD_LAYOUT(stela_linux_exit_record, target, 48);
STELA_LINUX_RECORD_LAYOUT(stela_linux_parameter_record, target, 48);
STELA_LINUX_RECORD_LAYOUT(stela_linux_setup_record, target, 48);
STELA_LINUX_RECORD_LAYOUT(stela_linux_info_record, text, 48);
STELA_LINUX_RECORD_LAYOUT(stela_linux_device_record, table, 56);
#undef STELA_LINUX_RECORD_LAYOUT
static_assert(sizeof(struct stela_linux_build_group) == 40);
static_assert(sizeof(struct stela_linux_build_unit) == 32);
static_assert(sizeof(struct stela_linux_registry_image) == 136);
static_assert(sizeof(struct stela_linux_registration_status) == 48);
static_assert(sizeof(struct stela_linux_registry_report) == 72);
#endif
@@ -0,0 +1,5 @@
/* SPDX-License-Identifier: MIT */
#include "fixture.h"
#include <stela/registration.h>
/* Selected no-registration source must still appear in unit/group inventory. */
int stela_registry_fixture_empty(void) { return 17; }
@@ -0,0 +1,55 @@
/* SPDX-License-Identifier: MIT */
#include "fixture.h"
#include <linux/pci_ids.h>
#include <linux/pci.h>
#include <linux/mod_devicetable.h>
#include <stela/registration.h>
/* Both TUs intentionally use the same static callback and parameter spellings. */
static int duplicate(void) { stela_registry_fixture_event(10); return 0; }
static void leave(void) { stela_registry_fixture_event(11); }
static int count;
static char *borrowed;
static int setup(char *value) { borrowed = value; stela_registry_fixture_event(12); return 1; }
static int early(char *value) { borrowed = value; stela_registry_fixture_event(13); return 0; }
static const struct pci_device_id ids[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_NVIDIA, 0x1f02) }, { }
};
module_param(count, int, 0644);
MODULE_PARM_DESC(count, "first occurrence");
module_param(borrowed, charp, 0);
__setup("fixture=", setup);
early_param("fixture_early", early);
MODULE_DEVICE_TABLE(pci, ids);
MODULE_INFO(alias, "fixture:first");
MODULE_LICENSE("GPL");
/* Same target at several phases is intentional; no private fn-name identity. */
early_initcall(duplicate);
pure_initcall(duplicate);
core_initcall(duplicate);
core_initcall_sync(duplicate);
postcore_initcall(duplicate);
postcore_initcall_sync(duplicate);
arch_initcall(duplicate);
arch_initcall_sync(duplicate);
subsys_initcall(duplicate);
subsys_initcall_sync(duplicate);
fs_initcall(duplicate);
fs_initcall_sync(duplicate);
rootfs_initcall(duplicate);
device_initcall(duplicate);
device_initcall_sync(duplicate);
late_initcall(duplicate);
late_initcall_sync(duplicate);
console_initcall(duplicate);
module_init(duplicate);
module_exit(leave);
const struct kernel_param *stela_fixture_first_count(void)
{
return &__param_count;
}
const struct kernel_param *stela_fixture_first_borrowed(void)
{
return &__param_borrowed;
}
@@ -0,0 +1,13 @@
/* SPDX-License-Identifier: MIT */
#ifndef STELA_REGISTRY_FIXTURE_H
#define STELA_REGISTRY_FIXTURE_H
#include <linux/module.h>
#include <stela/registry.h>
/* Authored controlled fixture effects; never substitutes for driver services. */
void stela_registry_fixture_event(unsigned int value);
extern const struct stela_linux_registry_image stela_linux_fixture_image;
const struct kernel_param *stela_fixture_first_count(void);
const struct kernel_param *stela_fixture_first_borrowed(void);
const struct kernel_param *stela_fixture_second_count(void);
const struct kernel_param *stela_fixture_third_count(void);
#endif
@@ -0,0 +1,69 @@
/* SPDX-License-Identifier: MIT */
#include "fixture.h"
#include <linux/string.h>
#include <linux/mod_devicetable.h>
#include <stela/test.h>
#include <stela/linux.h>
static unsigned int events[64], event_count;
void stela_registry_fixture_event(unsigned int value)
{
assert(event_count < ARRAY_SIZE(events));
events[event_count++] = value;
}
/* Link this with the ACTUAL generated fixture manifest and four original-
* macro fixture objects. It inspects/executes exact retained targets, without
* claiming registry phase/lifetime or hardware qualification. */
int main(void)
{
const struct stela_linux_registry_image *image = &stela_linux_fixture_image;
const struct stela_linux_init_record *module = NULL;
const struct stela_linux_build_unit *first = NULL, *second = NULL;
unsigned int normal = 0, sync = 0, early = 0, rootfs = 0, console = 0;
unsigned int modules = 0, obsolete = 0;
size_t i;
assert(image->abi_version == STELA_LINUX_REGISTRY_ABI);
assert(image->unit_count == 4 && image->group_count == 2);
assert(image->parameter_count == 4 && image->setup_count == 5);
assert(image->device_count == 1 && image->exit_count == 4);
assert(image->info_count == 10);
assert(image->init_count == 23);
assert(!strcmp(image->groups[0]->module_name, "nouveau"));
assert(!strcmp(image->groups[1]->module_name, "ch7006"));
first = image->units[0]; second = image->units[1];
assert(first != second && first->group == second->group);
assert(image->units[2]->group != first->group);
assert(image->parameters[0]->target == stela_fixture_first_count());
assert(image->parameters[1]->target == stela_fixture_first_borrowed());
assert(image->parameters[2]->target == stela_fixture_second_count());
assert(image->parameters[3]->target == stela_fixture_third_count());
assert(image->parameters[0]->target != image->parameters[2]->target);
assert(!strcmp(image->parameters[0]->target->name, "nouveau.count"));
assert(!strcmp(image->parameters[2]->target->name, "nouveau.count"));
for (i = 0; i < image->init_count; i++) {
const struct stela_linux_init_record *record = image->inits[i];
assert(record->header.unit_ordinal == record->unit->ordinal);
if (i && record->unit == image->inits[i - 1]->unit)
assert(record->header.emission_sequence > image->inits[i - 1]->header.emission_sequence);
if (record->header.kind == STELA_LINUX_REG_MODULE_INIT) {
modules++; if (!module) module = record; continue;
}
if (record->header.level == STELA_LINUX_REG_EARLY_LEVEL) early++;
else if (record->header.level == STELA_LINUX_REG_ROOTFS_LEVEL) rootfs++;
else if (record->header.kind == STELA_LINUX_REG_CONSOLE) console++;
else if (record->header.flags & STELA_LINUX_REG_SYNC) sync++;
else normal++;
}
assert(modules == 2 && early == 1 && rootfs == 1 && console == 1);
assert(normal == 10 && sync == 8);
for (i = 0; i < image->setup_count; i++) {
const struct stela_linux_setup_record *record = image->setups[i];
if (!record->target) { assert(!strcmp(record->label, "obsolete")); obsolete++; }
}
assert(obsolete == 1);
stela_linux_enter(&stela_linux_bare);
assert(module && module->target() == 0);
stela_linux_exit();
assert(event_count == 1 && events[0] == 10);
assert(image->devices[0]->size == 2 * sizeof(struct pci_device_id));
return 0;
}
@@ -0,0 +1,42 @@
/* SPDX-License-Identifier: MIT */
/* Each negative mode is compiled into a GENUINE ordinary object separately.
* Do not synthesize or patch binary object bytes. It is deliberately invalid
* registry input; no negative definition is linked into production. */
#if defined(FIXTURE_NOANCHOR)
#include <stela/registry.h>
int fixture_has_no_capture_header;
#else
#include <stela/registration.h>
#endif
#if defined(FIXTURE_NOANCHOR)
/* No record and no capture anchor: must fail rather than silently omit TU. */
#elif defined(FIXTURE_EMBEDDED_NUL)
MODULE_INFO(description, "visible\0hidden");
#elif defined(FIXTURE_BAD_INIT_TYPE)
static void wrong_init(void) { }
module_init(wrong_init);
#elif defined(FIXTURE_BAD_EXIT_TYPE)
static int wrong_exit(void) { return 0; }
module_exit(wrong_exit);
#elif defined(FIXTURE_BAD_SETUP_TYPE)
static int wrong_setup(const char *value) { (void)value; return 1; }
__setup("wrong=", wrong_setup);
#elif defined(FIXTURE_UNDEFINED)
extern const struct stela_linux_init_record stela_linux_reg__Fixture__Bad__i__0;
const void *fixture_reference = &stela_linux_reg__Fixture__Bad__i__0;
#elif defined(FIXTURE_COMMON)
/* Compile with -fcommon so the actual symbol table reports common data. */
struct stela_linux_init_record stela_linux_reg__Fixture__Bad__i__0;
#elif defined(FIXTURE_WEAK)
const struct stela_linux_init_record stela_linux_reg__Fixture__Bad__i__0
__attribute__((weak)) = { };
#elif defined(FIXTURE_MALFORMED)
const struct stela_linux_init_record stela_linux_reg__Fixture__Bad__unknown__0 = { };
#elif defined(FIXTURE_LOCAL)
static const struct stela_linux_init_record stela_linux_reg__Fixture__Bad__i__0
__attribute__((used)) = { };
#elif defined(FIXTURE_PREFIX)
const struct stela_linux_init_record stela_linux_reg__Fixture__Bad__i__0 = { };
#else
#error "Select one exact negative fixture mode"
#endif
@@ -0,0 +1,58 @@
/* SPDX-License-Identifier: MIT */
#include <linux/module.h>
#include <linux/string.h>
#include <stela/registration.h>
/* Separate authored image: genuine original wrappers and private descriptors,
* without changing the base 47-record capture fixture. */
static int plain, core_danger, count, danger, irq;
static bool enabled;
static char label[32];
static int custom_value;
static unsigned int custom_calls;
static const struct kernel_param *last_custom;
static int fixture_set(const char *value, const struct kernel_param *parameter)
{
last_custom = parameter;
custom_calls++;
return param_set_int(value, parameter);
}
static const struct kernel_param_ops fixture_ops = {
.set = fixture_set, .get = param_get_int,
};
core_param(core_plain, plain, int, 0600);
core_param_unsafe(core_danger, core_danger, int, 0);
module_param(enabled, bool, 0);
module_param_named(count_alias, count, int, 0644);
module_param_unsafe(danger, int, 0);
module_param_hw_named(irq_line, irq, int, irq, 0444);
module_param_string(label, label, sizeof(label), 0);
__core_param_cb(core_custom, &fixture_ops, &custom_value, 0);
module_param_cb(callback, &fixture_ops, &custom_value, 0);
module_param_cb_unsafe(danger_callback, &fixture_ops, &custom_value, 0);
core_param_cb(level_core, &fixture_ops, &custom_value, 0);
postcore_param_cb(level_postcore, &fixture_ops, &custom_value, 0);
arch_param_cb(level_arch, &fixture_ops, &custom_value, 0);
subsys_param_cb(level_subsys, &fixture_ops, &custom_value, 0);
fs_param_cb(level_fs, &fixture_ops, &custom_value, 0);
device_param_cb(level_device, &fixture_ops, &custom_value, 0);
late_param_cb(level_late, &fixture_ops, &custom_value, 0);
size_t stela_fixture_parameter_originals(const struct kernel_param *const **out)
{
static const struct kernel_param *const originals[] = {
&__param_core_plain, &__param_core_danger, &__param_enabled,
&__param_count_alias, &__param_danger, &__param_irq_line, &__param_label,
&__param_core_custom, &__param_callback, &__param_danger_callback,
&__param_level_core, &__param_level_postcore, &__param_level_arch,
&__param_level_subsys, &__param_level_fs, &__param_level_device,
&__param_level_late,
};
*out = originals;
return ARRAY_SIZE(originals);
}
bool stela_fixture_parameter_values_match(void)
{
return plain == 11 && core_danger == 12 && enabled && count == 13 &&
danger == 14 && irq == 15 && !strcmp(label, "fixture retained") &&
custom_value == 37 && custom_calls == 10 && last_custom == &__param_level_late;
}
@@ -0,0 +1,49 @@
/* SPDX-License-Identifier: MIT */
#include <linux/panic.h>
#include <stela/linux.h>
#include <stela/registry.h>
#include <stela/test.h>
extern const struct stela_linux_registry_image stela_linux_parameters_fixture_image;
size_t stela_fixture_parameter_originals(const struct kernel_param *const **out);
bool stela_fixture_parameter_values_match(void);
int main(void)
{
const struct stela_linux_registry_image *image = &stela_linux_parameters_fixture_image;
const struct kernel_param *const *originals;
struct stela_linux_registry *registry = NULL;
struct stela_linux_registry_report report;
const char arguments[] =
"core_plain=11 core_danger=12 fixture_params.enabled "
"fixture_params.count_alias=13 fixture_params.danger=14 fixture_params.irq_line=15 "
"fixture_params.label=\"fixture retained\" core_custom=20 fixture_params.callback=21 "
"fixture_params.danger_callback=22 fixture_params.level_core=31 "
"fixture_params.level_postcore=32 fixture_params.level_arch=33 "
"fixture_params.level_subsys=34 fixture_params.level_fs=35 "
"fixture_params.level_device=36 fixture_params.level_late=37";
assert(image->parameter_count == 17 && image->info_count == 5);
assert(image->init_count == 0 && image->setup_count == 0);
assert(stela_fixture_parameter_originals(&originals) == image->parameter_count);
for (size_t i = 0; i < image->parameter_count; i++) {
const struct stela_linux_parameter_record *record = image->parameters[i];
assert(record->target == originals[i]);
assert(record->header.level == originals[i]->level);
}
assert(originals[1]->flags == KERNEL_PARAM_FL_UNSAFE);
assert(originals[2]->ops->flags & KERNEL_PARAM_OPS_FL_NOARG);
assert(originals[4]->flags == KERNEL_PARAM_FL_UNSAFE);
assert(originals[5]->flags == KERNEL_PARAM_FL_HWPARAM);
assert(originals[9]->flags == KERNEL_PARAM_FL_UNSAFE);
for (size_t i = 10; i < 17; i++)
assert(originals[i]->level == (s8)(i - 9));
stela_linux_enter(&stela_linux_bare);
assert(stela_linux_registry_begin(image, arguments, sizeof(arguments) - 1, &registry) == 0);
assert(stela_linux_registry_early_parameters(registry, &report) == 0);
assert(stela_linux_registry_initial_parameters(registry, NULL, &report) == 0);
for (unsigned int stage = STELA_LINUX_STAGE_CONSOLE; stage < STELA_LINUX_STAGE_DONE; stage++)
assert(stela_linux_registry_run_stage(registry, stage, &report) == 0);
assert(stela_fixture_parameter_values_match());
assert(get_taint() & (1UL << TAINT_USER));
stela_linux_exit();
/* No fabricated whole-domain retirement authority or reset between boots. */
return 0;
}
@@ -0,0 +1,23 @@
/* SPDX-License-Identifier: MIT */
#include "fixture.h"
#include <stela/registration.h>
static int duplicate(void) { stela_registry_fixture_event(20); return 0; }
static void leave(void) { stela_registry_fixture_event(21); }
static int count;
static int setup(char *value) { (void)value; stela_registry_fixture_event(22); return -1; }
static int early(char *value) { (void)value; stela_registry_fixture_event(23); return -22; }
module_param(count, int, 0644);
__setup("fixture=", setup);
early_param("fixture-early", early);
/* Explicit unique-id obsolete handler must remain a real NULL setup target. */
__setup_param("obsolete", obsolete_fixture, NULL, 0);
core_initcall_sync(duplicate);
core_initcall(duplicate);
device_initcall(duplicate);
__exitcall(leave);
MODULE_INFO(description, "second TU, same real Kbuild group as first");
const struct kernel_param *stela_fixture_second_count(void)
{
return &__param_count;
}
@@ -0,0 +1,17 @@
/* SPDX-License-Identifier: MIT */
#include "fixture.h"
#include <stela/registration.h>
static int duplicate(void) { stela_registry_fixture_event(30); return -5; }
static void leave(void) { stela_registry_fixture_event(31); }
static int count;
module_param(count, int, 0);
module_init(duplicate);
module_exit(leave);
/* A generic exit is metadata, never guessed as an init inverse. */
__exitcall(leave);
MODULE_INFO(description, "independent real Kbuild group");
const struct kernel_param *stela_fixture_third_count(void)
{
return &__param_count;
}
@@ -0,0 +1,6 @@
/* SPDX-License-Identifier: MIT */
#include <stela/registration.h>
#ifndef STELA_LINUX_VIDEO_CMDLINE_SOURCE
#error "exact retained original drivers/video/cmdline.c source required"
#endif
#include STELA_LINUX_VIDEO_CMDLINE_SOURCE
@@ -0,0 +1,60 @@
/* SPDX-License-Identifier: MIT */
#include <linux/err.h>
#include <linux/string.h>
#include <stela/linux.h>
#include <stela/registry.h>
#include <stela/test.h>
#include <video/cmdline.h>
#include <video/nomodeset.h>
extern const struct stela_linux_registry_image stela_linux_video_fixture_image;
static unsigned int nomodeset_warnings;
static void log_message(void *context, int level, const char *message)
{
(void)context; (void)level;
if (strstr(message, "Booted with the nomodeset parameter."))
nomodeset_warnings++;
}
static const struct stela_linux_services services = { .log = log_message };
static const struct stela_linux_owner owner = { .services = &services };
/* Separate executable/process: original static video globals and the registry
* singleton are intentionally never reset to fake another boot. The registry
* retains storage because real video_setup keeps borrowed option pointers. */
int main(void)
{
char input[] = "nomodeset-suffix video=1024x768 video=HDMI-A-1:1920x1080 video=DP-1:off video=HDMI-A-1:2560x1440";
struct stela_linux_registry *registry = NULL;
struct stela_linux_registry_report report;
char *tail = (void *)1;
const char *global, *named, *disabled;
const struct stela_linux_registry_image *image = &stela_linux_video_fixture_image;
assert(image->setup_count == 2 && image->parameter_count == 0);
assert(image->init_count == 0 && image->exit_count == 0);
stela_linux_enter(&owner);
assert(!video_firmware_drivers_only());
assert(video_get_options(NULL) == NULL);
assert(stela_linux_registry_begin(image, input, sizeof(input) - 1, &registry) == 0);
/* Mutate borrowed caller input BEFORE parsing: registry must use its own copy. */
memset(input, 'X', sizeof(input) - 1);
assert(stela_linux_registry_early_parameters(registry, &report) == 0);
assert(stela_linux_registry_initial_parameters(registry, NULL, &report) == 0);
assert(stela_linux_registry_parse_result(registry, 1, &tail) == 0 && tail == NULL);
assert(video_firmware_drivers_only());
assert(nomodeset_warnings == 1);
global = video_get_options(NULL);
named = video_get_options("HDMI-A-1");
disabled = video_get_options("DP-1");
assert(global && !strcmp(global, "1024x768"));
assert(named && !strcmp(named, "2560x1440"));
assert(disabled && !strcmp(disabled, "off"));
assert(video_get_options("unconfigured") == global);
stela_linux_exit();
/* Original setup consumers outlive the borrowed execution owner. */
stela_linux_enter(&stela_linux_bare);
assert(video_firmware_drivers_only());
assert(video_get_options(NULL) == global && !strcmp(global, "1024x768"));
assert(video_get_options("HDMI-A-1") == named && !strcmp(named, "2560x1440"));
assert(video_get_options("DP-1") == disabled && !strcmp(disabled, "off"));
/* No whole-domain drain authority: keep genuine borrowed pointers pinned. */
stela_linux_exit();
return 0;
}
@@ -0,0 +1,7 @@
/* SPDX-License-Identifier: MIT */
/* Explicit source-path macro is the exact retained ORIGINAL input. */
#include <stela/registration.h>
#ifndef STELA_LINUX_VIDEO_NOMODESET_SOURCE
#error "exact retained original drivers/video/nomodeset.c source required"
#endif
#include STELA_LINUX_VIDEO_NOMODESET_SOURCE
@@ -0,0 +1,77 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/* Exact retained Linux init/main.c setup/repair/early bodies. Copyright (C)
* 1991, 1992 Linus Torvalds. Macro names adapt only the isolated fixture's
* table, function identity and diagnostic collection, never their semantics. */
#pragma GCC diagnostic push
/* Original source uses int strlen result; retain its bytes as the oracle. */
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#define obsolete_checksetup reference_obsolete_checksetup
#define repair_env_string reference_repair_env_string
#define do_early_param reference_do_early_param
#define __setup_start reference_setup_start
#define __setup_end reference_setup_end
static bool __init obsolete_checksetup(char *line)
{
const struct obs_kernel_param *p;
bool had_early_param = false;
p = __setup_start;
do {
int n = strlen(p->str);
if (parameqn(line, p->str, n)) {
if (p->early) {
/* Already done in parse_early_param?
* (Needs exact match on param part).
* Keep iterating, as we can have early
* params and __setups of same names 8( */
if (line[n] == '\0' || line[n] == '=')
had_early_param = true;
} else if (!p->setup_func) {
pr_warn("Parameter %s is obsolete, ignored\n",
p->str);
return true;
} else if (p->setup_func(line + n))
return true;
}
p++;
} while (p < __setup_end);
return had_early_param;
}
static void __init repair_env_string(char *param, char *val)
{
if (val) {
/* param=val or param="val"? */
if (val == param+strlen(param)+1)
val[-1] = '=';
else if (val == param+strlen(param)+2) {
val[-2] = '=';
memmove(val-1, val, strlen(val)+1);
} else
BUG();
}
}
static int __init do_early_param(char *param, char *val,
const char *unused, void *arg)
{
const struct obs_kernel_param *p;
for (p = __setup_start; p < __setup_end; p++) {
if (p->early && parameq(param, p->str)) {
if (p->setup_func(val) != 0)
pr_warn("Malformed early option '%s'\n", param);
}
}
/* We accept everything at this stage. */
return 0;
}
#undef obsolete_checksetup
#undef repair_env_string
#undef do_early_param
#undef __setup_start
#undef __setup_end
#pragma GCC diagnostic pop
@@ -0,0 +1,94 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/* Included only by the registry fixture. Exact original setup/early bodies
* below are an oracle separate from the candidate registry adapters. */
static const struct obs_kernel_param *reference_setup_start, *reference_setup_end;
#include <stela/registry_setup_reference.h>
struct setup_effect {
unsigned calls, logs;
int id[48], levels[48];
char values[48][96], messages[48][160];
};
static struct setup_effect *effect;
static int setup_record(unsigned id, char *value, int ret)
{
unsigned n=effect->calls++;
assert(n<ARRAY_SIZE(effect->id)); effect->id[n]=id;
const char *text=value ?: "<NULL>";
assert(strlen(text)<sizeof(effect->values[n])); strcpy(effect->values[n],text);
return ret;
}
static int setup_a(char *v) { return setup_record(1,v,-EINVAL); }
static int setup_b(char *v) { return setup_record(2,v,0); }
static int setup_bare(char *v) { return setup_record(3,v,0); }
static int setup_zero(char *v) { return setup_record(4,v,0); }
static int setup_consumed(char *v) { return setup_record(5,v,-EIO); }
static int setup_prefix(char *v) { return setup_record(6,v,1); }
static int setup_console(char *v) { return setup_record(7,v,0); }
static void setup_log(void *context,int level,const char *message)
{
(void)context;
unsigned n=effect->logs++;
assert(n<ARRAY_SIZE(effect->messages) && strlen(message)<sizeof(effect->messages[n]));
effect->levels[n]=level; strcpy(effect->messages[n],message);
}
static int original_unknown(char *param,char *val,const char *doing,void *context)
{
(void)doing; (void)context;
reference_repair_env_string(param,val);
return reference_obsolete_checksetup(param) ? 0 : -ENOENT;
}
static const char *const setup_differential_inputs[] = {
"", "same-name=abc", "same_name=\"two words\"", "bare", "bare=1",
"bareSuffix", "prefixSuffix", "obsoleteSuffix", "unknown=\"quoted value\"",
"same-name=abc same-name=abc", "console=ttyS0", "earlycon=x", "-- tail untouched",
"same-name=abc unknown -- tail", "\"same-name=two words\" bare", "obsolete bare same_name=",
};
static unsigned setup_differential_index;
static void setup_differential_case(void)
{
const struct stela_linux_services services={.log=setup_log};
const struct stela_linux_owner owner={.services=&services};
stela_linux_enter(&owner);
struct registry_fixture f; fixture_init(&f);
fixture_setup(&f,0,true,"same_name",setup_a);
fixture_setup(&f,0,true,"same_name",setup_b);
fixture_setup(&f,0,true,"bare",setup_bare);
fixture_setup(&f,0,false,"same_name=",setup_zero);
fixture_setup(&f,0,false,"same_name=",setup_consumed);
fixture_setup(&f,0,false,"prefix",setup_prefix);
fixture_setup(&f,0,false,"obsolete",NULL);
fixture_setup(&f,0,true,"earlycon",setup_console);
const char *input=setup_differential_inputs[setup_differential_index];
size_t length=strlen(input);
assert(length<256);
struct setup_effect actual={}, expected={};
effect=&actual;
begin_fixture(&f,input);
assert(!stela_linux_registry_early_parameters(test_registry,NULL));
int actual_error=stela_linux_registry_initial_parameters(test_registry,NULL,NULL);
char *actual_tail=NULL;
assert(!stela_linux_registry_parse_result(test_registry,1,&actual_tail));
struct obs_kernel_param table[8];
for(unsigned i=0;i<ARRAY_SIZE(table);++i)
table[i]=(struct obs_kernel_param){.str=f.setup[i].label,.setup_func=f.setup[i].target,
.early=f.setup[i].header.kind==STELA_LINUX_REG_EARLY};
reference_setup_start=table; reference_setup_end=table+ARRAY_SIZE(table);
unsigned char early[256], initial[256];
memset(early,0xa7,sizeof(early)); memset(initial,0xa7,sizeof(initial));
memcpy(early,input,length+1); memcpy(initial,input,length+1);
effect=&expected;
char *early_result=parse_args("early options",(char *)early,NULL,0,0,0,NULL,reference_do_early_param);
assert(!IS_ERR(early_result));
char *expected_tail=parse_args("Booting kernel",(char *)initial,NULL,0,-1,-1,NULL,original_unknown);
int expected_error=IS_ERR(expected_tail) ? (int)PTR_ERR(expected_tail) : 0;
assert(actual_error==expected_error);
assert(!memcmp(&actual,&expected,sizeof(actual)));
assert(!memcmp(test_registry->arguments,early,length+1));
assert(!memcmp(test_registry->arguments+test_registry->stride,initial,length+1));
if(IS_ERR(expected_tail)) assert(PTR_ERR(actual_tail)==PTR_ERR(expected_tail));
else if(expected_tail) {
assert(actual_tail && actual_tail-(test_registry->arguments+test_registry->stride)==expected_tail-(char *)initial);
assert(!strcmp(actual_tail,expected_tail));
} else assert(!actual_tail);
stela_linux_exit();
}
@@ -0,0 +1,16 @@
/* SPDX-License-Identifier: MIT */
/* Hosted-only process isolation: permanent production singleton state is never
* reset to run a second scenario. A signal/abnormal exit is a fixture failure. */
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
int stela_test_registry_case(void (*run)(void))
{
pid_t child = fork();
if (child < 0) return 0;
if (!child) { run(); _exit(0); }
int status;
while (waitpid(child,&status,0) < 0) if (errno != EINTR) return 0;
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
@@ -0,0 +1,189 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/* Exact retained kernel/panic.c source projections; only identifiers are
* lexically renamed below. The bounded test-only seq-buffer adapters are
* explicitly separate. No allocator, full panic, sysctl or parser reference
* is implied by these selected source bodies. */
#define tainted_mask reference_mask
#define taint_flags reference_flags
#define print_tainted_seq reference_print_seq
#define _print_tainted reference_print
#define print_tainted reference_print_tainted
#define print_tainted_verbose reference_print_verbose
#define test_taint reference_test_taint
#define get_taint reference_get_taint
#define add_taint reference_add_taint
#define panic_on_taint reference_panic_on_taint
#define panic_on_taint_nousertaint reference_nousertaint
#define panic_on_taint_setup reference_setup
#define __debug_locks_off reference_locks_off
#define panic stela_linux_fatal
#define seq_buf reference_seq_buf
#define seq_buf_puts reference_puts
#define seq_buf_printf reference_printf
#define seq_buf_putc reference_putc
#define seq_buf_init reference_seq_init
#define seq_buf_str reference_seq_str
#define taint_buf reference_buf
#define taint_buf_size reference_size
#define TAINT_FLAG(taint, _c_true, _c_false) \
[ TAINT_##taint ] = { \
.c_true = _c_true, .c_false = _c_false, \
.desc = #taint, \
}
/*
* NOTE: if you modify the taint_flags or TAINT_FLAGS_COUNT,
* please also modify tools/debugging/kernel-chktaint and
* Documentation/admin-guide/tainted-kernels.rst, including its
* small shell script that prints the TAINT_FLAGS_COUNT bits of
* /proc/sys/kernel/tainted.
*
* Also, update INIT_TAINT_BUF_MAX below.
*/
const struct taint_flag taint_flags[TAINT_FLAGS_COUNT] = {
TAINT_FLAG(PROPRIETARY_MODULE, 'P', 'G'),
TAINT_FLAG(FORCED_MODULE, 'F', ' '),
TAINT_FLAG(CPU_OUT_OF_SPEC, 'S', ' '),
TAINT_FLAG(FORCED_RMMOD, 'R', ' '),
TAINT_FLAG(MACHINE_CHECK, 'M', ' '),
TAINT_FLAG(BAD_PAGE, 'B', ' '),
TAINT_FLAG(USER, 'U', ' '),
TAINT_FLAG(DIE, 'D', ' '),
TAINT_FLAG(OVERRIDDEN_ACPI_TABLE, 'A', ' '),
TAINT_FLAG(WARN, 'W', ' '),
TAINT_FLAG(CRAP, 'C', ' '),
TAINT_FLAG(FIRMWARE_WORKAROUND, 'I', ' '),
TAINT_FLAG(OOT_MODULE, 'O', ' '),
TAINT_FLAG(UNSIGNED_MODULE, 'E', ' '),
TAINT_FLAG(SOFTLOCKUP, 'L', ' '),
TAINT_FLAG(LIVEPATCH, 'K', ' '),
TAINT_FLAG(AUX, 'X', ' '),
TAINT_FLAG(RANDSTRUCT, 'T', ' '),
TAINT_FLAG(TEST, 'N', ' '),
TAINT_FLAG(FWCTL, 'J', ' '),
};
#undef TAINT_FLAG
static void print_tainted_seq(struct seq_buf *s, bool verbose)
{
const char *sep = "";
int i;
if (!tainted_mask) {
seq_buf_puts(s, "Not tainted");
return;
}
seq_buf_printf(s, "Tainted: ");
for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
const struct taint_flag *t = &taint_flags[i];
bool is_set = test_bit(i, &tainted_mask);
char c = is_set ? t->c_true : t->c_false;
if (verbose) {
if (is_set) {
seq_buf_printf(s, "%s[%c]=%s", sep, c, t->desc);
sep = ", ";
}
} else {
seq_buf_putc(s, c);
}
}
}
static const char *_print_tainted(bool verbose)
{
struct seq_buf s;
BUILD_BUG_ON(ARRAY_SIZE(taint_flags) != TAINT_FLAGS_COUNT);
seq_buf_init(&s, taint_buf, taint_buf_size);
print_tainted_seq(&s, verbose);
return seq_buf_str(&s);
}
const char *print_tainted(void)
{
return _print_tainted(false);
}
const char *print_tainted_verbose(void)
{
return _print_tainted(true);
}
int test_taint(unsigned flag)
{
return test_bit(flag, &tainted_mask);
}
unsigned long get_taint(void)
{
return tainted_mask;
}
void add_taint(unsigned flag, enum lockdep_ok lockdep_ok)
{
if (lockdep_ok == LOCKDEP_NOW_UNRELIABLE && __debug_locks_off())
pr_warn("Disabling lock debugging due to kernel taint\n");
set_bit(flag, &tainted_mask);
if (tainted_mask & panic_on_taint) {
panic_on_taint = 0;
panic("panic_on_taint set ...");
}
}
static int __init panic_on_taint_setup(char *s)
{
char *taint_str;
if (!s)
return -EINVAL;
taint_str = strsep(&s, ",");
if (kstrtoul(taint_str, 16, &panic_on_taint))
return -EINVAL;
/* make sure panic_on_taint doesn't hold out-of-range TAINT flags */
panic_on_taint &= TAINT_FLAGS_MAX;
if (!panic_on_taint)
return -EINVAL;
if (s && !strcmp(s, "nousertaint"))
panic_on_taint_nousertaint = true;
pr_info("panic_on_taint: bitmask=0x%lx nousertaint_mode=%s\n",
panic_on_taint, str_enabled_disabled(panic_on_taint_nousertaint));
return 0;
}
#undef tainted_mask
#undef taint_flags
#undef print_tainted_seq
#undef _print_tainted
#undef print_tainted
#undef print_tainted_verbose
#undef test_taint
#undef get_taint
#undef add_taint
#undef panic_on_taint
#undef panic_on_taint_nousertaint
#undef panic_on_taint_setup
#undef __debug_locks_off
#undef panic
#undef seq_buf
#undef seq_buf_puts
#undef seq_buf_printf
#undef seq_buf_putc
#undef seq_buf_init
#undef seq_buf_str
#undef taint_buf
#undef taint_buf_size
@@ -0,0 +1,368 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/* Hosted inline fixtures. Direct state assignments below isolate cases only;
* the production service deliberately exports no reset or restart API. */
#include <linux/array_size.h>
#include <stela/test.h>
struct reference_seq_buf {
char *buffer;
size_t size, len;
};
static void reference_seq_init(struct reference_seq_buf *s, char *buffer, unsigned int size)
{
*s = (struct reference_seq_buf){.buffer = buffer, .size = size};
assert(size);
buffer[0] = '\0';
}
/* These adapters exercise exact original print_tainted_seq bodies over a
* bounded buffer. They are not substitutions for a production seq_buf API. */
static int reference_printf(struct reference_seq_buf *s, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
int n = vscnprintf(s->buffer + s->len, s->size - s->len, fmt, args);
va_end(args);
assert(n >= 0 && (size_t)n < s->size - s->len - 1);
s->len += (size_t)n;
return 0;
}
static int reference_puts(struct reference_seq_buf *s, const char *text)
{
return reference_printf(s, "%s", text);
}
static int reference_putc(struct reference_seq_buf *s, unsigned char c)
{
return reference_printf(s, "%c", c);
}
static const char *reference_seq_str(struct reference_seq_buf *s)
{
assert(s->len < s->size);
s->buffer[s->len] = '\0';
return s->buffer;
}
static unsigned long reference_mask =
IS_ENABLED(CONFIG_RANDSTRUCT) ? (1UL << TAINT_RANDSTRUCT) : 0;
static unsigned long reference_panic_on_taint;
static bool reference_nousertaint;
static int reference_debug_locks = 1;
static char reference_buf[350];
static size_t reference_size = sizeof(reference_buf);
static int reference_locks_off(void)
{
return __atomic_exchange_n(&reference_debug_locks, 0, __ATOMIC_SEQ_CST);
}
#include <stela/taint_reference.h>
struct taint_event {
int level;
char message[160];
};
static struct taint_event taint_events[16];
static unsigned int taint_event_count, taint_warnings;
static unsigned int taint_context_a, taint_context_b;
static bool expected_fatal_reference;
static unsigned long expected_fatal_mask;
static volatile int fatal_witness;
/* Separate hosted signal/fork helper verifies the real trap AND that the
* emergency callback saw the required state before it, and no code after it. */
int stela_taint_test_stops(void (*operation)(void), volatile int *witness, int expected);
static void taint_test_log(void *context, int level, const char *message)
{
assert(context == &taint_context_a || context == &taint_context_b);
if (level == LOGLEVEL_EMERG) {
assert(!strcmp(message, "panic_on_taint set ..."));
if (expected_fatal_reference) {
assert(reference_mask == expected_fatal_mask);
assert(reference_panic_on_taint == 0);
assert(reference_debug_locks == 0);
} else {
assert(get_taint() == expected_fatal_mask);
assert(panic_on_taint == 0);
assert(debug_locks == 0);
}
fatal_witness = 1;
return;
}
assert(taint_event_count < ARRAY_SIZE(taint_events));
struct taint_event *event = &taint_events[taint_event_count++];
event->level = level;
assert(strlen(message) < sizeof(event->message));
memcpy(event->message, message, strlen(message) + 1);
}
static void taint_test_warn(void *context, const char *file, int line, const char *condition)
{
assert(context == &taint_context_a || context == &taint_context_b);
assert(file && line > 0 && condition);
/* The warning callback executes before add_taint, including the first
* actual header WARN_ON_ONCE below. */
if (!taint_warnings)
assert(!test_taint(TAINT_WARN));
taint_warnings++;
}
static void same_event(unsigned int a, unsigned int b)
{
assert(taint_events[a].level == taint_events[b].level);
assert(!strcmp(taint_events[a].message, taint_events[b].message));
}
static void compare_formats(unsigned long mask)
{
/* Test-only case isolation, never an admission or retirement operation. */
tainted_mask = reference_mask = mask;
assert(get_taint() == reference_get_taint());
for (unsigned i = 0; i < TAINT_FLAGS_COUNT; i++)
assert(test_taint(i) == reference_test_taint(i));
assert(!strcmp(print_tainted(), reference_print_tainted()));
assert(!strcmp(print_tainted_verbose(), reference_print_verbose()));
assert(strlen(print_tainted_verbose()) < sizeof(taint_buffer));
}
static void formats_and_bits(void)
{
static const char characters[] = "PFSRMBUDAWCIOELKXTNJ";
static const char *const names[] = {
"PROPRIETARY_MODULE", "FORCED_MODULE", "CPU_OUT_OF_SPEC", "FORCED_RMMOD",
"MACHINE_CHECK", "BAD_PAGE", "USER", "DIE", "OVERRIDDEN_ACPI_TABLE", "WARN",
"CRAP", "FIRMWARE_WORKAROUND", "OOT_MODULE", "UNSIGNED_MODULE", "SOFTLOCKUP",
"LIVEPATCH", "AUX", "RANDSTRUCT", "TEST", "FWCTL",
};
assert(sizeof(characters) - 1 == TAINT_FLAGS_COUNT && ARRAY_SIZE(names) == TAINT_FLAGS_COUNT);
compare_formats(0);
assert(!strcmp(print_tainted(), "Not tainted"));
for (unsigned i = 0; i < TAINT_FLAGS_COUNT; i++) {
assert(taint_flags[i].c_true == characters[i]);
assert(taint_flags[i].c_false == (i == 0 ? 'G' : ' '));
assert(!strcmp(taint_flags[i].desc, names[i]));
assert(taint_flags[i].c_true == reference_flags[i].c_true);
assert(taint_flags[i].c_false == reference_flags[i].c_false);
assert(!strcmp(taint_flags[i].desc, reference_flags[i].desc));
compare_formats(1UL << i);
const char *short_string = print_tainted();
assert(strlen(short_string) == 9 + TAINT_FLAGS_COUNT);
assert(short_string[9 + i] == characters[i]);
const char *verbose = print_tainted_verbose();
assert(!strncmp(verbose, "Tainted: [", 10) && !strstr(verbose, ", "));
assert(strstr(verbose, names[i]));
/* Both variants return the permanent same buffer; later calls
* overwrite the earlier bytes, including shortening/NUL. */
assert(short_string == verbose);
}
/* Exercise every flag through each real add/test/get entry, including
* idempotent repeated addition, rather than only preloading format masks. */
tainted_mask = reference_mask = 0;
for (unsigned i = 0; i < TAINT_FLAGS_COUNT; i++) {
add_taint(i, LOCKDEP_STILL_OK);
reference_add_taint(i, LOCKDEP_STILL_OK);
add_taint(i, LOCKDEP_STILL_OK);
reference_add_taint(i, LOCKDEP_STILL_OK);
assert(get_taint() == ((1UL << (i + 1)) - 1));
assert(get_taint() == reference_get_taint());
assert(test_taint(i) && reference_test_taint(i));
}
compare_formats(TAINT_FLAGS_MAX);
assert(strlen(print_tainted_verbose()) + 1 == 328);
assert(!strcmp(print_tainted(), "Tainted: PFSRMBUDAWCIOELKXTNJ"));
compare_formats(0x55555);
compare_formats(0xaaaaa);
compare_formats((1UL << TAINT_PROPRIETARY_MODULE) | (1UL << TAINT_FWCTL));
}
static void lock_state(void)
{
tainted_mask = reference_mask = 0;
panic_on_taint = reference_panic_on_taint = 0;
debug_locks = reference_debug_locks = 1;
taint_event_count = 0;
add_taint(TAINT_USER, LOCKDEP_STILL_OK);
reference_add_taint(TAINT_USER, LOCKDEP_STILL_OK);
assert(debug_locks == 1 && reference_debug_locks == 1 && taint_event_count == 0);
add_taint(TAINT_USER, LOCKDEP_NOW_UNRELIABLE);
reference_add_taint(TAINT_USER, LOCKDEP_NOW_UNRELIABLE);
assert(debug_locks == 0 && reference_debug_locks == 0 && taint_event_count == 2);
same_event(0, 1);
assert(taint_events[0].level == LOGLEVEL_WARNING);
assert(!strcmp(taint_events[0].message, "Disabling lock debugging due to kernel taint\n"));
add_taint(TAINT_DIE, LOCKDEP_NOW_UNRELIABLE);
reference_add_taint(TAINT_DIE, LOCKDEP_NOW_UNRELIABLE);
assert(taint_event_count == 2);
assert(get_taint() == ((1UL << TAINT_USER) | (1UL << TAINT_DIE)));
assert(get_taint() == reference_get_taint());
/* add_taint's original warning is not gated by debug_locks_silent. */
debug_locks = reference_debug_locks = 1;
debug_locks_silent = 1;
add_taint(TAINT_AUX, LOCKDEP_NOW_UNRELIABLE);
reference_add_taint(TAINT_AUX, LOCKDEP_NOW_UNRELIABLE);
assert(taint_event_count == 4);
same_event(2, 3);
debug_locks_silent = 0;
}
static void setup_case(const char *input, int expected_return,
unsigned long expected_mask, bool expected_nousertaint)
{
char owned[80], original[80];
char *a = NULL, *b = NULL;
if (input) {
assert(strlen(input) < sizeof(owned));
memcpy(owned, input, strlen(input) + 1);
memcpy(original, input, strlen(input) + 1);
a = owned;
b = original;
}
taint_event_count = 0;
int actual = panic_on_taint_setup(a);
unsigned int produced = taint_event_count;
int reference = reference_setup(b);
assert(actual == expected_return && reference == actual);
assert(panic_on_taint == expected_mask && reference_panic_on_taint == expected_mask);
assert(panic_on_taint_nousertaint == expected_nousertaint);
assert(reference_nousertaint == expected_nousertaint);
if (input)
assert(!memcmp(owned, original, strlen(input) + 1));
assert(taint_event_count == 2 * produced);
if (!actual) {
assert(produced == 1 && taint_events[0].level == LOGLEVEL_INFO);
same_event(0, 1);
} else {
assert(!produced);
}
}
static void panic_setup(void)
{
panic_on_taint = reference_panic_on_taint = 0;
panic_on_taint_nousertaint = reference_nousertaint = false;
setup_case(NULL, -EINVAL, 0, false);
setup_case("", -EINVAL, 0, false);
setup_case("40", 0, 0x40, false);
setup_case("bogus,nousertaint", -EINVAL, 0x40, false);
setup_case("100000", -EINVAL, 0, false);
setup_case("100040,nousertaint", 0, 0x40, true);
setup_case("0x200", 0, 0x200, true);
setup_case("+00040\n", 0, 0x40, true);
setup_case("80,nousertaint,extra", 0, 0x80, true);
setup_case("ffffffffffffffff", 0, TAINT_FLAGS_MAX, true);
setup_case("10000000000000000", -EINVAL, TAINT_FLAGS_MAX, true);
setup_case("0", -EINVAL, 0, true);
/* Wrong or repeated suffixes are accepted but do not enable the flag. */
panic_on_taint_nousertaint = reference_nousertaint = false;
setup_case("40,nousertaint,extra", 0, 0x40, false);
setup_case("40,NOUSER TAINT", 0, 0x40, false);
setup_case("40,", 0, 0x40, false);
setup_case("40,nousertaint", 0, 0x40, true);
setup_case("80", 0, 0x80, true);
}
static void production_fatal(void)
{
expected_fatal_reference = false;
expected_fatal_mask = (1UL << TAINT_USER) | (1UL << TAINT_AUX);
tainted_mask = 1UL << TAINT_AUX;
panic_on_taint = 1UL << TAINT_USER;
panic_on_taint_nousertaint = true;
debug_locks = 1;
fatal_witness = 0;
add_taint(TAINT_USER, LOCKDEP_NOW_UNRELIABLE);
fatal_witness = 2;
}
static void original_fatal(void)
{
expected_fatal_reference = true;
expected_fatal_mask = (1UL << TAINT_USER) | (1UL << TAINT_AUX);
reference_mask = 1UL << TAINT_AUX;
reference_panic_on_taint = 1UL << TAINT_USER;
reference_nousertaint = true;
reference_debug_locks = 1;
fatal_witness = 0;
reference_add_taint(TAINT_USER, LOCKDEP_NOW_UNRELIABLE);
fatal_witness = 2;
}
static void fatal_without_logger(void)
{
const struct stela_linux_owner bare = {.services = stela_linux_bare.services};
stela_linux_exit();
stela_linux_enter(&bare);
stela_linux_fatal("test terminal stop without a logger");
}
static void bad_flag(void)
{
add_taint(TAINT_FLAGS_COUNT, LOCKDEP_STILL_OK);
}
static void bad_test_flag(void)
{
(void)test_taint(~0U);
}
static void outside_owner(void)
{
stela_linux_exit();
(void)get_taint();
}
static void warn_once_site(bool condition)
{
(void)WARN_ON_ONCE(condition);
}
int main(void)
{
const struct stela_linux_services services = {.log = taint_test_log, .warn = taint_test_warn};
const struct stela_linux_owner a = {.services = &services, .context = &taint_context_a};
const struct stela_linux_owner b = {.services = &services, .context = &taint_context_b};
stela_linux_enter(&a);
assert(get_taint() == (IS_ENABLED(CONFIG_RANDSTRUCT) ? (1UL << TAINT_RANDSTRUCT) : 0));
assert(debug_locks == 1 && debug_locks_silent == 0);
formats_and_bits();
lock_state();
unsigned long permanent = get_taint();
stela_linux_exit();
stela_linux_enter(&b);
assert(get_taint() == permanent && debug_locks == 0);
/* A different owner and repeated addition keep the same image state. */
add_taint(TAINT_USER, LOCKDEP_STILL_OK);
assert(get_taint() == permanent);
panic_setup();
panic_on_taint = 0;
tainted_mask = 0;
taint_warnings = 0;
warn_once_site(false);
assert(!taint_warnings && !get_taint());
warn_once_site(true);
warn_once_site(true);
assert(taint_warnings == 1 && get_taint() == (1UL << TAINT_WARN));
stela_linux_exit();
stela_linux_enter(&a);
warn_once_site(true);
assert(taint_warnings == 1 && get_taint() == (1UL << TAINT_WARN));
stela_linux_warn(__FILE__, __LINE__, "exact taint flags", BUGFLAG_TAINT(TAINT_FWCTL));
assert(taint_warnings == 2 && test_taint(TAINT_FWCTL));
assert(stela_taint_test_stops(production_fatal, &fatal_witness, 1));
assert(stela_taint_test_stops(original_fatal, &fatal_witness, 1));
assert(stela_test_traps(fatal_without_logger));
/* Validation errors are terminal, so their dedicated loggerless owner
* avoids the panic-specific emergency-state assertions above. */
stela_linux_exit();
stela_linux_enter(&stela_linux_bare);
assert(stela_test_traps(bad_flag));
assert(stela_test_traps(bad_test_flag));
assert(stela_test_traps(outside_owner));
stela_linux_exit();
printf("Linux taint: original state/format/setup differential, owners, warnings and fatal ordering passed\n");
return 0;
}
@@ -0,0 +1,40 @@
/* SPDX-License-Identifier: MIT */
/* Host-only trap observer; compile outside the Linux header environment,
* beside stela/test.c. Never part of a native image or Linux service. */
#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
_Static_assert(__builtin_types_compatible_p(sig_atomic_t, int),
"hosted witness requires int sig_atomic_t");
static volatile sig_atomic_t *stop_witness;
static sig_atomic_t stop_expected;
static void stopped(int signal_number)
{
(void)signal_number;
_Exit(*stop_witness == stop_expected ? 86 : 89);
}
int stela_taint_test_stops(void (*operation)(void), volatile int *witness, int expected)
{
pid_t child = fork();
if (child < 0)
abort();
if (!child) {
stop_witness = witness;
stop_expected = expected;
if (signal(SIGILL, stopped) == SIG_ERR)
_Exit(87);
operation();
_Exit(88);
}
int status;
while (waitpid(child, &status, 0) < 0)
if (errno != EINTR)
abort();
return WIFEXITED(status) && WEXITSTATUS(status) == 86;
}
@@ -20,6 +20,9 @@ struct stela_linux_task_ops {
/* Actual CPU/IRQ/RSP/current ticket validation, bounded and allocation-
* free. The retained binding/code outlive this attached task. */
bool (*is_current)(void *binding, const struct stela_linux_task_context *context);
/* Exact active-job signal; caller already proved a real same-CPU C
* current and retained target lifetime. No allocation/switch/final drop. */
int (*wake_target)(void *binding, u64 expected_sequence);
};
struct stela_linux_task_scope_ops {
@@ -34,6 +37,7 @@ struct stela_linux_task_scope_ops {
struct stela_linux_lease {
const struct stela_linux_owner *owner;
unsigned long irq_flags;
u64 generation;
};
void stela_linux_lease_snapshot(struct stela_linux_lease *lease);
bool stela_linux_lease_matches(const struct stela_linux_lease *lease);
@@ -62,11 +66,20 @@ void stela_linux_task_release(struct stela_linux_task *task);
int stela_linux_task_scope_begin(struct stela_linux_task *task,
const struct stela_linux_task_scope_ops *ops, void *scope);
int stela_linux_task_scope_end(struct stela_linux_task *task);
/* Internal adapters only; these are not Linux schedule/wake exports. A true
* schedule_preempt_disabled adapter must prove it owns the sole preempt level;
* count==1 by itself cannot distinguish that level from an outer RCU reader. */
/* Internal prepared transition hooks. The selected original mutex scheduler
* adapter owns the sole preempt level; count==1 alone does not distinguish
* that level from an outer RCU reader. General schedule APIs remain separate. */
int stela_linux_task_park(bool scheduler_preempt_disabled);
int stela_linux_task_yield(void);
struct task_struct *stela_linux_current(void);
struct thread_info *stela_linux_thread_info(void);
/* Narrow kernel-wait cancellation, not POSIX process/siginfo delivery. Values
* 1/2 post actual SIGUSR1/SIGKILL bits. Target metadata is retained separately;
* an old sequence returns -ESTALE before reading future-job state. */
int stela_linux_task_signal(struct stela_linux_task *task, u64 expected_sequence,
unsigned int kind);
int stela_linux_task_ack_signal(unsigned int kind);
unsigned int stela_linux_task_pending_signals(void);
unsigned int stela_linux_task_waiting_io(void);
unsigned int stela_linux_task_waiting_load(void);
#endif
+390 -4
View File
@@ -1,7 +1,8 @@
//! Actual Linux task metadata on retained cooperative continuations.
//!
//! This binds original C task_struct/current and the entered service lease.
//! It admits neither original mutex/signal/I/O/WW services nor a native producer.
//! The shared normal/WW mutex adapter supplies genuine wake/signal/I/O effects.
//! Native producers and the distinct RT-mutex/I2C extension remain unadmitted.
use crate::platform::work::{
ContextId, LeaveReason, ParkOutcome, Runtime, SwitchBinding, TaskContext, WakeHandle, WorkError,
};
@@ -9,7 +10,7 @@ use alloc::sync::Arc;
use core::{
cell::UnsafeCell,
ffi::c_void,
mem::MaybeUninit,
mem::{ManuallyDrop, MaybeUninit},
pin::Pin,
ptr::NonNull,
sync::atomic::{AtomicBool, AtomicU64, Ordering},
@@ -18,6 +19,7 @@ use core::{
#[repr(C)]
struct TaskOps {
is_current: unsafe extern "C" fn(*mut c_void, *const TaskContext) -> bool,
wake_target: unsafe extern "C" fn(*mut c_void, u64) -> i32,
}
#[repr(C)]
struct ScopeOps {
@@ -49,6 +51,7 @@ unsafe extern "C" {
scope: *mut c_void,
) -> i32;
fn stela_linux_task_scope_end(task: *mut CTask) -> i32;
fn stela_linux_task_signal(task: *mut CTask, expected_sequence: u64, kind: u32) -> i32;
}
static QUARANTINED: AtomicU64 = AtomicU64::new(0);
@@ -65,6 +68,7 @@ pub fn quarantined() -> u64 {
pub struct TaskBinding<const N: usize> {
task: NonNull<CTask>,
first: UnsafeCell<MaybeUninit<WakeHandle<N>>>,
target: UnsafeCell<MaybeUninit<WakeHandle<N>>>,
published: AtomicBool,
detached: AtomicBool,
released: bool,
@@ -86,6 +90,7 @@ fn status(value: i32) -> Result<(), WorkError> {
impl<const N: usize> TaskBinding<N> {
const OPS: TaskOps = TaskOps {
is_current: Self::current,
wake_target: Self::wake_target,
};
const SCOPE_OPS: ScopeOps = ScopeOps {
park: Self::park,
@@ -107,6 +112,7 @@ impl<const N: usize> TaskBinding<N> {
Ok(Arc::new(Self {
task,
first: UnsafeCell::new(MaybeUninit::uninit()),
target: UnsafeCell::new(MaybeUninit::uninit()),
published: AtomicBool::new(false),
detached: AtomicBool::new(false),
released: false,
@@ -122,7 +128,10 @@ impl<const N: usize> TaskBinding<N> {
let handle = runtime.bind_current(self.clone())?;
// SAFETY: one successful Runtime attachment owns this same-CPU initial
// publication. Runtime retains this binding before returning the handle.
unsafe { (*self.first.get()).write(handle) };
unsafe {
(*self.first.get()).write(handle.clone());
(*self.target.get()).write(handle);
};
self.published.store(true, Ordering::Release);
Ok(())
}
@@ -142,6 +151,31 @@ impl<const N: usize> TaskBinding<N> {
pub fn current_wake(&self) -> Result<WakeHandle<N>, WorkError> {
self.first()?.renew_current()
}
/// Capture this actual current job, retaining metadata independently of
/// original C usage refs. An old target may outlive clean job completion;
/// its expected sequence can never signal or inspect a future job.
pub fn target_current(self: &Arc<Self>) -> Result<TargetTask<N>, WorkError> {
let wake = self.current_wake()?;
Ok(TargetTask { binding: ManuallyDrop::new(self.clone()), wake: ManuallyDrop::new(wake) })
}
unsafe extern "C" fn wake_target(binding: *mut c_void, expected: u64) -> i32 {
// SAFETY: C validated an actual entered same-CPU caller and retained
// target reference. It cannot run a callback/switch or free this Arc.
let this = unsafe { &*binding.cast::<Self>() };
if !this.published.load(Ordering::Acquire) || this.detached.load(Ordering::Acquire) {
return -116; // ESTALE
}
// SAFETY: same-CPU exclusion and acquired initial publication; only an
// actual new-job arrive updates this field, before C can target it.
let handle = unsafe { (*this.target.get()).assume_init_ref() };
if expected == 0 || handle.sequence() != expected { return -116; }
match handle.wake() {
Ok(()) => 0, Err(WorkError::Busy) => -16,
Err(WorkError::Closed) => -116, Err(_) => -1,
}
}
fn validate(&self, context: &TaskContext) -> Result<(), WorkError> {
let handle = self.current_wake()?;
if handle.context_id().get() != context.context_id || handle.sequence() != context.sequence
@@ -289,6 +323,16 @@ unsafe impl<const N: usize> SwitchBinding for TaskBinding<N> {
}
unsafe fn arrive(&self, context: &TaskContext, new_job: bool) -> Result<(), WorkError> {
self.validate(context)?;
if new_job {
let next = self.current_wake()?;
// SAFETY: actual same-CPU destination stack/IF0, no foreign C or
// IRQ task-pointer reader. The mutable field borrow ends before
// any hook. Runtime retains Queue/signal so old Drop is nonfinal.
let previous = unsafe {
core::ptr::replace((*self.target.get()).assume_init_mut(), next)
};
drop(previous);
}
// SAFETY: actual resumed/new job stack and existing ticket before IF restore.
status(unsafe { stela_linux_task_arrive(self.task.as_ptr(), context, new_job) })
}
@@ -320,7 +364,65 @@ impl<const N: usize> Drop for TaskBinding<N> {
if self.published.load(Ordering::Acquire) {
// SAFETY: exclusive Self destruction and acquired single publication.
// WakeHandle itself quarantines final roots on IRQ/foreign CPU Drop.
unsafe { (*self.first.get()).assume_init_drop() };
unsafe {
(*self.target.get()).assume_init_drop();
(*self.first.get()).assume_init_drop();
};
}
}
}
/// The two observable kernel-wait cancellation classes. These post real
/// original SIGUSR1/SIGKILL pending bits; no POSIX process termination, siginfo
/// delivery, realtime queue or guest signal ABI is implied.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u32)]
pub enum WaitSignal { Interrupt = 1, Fatal = 2 }
/// Owns metadata and an immutable expected job, not a permanent C usage ref.
/// Completion can close the job while this handle is retained. Only the plain
/// WakeHandle is an IRQ signal view; TargetTask's C operations are process-only.
pub struct TargetTask<const N: usize> {
binding: ManuallyDrop<Arc<TaskBinding<N>>>,
wake: ManuallyDrop<WakeHandle<N>>,
}
impl<const N: usize> Clone for TargetTask<N> {
fn clone(&self) -> Self {
Self { binding: self.binding.clone(), wake: self.wake.clone() }
}
}
impl<const N: usize> TargetTask<N> {
pub fn context_id(&self) -> ContextId { self.wake.context_id() }
pub fn sequence(&self) -> u64 { self.wake.sequence() }
/// Post to the captured job only. Closed/reused jobs return Closed before
/// future C state is accessed; retaining this target is not a Linux task ref.
///
/// # Safety
/// Call on the real same-CPU entered Linux process continuation described
/// by `caller`, with shared service roots retained. Do not call from IRQ,
/// IF0 switch hooks, a dispatcher, or outside run_scoped/Linux entry.
pub unsafe fn signal(&self, caller: Pin<&Runtime<N>>, kind: WaitSignal) -> Result<(), WorkError> {
self.wake.check_process()?;
caller.current_context()?;
// SAFETY: immutable expected generation plus separately retained C
// metadata; caller proves actual entered Linux process authority.
match unsafe { stela_linux_task_signal(self.binding.task.as_ptr(), self.sequence(), kind as u32) } {
0 => Ok(()), -116 => Err(WorkError::Closed), -16 => Err(WorkError::Busy),
_ => Err(WorkError::CorruptContext),
}
}
}
impl<const N: usize> Drop for TargetTask<N> {
fn drop(&mut self) {
if self.wake.check_process().is_ok() {
// SAFETY: qualified process CPU. Native callers retain the normal
// flags-restored release boundary; no switch hook owns a TargetTask.
// Keep the immutable wake owner until after binding destruction.
unsafe { ManuallyDrop::drop(&mut self.binding); ManuallyDrop::drop(&mut self.wake); }
} else {
// Never let an old producer's final owner release run in native
// IRQ/foreign-CPU context. Keep BOTH metadata and provider roots.
QUARANTINED.fetch_add(1, Ordering::Relaxed);
}
}
}
@@ -797,4 +899,288 @@ pub(crate) mod tests {
assert_eq!(quarantined(), 0);
unsafe { stela_linux_task_test_taskless() };
}
#[repr(C)]
struct MutexCall {
scenario: u32,
role: u32,
context: *mut c_void,
checkpoint: unsafe extern "C" fn(*mut c_void, u32),
}
unsafe extern "C" {
fn stela_linux_mutex_test_run(context: *mut c_void);
}
struct MutexRole {
fixture: alloc::sync::Weak<MutexFixture>,
scenario: u32,
role: usize,
}
struct MutexFixture {
cpu: Arc<CpuModel>,
runtime: AtomicPtr<Runtime<16>>,
bindings: [Mutex<Option<Arc<TaskBinding<16>>>>; 4],
targets: [Mutex<Option<TargetTask<16>>>; 5],
jobs: [Box<MutexRole>; 5],
completed: AtomicU64,
signals: AtomicU64,
stale: AtomicU64,
prepare_signals: AtomicU64,
self_signals: AtomicU64,
}
impl MutexFixture {
fn new(cpu: Arc<CpuModel>, scenario: u32) -> Arc<Self> {
Arc::new_cyclic(|weak| Self {
cpu,
runtime: AtomicPtr::new(ptr::null_mut()),
bindings: core::array::from_fn(|_| Mutex::new(None)),
targets: core::array::from_fn(|_| Mutex::new(None)),
// All stable callback storage is allocated before publication;
// neither original wake_q nor PREPARE callbacks allocate it.
jobs: core::array::from_fn(|role| Box::new(MutexRole {
fixture: weak.clone(),
scenario,
role,
})),
completed: AtomicU64::new(0),
signals: AtomicU64::new(0),
stale: AtomicU64::new(0),
prepare_signals: AtomicU64::new(0),
self_signals: AtomicU64::new(0),
})
}
unsafe fn runtime(&self) -> Pin<&Runtime<16>> {
self.cpu.check_cpu().unwrap();
// SAFETY: this private hosted fixture's retained executor owns the
// exact pinned Runtime until all callbacks end and bindings detach.
unsafe { Pin::new_unchecked(&*self.runtime.load(Ordering::Acquire)) }
}
fn binding(&self, index: usize) -> Arc<TaskBinding<16>> {
if let Some(binding) = self.bindings[index].lock().unwrap().clone() {
return binding;
}
// SAFETY: real process stack/CPU, outside entered C/IF0 hooks.
let binding = unsafe { TaskBinding::new() }.unwrap();
binding.bind_current(unsafe { self.runtime() }).unwrap();
*self.bindings[index].lock().unwrap() = Some(binding.clone());
binding
}
fn context(&self, role: usize) -> *mut c_void {
&*self.jobs[role] as *const MutexRole as *mut c_void
}
fn target(&self, role: usize) -> TargetTask<16> {
// This is also used in an original RCU process-retirement callback.
// Refuse contention instead of blocking at SOFTIRQ_OFFSET; cloning
// only increments retained owners, with nonfinal drops afterward.
self.targets[role].try_lock().unwrap().as_ref().unwrap().clone()
}
fn enqueue(&self, role: usize) {
let lane = if role == 1 || role == 4 { Kind::Notify } else { Kind::General };
// SAFETY: fixture owns stable job storage until every real callback
// completes. Enqueue is bounded, with no callback or heap allocation.
unsafe { self.runtime().queue().execute(lane, mutex_role, self.context(role)) }.unwrap();
}
}
unsafe fn mutex_job<'a>(context: *mut c_void) -> &'a MutexRole {
// SAFETY: stable boxed role retained by the actual Queue fixture owner.
unsafe { &*context.cast::<MutexRole>() }
}
unsafe extern "C" fn mutex_checkpoint(context: *mut c_void, event: u32) {
let job = unsafe { mutex_job(context) };
let f = job.fixture.upgrade().unwrap();
let runtime = unsafe { f.runtime() };
match event {
1 => {
f.enqueue(1);
if job.scenario == 0 {
f.enqueue(2);
f.enqueue(3);
}
}
2 | 3 | 4 => {
let target = f.target(1);
let kind = if event == 3 { WaitSignal::Fatal } else { WaitSignal::Interrupt };
// SAFETY: called by the real same-CPU entered C owner. Event4
// is process PREPARE's bounded softirq-accounted callback, not
// a native interrupt producer or an IF0 switch hook.
unsafe { target.signal(runtime, kind) }.unwrap();
if event == 4 {
f.prepare_signals.fetch_add(1, Ordering::Relaxed);
} else {
f.signals.fetch_add(1, Ordering::Relaxed);
}
}
5 => {
let old = f.target(1);
assert_eq!(unsafe { old.signal(runtime, WaitSignal::Fatal) }, Err(WorkError::Closed));
f.stale.fetch_add(1, Ordering::Relaxed);
}
6 => f.enqueue(4),
7 | 8 => {
let target = f.target(0);
let kind = if event == 7 { WaitSignal::Interrupt } else { WaitSignal::Fatal };
// SAFETY: actual entered current posts to its own expected job.
unsafe { target.signal(runtime, kind) }.unwrap();
f.self_signals.fetch_add(1, Ordering::Relaxed);
}
10 => {
let target = f.target(1);
let wake = (*target.wake).clone();
drop(target);
// Explicit hosted IRQ model: only the retained generic atomic
// signal view is reachable here, never a C task/Runtime pointer.
f.cpu.irq.store(true, Ordering::Release);
wake.wake().unwrap();
wake.wake().unwrap(); // coalesced repeated wake before resume
f.cpu.irq.store(false, Ordering::Release);
drop(wake);
}
_ => panic!("unexpected mutex checkpoint"),
}
}
unsafe extern "C" fn mutex_role(context: *mut c_void) {
let job = unsafe { mutex_job(context) };
let f = job.fixture.upgrade().unwrap();
let runtime = unsafe { f.runtime() };
let index = if job.role == 4 { 1 } else { job.role };
let binding = f.binding(index);
let target = binding.target_current().unwrap();
if job.role == 4 {
let old = f.target(1);
assert_eq!(old.context_id(), target.context_id());
assert_ne!(old.sequence(), target.sequence());
}
*f.targets[job.role].try_lock().unwrap() = Some(target);
let mut call = MutexCall {
scenario: job.scenario,
role: job.role as u32,
context,
checkpoint: mutex_checkpoint,
};
// SAFETY: only shared retained Runtime/owner roots span suspension;
// call is an actual immovable stack local until this C body returns.
unsafe {
binding.run_scoped(runtime, stela_linux_mutex_test_run, ptr::from_mut(&mut call).cast())
}.unwrap();
f.completed.fetch_add(1, Ordering::Relaxed);
}
fn exact_mutex_child(selector: &str) {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", selector, "--ignored", "--test-threads=1", "--nocapture", "--format=pretty", "--color=never"])
.output().unwrap();
let stdout = std::string::String::from_utf8_lossy(&output.stdout);
let stderr = std::string::String::from_utf8_lossy(&output.stderr);
let expected = std::format!("test {selector} ... ok");
let named = stdout.lines().any(|line| line == expected);
let one = stdout.lines().any(|line| line.starts_with("test result: ok. 1 passed; 0 failed; 0 ignored;"));
assert!(output.status.success() && named && one,
"mutex child did not execute/pass exactly once ({}):\n{}{}", output.status, stdout, stderr);
}
pub(crate) fn run_mutex_child() {
exact_mutex_child("gpu::linux::task::tests::mutex_child");
exact_mutex_child("gpu::linux::task::tests::mutex_quarantine_child");
}
#[test]
#[ignore = "isolated exact child of gpu::c_tests::linux_mutex_wait"]
fn mutex_child() {
// SAFETY: isolated canonical allocator registry, same real GlobalAlloc
// owns ordinary and raw-span allocations and their exact-layout frees.
assert!(unsafe { crate::gpu::linux::heap::register(try_allocate) }.is_ok());
assert_eq!(core::mem::size_of::<MutexCall>(), 24);
let dropped = Arc::new(AtomicU64::new(0));
for scenario in 0..11 {
let cpu = CpuModel::new();
let f = MutexFixture::new(cpu.clone(), scenario);
let queue = unsafe { Queue::<16>::new(cpu.clone(), f.clone()) }.unwrap();
let executor = Executor::new_hosted_for_test(queue, stacks(&dropped, 16 * 1024)).unwrap();
let runtime = executor.runtime();
f.runtime.store(runtime.get_ref() as *const Runtime<16> as *mut Runtime<16>, Ordering::Release);
// SAFETY: actual guarded stacks and retained fixture/job roots, no
// C owner/ref survives completion, no native admission is asserted.
unsafe { runtime.call_foreground(mutex_role, f.context(0), 100000) }.unwrap();
assert_eq!(f.completed.load(Ordering::Relaxed), if scenario == 0 { 5 } else { 2 });
assert_eq!(f.prepare_signals.load(Ordering::Relaxed), u64::from(scenario == 5));
assert_eq!(f.stale.load(Ordering::Relaxed), if scenario == 0 { 2 } else { 0 });
let expected_signals = match scenario { 1 | 3 | 4 | 6 | 9 => 1, 2 => 2, _ => 0 };
assert_eq!(f.signals.load(Ordering::Relaxed), expected_signals);
assert_eq!(f.self_signals.load(Ordering::Relaxed), if scenario < 7 || scenario == 10 { 2 } else { 0 });
// All expected-job snapshots are now inert even though metadata is
// still retained. Taking them in process context breaks Arc cycles.
for slot in &f.targets {
if let Some(target) = slot.lock().unwrap().take() {
assert_eq!(target.wake.wake(), Err(WorkError::Closed));
drop(target);
}
}
assert_eq!(cpu.flags.load(Ordering::Acquire), 0x202);
runtime.queue().close().unwrap();
assert_eq!(unsafe { runtime.retire() }, Err(WorkError::Pending));
for slot in &f.bindings {
if let Some(binding) = slot.lock().unwrap().take() {
let retained = unsafe { runtime.detach_binding(binding.context_id().unwrap()) }.unwrap();
assert_eq!(cpu.flags.load(Ordering::Acquire), 0x202);
drop(retained);
// SAFETY: actual jobs completed; C refs, waiters, signal
// snapshots and all producer borrows ended independently.
assert!(unsafe { binding.release_quiescent() }.is_ok());
}
}
unsafe { runtime.retire() }.unwrap();
drop(executor);
assert_eq!(dropped.load(Ordering::Relaxed), (u64::from(scenario) + 1) * 4);
assert_eq!(quarantined(), 0);
assert!(!RAW.occupied.load(Ordering::Acquire));
unsafe { stela_linux_task_test_taskless() };
}
}
unsafe extern "C" fn quarantine_targets(context: *mut c_void) {
// No Linux entry is needed for capture/drop mechanics. Runtime still
// provides actual current/C task identity on its real guarded stack.
let job = unsafe { mutex_job(context) };
let f = job.fixture.upgrade().unwrap();
let binding = f.binding(0);
let baseline = Arc::strong_count(&binding);
let target = binding.target_current().unwrap();
let foreign = target.clone();
thread::spawn(move || drop(foreign)).join().unwrap();
assert_eq!(quarantined(), 1);
assert_eq!(Arc::strong_count(&binding), baseline + 2);
let irq = target.clone();
f.cpu.irq.store(true, Ordering::Release);
drop(irq);
f.cpu.irq.store(false, Ordering::Release);
assert_eq!(quarantined(), 2);
assert_eq!(Arc::strong_count(&binding), baseline + 3);
drop(target);
assert_eq!(Arc::strong_count(&binding), baseline + 2);
}
#[test]
#[ignore = "isolated exact child; intentional quarantine cannot share normal teardown proof"]
fn mutex_quarantine_child() {
let dropped = Arc::new(AtomicU64::new(0));
let cpu = CpuModel::new();
let f = MutexFixture::new(cpu.clone(), 0);
let queue = unsafe { Queue::<16>::new(cpu, f.clone()) }.unwrap();
let executor = Executor::new_hosted_for_test(queue, stacks(&dropped, 16 * 1024)).unwrap();
let runtime = executor.runtime();
f.runtime.store(runtime.get_ref() as *const Runtime<16> as *mut Runtime<16>, Ordering::Release);
unsafe { runtime.call_foreground(quarantine_targets, f.context(0), 100000) }.unwrap();
runtime.queue().close().unwrap();
let binding = f.bindings[0].lock().unwrap().take().unwrap();
let retained = unsafe { runtime.detach_binding(binding.context_id().unwrap()) }.unwrap();
drop(retained);
// The two improper drops intentionally kept real metadata owners. A
// claimed unique release must refuse; no final C free is smuggled into
// the foreign thread/IRQ model or inferred from task usage alone.
let unreleased = unsafe { binding.release_quiescent() }.err().unwrap();
assert_eq!(Arc::strong_count(&unreleased), 3);
drop(unreleased); // nonfinal process-context drop; two retained owners remain
unsafe { runtime.retire() }.unwrap();
drop(executor);
assert_eq!(dropped.load(Ordering::Relaxed), 4);
assert_eq!(quarantined(), 2);
}
}
@@ -579,6 +579,12 @@ impl<const N: usize> WakeHandle<N> {
/// Qualified same-CPU process/IRQ admission only; never resume inline or
/// change the foreign condition. Close permits wakes for admitted jobs.
/// Release/acquire pending plus final IF exclusion covers wake at park.
/// Qualify process-context owner release on this retained queue's actual
/// CPU, including after job close. This grants no current task/RSP, live
/// sequence, Linux entry or native producer authority and signals nothing.
pub(crate) fn check_process(&self) -> Result<(), WorkError> {
self.queue.process()
}
pub fn wake(&self) -> Result<(), WorkError> {
let mut guard = self.queue.lock()?;
if guard.state().poisoned
+6
View File
@@ -41,3 +41,9 @@
/COPYING
/README
/Makefile
/kernel/locking/mutex.c
/kernel/locking/mutex.h
/kernel/locking/ww_mutex.h
/kernel/sched/core.c
/kernel/sched/Makefile
/kernel/sched/wait_support.c
@@ -0,0 +1,274 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Tyler Smith <74526874+tylertms@users.noreply.github.com>
Date: Sat, 24 Oct 2026 02:15:00 -0400
Subject: [PATCH] refactor(sched): separate shared wait support
---
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -1098,93 +1098,6 @@
return false;
}
#endif
-
-static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
-{
- struct wake_q_node *node = &task->wake_q;
-
- /*
- * Atomically grab the task, if ->wake_q is !nil already it means
- * it's already queued (either by us or someone else) and will get the
- * wakeup due to that.
- *
- * In order to ensure that a pending wakeup will observe our pending
- * state, even in the failed case, an explicit smp_mb() must be used.
- */
- smp_mb__before_atomic();
- if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
- return false;
-
- /*
- * The head is context local, there can be no concurrency.
- */
- *head->lastp = node;
- head->lastp = &node->next;
- return true;
-}
-
-/**
- * wake_q_add() - queue a wakeup for 'later' waking.
- * @head: the wake_q_head to add @task to
- * @task: the task to queue for 'later' wakeup
- *
- * Queue a task for later wakeup, most likely by the wake_up_q() call in the
- * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
- * instantly.
- *
- * This function must be used as-if it were wake_up_process(); IOW the task
- * must be ready to be woken at this location.
- */
-void wake_q_add(struct wake_q_head *head, struct task_struct *task)
-{
- if (__wake_q_add(head, task))
- get_task_struct(task);
-}
-
-/**
- * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
- * @head: the wake_q_head to add @task to
- * @task: the task to queue for 'later' wakeup
- *
- * Queue a task for later wakeup, most likely by the wake_up_q() call in the
- * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
- * instantly.
- *
- * This function must be used as-if it were wake_up_process(); IOW the task
- * must be ready to be woken at this location.
- *
- * This function is essentially a task-safe equivalent to wake_q_add(). Callers
- * that already hold reference to @task can call the 'safe' version and trust
- * wake_q to do the right thing depending whether or not the @task is already
- * queued for wakeup.
- */
-void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
-{
- if (!__wake_q_add(head, task))
- put_task_struct(task);
-}
-
-void wake_up_q(struct wake_q_head *head)
-{
- struct wake_q_node *node = head->first;
-
- while (node != WAKE_Q_TAIL) {
- struct task_struct *task;
-
- task = container_of(node, struct task_struct, wake_q);
- node = node->next;
- /* pairs with cmpxchg_relaxed() in __wake_q_add() */
- WRITE_ONCE(task->wake_q.next, NULL);
- /* Task can safely be re-inserted now. */
-
- /*
- * wake_up_process() executes a full barrier, which pairs with
- * the queueing in wake_q_add() so as not to miss wakeups.
- */
- wake_up_process(task);
- put_task_struct(task);
- }
-}
/*
* resched_curr - mark rq's current task 'to be rescheduled now'.
@@ -8175,20 +8088,6 @@
return "VOLUNTARY";
return "NONE";
-}
-
-int io_schedule_prepare(void)
-{
- int old_iowait = current->in_iowait;
-
- current->in_iowait = 1;
- blk_flush_plug(current->plug, true);
- return old_iowait;
-}
-
-void io_schedule_finish(int token)
-{
- current->in_iowait = token;
}
/*
diff --git a/kernel/sched/Makefile b/kernel/sched/Makefile
--- a/kernel/sched/Makefile
+++ b/kernel/sched/Makefile
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: GPL-2.0
CONTEXT_ANALYSIS_core.o := y
+CONTEXT_ANALYSIS_wait_support.o := y
CONTEXT_ANALYSIS_fair.o := y
# The compilers are complaining about unused variables inside an if(0) scope
@@ -23,6 +24,7 @@
# I turn this off for IA-64 only. Andreas Schwab says it's also needed on m68k
# to get a correct value for the wait-channel (WCHAN in ps). --davidm
CFLAGS_core.o := $(PROFILING) -fno-omit-frame-pointer
+CFLAGS_wait_support.o := $(CFLAGS_core.o)
endif
# Branch profiling isn't noinstr-safe
@@ -36,7 +38,7 @@
# These compilation units have roughly the same size and complexity - so their
# build parallelizes well and finishes roughly at once:
#
-obj-y += core.o
+obj-y += core.o wait_support.o
obj-y += fair.o
obj-y += build_policy.o
obj-y += build_utility.o
diff --git a/kernel/sched/wait_support.c b/kernel/sched/wait_support.c
new file mode 100644
--- /dev/null
+++ b/kernel/sched/wait_support.c
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * kernel/sched/core.c
+ *
+ * Core kernel CPU scheduler code
+ *
+ * Copyright (C) 1991-2002 Linus Torvalds
+ * Copyright (C) 1998-2024 Ingo Molnar, Red Hat
+ */
+/* Wait support mechanically separated from core.c. Bodies and API effects
+ * remain original; the target scheduler supplies real wake/task services. */
+#include <linux/blkdev.h>
+#include <linux/sched/task.h>
+#include <linux/sched/wake_q.h>
+
+static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
+{
+ struct wake_q_node *node = &task->wake_q;
+
+ /*
+ * Atomically grab the task, if ->wake_q is !nil already it means
+ * it's already queued (either by us or someone else) and will get the
+ * wakeup due to that.
+ *
+ * In order to ensure that a pending wakeup will observe our pending
+ * state, even in the failed case, an explicit smp_mb() must be used.
+ */
+ smp_mb__before_atomic();
+ if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
+ return false;
+
+ /*
+ * The head is context local, there can be no concurrency.
+ */
+ *head->lastp = node;
+ head->lastp = &node->next;
+ return true;
+}
+
+/**
+ * wake_q_add() - queue a wakeup for 'later' waking.
+ * @head: the wake_q_head to add @task to
+ * @task: the task to queue for 'later' wakeup
+ *
+ * Queue a task for later wakeup, most likely by the wake_up_q() call in the
+ * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
+ * instantly.
+ *
+ * This function must be used as-if it were wake_up_process(); IOW the task
+ * must be ready to be woken at this location.
+ */
+void wake_q_add(struct wake_q_head *head, struct task_struct *task)
+{
+ if (__wake_q_add(head, task))
+ get_task_struct(task);
+}
+
+/**
+ * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
+ * @head: the wake_q_head to add @task to
+ * @task: the task to queue for 'later' wakeup
+ *
+ * Queue a task for later wakeup, most likely by the wake_up_q() call in the
+ * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
+ * instantly.
+ *
+ * This function must be used as-if it were wake_up_process(); IOW the task
+ * must be ready to be woken at this location.
+ *
+ * This function is essentially a task-safe equivalent to wake_q_add(). Callers
+ * that already hold reference to @task can call the 'safe' version and trust
+ * wake_q to do the right thing depending whether or not the @task is already
+ * queued for wakeup.
+ */
+void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
+{
+ if (!__wake_q_add(head, task))
+ put_task_struct(task);
+}
+
+void wake_up_q(struct wake_q_head *head)
+{
+ struct wake_q_node *node = head->first;
+
+ while (node != WAKE_Q_TAIL) {
+ struct task_struct *task;
+
+ task = container_of(node, struct task_struct, wake_q);
+ node = node->next;
+ /* pairs with cmpxchg_relaxed() in __wake_q_add() */
+ WRITE_ONCE(task->wake_q.next, NULL);
+ /* Task can safely be re-inserted now. */
+
+ /*
+ * wake_up_process() executes a full barrier, which pairs with
+ * the queueing in wake_q_add() so as not to miss wakeups.
+ */
+ wake_up_process(task);
+ put_task_struct(task);
+ }
+}
+
+int io_schedule_prepare(void)
+{
+ int old_iowait = current->in_iowait;
+
+ current->in_iowait = 1;
+ blk_flush_plug(current->plug, true);
+ return old_iowait;
+}
+
+void io_schedule_finish(int token)
+{
+ current->in_iowait = token;
+}
+