Skip to main content

fuchsia_component_config/
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
5//! Generic traits for configuration.
6
7use fuchsia_inspect::Node;
8use fuchsia_runtime::{HandleInfo, HandleType, take_startup_handle};
9
10pub trait Config: Sized {
11    /// Take the config startup handle and parse its contents.
12    ///
13    /// # Panics
14    ///
15    /// If the config startup handle was already taken or if it is not valid.
16    fn take_from_startup_handle() -> Self {
17        let handle_info = HandleInfo::new(HandleType::ComponentConfigVmo, 0);
18        let config_vmo: zx::Vmo =
19            take_startup_handle(handle_info).expect("Config VMO handle must be present.").into();
20        Self::from_vmo(&config_vmo).expect("Config VMO handle must be valid.")
21    }
22
23    /// Parse `Self` from `vmo`.
24    fn from_vmo(vmo: &zx::Vmo) -> Result<Self, Error> {
25        let config_size = vmo.get_content_size().map_err(Error::GettingContentSize)?;
26        let config_bytes = vmo.read_to_vec(0, config_size).map_err(Error::ReadingConfigBytes)?;
27        Self::from_bytes(&config_bytes)
28    }
29
30    /// Parse `Self` from `bytes`.
31    fn from_bytes(bytes: &[u8]) -> Result<Self, Error>;
32
33    /// Returns a VMO containing the serialized version of `self`.
34    fn to_vmo(&self) -> Result<zx::Vmo, Error> {
35        let bytes = self.to_bytes()?;
36        let vmo = zx::Vmo::create(bytes.len() as u64).map_err(Error::VmoCreate)?;
37        vmo.write(&bytes, 0).map_err(Error::WritingConfigBytes)?;
38        Ok(vmo)
39    }
40
41    /// Returns the serialized version of `self`.
42    fn to_bytes(&self) -> Result<Vec<u8>, Error>;
43
44    /// Record config into inspect node.
45    fn record_inspect(&self, inspector_node: &Node);
46}
47
48#[derive(Debug, thiserror::Error)]
49pub enum Error {
50    #[error("Failed to get content size of VMO")]
51    GettingContentSize(#[source] zx::Status),
52    #[error("Failed to read content of VMO")]
53    ReadingConfigBytes(#[source] zx::Status),
54    #[error("VMO is too small for this config library")]
55    TooFewBytes,
56    #[error(
57        "ABI checksum mismatch, expected library checksum {expected_checksum:?}, got {observed_checksum:?}"
58    )]
59    ChecksumMismatch { expected_checksum: Vec<u8>, observed_checksum: Vec<u8> },
60    #[error("Failed to unpersist the non-checksum bytes of the VMO as this library's FIDL type")]
61    Unpersist(#[source] fidl::Error),
62    #[error("Failed to persist the config as this library's FIDL type")]
63    Persist(#[source] fidl::Error),
64    #[error("Failed to create VMO for config")]
65    VmoCreate(#[source] zx::Status),
66    #[error("Failed to write serialized config to VMO")]
67    WritingConfigBytes(#[source] zx::Status),
68}