blob: 24dbc8994a96e864d68de7739ce2e2b2bb5c46da [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::{Error, anyhow, bail};
use bstr::BString;
use starnix_core::task::Kernel;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
/// Trait implemented by statically linked Starnix kernel modules.
pub trait StarnixModule: Send + Sync {
/// Unique module name used in `program.modules` (for example `"ashmem"` or `"magma"`).
fn name(&self) -> &str;
/// Validates `modprobe`-style arguments passed to this module.
///
/// By default, rejects any non-empty argument list.
fn validate_args(&self, args: &[&str]) -> Result<(), Error> {
if !args.is_empty() {
bail!("module '{}' does not accept arguments: {args:?}", self.name());
}
Ok(())
}
/// Initializes the module in `kernel` with the validated `args`.
///
/// Modules can read container-level features via `kernel.features` and share cross-module
/// state through `kernel.expando`.
fn init(&self, kernel: &Arc<Kernel>, args: &[&str]) -> Result<(), Error>;
/// Returns any extra kernel command-line parameters contributed by this module when enabled.
fn extra_cmdline_params(&self, _args: &[&str]) -> Result<Option<BString>, Error> {
Ok(None)
}
}
type NoArgInitFn = fn(&Arc<Kernel>) -> Result<(), Error>;
type ArgValidateFn = fn(&[&str]) -> Result<(), Error>;
type ArgInitFn = fn(&Arc<Kernel>, &[&str]) -> Result<(), Error>;
#[derive(Clone, Copy)]
enum FnModuleKind {
NoArgs(NoArgInitFn),
WithArgs { validate: ArgValidateFn, init: ArgInitFn },
}
/// Ergonomic [`StarnixModule`] adapter for function-based modules that do not need custom
/// command-line parameters.
#[derive(Clone, Copy)]
pub struct FnModule {
name: &'static str,
kind: FnModuleKind,
}
impl fmt::Debug for FnModule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let accepts_args = matches!(self.kind, FnModuleKind::WithArgs { .. });
f.debug_struct("FnModule")
.field("name", &self.name)
.field("accepts_args", &accepts_args)
.finish_non_exhaustive()
}
}
impl FnModule {
/// Creates a module that rejects all arguments and initializes via `init`.
pub const fn no_args(name: &'static str, init: NoArgInitFn) -> Self {
Self { name, kind: FnModuleKind::NoArgs(init) }
}
/// Creates a module that validates arguments with `validate` and initializes via `init`.
pub const fn with_args(name: &'static str, validate: ArgValidateFn, init: ArgInitFn) -> Self {
Self { name, kind: FnModuleKind::WithArgs { validate, init } }
}
}
impl StarnixModule for FnModule {
fn name(&self) -> &str {
self.name
}
fn validate_args(&self, args: &[&str]) -> Result<(), Error> {
match self.kind {
FnModuleKind::NoArgs(_) => {
if !args.is_empty() {
bail!("module '{}' does not accept arguments: {args:?}", self.name);
}
Ok(())
}
FnModuleKind::WithArgs { validate, .. } => validate(args),
}
}
fn init(&self, kernel: &Arc<Kernel>, args: &[&str]) -> Result<(), Error> {
match self.kind {
FnModuleKind::NoArgs(init) => init(kernel),
FnModuleKind::WithArgs { init, .. } => init(kernel, args),
}
}
}
struct RegisteredModule {
module: Box<dyn StarnixModule>,
default_enabled: bool,
}
type CrossModuleValidator = Box<dyn Fn(&Modules) -> Result<(), Error> + Send + Sync>;
/// Registry of statically linked [`StarnixModule`] implementations available to a Starnix kernel
/// binary.
#[derive(Default)]
pub struct ModuleRegistry {
modules: BTreeMap<String, RegisteredModule>,
conflicts: Vec<(String, String)>,
validators: Vec<CrossModuleValidator>,
}
impl fmt::Debug for ModuleRegistry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let registered: Vec<&str> = self.modules.keys().map(String::as_str).collect();
let defaults: Vec<&str> = self.default_modules().collect();
f.debug_struct("ModuleRegistry")
.field("modules", &registered)
.field("default_modules", &defaults)
.field("conflicts", &self.conflicts)
.finish_non_exhaustive()
}
}
impl ModuleRegistry {
/// Creates an empty module registry.
pub fn new() -> Self {
Self::default()
}
/// Registers an opt-in module.
///
/// Panics if a module with the same name is already registered or if the name is invalid.
pub fn register(&mut self, module: impl StarnixModule + 'static) -> &mut Self {
self.register_boxed(Box::new(module), false)
}
/// Registers a module that is enabled by default for all containers unless explicitly disabled
/// via `"-<module>"`.
///
/// Panics if a module with the same name is already registered or if the name is invalid.
pub fn register_default(&mut self, module: impl StarnixModule + 'static) -> &mut Self {
self.register_boxed(Box::new(module), true)
}
fn register_boxed(
&mut self,
module: Box<dyn StarnixModule>,
default_enabled: bool,
) -> &mut Self {
let name = module.name().to_string();
assert!(!name.is_empty(), "module name must not be empty");
assert!(!name.starts_with('-'), "module name '{name}' must not start with '-'");
assert!(
!name.chars().any(char::is_whitespace),
"module name '{name}' must not contain whitespace"
);
let existing =
self.modules.insert(name.clone(), RegisteredModule { module, default_enabled });
assert!(existing.is_none(), "module '{name}' is already registered");
self
}
/// Configures whether the already-registered module `name` is enabled by default.
///
/// Panics if `name` is not registered.
pub fn set_default_enabled(&mut self, name: &str, default_enabled: bool) -> &mut Self {
let entry = self
.modules
.get_mut(name)
.unwrap_or_else(|| panic!("module '{name}' is not registered"));
entry.default_enabled = default_enabled;
self
}
/// Declares that `module_a` and `module_b` are mutually exclusive and cannot be enabled at the
/// same time.
///
/// Panics if `module_a` and `module_b` are identical or if either module is not registered.
pub fn register_conflict(
&mut self,
module_a: impl Into<String>,
module_b: impl Into<String>,
) -> &mut Self {
let module_a = module_a.into();
let module_b = module_b.into();
assert!(module_a != module_b, "module '{module_a}' cannot conflict with itself");
assert!(self.modules.contains_key(&module_a), "module '{module_a}' is not registered");
assert!(self.modules.contains_key(&module_b), "module '{module_b}' is not registered");
self.conflicts.push((module_a, module_b));
self
}
/// Registers a custom cross-module validation hook invoked by [`Modules::validate`].
pub fn add_validator<F>(&mut self, validator: F) -> &mut Self
where
F: Fn(&Modules) -> Result<(), Error> + Send + Sync + 'static,
{
self.validators.push(Box::new(validator));
self
}
/// Returns whether a module named `name` is registered.
pub fn contains(&self, name: &str) -> bool {
self.modules.contains_key(name)
}
/// Returns the registered module implementation for `name`, if any.
pub fn get(&self, name: &str) -> Option<&dyn StarnixModule> {
self.modules.get(name).map(|entry| entry.module.as_ref())
}
/// Iterates over the names of all registered modules enabled by default, in sorted order.
pub fn default_modules(&self) -> impl Iterator<Item = &str> {
self.modules
.iter()
.filter(|(_, entry)| entry.default_enabled)
.map(|(name, _)| name.as_str())
}
/// Iterates over the names of all registered modules, in sorted order.
pub fn module_names(&self) -> impl Iterator<Item = &str> {
self.modules.keys().map(String::as_str)
}
/// Creates a new [`Modules`] configuration seeded with this registry's default-enabled modules.
pub fn new_modules(self: &Arc<Self>) -> Modules {
Modules::new(Arc::clone(self))
}
/// Validates that `name` is a registered module and that `args` (if `Some`) are valid for it.
fn validate_module(&self, name: &str, args: Option<&[&str]>) -> Result<(), Error> {
let module = self.get(name).ok_or_else(|| anyhow!("unsupported module: {name}"))?;
if let Some(args) = args {
module.validate_args(args)?;
}
Ok(())
}
}
/// Per-container configuration of enabled and disabled Starnix kernel modules backed by a
/// [`ModuleRegistry`].
#[derive(Clone)]
pub struct Modules {
registry: Arc<ModuleRegistry>,
/// Map from module name to `Some(args)` when enabled, or `None` when explicitly disabled via
/// `"-<module>"`.
entries: BTreeMap<String, Option<Vec<String>>>,
}
impl fmt::Debug for Modules {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Modules").field("entries", &self.entries).finish_non_exhaustive()
}
}
impl Modules {
/// Creates a new container module configuration seeded with `registry`'s default-enabled
/// modules.
pub fn new(registry: Arc<ModuleRegistry>) -> Self {
let entries = registry
.default_modules()
.map(|module| (module.to_string(), Some(Vec::new())))
.collect();
Self { registry, entries }
}
/// Returns the [`ModuleRegistry`] backing this configuration.
pub fn registry(&self) -> &Arc<ModuleRegistry> {
&self.registry
}
/// Parses and registers a single module specification string (`"<module> [key=value...]"` or
/// `"-<module>"`).
pub fn add_spec(&mut self, spec: &str) -> Result<(), Error> {
let mut tokens = spec.split_whitespace();
let name = tokens.next().ok_or_else(|| anyhow!("empty module specification"))?;
if let Some(disabled_module) = name.strip_prefix('-') {
if disabled_module.is_empty() || disabled_module.starts_with('-') {
bail!("invalid module specification: {spec}");
}
if tokens.next().is_some() {
bail!("cannot specify arguments when disabling module '{disabled_module}'");
}
self.disable(disabled_module);
return Ok(());
}
let args = tokens.map(String::from).collect();
self.add_with_args(name, args);
Ok(())
}
/// Disables `module`, preventing it from being initialized even if enabled by default or in an
/// included manifest shard.
pub fn disable(&mut self, module: &str) {
self.entries.insert(module.to_string(), None);
}
/// Enables `module` with no arguments, preserving any arguments or explicit disablement already
/// configured for `module`.
pub fn enable(&mut self, module: &str) {
self.add_with_args(module, Vec::new());
}
/// Enables `module` with `args` unless `module` has been explicitly disabled.
///
/// If `args` is empty and `module` is already enabled, any existing arguments configured for
/// `module` are preserved so that bare `<module>` entries (for example from an included
/// manifest shard) do not overwrite explicit module arguments.
pub fn add_with_args(&mut self, module: &str, args: Vec<String>) {
match self.entries.get_mut(module) {
Some(None) => {}
Some(Some(existing_args)) => {
if !args.is_empty() {
*existing_args = args;
}
}
None => {
self.entries.insert(module.to_string(), Some(args));
}
}
}
/// Returns whether `module` is enabled.
pub fn is_enabled(&self, module: &str) -> bool {
self.args(module).is_some()
}
/// Returns the arguments configured for `module`, if enabled.
pub fn args(&self, module: &str) -> Option<&[String]> {
self.entries.get(module)?.as_deref()
}
/// Validates all configured module names, module arguments, registered conflicts, and
/// cross-module validation hooks against this configuration's [`ModuleRegistry`].
pub fn validate(&self) -> Result<(), Error> {
for (module, args) in &self.entries {
let arg_refs: Option<Vec<&str>> =
args.as_ref().map(|a| a.iter().map(String::as_str).collect());
self.registry.validate_module(module, arg_refs.as_deref())?;
}
for (module_a, module_b) in &self.registry.conflicts {
if self.is_enabled(module_a) && self.is_enabled(module_b) {
bail!("modules '{module_a}' and '{module_b}' cannot be enabled simultaneously");
}
}
for validator in &self.registry.validators {
validator(self)?;
}
Ok(())
}
/// Validates this configuration and returns any extra kernel command-line parameters
/// contributed by enabled modules.
pub fn extra_cmdline_params(&self) -> Result<Option<BString>, Error> {
self.validate()?;
let mut combined: Option<BString> = None;
for (name, args) in &self.entries {
if let Some(args) = args {
let module =
self.registry.get(name).ok_or_else(|| anyhow!("unsupported module: {name}"))?;
let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
if let Some(params) = module.extra_cmdline_params(&arg_refs)?
&& !params.is_empty()
{
match &mut combined {
Some(existing) => {
existing.extend_from_slice(b" ");
existing.extend_from_slice(&params);
}
None => combined = Some(params),
}
}
}
}
Ok(combined)
}
/// Records the enabled modules and their arguments under a `"modules"` child Inspect node.
pub fn record_inspect(&self, parent_node: &fuchsia_inspect::Node) {
parent_node.record_child("modules", |inspect_node| {
for (module, args) in &self.entries {
if let Some(args) = args {
inspect_node.record_string(module, args.join(" "));
}
}
});
}
/// Validates and initializes all enabled modules in `kernel`.
pub fn init_modules(&self, kernel: &Arc<Kernel>) -> Result<(), Error> {
self.validate()?;
for (name, args) in &self.entries {
if let Some(args) = args {
let module =
self.registry.get(name).ok_or_else(|| anyhow!("unsupported module: {name}"))?;
let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
module.init(kernel, &arg_refs)?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{FnModule, ModuleRegistry, Modules, StarnixModule};
use anyhow::{Error, bail};
use bstr::BString;
use starnix_core::task::Kernel;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
struct CmdlineTestModule {
name: &'static str,
extra_cmdline_called: Arc<AtomicBool>,
}
impl StarnixModule for CmdlineTestModule {
fn name(&self) -> &str {
self.name
}
fn validate_args(&self, args: &[&str]) -> Result<(), Error> {
if args.iter().any(|&arg| arg != "ok") {
bail!("invalid {} argument: {args:?}", self.name);
}
Ok(())
}
fn init(&self, _kernel: &Arc<Kernel>, _args: &[&str]) -> Result<(), Error> {
Ok(())
}
fn extra_cmdline_params(&self, args: &[&str]) -> Result<Option<BString>, Error> {
self.extra_cmdline_called.store(true, Ordering::SeqCst);
Ok(Some(BString::from(format!("{}={}", self.name, args.join(",")))))
}
}
#[fuchsia::test]
fn fn_module_debug_clone_copy_and_non_exhaustive_debug() {
let no_args = FnModule::no_args("alpha", |_kernel| Ok(()));
let copied: FnModule = no_args;
let cloned = copied.clone();
assert_eq!(cloned.name(), "alpha");
let debug_no_args = format!("{no_args:?}");
assert!(debug_no_args.contains("FnModule"));
assert!(debug_no_args.contains("alpha"));
assert!(debug_no_args.contains("accepts_args: false"));
assert!(debug_no_args.contains(".."));
let with_args = FnModule::with_args("beta", |_args| Ok(()), |_kernel, _args| Ok(()));
let debug_with_args = format!("{with_args:?}");
assert!(debug_with_args.contains("beta"));
assert!(debug_with_args.contains("accepts_args: true"));
assert!(debug_with_args.contains(".."));
let mut registry = ModuleRegistry::new();
registry.register(no_args).register(with_args);
let debug_registry = format!("{registry:?}");
assert!(debug_registry.contains("ModuleRegistry"));
assert!(debug_registry.contains(".."));
let modules = Modules::new(Arc::new(registry));
let debug_modules = format!("{modules:?}");
assert!(debug_modules.contains("Modules"));
assert!(debug_modules.contains(".."));
}
#[fuchsia::test]
fn set_default_enabled_toggles_registered_module() {
let mut registry = ModuleRegistry::new();
registry.register(FnModule::no_args("alpha", |_kernel| Ok(())));
assert_eq!(registry.default_modules().collect::<Vec<_>>(), Vec::<&str>::new());
registry.set_default_enabled("alpha", true);
assert_eq!(registry.default_modules().collect::<Vec<_>>(), vec!["alpha"]);
registry.set_default_enabled("alpha", false);
assert_eq!(registry.default_modules().collect::<Vec<_>>(), Vec::<&str>::new());
registry.set_default_enabled("alpha", true);
let modules = Arc::new(registry).new_modules();
assert!(modules.is_enabled("alpha"));
assert_eq!(modules.args("alpha"), Some(&[][..]));
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "is not registered")]
fn set_default_enabled_rejects_unregistered_module() {
let mut registry = ModuleRegistry::new();
registry.set_default_enabled("missing", true);
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "must not be empty")]
fn register_rejects_empty_module_name() {
let mut registry = ModuleRegistry::new();
registry.register(FnModule::no_args("", |_kernel| Ok(())));
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "must not start with '-'")]
fn register_rejects_leading_dash_module_name() {
let mut registry = ModuleRegistry::new();
registry.register(FnModule::no_args("-foo", |_kernel| Ok(())));
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "is already registered")]
fn register_rejects_duplicate_module_name() {
let mut registry = ModuleRegistry::new();
registry
.register(FnModule::no_args("alpha", |_kernel| Ok(())))
.register(FnModule::no_args("alpha", |_kernel| Ok(())));
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "must not contain whitespace")]
fn register_rejects_whitespace_in_module_name() {
let mut registry = ModuleRegistry::new();
registry.register(FnModule::no_args("bad name", |_kernel| Ok(())));
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "must not contain whitespace")]
fn register_rejects_tab_in_module_name() {
let mut registry = ModuleRegistry::new();
registry.register(FnModule::no_args("bad\tname", |_kernel| Ok(())));
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "cannot conflict with itself")]
fn register_conflict_rejects_self_conflict() {
let mut registry = ModuleRegistry::new();
registry.register(FnModule::no_args("alpha", |_kernel| Ok(())));
registry.register_conflict("alpha", "alpha");
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "is not registered")]
fn register_conflict_rejects_unregistered_first_module() {
let mut registry = ModuleRegistry::new();
registry.register(FnModule::no_args("beta", |_kernel| Ok(())));
registry.register_conflict("alpha", "beta");
}
#[fuchsia::test(logging = false)]
#[should_panic(expected = "is not registered")]
fn register_conflict_rejects_unregistered_second_module() {
let mut registry = ModuleRegistry::new();
registry.register(FnModule::no_args("alpha", |_kernel| Ok(())));
registry.register_conflict("alpha", "beta");
}
#[fuchsia::test]
fn extra_cmdline_params_validates_before_invoking_module() {
let called = Arc::new(AtomicBool::new(false));
let mut registry = ModuleRegistry::new();
registry
.register(CmdlineTestModule {
name: "cmdmod",
extra_cmdline_called: Arc::clone(&called),
})
.register(FnModule::no_args("other", |_kernel| Ok(())))
.register_conflict("cmdmod", "other");
let registry = Arc::new(registry);
// Invalid args must fail validation without invoking extra_cmdline_params().
let mut invalid = registry.new_modules();
invalid.add_spec("cmdmod bad").expect("add_spec syntax valid");
assert!(invalid.extra_cmdline_params().is_err());
assert!(!called.load(Ordering::SeqCst));
// Conflicting modules must fail validation without invoking extra_cmdline_params().
let mut conflict = registry.new_modules();
conflict.add_spec("cmdmod ok").expect("add_spec syntax valid");
conflict.add_spec("other").expect("add_spec syntax valid");
assert!(conflict.extra_cmdline_params().is_err());
assert!(!called.load(Ordering::SeqCst));
// Disabling an unknown module must fail validation without invoking extra_cmdline_params().
let mut unknown_disabled = registry.new_modules();
unknown_disabled.add_spec("cmdmod ok").expect("add_spec syntax valid");
unknown_disabled.add_spec("-nonexistent").expect("add_spec syntax valid");
assert!(unknown_disabled.extra_cmdline_params().is_err());
assert!(!called.load(Ordering::SeqCst));
// Disabling a registered module skips its extra_cmdline_params() cleanly.
let mut disabled = registry.new_modules();
disabled.add_spec("-cmdmod").expect("add_spec syntax valid");
assert_eq!(disabled.extra_cmdline_params().expect("disabled validates"), None);
assert!(!called.load(Ordering::SeqCst));
// Valid enabled module passes validation and emits its cmdline parameters.
let mut valid = registry.new_modules();
valid.add_spec("cmdmod ok").expect("add_spec syntax valid");
assert_eq!(
valid.extra_cmdline_params().expect("valid cmdline"),
Some(BString::from("cmdmod=ok"))
);
assert!(called.load(Ordering::SeqCst));
}
}