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    DataCollectionConsentSync,
48    HvdcpOpti,
49    Wifi,
50    AdditionalMounts,
51    WakeupTest,
52    MmcblkStub,
53    // TODO(https://fxbug.dev/485370648) remove when unnecessary
54    FakeIon,
55}
56
57/// Error returned when a feature is not recognized.
58#[derive(Debug, Error)]
59#[error("unsupported feature: {0}")]
60pub struct UnsupportedFeatureError(String);
61
62impl Feature {
63    /// Parses the name of a feature from a string.
64    pub fn try_parse(s: &str) -> Result<Feature, UnsupportedFeatureError> {
65        Feature::from_str(s).map_err(|_| UnsupportedFeatureError(s.to_string()))
66    }
67
68    /// Parses a feature and args from a string.
69    pub fn try_parse_feature_and_args(
70        s: &str,
71    ) -> Result<(Feature, Option<String>), UnsupportedFeatureError> {
72        let (raw_flag, raw_args) =
73            s.split_once(':').map(|(f, a)| (f, Some(a.to_string()))).unwrap_or((s, None));
74        Self::try_parse(raw_flag).map(|feature| (feature, raw_args))
75    }
76}
77
78/// A feature together with any arguments that go along with it, if specified.
79#[derive(Debug, Clone, PartialEq)]
80pub struct FeatureAndArgs {
81    /// The feature.
82    pub feature: Feature,
83    /// If specified, the (unparsed) arguments for the feature.
84    pub raw_args: Option<String>,
85}
86
87impl FeatureAndArgs {
88    /// Parses a feature and args from a string that separates them with `:`, e.g. "bpf:v2".
89    ///
90    /// If there is no `:` then the whole string is interpreted as the feature name.
91    pub fn try_parse(s: &str) -> Result<FeatureAndArgs, UnsupportedFeatureError> {
92        let (raw_flag, raw_args) =
93            s.split_once(':').map(|(f, a)| (f, Some(a.to_string()))).unwrap_or((s, None));
94        let feature = Feature::try_parse(raw_flag)?;
95        Ok(FeatureAndArgs { feature, raw_args })
96    }
97}
98
99impl Display for FeatureAndArgs {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
101        let FeatureAndArgs { feature, raw_args } = self;
102        match raw_args {
103            None => feature.fmt(f),
104            Some(raw_args) => format_args!("{feature}:{raw_args}").fmt(f),
105        }
106    }
107}
108
109#[cfg(test)]
110mod test {
111    use super::*;
112
113    #[test]
114    fn feature_serde() {
115        for (feature, expected_str) in [
116            (Feature::AndroidSerialno, "android_serialno"),
117            (Feature::AndroidBootreason, "android_bootreason"),
118            (Feature::AspectRatio, "aspect_ratio"),
119            (Feature::Container, "container"),
120            (Feature::CustomArtifacts, "custom_artifacts"),
121            (Feature::Ashmem, "ashmem"),
122            (Feature::BootNotifier, "boot_notifier"),
123            (Feature::BootNotifierCpuBoost, "boot_notifier_cpu_boost"),
124            (Feature::Framebuffer, "framebuffer"),
125            (Feature::Gralloc, "gralloc"),
126            (Feature::Kgsl, "kgsl"),
127            (Feature::Magma, "magma"),
128            (Feature::MagmaSupportedVendors, "magma_supported_vendors"),
129            (Feature::Nanohub, "nanohub"),
130            (Feature::NetworkManager, "network_manager"),
131            (Feature::Gfxstream, "gfxstream"),
132            (Feature::Bpf, "bpf"),
133            (Feature::EnableSuid, "enable_suid"),
134            (Feature::IoUring, "io_uring"),
135            (Feature::ErrorOnFailedReboot, "error_on_failed_reboot"),
136            (Feature::Perfetto, "perfetto"),
137            (Feature::PingGroupRange, "ping_group_range"),
138            (Feature::RootfsRw, "rootfs_rw"),
139            (Feature::Selinux, "selinux"),
140            (Feature::SelinuxTestSuite, "selinux_test_suite"),
141            (Feature::TestData, "test_data"),
142            (Feature::Thermal, "thermal"),
143            (Feature::Cooling, "cooling"),
144            (Feature::DataCollectionConsentSync, "data_collection_consent_sync"),
145            (Feature::HvdcpOpti, "hvdcp_opti"),
146            (Feature::Wifi, "wifi"),
147            (Feature::AdditionalMounts, "additional_mounts"),
148            (Feature::WakeupTest, "wakeup_test"),
149            (Feature::MmcblkStub, "mmcblk_stub"),
150            // TODO(https://fxbug.dev/485370648) remove when unnecessary
151            (Feature::FakeIon, "fake_ion"),
152        ] {
153            let string = feature.to_string();
154            assert_eq!(string.as_str(), expected_str);
155            assert_eq!(Feature::try_parse(&string).expect("should parse"), feature);
156        }
157    }
158
159    #[test]
160    fn deserialize_feature_and_args() {
161        let FeatureAndArgs { feature, raw_args } =
162            FeatureAndArgs::try_parse("bpf:v2").expect("should parse successfully");
163        assert_eq!(feature, Feature::Bpf);
164        assert_eq!(raw_args.as_ref().expect("should be populated"), "v2");
165    }
166}