Skip to main content

starnix_features/
lib.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use strum_macros::EnumString;
6use thiserror::Error;
7
8use std::fmt::Display;
9use std::str::FromStr;
10
11/// Features are a way to enable or disable specific starnix behaviors.
12///
13/// These are specified in the component manifest of the starnix container,
14/// or explicitly provided to the kernel constructor in tests.
15#[derive(Debug, Clone, Copy, PartialEq, EnumString, strum_macros::Display)]
16#[strum(serialize_all = "snake_case")]
17pub enum Feature {
18    AndroidSerialno,
19    AndroidBootreason,
20    AspectRatio,
21    Container,
22    CustomArtifacts,
23    Ashmem,
24    BootNotifier,
25    BootNotifierCpuBoost,
26    Framebuffer,
27    Gralloc,
28    Kgsl,
29    Magma,
30    MagmaSupportedVendors,
31    Nanohub,
32    Fastrpc,
33    NetworkManager,
34    Gfxstream,
35    Bpf,
36    EnableSuid,
37    IoUring,
38    ErrorOnFailedReboot,
39    Perfetto,
40    PingGroupRange,
41    RootfsRw,
42    Selinux,
43    SelinuxTestSuite,
44    TestData,
45    Thermal,
46    Cooling,
47    HvdcpOpti,
48    Wifi,
49    AdditionalMounts,
50    WakeupTest,
51    MmcblkStub,
52    // TODO(https://fxbug.dev/485370648) remove when unnecessary
53    FakeIon,
54}
55
56/// Error returned when a feature is not recognized.
57#[derive(Debug, Error)]
58#[error("unsupported feature: {0}")]
59pub struct UnsupportedFeatureError(String);
60
61impl Feature {
62    /// Parses the name of a feature from a string.
63    pub fn try_parse(s: &str) -> Result<Feature, UnsupportedFeatureError> {
64        Feature::from_str(s).map_err(|_| UnsupportedFeatureError(s.to_string()))
65    }
66
67    /// Parses a feature and args from a string.
68    pub fn try_parse_feature_and_args(
69        s: &str,
70    ) -> Result<(Feature, Option<String>), UnsupportedFeatureError> {
71        let (raw_flag, raw_args) =
72            s.split_once(':').map(|(f, a)| (f, Some(a.to_string()))).unwrap_or((s, None));
73        Self::try_parse(raw_flag).map(|feature| (feature, raw_args))
74    }
75}
76
77/// A feature together with any arguments that go along with it, if specified.
78#[derive(Debug, Clone, PartialEq)]
79pub struct FeatureAndArgs {
80    /// The feature.
81    pub feature: Feature,
82    /// If specified, the (unparsed) arguments for the feature.
83    pub raw_args: Option<String>,
84}
85
86impl FeatureAndArgs {
87    /// Parses a feature and args from a string that separates them with `:`, e.g. "bpf:v2".
88    ///
89    /// If there is no `:` then the whole string is interpreted as the feature name.
90    pub fn try_parse(s: &str) -> Result<FeatureAndArgs, UnsupportedFeatureError> {
91        let (raw_flag, raw_args) =
92            s.split_once(':').map(|(f, a)| (f, Some(a.to_string()))).unwrap_or((s, None));
93        let feature = Feature::try_parse(raw_flag)?;
94        Ok(FeatureAndArgs { feature, raw_args })
95    }
96}
97
98impl Display for FeatureAndArgs {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
100        let FeatureAndArgs { feature, raw_args } = self;
101        match raw_args {
102            None => feature.fmt(f),
103            Some(raw_args) => format_args!("{feature}:{raw_args}").fmt(f),
104        }
105    }
106}
107
108#[cfg(test)]
109mod test {
110    use super::*;
111
112    #[test]
113    fn feature_serde() {
114        for (feature, expected_str) in [
115            (Feature::AndroidSerialno, "android_serialno"),
116            (Feature::AndroidBootreason, "android_bootreason"),
117            (Feature::AspectRatio, "aspect_ratio"),
118            (Feature::Container, "container"),
119            (Feature::CustomArtifacts, "custom_artifacts"),
120            (Feature::Ashmem, "ashmem"),
121            (Feature::BootNotifier, "boot_notifier"),
122            (Feature::BootNotifierCpuBoost, "boot_notifier_cpu_boost"),
123            (Feature::Framebuffer, "framebuffer"),
124            (Feature::Gralloc, "gralloc"),
125            (Feature::Kgsl, "kgsl"),
126            (Feature::Magma, "magma"),
127            (Feature::MagmaSupportedVendors, "magma_supported_vendors"),
128            (Feature::Nanohub, "nanohub"),
129            (Feature::NetworkManager, "network_manager"),
130            (Feature::Gfxstream, "gfxstream"),
131            (Feature::Bpf, "bpf"),
132            (Feature::EnableSuid, "enable_suid"),
133            (Feature::IoUring, "io_uring"),
134            (Feature::ErrorOnFailedReboot, "error_on_failed_reboot"),
135            (Feature::Perfetto, "perfetto"),
136            (Feature::PingGroupRange, "ping_group_range"),
137            (Feature::RootfsRw, "rootfs_rw"),
138            (Feature::Selinux, "selinux"),
139            (Feature::SelinuxTestSuite, "selinux_test_suite"),
140            (Feature::TestData, "test_data"),
141            (Feature::Thermal, "thermal"),
142            (Feature::Cooling, "cooling"),
143            (Feature::HvdcpOpti, "hvdcp_opti"),
144            (Feature::Wifi, "wifi"),
145            (Feature::AdditionalMounts, "additional_mounts"),
146            (Feature::WakeupTest, "wakeup_test"),
147            (Feature::MmcblkStub, "mmcblk_stub"),
148            // TODO(https://fxbug.dev/485370648) remove when unnecessary
149            (Feature::FakeIon, "fake_ion"),
150        ] {
151            let string = feature.to_string();
152            assert_eq!(string.as_str(), expected_str);
153            assert_eq!(Feature::try_parse(&string).expect("should parse"), feature);
154        }
155    }
156
157    #[test]
158    fn deserialize_feature_and_args() {
159        let FeatureAndArgs { feature, raw_args } =
160            FeatureAndArgs::try_parse("bpf:v2").expect("should parse successfully");
161        assert_eq!(feature, Feature::Bpf);
162        assert_eq!(raw_args.as_ref().expect("should be populated"), "v2");
163    }
164}