diff --git a/Cargo.lock b/Cargo.lock index 9ad8b71009..57916347e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1602,6 +1602,8 @@ version = "0.1.0" dependencies = [ "aes", "cc", + "libc", + "object", "sha2", "subtle", "triomphe", diff --git a/crates/stela-drivers/Cargo.toml b/crates/stela-drivers/Cargo.toml index 48c9a0acdc..ceca30f208 100644 --- a/crates/stela-drivers/Cargo.toml +++ b/crates/stela-drivers/Cargo.toml @@ -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]] diff --git a/crates/stela-drivers/build/inputs.rs b/crates/stela-drivers/build/inputs.rs new file mode 100644 index 0000000000..5b5cd9f198 --- /dev/null +++ b/crates/stela-drivers/build/inputs.rs @@ -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 = std::result::Result; +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, 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, pub roots: Vec, pub stats: Stats } +#[derive(Clone)] +struct Record { root: RootId, relative: PathBuf, path: PathBuf, expected: Option, max_bytes: u64, observed: Option } +struct DirectoryGuard { root: RootId, relative: Option, identity: Identity, names: Option> } + +/// 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, records: Vec, paths: BTreeMap, + directories: BTreeMap, stats: Stats, +} +impl Inputs { + pub fn new(limits: Limits) -> Result { + 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 { + 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> { + 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>)> { + 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>)> { + 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 { 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> { 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 { + 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> { + 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 { + 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(¤t)? == 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(value: io::Result) -> Result { value.map_err(|error| error.to_string()) } + fn convert(value: &libc::stat) -> Result { + 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 { + let mut value = MaybeUninit::::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::new(value.as_bytes()).map_err(|error| format!("invalid input component: {error}")) } + fn open_at(parent: RawFd, name: &OsStr, flags: i32) -> Result { + 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 { + 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, pub bytes: Option> } + pub(super) struct Root { pub path: PathBuf, pub identity: Identity, directory: File } + impl Root { + pub fn new(selected: &Path) -> Result { + 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(¤t)?), "selected input root changed"); Ok(()) } + fn walk(&self, path: Option<&Path>, hook: &mut impl FnMut(Step) -> Result<()>) -> Result { + 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 { self.walk(relative, &mut |_| Ok(())) } + pub fn capture(&self, relative: &Path, limit: u64, hash: bool, retain: bool, hook: &mut impl FnMut(Step) -> Result<()>) -> Result { + 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::::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)> { + 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::::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, pub bytes: Option> } + fn unsupported() -> Result { Err("safe no-follow input operations unsupported on this host".into()) } + impl Root { + pub fn new(_: &Path) -> Result { unsupported() } + pub fn check(&self) -> Result<()> { unsupported() } + pub fn directory(&self, _: Option<&Path>) -> Result { unsupported() } + pub fn names(&self, _: &Path, _: usize) -> Result<(Identity, Vec)> { unsupported() } + pub fn capture(&self, _: &Path, _: u64, _: bool, _: bool, _: &mut impl FnMut(Step) -> Result<()>) -> Result { 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, 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()); + } +} diff --git a/crates/stela-drivers/build/linux_registry.rs b/crates/stela-drivers/build/linux_registry.rs new file mode 100644 index 0000000000..ed3688e6f1 --- /dev/null +++ b/crates/stela-drivers/build/linux_registry.rs @@ -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 = std::result::Result; +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, 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, Key, Vec)> { + 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, + /// Complete captured include/config/generated-header dependency closure. + pub dependencies: Vec, +} +#[derive(Clone, Debug)] +pub struct Plan { + pub roots: Vec, 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, pub units: Vec, +} +#[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__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 { + 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> { + 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, + pub expected_error: Option, +} +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 { + 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::>().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 \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}"); + } + +} diff --git a/crates/stela-drivers/build/native.rs b/crates/stela-drivers/build/native.rs index b6afc0fac8..b572a470fc 100644 --- a/crates/stela-drivers/build/native.rs +++ b/crates/stela-drivers/build/native.rs @@ -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"), diff --git a/crates/stela-drivers/src/gpu/compat/linux/kernel/linux.c b/crates/stela-drivers/src/gpu/compat/linux/kernel/linux.c index ca84800f03..8cb06bf479 100644 --- a/crates/stela-drivers/src/gpu/compat/linux/kernel/linux.c +++ b/crates/stela-drivers/src/gpu/compat/linux/kernel/linux.c @@ -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 #include #include #include @@ -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 +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 diff --git a/crates/stela-drivers/src/gpu/compat/linux/kernel/params.c b/crates/stela-drivers/src/gpu/compat/linux/kernel/params.c index 024403a31e..36c714cd62 100644 --- a/crates/stela-drivers/src/gpu/compat/linux/kernel/params.c +++ b/crates/stela-drivers/src/gpu/compat/linux/kernel/params.c @@ -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 #include #include @@ -15,6 +15,254 @@ #include #include +/* 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 +#include +#include +#include +#include +#include + +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, ¶m, &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 +#endif diff --git a/crates/stela-drivers/src/gpu/compat/linux/kernel/registry.c b/crates/stela-drivers/src/gpu/compat/linux/kernel/registry.c new file mode 100644 index 0000000000..1b798b3aa8 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/kernel/registry.c @@ -0,0 +1,1120 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Static registry ownership is Stela code. The setup/early option adapters are + * derived from Linux init/main.c, Copyright (C) 1991, 1992 Linus Torvalds + * (Linux pin cc9de5d4), retaining the original + * prefix, warning and consumed conventions. No driver initializer is copied. + * One entered serialized Linux context; no native interrupt/module loader ABI. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PARSE_PASSES 10U /* early, initial, then levels 0..7 */ +struct stela_linux_registry { + const struct stela_linux_registry_image *image; + struct stela_linux_registration_status *status; + const struct kernel_param **parameters; + size_t *completed; + char *arguments; + char *parse_results[PARSE_PASSES]; + unsigned int parsed_passes; + size_t allocation_size, stride, record_count, completed_count; + unsigned int option_phase, next_stage; + bool busy, quarantined, parameter_error, retired; + struct stela_linux_registry_report report; +}; +static struct stela_linux_registry *active; +static const struct stela_linux_registry_image *owned_image; +static bool permanently_retired; +#ifdef STELA_LINUX_REGISTRY_TEST +static bool fail_registry_allocation; +static size_t registry_allocations, registry_releases; +#endif + +struct call_guard { + struct stela_linux_lease lease; + const struct stela_linux_services *services; + void *context; +}; +struct parse_context { + struct stela_linux_registry *registry; + const struct call_guard *guard; + const struct stela_linux_registry_unknown_options *policy; + bool early, positive_callback; +}; + +static int guard_begin(struct call_guard *guard) +{ + stela_linux_lease_snapshot(&guard->lease); + if (!guard->lease.owner || !stela_linux_quiescent()) + return -EPERM; + guard->services = guard->lease.owner->services; + guard->context = guard->lease.owner->context; + return 0; +} +static int guard_check(struct stela_linux_registry *r, const struct call_guard *guard) +{ + if (!stela_linux_lease_matches(&guard->lease) || + guard->lease.owner->services != guard->services || + guard->lease.owner->context != guard->context || !stela_linux_quiescent()) { + r->quarantined = true; + r->report.terminal = 1; + r->report.last_error = -EPROTO; + return -EPROTO; + } + return 0; +} +static int enter_call(struct stela_linux_registry *r, struct call_guard *guard) +{ + if (!r || r != active || r->retired) + return -EINVAL; + if (r->quarantined) + return -EPROTO; + if (r->busy) + return -EBUSY; + int error = guard_begin(guard); + if (!error) + r->busy = true; + return error; +} +static int leave_call(struct stela_linux_registry *r, const struct call_guard *guard, + int error, struct stela_linux_registry_report *out) +{ + int fault = guard_check(r, guard); + if (!fault) + r->busy = false; + r->report.next_stage = r->next_stage; + if (out) + *out = r->report; + return fault ?: error; +} +static bool add_size(size_t *value, size_t count, size_t item) +{ + if (count > (SIZE_MAX - *value) / item) + return false; + *value += count * item; + return true; +} +static bool aligned_size(size_t *value, size_t align) +{ + if (*value > SIZE_MAX - (align - 1)) + return false; + *value = (*value + align - 1) & ~(align - 1); + return true; +} +static size_t status_offset(const struct stela_linux_registry_image *im, unsigned kind) +{ + size_t n = 0; + if (kind == STELA_LINUX_REG_INIT || kind == STELA_LINUX_REG_MODULE_INIT || + kind == STELA_LINUX_REG_CONSOLE) + return n; + n += im->init_count; + if (kind == STELA_LINUX_REG_EXIT || kind == STELA_LINUX_REG_MODULE_EXIT) + return n; + n += im->exit_count; + if (kind == STELA_LINUX_REG_PARAMETER) + return n; + n += im->parameter_count; + if (kind == STELA_LINUX_REG_INFO) + return n; + n += im->info_count; + if (kind == STELA_LINUX_REG_DEVICE) + return n; + return n + im->device_count; +} +static const struct stela_linux_registration_header *record_header( + const struct stela_linux_registry_image *im, size_t index) +{ + if (index < im->init_count) return &im->inits[index]->header; + index -= im->init_count; + if (index < im->exit_count) return &im->exits[index]->header; + index -= im->exit_count; + if (index < im->parameter_count) return &im->parameters[index]->header; + index -= im->parameter_count; + if (index < im->info_count) return &im->infos[index]->header; + index -= im->info_count; + if (index < im->device_count) return &im->devices[index]->header; + index -= im->device_count; + return &im->setups[index]->header; +} +static bool group_member(const struct stela_linux_registry_image *im, + const struct stela_linux_build_group *group) +{ + for (size_t i = 0; i < im->group_count; ++i) + if (im->groups[i] == group) return true; + return false; +} +static size_t unit_index(const struct stela_linux_registry_image *im, + const struct stela_linux_build_unit *unit) +{ + for (size_t i = 0; i < im->unit_count; ++i) + if (im->units[i] == unit) return i; + return im->unit_count; +} +static int header_shape(const struct stela_linux_registry_image *im, + const struct stela_linux_registration_header *h, + const struct stela_linux_build_group *group, + const struct stela_linux_build_unit *unit, const char *label) +{ + if (!h || h->abi_version != STELA_LINUX_REGISTRY_ABI || !label || + !group_member(im, group) || unit_index(im, unit) == im->unit_count || + unit->group != group || h->unit_ordinal != unit->ordinal) + return -EINVAL; + if (h->flags & ~STELA_LINUX_REG_SYNC) + return -EOPNOTSUPP; + return 0; +} +/* No callback/allocation precedes complete static shape/relationship checking. + * Pointer readability, full strings, source provenance and pinned lifetime are + * producer obligations; C cannot validate arbitrary foreign addresses. */ +static int image_shape(const struct stela_linux_registry_image *im, size_t *total) +{ + if (!im || im->abi_version != STELA_LINUX_REGISTRY_ABI || im->reserved || + (im->init_count && !im->inits) || (im->exit_count && !im->exits) || + (im->parameter_count && !im->parameters) || (im->info_count && !im->infos) || + (im->device_count && !im->devices) || (im->setup_count && !im->setups) || + (im->group_count && !im->groups) || (im->unit_count && !im->units) || + im->parameter_count > UINT_MAX) + return -EINVAL; + size_t n = 0; + const size_t counts[] = {im->init_count, im->exit_count, im->parameter_count, + im->info_count, im->device_count, im->setup_count}; + for (size_t i = 0; i < ARRAY_SIZE(counts); ++i) + if (!add_size(&n, counts[i], 1)) return -EOVERFLOW; + if (n > SIZE_MAX / sizeof(struct stela_linux_registration_status) || + im->group_count > SIZE_MAX / sizeof(void *) || im->unit_count > SIZE_MAX / sizeof(void *)) + return -EOVERFLOW; + for (size_t i = 0; i < im->group_count; ++i) { + const struct stela_linux_build_group *g = im->groups[i]; + if (!g || g->abi_version != STELA_LINUX_REGISTRY_ABI || g->reserved || + !g->module_name || !*g->module_name || !g->module_file || !*g->module_file || + !g->provenance || !*g->provenance) + return -EINVAL; + for (size_t j = 0; j < i; ++j) + if (im->groups[j] == g || (im->groups[j]->domain_ordinal == g->domain_ordinal && + im->groups[j]->group_ordinal == g->group_ordinal)) return -EINVAL; + } + for (size_t i = 0; i < im->unit_count; ++i) { + const struct stela_linux_build_unit *u = im->units[i]; + if (!u || u->abi_version != STELA_LINUX_REGISTRY_ABI || !group_member(im, u->group) || + !u->source_path || !*u->source_path || !u->provenance || !*u->provenance) + return -EINVAL; + for (size_t j = 0; j < i; ++j) + if (im->units[j] == u || im->units[j]->ordinal == u->ordinal) return -EINVAL; + } +#define CHECK_RECORD(rec) do { \ + if (!(rec)) return -EINVAL; \ + int shape = header_shape(im, &(rec)->header, (rec)->group, (rec)->unit, (rec)->label); \ + if (shape) return shape; \ +} while (0) + for (size_t i = 0; i < im->init_count; ++i) { + const struct stela_linux_init_record *v = im->inits[i]; CHECK_RECORD(v); + const struct stela_linux_registration_header *h = &v->header; + if (!v->target) return -EINVAL; + if (h->kind == STELA_LINUX_REG_MODULE_INIT) { + if (h->level != 6 || h->flags) return -EINVAL; + for (size_t j = 0; j < i; ++j) + if (im->inits[j]->header.kind == STELA_LINUX_REG_MODULE_INIT && + im->inits[j]->group == v->group) return -EINVAL; + } else if (h->kind == STELA_LINUX_REG_CONSOLE) { + if (h->level != STELA_LINUX_REG_CONSOLE_LEVEL || h->flags) return -EINVAL; + } else if (h->kind == STELA_LINUX_REG_INIT) { + if (!((h->level >= 0 && h->level <= 7) || h->level == STELA_LINUX_REG_EARLY_LEVEL || + h->level == STELA_LINUX_REG_ROOTFS_LEVEL) || (h->level < 1 && h->flags)) return -EINVAL; + } else return -EINVAL; + } + for (size_t i = 0; i < im->exit_count; ++i) { + const struct stela_linux_exit_record *v = im->exits[i]; CHECK_RECORD(v); + if (!v->target || v->header.level != -1 || v->header.flags || + (v->header.kind != STELA_LINUX_REG_EXIT && v->header.kind != STELA_LINUX_REG_MODULE_EXIT)) + return -EINVAL; + if (v->header.kind == STELA_LINUX_REG_MODULE_EXIT) + for (size_t j = 0; j < i; ++j) + if (im->exits[j]->header.kind == STELA_LINUX_REG_MODULE_EXIT && + im->exits[j]->group == v->group) return -EINVAL; + } + for (size_t i = 0; i < im->parameter_count; ++i) { + const struct stela_linux_parameter_record *v = im->parameters[i]; CHECK_RECORD(v); + const struct kernel_param *p = v->target; + if (!p || !p->name || !p->ops || v->header.kind != STELA_LINUX_REG_PARAMETER || + v->header.flags || p->level < -1 || p->level > 7 || v->header.level != p->level) + return -EINVAL; + if (p->flags & ~(KERNEL_PARAM_FL_UNSAFE | KERNEL_PARAM_FL_HWPARAM) || + p->ops->flags & ~KERNEL_PARAM_OPS_FL_NOARG) return -EOPNOTSUPP; + for (size_t j = 0; j < i; ++j) + if (im->parameters[j]->target == p) return -EINVAL; + } + for (size_t i = 0; i < im->setup_count; ++i) { + const struct stela_linux_setup_record *v = im->setups[i]; CHECK_RECORD(v); + if (v->header.level != -1 || v->header.flags || + (v->header.kind != STELA_LINUX_REG_SETUP && v->header.kind != STELA_LINUX_REG_EARLY) || + (v->header.kind == STELA_LINUX_REG_EARLY && !v->target)) return -EINVAL; + } +#undef CHECK_RECORD + for (size_t i = 0; i < im->info_count; ++i) { + const struct stela_linux_info_record *v = im->infos[i]; + if (!v) return -EINVAL; + int error = header_shape(im, &v->header, v->group, v->unit, v->tag); + if (error) return error; + if (!v->text || v->header.kind != STELA_LINUX_REG_INFO || v->header.level != -1 || + v->header.flags) return -EINVAL; + } + for (size_t i = 0; i < im->device_count; ++i) { + const struct stela_linux_device_record *v = im->devices[i]; + if (!v) return -EINVAL; + int error = header_shape(im, &v->header, v->group, v->unit, v->type); + if (error) return error; + if (!v->table || !v->size || v->header.kind != STELA_LINUX_REG_DEVICE || + v->header.level != -1 || v->header.flags) return -EINVAL; + } + /* Global sequence uniqueness; each typed array retains source/link order. */ + for (size_t i = 0; i < n; ++i) { + const struct stela_linux_registration_header *h = record_header(im, i); + for (size_t j = 0; j < i; ++j) { + const struct stela_linux_registration_header *p = record_header(im, j); + if (p->unit_ordinal == h->unit_ordinal && p->emission_sequence == h->emission_sequence) + return -EINVAL; + } + } + size_t off = 0; + for (size_t a = 0; a < ARRAY_SIZE(counts); ++a) { + for (size_t j = 1; j < counts[a]; ++j) { + const struct stela_linux_registration_header *prev = record_header(im, off + j - 1); + const struct stela_linux_registration_header *cur = record_header(im, off + j); + size_t pi = im->unit_count, ci = im->unit_count; + for (size_t k = 0; k < im->unit_count; ++k) { + if (im->units[k]->ordinal == prev->unit_ordinal) pi = k; + if (im->units[k]->ordinal == cur->unit_ordinal) ci = k; + } + if (pi > ci || (pi == ci && prev->emission_sequence >= cur->emission_sequence)) + return -EINVAL; + } + off += counts[a]; + } + *total = n; + return 0; +} +int stela_linux_registry_begin(const struct stela_linux_registry_image *im, + const char *bytes, size_t length, struct stela_linux_registry **out) +{ + if (!out) return -EINVAL; + *out = NULL; + struct call_guard guard; + int error = guard_begin(&guard); + if (error) return error; + if (active || owned_image || permanently_retired) return -EBUSY; + if ((!bytes && length) || length == SIZE_MAX) return -EINVAL; + /* Original next_arg indexes one token with unsigned int. Preserve that + * admitted domain; do not wrap its genuine loop for a >4GiB token. */ + if (length > UINT_MAX) return -E2BIG; + if (length && memchr(bytes, 0, length)) return -EINVAL; + size_t records; + error = image_shape(im, &records); + if (error) return error; + /* Every diagnostic/status counter is exact; reject an unrepresentable worst + * case before callbacks instead of wrapping a progress ledger. */ + size_t bound = 0; + if (im->setup_count == SIZE_MAX || + !add_size(&bound, length + 1, im->setup_count + 1) || + bound > (SIZE_MAX - im->init_count - im->exit_count) / PARSE_PASSES) + return -EOVERFLOW; + size_t size = sizeof(struct stela_linux_registry), status_at, view_at, order_at, args_at; + if (!aligned_size(&size, __alignof__(struct stela_linux_registration_status))) return -EOVERFLOW; + status_at = size; + if (!add_size(&size, records, sizeof(struct stela_linux_registration_status)) || + !aligned_size(&size, __alignof__(const struct kernel_param *))) return -EOVERFLOW; + view_at = size; + if (!add_size(&size, im->parameter_count, sizeof(const struct kernel_param *)) || + !aligned_size(&size, __alignof__(size_t))) return -EOVERFLOW; + order_at = size; + if (!add_size(&size, im->init_count, sizeof(size_t))) return -EOVERFLOW; + args_at = size; + if (!add_size(&size, PARSE_PASSES, length + 1)) return -EOVERFLOW; + struct stela_linux_registry *r; +#ifdef STELA_LINUX_REGISTRY_TEST + r = fail_registry_allocation ? NULL : stela_linux_heap_alloc(size, __alignof__(*r)); + if (r) registry_allocations++; +#else + r = stela_linux_heap_alloc(size, __alignof__(*r)); +#endif + if (!r) return -ENOMEM; + memset(r, 0, size); + r->image = im; + r->status = (void *)((char *)r + status_at); + r->parameters = (void *)((char *)r + view_at); + r->completed = (void *)((char *)r + order_at); + r->arguments = (char *)r + args_at; + r->allocation_size = size; + r->stride = length + 1; + r->record_count = records; + for (size_t i = 0; i < PARSE_PASSES; ++i) { + if (length) memcpy(r->arguments + i * r->stride, bytes, length); + r->arguments[i * r->stride + length] = 0; + } + for (size_t i = 0; i < im->parameter_count; ++i) r->parameters[i] = im->parameters[i]->target; + for (size_t i = 0; i < records; ++i) { + const struct stela_linux_registration_header *h = record_header(im, i); + r->status[i].kind = h->kind; + r->status[i].unit_ordinal = h->unit_ordinal; + r->status[i].emission_sequence = h->emission_sequence; + r->status[i].level = h->level; + } + /* Heap service is canonical and cannot transfer Linux execution ownership. */ + if (guard_check(r, &guard)) { + active = r; owned_image = im; /* quarantine: never free via changed context */ + return -EPROTO; + } + active = r; + owned_image = im; + *out = r; + return 0; +} +static void started(struct stela_linux_registry *r, size_t index) +{ + r->status[index].state = STELA_LINUX_RECORD_RUNNING; + r->status[index].invocations++; + r->report.invocations++; +} +static void returned(struct stela_linux_registry *r, size_t index, int result) +{ + struct stela_linux_registration_status *s = &r->status[index]; + s->returned = result; + s->state = result < 0 ? STELA_LINUX_RECORD_NEGATIVE : + result > 0 ? STELA_LINUX_RECORD_POSITIVE : STELA_LINUX_RECORD_ZERO; + if (result < 0) r->report.returned_negative++; + else if (result > 0) r->report.returned_positive++; + else r->report.returned_zero++; +} +static int observe(void *argument, enum stela_linux_param_event event, + const struct kernel_param *parameter, char *param, char *val, int result) +{ + struct parse_context *c = argument; + struct stela_linux_registry *r = c->registry; + (void)param; (void)val; + int error = guard_check(r, c->guard); + if (error) return error; + if ((event == STELA_LINUX_PARAM_AFTER_SET || event == STELA_LINUX_PARAM_AFTER_UNKNOWN) && result > 0) + c->positive_callback = true; + if (!parameter) return 0; + for (size_t i = 0; i < r->image->parameter_count; ++i) + if (r->parameters[i] == parameter) { + size_t index = status_offset(r->image, STELA_LINUX_REG_PARAMETER) + i; + if (event == STELA_LINUX_PARAM_BEFORE_SET) started(r, index); + else if (event == STELA_LINUX_PARAM_AFTER_SET) returned(r, index, result); + return 0; + } + return -EPROTO; +} +/* Original init/main.c repair_env_string, with an explicit terminal boundary + * for its impossible tokenizer-shape BUG. */ +static void repair_env_string(char *param, char *val) +{ + if (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 __builtin_trap(); + } +} +static int option_unknown(char *param, char *val, const char *doing, void *argument) +{ + struct parse_context *c = argument; + struct stela_linux_registry *r = c->registry; + const struct stela_linux_registry_image *im = r->image; + (void)doing; + bool had_early = false; + if (!c->early) repair_env_string(param, val); + for (size_t i = 0; i < im->setup_count; ++i) { + const struct stela_linux_setup_record *s = im->setups[i]; + bool is_early = s->header.kind == STELA_LINUX_REG_EARLY; + size_t n = strlen(s->label); + if (c->early ? (!is_early || !parameq(param, s->label)) : !parameqn(param, s->label, n)) + continue; + if (!c->early && is_early) { + if (!param[n] || param[n] == '=') had_early = true; + continue; + } + size_t index = status_offset(im, STELA_LINUX_REG_SETUP) + i; + if (guard_check(r, c->guard)) return -EPROTO; + if (!s->target) { + pr_warn("Parameter %s is obsolete, ignored\n", s->label); + r->status[index].warnings++; r->report.warnings++; + r->status[index].consumed++; r->report.consumed++; + return guard_check(r, c->guard) ?: 0; + } + started(r, index); + int ret = s->target(c->early ? val : param + n); + returned(r, index, ret); + if (guard_check(r, c->guard)) return -EPROTO; + if (c->early) { + if (ret) { + pr_warn("Malformed early option '%s'\n", param); + r->status[index].warnings++; r->report.warnings++; + if (guard_check(r, c->guard)) return -EPROTO; + } + } else if (ret) { + r->status[index].consumed++; r->report.consumed++; + return 0; + } + } + if (c->early || had_early) { + if (had_early) r->report.consumed++; + return 0; + } + r->report.unhandled++; + if (!c->policy || !c->policy->unhandled_option) return -ENOENT; + int ret = c->policy->unhandled_option(c->policy->context, param); + return guard_check(r, c->guard) ?: ret; +} +static int ignore_unknown(char *param, char *val, const char *doing, void *argument) +{ + (void)param; (void)val; (void)doing; (void)argument; + return 0; +} +static int parse_pass(struct stela_linux_registry *r, const struct call_guard *guard, + unsigned int pass, int level, bool early, + const struct stela_linux_registry_unknown_options *policy) +{ + struct parse_context c = {.registry = r, .guard = guard, .policy = policy, .early = early}; + const struct stela_linux_param_observer observer = {.observe = observe, .context = &c}; + bool initial = pass < 2; + struct stela_linux_params_result parsed = stela_linux_parse_args_view( + early ? "early options" : initial ? "Booting kernel" : "initcall", + r->arguments + pass * r->stride, early ? NULL : r->parameters, + early ? 0 : (unsigned int)r->image->parameter_count, (s16)level, (s16)level, + &c, initial ? option_unknown : ignore_unknown, &observer); + r->parse_results[pass] = parsed.result; + r->parsed_passes |= 1U << pass; + if (parsed.observer_error) { + r->quarantined = true; r->report.terminal = 1; + r->report.last_error = parsed.observer_error; + return parsed.observer_error; + } + if (guard_check(r, guard)) return -EPROTO; + int error = IS_ERR(parsed.result) ? (int)PTR_ERR(parsed.result) : 0; + if (!error && parsed.result) { + unsigned long value = (unsigned long)parsed.result; + unsigned long start = (unsigned long)(r->arguments + pass * r->stride); + /* Original parse_args encodes a positive callback result as ERR_PTR(ret), + * which IS_ERR cannot recognize. Preserve those exact source bytes/result, + * but never grant startup on that invalid callback contract or treat a low + * integer as a -- tail (even if its address aliases a low native heap). */ + if (c.positive_callback || value < start || value - start >= r->stride) error = -EPROTO; + } + if (error) { r->parameter_error = true; r->report.last_error = error; } + /* Every pass keeps its writable bytes and original -- tail alive. No Linux + * init argv/env policy or ownership of arbitrary tail consumers is invented. */ + return error; +} +int stela_linux_registry_early_parameters(struct stela_linux_registry *r, + struct stela_linux_registry_report *out) +{ + struct call_guard guard; + int error = enter_call(r, &guard); + if (error) return error; + if (r->option_phase || r->parameter_error) error = -EALREADY; + else { r->option_phase = 1; error = parse_pass(r, &guard, 0, 0, true, NULL); } + return leave_call(r, &guard, error, out); +} +int stela_linux_registry_initial_parameters(struct stela_linux_registry *r, + const struct stela_linux_registry_unknown_options *policy, + struct stela_linux_registry_report *out) +{ + struct call_guard guard; + int error = enter_call(r, &guard); + if (error) return error; + if (r->option_phase != 1 || r->parameter_error) error = -EALREADY; + else { r->option_phase = 2; error = parse_pass(r, &guard, 1, -1, false, policy); } + return leave_call(r, &guard, error, out); +} +static bool stage_record(const struct stela_linux_init_record *v, unsigned int stage, unsigned sync) +{ + if (stage == STELA_LINUX_STAGE_CONSOLE) return v->header.kind == STELA_LINUX_REG_CONSOLE; + if (stage == STELA_LINUX_STAGE_EARLY) + return v->header.kind == STELA_LINUX_REG_INIT && v->header.level == STELA_LINUX_REG_EARLY_LEVEL; + int level = (int)stage - STELA_LINUX_STAGE_PURE; + if (sync == 2) return level == 5 && v->header.level == STELA_LINUX_REG_ROOTFS_LEVEL; + return v->header.kind != STELA_LINUX_REG_CONSOLE && v->header.level == level && + (unsigned int)!!(v->header.flags & STELA_LINUX_REG_SYNC) == sync; +} +int stela_linux_registry_run_stage(struct stela_linux_registry *r, unsigned int stage, + struct stela_linux_registry_report *out) +{ + struct call_guard guard; + int error = enter_call(r, &guard); + if (error) return error; + if (r->option_phase != 2 || r->parameter_error || stage != r->next_stage || + stage >= STELA_LINUX_STAGE_DONE) + return leave_call(r, &guard, -EINVAL, out); + if (stage >= STELA_LINUX_STAGE_PURE) { + unsigned level = stage - STELA_LINUX_STAGE_PURE; + error = parse_pass(r, &guard, level + 2, (int)level, false, NULL); + if (error) return leave_call(r, &guard, error, out); + } + if (stage == STELA_LINUX_STAGE_CONSOLE) { +#ifdef CONFIG_NULL_TTY_DEFAULT_CONSOLE + /* Genuine preferred-console state/provider must be supplied before enabling + * this configuration. No invented default-console policy. */ + return leave_call(r, &guard, -EOPNOTSUPP, out); +#else + n_tty_init(); + if (guard_check(r, &guard)) return leave_call(r, &guard, -EPROTO, out); +#endif + } + int first_error = 0; + unsigned passes = stage == STELA_LINUX_STAGE_FS ? 3 : stage >= STELA_LINUX_STAGE_PURE ? 2 : 1; + for (unsigned sync = 0; sync < passes; ++sync) + for (size_t i = 0; i < r->image->init_count; ++i) { + const struct stela_linux_init_record *v = r->image->inits[i]; + if (!stage_record(v, stage, sync)) continue; + started(r, i); + int ret = v->target(); + returned(r, i, ret); + if (guard_check(r, &guard)) return leave_call(r, &guard, -EPROTO, out); + if (v->header.kind == STELA_LINUX_REG_MODULE_INIT && !ret) + r->completed[r->completed_count++] = i; + if (ret < 0) { if (!first_error) first_error = ret; r->report.last_error = ret; } + else if (ret > 0 && v->header.kind != STELA_LINUX_REG_CONSOLE) { + pr_warn("initcall %s returned with positive result %d\n", v->label, ret); + r->status[i].warnings++; r->report.warnings++; + if (guard_check(r, &guard)) return leave_call(r, &guard, -EPROTO, out); + } + } + r->next_stage++; + return leave_call(r, &guard, first_error, out); +} +int stela_linux_registry_status(const struct stela_linux_registry *r, size_t index, + struct stela_linux_registration_status *out) +{ + struct call_guard guard; + if (!r || r != active || !out || index >= r->record_count) return -EINVAL; + int error = guard_begin(&guard); + if (error) return error; + *out = r->status[index]; + return 0; +} +int stela_linux_registry_parse_result(const struct stela_linux_registry *r, unsigned int pass, + char **out) +{ + struct call_guard guard; + if (!r || r != active || !out || pass >= PARSE_PASSES || !(r->parsed_passes & (1U << pass))) + return -EINVAL; + int error = guard_begin(&guard); + if (error) return error; + *out = r->parse_results[pass]; + return 0; +} +static const struct stela_linux_exit_record *paired_exit( + const struct stela_linux_registry_image *im, const struct stela_linux_build_group *group, + size_t *index) +{ + for (size_t i = 0; i < im->exit_count; ++i) + if (im->exits[i]->header.kind == STELA_LINUX_REG_MODULE_EXIT && im->exits[i]->group == group) { + *index = i; + return im->exits[i]; + } + return NULL; +} +int stela_linux_registry_retire(struct stela_linux_registry **handle, + const struct stela_linux_registry_retirement *authority) +{ + if (!handle) return -EINVAL; + struct stela_linux_registry *r = *handle; + struct call_guard guard; + int error = enter_call(r, &guard); + if (error) return error; + const struct stela_linux_registry_image *im = r->image; + if (!authority || !authority->drain_all_consumers || authority->image != im || + authority->group_count != im->group_count || (im->group_count && !authority->groups)) + return leave_call(r, &guard, -EOPNOTSUPP, NULL); + for (size_t i = 0; i < im->group_count; ++i) + if (authority->groups[i] != im->groups[i]) + return leave_call(r, &guard, -EOPNOTSUPP, NULL); + /* There is no invented inverse for arbitrary builtin/console initcalls. Any + * invoked one is conservatively permanent, including a failed one with + * unknown residual effects. Do not free values it may still reference. */ + for (size_t i = 0; i < im->init_count; ++i) { + const struct stela_linux_init_record *v = im->inits[i]; + if (r->status[i].invocations && v->header.kind != STELA_LINUX_REG_MODULE_INIT) + return leave_call(r, &guard, -EOPNOTSUPP, NULL); + } + for (size_t i = 0; i < r->completed_count; ++i) { + size_t ignored; + if (!paired_exit(im, im->inits[r->completed[i]]->group, &ignored)) + return leave_call(r, &guard, -EOPNOTSUPP, NULL); + } + error = authority->drain_all_consumers(authority->context); + if (guard_check(r, &guard)) return leave_call(r, &guard, -EPROTO, NULL); + if (error) return leave_call(r, &guard, error < 0 ? error : -EPROTO, NULL); + /* Once actual draining has committed, context faults quarantine the remaining + * state. No repeat drain/exit/free is then possible through this handle. */ + for (size_t n = r->completed_count; n; --n) { + size_t i; + const struct stela_linux_exit_record *v = paired_exit(im, im->inits[r->completed[n-1]]->group, &i); + size_t index = status_offset(im, STELA_LINUX_REG_EXIT) + i; + started(r, index); + v->target(); + returned(r, index, 0); + if (guard_check(r, &guard)) return leave_call(r, &guard, -EPROTO, NULL); + } + stela_linux_rcu_finish(); + if (guard_check(r, &guard)) return leave_call(r, &guard, -EPROTO, NULL); + for (size_t i = 0; i < im->parameter_count; ++i) { + const struct kernel_param *p = im->parameters[i]->target; + if (p->ops->free) { + p->ops->free(p->arg); + if (guard_check(r, &guard)) return leave_call(r, &guard, -EPROTO, NULL); + } + } + stela_linux_rcu_finish(); + if (guard_check(r, &guard)) return leave_call(r, &guard, -EPROTO, NULL); + size_t size = r->allocation_size; + r->retired = true; + permanently_retired = true; + active = NULL; + *handle = NULL; + stela_linux_heap_free(r, size, __alignof__(*r)); +#ifdef STELA_LINUX_REGISTRY_TEST + registry_releases++; +#endif + return 0; +} + +#ifdef STELA_LINUX_REGISTRY_TEST +#include +#include +#include +/* Each finite scenario runs in its own process. This never resets production + * singleton/retirement state or turns a returned callback into a fake driver. */ +int stela_test_registry_case(void (*run)(void)); +static unsigned events[128], event_count, drains, frees, live_i2c; +static bool consumers_stopped; +static const char *retained_value; +static struct stela_linux_registry *test_registry; +static struct stela_linux_owner *mutable_owner; +static void event(unsigned id) { assert(event_count < ARRAY_SIZE(events)); events[event_count++] = id; } +#define INIT_FN(n, result) static int init_##n(void) { event(n); return result; } +INIT_FN(1, 0) INIT_FN(2, -ENODEV) INIT_FN(3, 0) +INIT_FN(10, 0) INIT_FN(11, 0) INIT_FN(12, 0) INIT_FN(13, 0) +INIT_FN(14, 0) INIT_FN(15, 0) INIT_FN(16, 0) INIT_FN(17, 0) +INIT_FN(18, 0) INIT_FN(19, 0) INIT_FN(20, 0) INIT_FN(21, 0) +INIT_FN(22, 0) INIT_FN(23, 0) INIT_FN(24, 0) +INIT_FN(26, 3) INIT_FN(27, -EINVAL) INIT_FN(28, 0) +#undef INIT_FN +static void exit_1(void) { assert(consumers_stopped && !live_i2c); event(101); } +static void exit_2(void) { event(102); assert(0); } +static void exit_3(void) { assert(consumers_stopped && !live_i2c); event(103); } +static int drain_consumers(void *context) +{ + assert(context == &live_i2c); + drains++; + if (live_i2c) return -EBUSY; + consumers_stopped = true; + return 0; +} +static int set_retained(const char *v, const struct kernel_param *p) +{ + assert(p->arg == &retained_value); + retained_value = v; + event(50); + return 0; +} +static void free_retained(void *arg) +{ + assert(arg == &retained_value && consumers_stopped); + assert(event_count >= 2 && events[event_count-1] == 101 && events[event_count-2] == 103); + assert(!strcmp(retained_value, "kept after owner exit")); + frees++; event(150); +} +static const struct kernel_param_ops retained_ops = {.set = set_retained, .free = free_retained}; +struct registry_fixture { + struct stela_linux_build_group group[3]; + const struct stela_linux_build_group *groups[3]; + struct stela_linux_build_unit unit[3]; + const struct stela_linux_build_unit *units[3]; + struct stela_linux_init_record init[24]; + const struct stela_linux_init_record *inits[24]; + struct stela_linux_exit_record exit[3]; + const struct stela_linux_exit_record *exits[3]; + struct stela_linux_parameter_record parameter[3]; + const struct stela_linux_parameter_record *parameters[3]; + struct stela_linux_setup_record setup[10]; + const struct stela_linux_setup_record *setups[10]; + struct stela_linux_registry_image image; + u32 sequence[3]; +}; +static void fixture_init(struct registry_fixture *f) +{ + memset(f, 0, sizeof(*f)); + for (unsigned i = 0; i < 3; ++i) { + f->group[i] = (struct stela_linux_build_group){.abi_version = 1, .domain_ordinal = 7, + .group_ordinal = i + 1, .module_name = "same-name", .module_file = "fixture/real-group", + .provenance = "explicit test-only compiled cohort"}; + f->unit[i] = (struct stela_linux_build_unit){.abi_version = 1, .ordinal = i + 1, + .group = &f->group[i], .source_path = "fixture/unit.c", .provenance = "reviewed link position"}; + f->groups[i] = &f->group[i]; f->units[i] = &f->unit[i]; + } + f->image = (struct stela_linux_registry_image){.abi_version = 1, + .inits = f->inits, .exits = f->exits, .parameters = f->parameters, .setups = f->setups, + .groups = f->groups, .group_count = 3, .units = f->units, .unit_count = 3}; +} +static struct stela_linux_registration_header fixture_header(struct registry_fixture *f, + unsigned u, unsigned kind, int level, unsigned flags) +{ + return (struct stela_linux_registration_header){.abi_version = 1, .kind = (u16)kind, + .level = (s8)level, .flags = (u8)flags, .unit_ordinal = u + 1, .emission_sequence = f->sequence[u]++}; +} +static void fixture_call(struct registry_fixture *f, unsigned u, unsigned kind, int level, + unsigned flags, initcall_t fn) +{ + size_t i = f->image.init_count++; + f->init[i] = (struct stela_linux_init_record){.header = fixture_header(f,u,kind,level,flags), + .group = &f->group[u], .unit = &f->unit[u], .label = "original-static-init", .target = fn}; + f->inits[i] = &f->init[i]; +} +static void fixture_exit(struct registry_fixture *f, unsigned u, exitcall_t fn) +{ + size_t i = f->image.exit_count++; + f->exit[i] = (struct stela_linux_exit_record){.header = fixture_header(f,u,STELA_LINUX_REG_MODULE_EXIT,-1,0), + .group = &f->group[u], .unit = &f->unit[u], .label = "original-static-exit", .target = fn}; + f->exits[i] = &f->exit[i]; +} +static void fixture_parameter(struct registry_fixture *f, unsigned u, const struct kernel_param *p) +{ + size_t i = f->image.parameter_count++; + f->parameter[i] = (struct stela_linux_parameter_record){ + .header = fixture_header(f,u,STELA_LINUX_REG_PARAMETER,p->level,0), + .group = &f->group[u], .unit = &f->unit[u], .label = p->name, .target = p}; + f->parameters[i] = &f->parameter[i]; +} +static void fixture_setup(struct registry_fixture *f, unsigned u, bool early, + const char *name, int (*fn)(char *)) +{ + size_t i = f->image.setup_count++; + f->setup[i] = (struct stela_linux_setup_record){ + .header = fixture_header(f,u,early ? STELA_LINUX_REG_EARLY : STELA_LINUX_REG_SETUP,-1,0), + .group = &f->group[u], .unit = &f->unit[u], .label = name, .target = fn}; + f->setups[i] = &f->setup[i]; +} +static void begin_fixture(struct registry_fixture *f, const char *args) +{ + assert(!stela_linux_registry_begin(&f->image, args, strlen(args), &test_registry)); + assert(test_registry && test_registry == active); +} +static void option_phases(void) +{ + assert(!stela_linux_registry_early_parameters(test_registry, NULL)); + assert(!stela_linux_registry_initial_parameters(test_registry, NULL, NULL)); +} +static void all_stages(int device_error) +{ + for (unsigned stage = 0; stage < STELA_LINUX_STAGE_DONE; ++stage) + assert(stela_linux_registry_run_stage(test_registry, stage, NULL) == + (stage == STELA_LINUX_STAGE_DEVICE ? device_error : 0)); +} +static struct stela_linux_registry_retirement fixture_authority(struct registry_fixture *f) +{ + return (struct stela_linux_registry_retirement){.image = &f->image, + .groups = f->groups, .group_count = 3, .drain_all_consumers = drain_consumers, + .context = &live_i2c}; +} +static void lifecycle_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + fixture_call(&f,0,STELA_LINUX_REG_MODULE_INIT,6,0,init_1); + fixture_call(&f,1,STELA_LINUX_REG_MODULE_INIT,6,0,init_2); + fixture_call(&f,2,STELA_LINUX_REG_MODULE_INIT,6,0,init_3); + fixture_exit(&f,0,exit_1); fixture_exit(&f,1,exit_2); fixture_exit(&f,2,exit_3); + struct kernel_param p = {.name = "borrow", .ops = &retained_ops, .level = -1, .arg = &retained_value}; + fixture_parameter(&f,0,&p); + begin_fixture(&f, "borrow=\"kept after owner exit\""); + option_phases(); + assert(event_count == 1 && events[0] == 50); + const char *kept = retained_value; + stela_linux_exit(); + const struct stela_linux_services s = {}; + const struct stela_linux_owner different = {.services = &s, .context = &f}; + stela_linux_enter(&different); + assert(retained_value == kept && !strcmp(kept,"kept after owner exit")); + assert(stela_linux_registry_run_stage(test_registry,STELA_LINUX_STAGE_DEVICE,NULL) == -EINVAL); + all_stages(-ENODEV); + assert(event_count == 4 && events[1] == 1 && events[2] == 2 && events[3] == 3); + struct stela_linux_registration_status status; + assert(!stela_linux_registry_status(test_registry,1,&status)); + assert(status.state == STELA_LINUX_RECORD_NEGATIVE && status.returned == -ENODEV && status.invocations == 1); + assert(stela_linux_registry_retire(&test_registry,NULL) == -EOPNOTSUPP && !drains && !frees); + struct stela_linux_registry_retirement a = fixture_authority(&f); + a.group_count--; + assert(stela_linux_registry_retire(&test_registry,&a) == -EOPNOTSUPP && !drains); + a.group_count++; + live_i2c = 1; + assert(stela_linux_registry_retire(&test_registry,&a) == -EBUSY && drains == 1 && event_count == 4 && !frees); + assert(!strcmp(retained_value,"kept after owner exit")); + live_i2c = 0; + assert(!stela_linux_registry_retire(&test_registry,&a)); + assert(!test_registry && !active && permanently_retired && frees == 1 && drains == 2); + assert(event_count == 7 && events[4] == 103 && events[5] == 101 && events[6] == 150); + struct stela_linux_registry *second = (void *)1; + assert(stela_linux_registry_begin(&f.image,"",0,&second) == -EBUSY && !second); + stela_linux_exit(); +} +static void ordering_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + /* Unit0 emits sync before normal; reviewed section order still places ALL + * normal calls from BOTH units before either unit's sync entry. */ + fixture_call(&f,0,STELA_LINUX_REG_INIT,1,1,init_13); + fixture_call(&f,0,STELA_LINUX_REG_CONSOLE,-4,0,init_10); + fixture_call(&f,0,STELA_LINUX_REG_INIT,-2,0,init_11); + fixture_call(&f,0,STELA_LINUX_REG_INIT,0,0,init_12); + fixture_call(&f,0,STELA_LINUX_REG_INIT,1,0,init_14); + fixture_call(&f,0,STELA_LINUX_REG_INIT,2,0,init_17); + fixture_call(&f,0,STELA_LINUX_REG_INIT,3,0,init_18); + fixture_call(&f,0,STELA_LINUX_REG_INIT,4,0,init_19); + fixture_call(&f,0,STELA_LINUX_REG_INIT,5,1,init_21); + fixture_call(&f,0,STELA_LINUX_REG_INIT,-3,0,init_22); + fixture_call(&f,0,STELA_LINUX_REG_INIT,5,0,init_20); + fixture_call(&f,0,STELA_LINUX_REG_INIT,6,0,init_23); + fixture_call(&f,0,STELA_LINUX_REG_INIT,7,0,init_24); + fixture_call(&f,1,STELA_LINUX_REG_INIT,1,1,init_16); + fixture_call(&f,1,STELA_LINUX_REG_INIT,1,0,init_15); + begin_fixture(&f, ""); option_phases(); all_stages(0); + const unsigned expected[] = {10,11,12,14,15,13,16,17,18,19,20,21,22,23,24}; + assert(event_count == ARRAY_SIZE(expected) && !memcmp(events,expected,sizeof(expected))); + struct stela_linux_registry_retirement a = fixture_authority(&f); + assert(stela_linux_registry_retire(&test_registry,&a) == -EOPNOTSUPP && !drains); + stela_linux_exit(); /* Permanent original globals/token storage stay pinned. */ +} +static unsigned early_count, normal_count, warnings, policies; +static char policy_option[80]; +static int early_match(char *v) { early_count++; assert(v && !strcmp(v,"abc")); return -EINVAL; } +static int early_second(char *v) { early_count++; assert(v && !strcmp(v,"abc")); return 0; } +static int bare_early(char *v) { early_count++; assert(!v); return 0; } +static int legacy_zero(char *v) { normal_count++; assert(!strcmp(v,"abc")); return 0; } +static int legacy_negative(char *v) { normal_count++; assert(!strcmp(v,"abc")); return -EIO; } +static int suffix_handler(char *v) { normal_count++; assert(!strcmp(v,"Suffix")); return 1; } +static int should_not_run(char *v) { (void)v; assert(0); return 0; } +static void option_log(void *context, int level, const char *message) +{ + assert(context == &warnings); + if (!strcmp(message,"Malformed early option 'same-name'\n")) { assert(level == 4); warnings++; } + else if (!strcmp(message,"Parameter obsolete is obsolete, ignored\n")) { assert(level == 4); warnings++; } +} +static int policy_handler(void *context, char *text) +{ + assert(context == &policies); + policies++; + assert(strlen(text) < sizeof(policy_option)); strcpy(policy_option,text); + return 0; +} +static void option_case(void) +{ + const struct stela_linux_services services = {.log = option_log}; + const struct stela_linux_owner owner = {.services = &services,.context = &warnings}; + stela_linux_enter(&owner); + struct registry_fixture f; fixture_init(&f); + fixture_setup(&f,0,true,"same_name",early_match); + fixture_setup(&f,0,true,"same_name",early_second); + fixture_setup(&f,0,true,"bare",bare_early); + fixture_setup(&f,0,false,"same_name=",legacy_zero); + fixture_setup(&f,0,false,"same_name=",legacy_negative); + fixture_setup(&f,0,false,"prefix",suffix_handler); + fixture_setup(&f,0,false,"obsolete",NULL); + fixture_setup(&f,0,false,"known=",should_not_run); + fixture_setup(&f,0,true,"earlycon",should_not_run); + int known = 0; + struct kernel_param kp = {.name="known",.ops=¶m_ops_int,.level=2,.arg=&known}; + fixture_parameter(&f,0,&kp); + begin_fixture(&f,"same-name=abc bare prefixSuffix obsolete known=9 console=ttyS0 unhandled=\"quoted value\" -- tail untouched"); + assert(!stela_linux_registry_early_parameters(test_registry,NULL)); + assert(early_count == 3 && !normal_count && warnings == 1 && !known); + assert(stela_linux_registry_early_parameters(test_registry,NULL) == -EALREADY && early_count == 3); + struct stela_linux_registry_unknown_options policy = {.unhandled_option=policy_handler,.context=&policies}; + assert(!stela_linux_registry_initial_parameters(test_registry,&policy,NULL)); + assert(early_count == 3 && normal_count == 3 && warnings == 2 && !known); + assert(policies == 2 && !strcmp(policy_option,"unhandled=quoted value")); + char *tail = NULL; + assert(!stela_linux_registry_parse_result(test_registry,1,&tail) && !strcmp(tail,"tail untouched")); + assert(!stela_linux_registry_parse_result(test_registry,0,&tail) && !strcmp(tail,"tail untouched")); + assert(stela_linux_registry_parse_result(test_registry,2,&tail) == -EINVAL); + all_stages(0); + assert(known == 9 && early_count == 3 && normal_count == 3 && policies == 2); + stela_linux_exit(); +} +static int violate_irq(void) { event(60); arch_local_irq_disable(); return 0; } +static int violate_owner(void) { event(61); stela_linux_exit(); stela_linux_enter(&stela_linux_bare); return 0; } +static int violate_same_owner(void) { event(64); stela_linux_exit(); stela_linux_enter(mutable_owner); return 0; } +static int violate_context(void) { event(62); mutable_owner->context = &events; return 0; } +static int reentrant_call(void) +{ + assert(stela_linux_registry_run_stage(test_registry,STELA_LINUX_STAGE_DEVICE,NULL) == -EBUSY); + event(63); return 0; +} +static void context_case_with(initcall_t fn) +{ + struct stela_linux_services services = {}; + struct stela_linux_owner owner = {.services=&services,.context=&drains}; + mutable_owner = &owner; + stela_linux_enter(&owner); + struct registry_fixture f; fixture_init(&f); + fixture_call(&f,0,STELA_LINUX_REG_MODULE_INIT,6,0,fn); + fixture_call(&f,1,STELA_LINUX_REG_MODULE_INIT,6,0,init_3); + begin_fixture(&f, ""); option_phases(); + for (unsigned stage=0;stagequarantined && active == test_registry && event_count == 1 && !frees && !drains); + assert(stela_linux_registry_run_stage(test_registry,STELA_LINUX_STAGE_LATE,NULL) == -EPROTO); + /* Fault state is retained; no counter/owner repair or cleanup is performed. */ +} +static void irq_case(void) { context_case_with(violate_irq); } +static void owner_case(void) { context_case_with(violate_owner); } +static void context_case(void) { context_case_with(violate_context); } +static void same_owner_case(void) { context_case_with(violate_same_owner); } +static void reentry_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + fixture_call(&f,0,STELA_LINUX_REG_MODULE_INIT,6,0,reentrant_call); + begin_fixture(&f, ""); option_phases(); all_stages(0); + assert(event_count == 1 && events[0] == 63 && !test_registry->quarantined); + stela_linux_exit(); +} +static void shape_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + fixture_call(&f,0,STELA_LINUX_REG_MODULE_INIT,6,0,init_1); + struct stela_linux_registry *r=(void *)1; + f.init[0].header.flags=1; + assert(stela_linux_registry_begin(&f.image,"",0,&r) == -EINVAL && !r && !active && !event_count); + f.init[0].header.flags=0; + f.units[1]=f.units[0]; + assert(stela_linux_registry_begin(&f.image,"",0,&r) == -EINVAL && !r && !active); + f.units[1]=&f.unit[1]; + const char embedded[]={'a',0,'b'}; + assert(stela_linux_registry_begin(&f.image,embedded,sizeof(embedded),&r) == -EINVAL && !r && !active); + assert(stela_linux_registry_begin(&f.image,NULL,SIZE_MAX,&r) == -EINVAL && !r && !active); + assert(stela_linux_registry_begin(&f.image,"x",(size_t)UINT_MAX+1,&r) == -E2BIG && !r && !active); + fail_registry_allocation = true; + assert(stela_linux_registry_begin(&f.image,"",0,&r) == -ENOMEM && !r && !active && !owned_image); + assert(!registry_allocations && !registry_releases && !event_count); + fail_registry_allocation = false; + assert(!stela_linux_registry_begin(&f.image,"",0,&r) && r && registry_allocations == 1); + assert(stela_linux_registry_begin(&f.image,"",0,&test_registry) == -EBUSY && !test_registry); + test_registry=r; + assert(stela_linux_registry_initial_parameters(r,NULL,NULL) == -EALREADY); + assert(stela_linux_registry_run_stage(r,STELA_LINUX_STAGE_CONSOLE,NULL) == -EINVAL && !event_count); + stela_linux_exit(); +} +static void parameter_failure_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + fixture_call(&f,0,STELA_LINUX_REG_MODULE_INIT,6,0,init_1); + int first=81, later=82; + struct kernel_param a={.name="first",.ops=¶m_ops_int,.level=-1,.arg=&first}; + struct kernel_param b={.name="later",.ops=¶m_ops_int,.level=-1,.arg=&later}; + fixture_parameter(&f,0,&a); fixture_parameter(&f,0,&b); + begin_fixture(&f,"first=invalid later=42 unknown -- tail"); + assert(!stela_linux_registry_early_parameters(test_registry,NULL)); + struct stela_linux_registry_report report; + assert(stela_linux_registry_initial_parameters(test_registry,NULL,&report) == -ENOENT); + assert(first == 81 && later == 42 && !event_count && report.last_error == -ENOENT); + char *result=NULL; + assert(!stela_linux_registry_parse_result(test_registry,1,&result) && IS_ERR(result) && PTR_ERR(result)==-ENOENT); + assert(stela_linux_registry_initial_parameters(test_registry,NULL,NULL) == -EALREADY); + assert(stela_linux_registry_run_stage(test_registry,0,NULL) == -EINVAL && !event_count); + struct stela_linux_registry_retirement authority=fixture_authority(&f); + assert(!stela_linux_registry_retire(&test_registry,&authority)); + assert(!test_registry && !event_count && drains==1 && registry_releases==1); + stela_linux_exit(); +} +static void missing_exit_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + fixture_call(&f,0,STELA_LINUX_REG_MODULE_INIT,6,0,init_1); + begin_fixture(&f,""); option_phases(); all_stages(0); + struct stela_linux_registry_retirement authority=fixture_authority(&f); + assert(stela_linux_registry_retire(&test_registry,&authority)==-EOPNOTSUPP); + assert(event_count==1 && events[0]==1 && !drains && !registry_releases); + stela_linux_exit(); +} +static void console_returns_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + fixture_call(&f,0,STELA_LINUX_REG_CONSOLE,-4,0,init_26); + fixture_call(&f,0,STELA_LINUX_REG_CONSOLE,-4,0,init_27); + fixture_call(&f,1,STELA_LINUX_REG_CONSOLE,-4,0,init_28); + begin_fixture(&f,""); option_phases(); + struct stela_linux_registry_report report; + assert(stela_linux_registry_run_stage(test_registry,0,&report)==-EINVAL); + assert(event_count==3 && events[0]==26 && events[1]==27 && events[2]==28); + assert(report.returned_positive==1 && report.returned_negative==1 && report.returned_zero==1); + assert(!report.warnings && report.next_stage==STELA_LINUX_STAGE_EARLY); + struct stela_linux_registration_status status; + assert(!stela_linux_registry_status(test_registry,0,&status) && status.returned==3); + assert(!stela_linux_registry_status(test_registry,1,&status) && status.returned==-EINVAL); + assert(!stela_linux_registry_status(test_registry,2,&status) && status.returned==0); + for(unsigned stage=STELA_LINUX_STAGE_EARLY;stagearg=(!strcmp(v,"new")); return 7; +} +static void positive_parameter_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + int value=0; + const struct kernel_param_ops ops={.set=positive_set}; + struct kernel_param p={.name="positive",.ops=&ops,.level=-1,.arg=&value}; + fixture_parameter(&f,0,&p); + begin_fixture(&f,"positive=new -- tail"); + assert(!stela_linux_registry_early_parameters(test_registry,NULL)); + struct stela_linux_registry_report report; + assert(stela_linux_registry_initial_parameters(test_registry,NULL,&report)==-EPROTO); + assert(value==1 && report.last_error==-EPROTO && !report.terminal); + char *result=NULL; + assert(!stela_linux_registry_parse_result(test_registry,1,&result) && result==ERR_PTR(7)); + struct stela_linux_registration_status status; + assert(!stela_linux_registry_status(test_registry,0,&status) && status.returned==7); + assert(stela_linux_registry_run_stage(test_registry,0,NULL)==-EINVAL && !event_count); + stela_linux_exit(); +} +#include +int main(void) +{ + for(setup_differential_index=0;setup_differential_index #include +/* 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 +/* 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; diff --git a/crates/stela-drivers/src/gpu/compat/linux/kernel/taint.c b/crates/stela-drivers/src/gpu/compat/linux/kernel/taint.c new file mode 100644 index 0000000000..15d292d714 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/kernel/taint.c @@ -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 + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 +#endif diff --git a/crates/stela-drivers/src/gpu/compat/linux/kernel/task.c b/crates/stela-drivers/src/gpu/compat/linux/kernel/task.c index 8a855aaa42..824e1c98dc 100644 --- a/crates/stela-drivers/src/gpu/compat/linux/kernel/task.c +++ b/crates/stela-drivers/src/gpu/compat/linux/kernel/task.c @@ -3,10 +3,13 @@ * This implements identity/lease transitions, not a substitute Linux scheduler. */ #include #include +#include #include #include #include #include +#include +#include #include #include #include @@ -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; +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/linux.h b/crates/stela-drivers/src/gpu/compat/linux/stela/linux.h index 0d6a108777..c8e9e0a816 100644 --- a/crates/stela-drivers/src/gpu/compat/linux/stela/linux.h +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/linux.h @@ -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 #include 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 diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/module.h b/crates/stela-drivers/src/gpu/compat/linux/stela/module.h index d689810302..5c761f5ad4 100644 --- a/crates/stela-drivers/src/gpu/compat/linux/stela/module.h +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/module.h @@ -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 +#if defined(STELA_LINUX_CAPTURE_REGISTRATIONS) +#include +#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 diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/mutex_test.c b/crates/stela-drivers/src/gpu/compat/linux/stela/mutex_test.c new file mode 100644 index 0000000000..c51a58e213 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/mutex_test.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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); +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/params-parser-test.h b/crates/stela-drivers/src/gpu/compat/linux/stela/params-parser-test.h new file mode 100644 index 0000000000..4bedb23c59 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/params-parser-test.h @@ -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 + +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 +#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[] = {¶meter, &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; +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/params-reference.h b/crates/stela-drivers/src/gpu/compat/linux/stela/params-reference.h new file mode 100644 index 0000000000..ec22b93af4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/params-reference.h @@ -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(¶ms[i])) + err = params[i].ops->set(val, ¶ms[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, ¶m, &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); +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/params.h b/crates/stela-drivers/src/gpu/compat/linux/stela/params.h new file mode 100644 index 0000000000..37cc5c1d33 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/params.h @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef STELA_PARAMS_H +#define STELA_PARAMS_H +#include + +/* 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 diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registration.h b/crates/stela-drivers/src/gpu/compat/linux/stela/registration.h new file mode 100644 index 0000000000..04f0ac1303 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registration.h @@ -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 +#include +#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 diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry.h b/crates/stela-drivers/src/gpu/compat/linux/stela/registry.h new file mode 100644 index 0000000000..59d6eccc89 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry.h @@ -0,0 +1,177 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_LINUX_REGISTRY_H +#define STELA_LINUX_REGISTRY_H +#include +#include +#include +#include + +/* 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 diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/empty.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/empty.c new file mode 100644 index 0000000000..1e141e4f0a --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/empty.c @@ -0,0 +1,5 @@ +/* SPDX-License-Identifier: MIT */ +#include "fixture.h" +#include +/* Selected no-registration source must still appear in unit/group inventory. */ +int stela_registry_fixture_empty(void) { return 17; } diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/first.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/first.c new file mode 100644 index 0000000000..055f04bfc4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/first.c @@ -0,0 +1,55 @@ +/* SPDX-License-Identifier: MIT */ +#include "fixture.h" +#include +#include +#include +#include +/* 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; +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/fixture.h b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/fixture.h new file mode 100644 index 0000000000..c0c690a7e7 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/fixture.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_REGISTRY_FIXTURE_H +#define STELA_REGISTRY_FIXTURE_H +#include +#include +/* 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 diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/inspect.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/inspect.c new file mode 100644 index 0000000000..2bcf4fc4d5 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/inspect.c @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: MIT */ +#include "fixture.h" +#include +#include +#include +#include +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; +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/negative.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/negative.c new file mode 100644 index 0000000000..5f01a2b41c --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/negative.c @@ -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 +int fixture_has_no_capture_header; +#else +#include +#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 diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/parameters.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/parameters.c new file mode 100644 index 0000000000..0937894a02 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/parameters.c @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: MIT */ +#include +#include +#include +/* 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; +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/parameters_inspect.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/parameters_inspect.c new file mode 100644 index 0000000000..8233cad0f6 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/parameters_inspect.c @@ -0,0 +1,49 @@ +/* SPDX-License-Identifier: MIT */ +#include +#include +#include +#include +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, ®istry) == 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; +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/second.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/second.c new file mode 100644 index 0000000000..5768d9116b --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/second.c @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: MIT */ +#include "fixture.h" +#include +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; +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/third.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/third.c new file mode 100644 index 0000000000..2b840b844d --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/third.c @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: MIT */ +#include "fixture.h" +#include +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; +} diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/video_cmdline.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/video_cmdline.c new file mode 100644 index 0000000000..31bb5c8215 --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/video_cmdline.c @@ -0,0 +1,6 @@ +/* SPDX-License-Identifier: MIT */ +#include +#ifndef STELA_LINUX_VIDEO_CMDLINE_SOURCE +#error "exact retained original drivers/video/cmdline.c source required" +#endif +#include STELA_LINUX_VIDEO_CMDLINE_SOURCE diff --git a/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/video_inspect.c b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/video_inspect.c new file mode 100644 index 0000000000..0d1730a54a --- /dev/null +++ b/crates/stela-drivers/src/gpu/compat/linux/stela/registry_fixture/video_inspect.c @@ -0,0 +1,60 @@ +/* SPDX-License-Identifier: MIT */ +#include +#include +#include +#include +#include +#include