Skip to main content

intel_crashlog/collateral/
embedded.rs

1// Copyright (C) 2025 Intel Corporation
2// SPDX-License-Identifier: MIT
3
4use super::{CollateralManager, CollateralTree, ItemPath, PVSS};
5use crate::Error;
6use crate::utils::Map;
7#[cfg(not(feature = "std"))]
8use alloc::vec::Vec;
9
10/// Provides access to a collateral tree embedded in the library.
11#[derive(Default)]
12pub struct EmbeddedTree {
13    registry: Map<PVSS, Map<ItemPath, &'static [u8]>>,
14}
15
16impl EmbeddedTree {
17    fn new() -> Self {
18        let mut tree = Self::default();
19        include!(concat!(env!("OUT_DIR"), "/embedded_collateral_tree.rs"));
20        tree
21    }
22
23    fn insert_item(
24        &mut self,
25        product: &str,
26        variant: &str,
27        stepping: &str,
28        security: &str,
29        path: &str,
30        content: &'static [u8],
31    ) {
32        let pvss = PVSS {
33            product: product.into(),
34            variant: variant.into(),
35            stepping: stepping.into(),
36            security: security.into(),
37        };
38        if !self.registry.contains_key(&pvss) {
39            self.registry.insert(pvss.clone(), Map::default());
40        }
41
42        if let Some(items) = self.registry.get_mut(&pvss) {
43            items.insert(path.parse().unwrap(), content);
44        }
45    }
46}
47
48impl CollateralTree for EmbeddedTree {
49    fn get(&self, pvss: &PVSS, item: &ItemPath) -> Result<Vec<u8>, Error> {
50        self.registry
51            .get(pvss)
52            .ok_or_else(|| Error::MissingCollateral(pvss.clone(), item.clone()))
53            .and_then(|items| {
54                items
55                    .get(item)
56                    .ok_or_else(|| Error::MissingCollateral(pvss.clone(), item.clone()))
57            })
58            .map(|data| Vec::from(*data))
59    }
60
61    fn search(&self, item: &ItemPath) -> Result<Vec<PVSS>, Error> {
62        let mut hits = Vec::new();
63
64        for (pvss, items) in self.registry.iter() {
65            if items.contains_key(item) {
66                hits.push(pvss.clone());
67            }
68        }
69
70        Ok(hits)
71    }
72}
73
74impl CollateralManager<EmbeddedTree> {
75    /// Creates a [`CollateralManager`] that uses a collateral tree embedded in the library.
76    /// This allows the collateral items to be used without requiring any file system access.
77    /// The collateral items will be loaded in memory alongside the library code.
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use intel_crashlog::prelude::*;
83    ///
84    /// let collateral_manager = CollateralManager::embedded_tree();
85    /// assert!(collateral_manager.is_ok());
86    /// ```
87    pub fn embedded_tree() -> Result<Self, Error> {
88        Self::new(EmbeddedTree::new())
89    }
90}