dynlink/
compartment.rs

1//! Compartments are an abstraction for isolation of library components, but they are not done yet.
2
3use std::{
4    collections::HashMap,
5    fmt::{Debug, Display},
6};
7
8use petgraph::stable_graph::NodeIndex;
9use talc::{ErrOnOom, Talc};
10
11use crate::{context::NewCompartmentFlags, engines::Backing, library::LibraryId, tls::TlsInfo};
12
13mod tls;
14
15#[repr(C)]
16/// A compartment that contains libraries (and a local runtime).
17pub struct Compartment {
18    pub name: String,
19    pub id: CompartmentId,
20    pub(crate) new_comp_flags: NewCompartmentFlags,
21    // Library names are per-compartment.
22    pub(crate) library_names: HashMap<String, NodeIndex>,
23    // We maintain an allocator, so we can alloc data within the compartment.
24    pub(super) allocator: Talc<ErrOnOom>,
25    pub(super) alloc_objects: Vec<Backing>,
26
27    // Information for TLS. We store all the "active" generations.
28    pub(crate) tls_info: HashMap<u64, TlsInfo>,
29    pub(crate) tls_gen: u64,
30}
31
32/// ID type for a compartment.
33#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Ord, Eq, Hash)]
34#[repr(transparent)]
35pub struct CompartmentId(pub(crate) usize);
36
37impl Display for CompartmentId {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        write!(f, "{}", self.0)
40    }
41}
42
43impl CompartmentId {
44    /// Get the raw integer representing compartment ID.
45    pub fn raw(&self) -> usize {
46        self.0
47    }
48}
49
50pub const MONITOR_COMPARTMENT_ID: CompartmentId = CompartmentId(0);
51impl Compartment {
52    pub(crate) fn new(
53        name: String,
54        id: CompartmentId,
55        new_comp_flags: NewCompartmentFlags,
56    ) -> Self {
57        Self {
58            name,
59            id,
60            new_comp_flags,
61            library_names: HashMap::new(),
62            allocator: Talc::new(ErrOnOom),
63            alloc_objects: vec![],
64            tls_info: HashMap::new(),
65            tls_gen: 0,
66        }
67    }
68
69    /// Get an iterator over the IDs of libraries in this compartment.
70    pub fn library_ids(&self) -> impl Iterator<Item = LibraryId> + '_ {
71        self.library_names.values().map(|idx| LibraryId(*idx))
72    }
73}
74
75impl core::fmt::Display for Compartment {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        write!(f, "{}", self.name)
78    }
79}
80
81impl Debug for Compartment {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        write!(f, "Compartment[{}]", self.name)
84    }
85}
86
87impl Drop for Compartment {
88    fn drop(&mut self) {
89        tracing::debug!("dynlink: drop compartment {:?}", self);
90    }
91}