Skip to main content

fic/microkit/
entrypoints.rs

1//! A PD's kernel entry points, [`EntryPoints`]: the processes its
2//! `@bind(microkit.<entry>)`s name.
3
4use anyhow::{bail, Result};
5
6use crate::ast::ChannelKind;
7use crate::base::{Entry, PdId, ProcId};
8use crate::tast::TyEnv;
9
10/// The `platform` namespace in `@bind(<platform>.<entry>)` for Microkit.
11const PLATFORM: &str = "microkit";
12
13/// The kernel entry points a Microkit protection domain exposes.
14///
15/// `init` (boot, once) and `notified` (the event loop) are **mandatory** —
16/// Microkit invokes both on every PD — so the type stores them
17/// non-optionally: a resolved `EntryPoints` cannot exist without both (see
18/// [`EntryPoints::resolve`]). `protected` answers a `Sync` channel's
19/// protected-procedure call. It is optional, libmicrokit's own answering
20/// otherwise, but a PD binds it only if a `Sync` channel ends at it
21/// ([`EntryPoints::check_protected`]).
22#[derive(Debug, Clone, Copy)]
23pub struct EntryPoints {
24    /// `@bind(microkit.init)` — the boot handler.
25    pub init: ProcId,
26    /// `@bind(microkit.notified)` — the event loop.
27    pub notified: ProcId,
28    /// `@bind(microkit.protected)` — the protected-procedure handler.
29    pub protected: Option<ProcId>,
30}
31
32impl EntryPoints {
33    /// A PD's Microkit entry points, from its program's `@bind`s. A result
34    /// always carries both mandatory ones.
35    ///
36    /// # Errors
37    ///
38    /// If either mandatory entry point (`microkit.init`,
39    /// `microkit.notified`) is unbound.
40    pub fn resolve(pd_name: &str, entries: &[Entry]) -> Result<Self> {
41        let lookup = |entry: &str| {
42            entries
43                .iter()
44                .find(|e| e.platform == PLATFORM && e.entry == entry)
45                .map(|e| e.process)
46        };
47
48        match (lookup("init"), lookup("notified")) {
49            (Some(init), Some(notified)) => Ok(Self {
50                init,
51                notified,
52                protected: lookup("protected"),
53            }),
54            (init, notified) => {
55                let mut missing = Vec::new();
56                if init.is_none() {
57                    missing.push("microkit.init");
58                }
59                if notified.is_none() {
60                    missing.push("microkit.notified");
61                }
62                bail!(
63                    "protection domain `{pd_name}` is missing mandatory kernel entry \
64                     point(s): {} (every Microkit PD must `@bind` them)",
65                    missing.join(", ")
66                )
67            }
68        }
69    }
70
71    /// `pd` binds `microkit.protected` only if a `Sync` channel ends at it.
72    ///
73    /// # Errors
74    ///
75    /// A `protected` process in a PD no `Sync` channel ends at, which
76    /// nothing calls.
77    pub fn check_protected(&self, tenv: &TyEnv, pd: PdId) -> Result<()> {
78        let sync_in = tenv
79            .chans
80            .iter()
81            .any(|c| c.kind == ChannelKind::SyncUni && c.receiver.pd == pd);
82        if self.protected.is_some() && !sync_in {
83            bail!(
84                "protection domain `{}` binds `microkit.protected`, but no `Sync` channel \
85                 ends at it",
86                tenv.pds[pd].name
87            );
88        }
89        Ok(())
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    use crate::base::{Idx, PdId};
97    use crate::tast::env::built;
98    use crate::tast::Tast;
99
100    /// The resolved project of `dd`'s program `fi`.
101    fn project(fi: &str) -> Tast {
102        built(FIS, &[("dd", fi)]).expect("builds").0
103    }
104
105    fn resolve(tast: &Tast) -> Result<EntryPoints> {
106        EntryPoints::resolve("dd", &tast.bodies[PdId::new(1)].entries)
107    }
108
109    const FIS: &str = "ProtectionDomain a(10);\n\
110                       ProtectionDomain dd(30);\n\
111                       Chan o2d = a <-> dd;\n\
112                       Chan d2i = dd <-> a;";
113
114    /// A program binding both mandatory entry points, out of declaration
115    /// order and with names other than `Init` / `Notified`.
116    const BOTH: &str = "proc Other() { o2d? -> Other(); }\n\
117                        @bind(microkit.notified)\n\
118                        proc Handler() { d2i? -> Handler(); }\n\
119                        @bind(microkit.init)\n\
120                        proc Boot() { Skip; }";
121
122    #[test]
123    fn resolves_both_entry_points_by_bind_not_name_or_order() {
124        let env = project(BOTH);
125        let entries = resolve(&env).unwrap();
126        let processes = &env.bodies[PdId::new(1)].processes;
127        assert_eq!(processes[entries.init].sig.name, "Boot");
128        assert_eq!(processes[entries.notified].sig.name, "Handler");
129    }
130
131    #[test]
132    fn resolve_names_the_missing_entry_point() {
133        // Only `notified` bound → error names the missing `microkit.init`.
134        let env = project(
135            "@bind(microkit.notified)\n\
136             proc Notified() { o2d? -> d2i! -> Notified(); }",
137        );
138        let err = resolve(&env).unwrap_err().to_string();
139        assert!(err.contains("microkit.init"), "got: {err}");
140        assert!(!err.contains("microkit.notified"), "got: {err}");
141        assert!(err.contains("dd"), "got: {err}");
142    }
143
144    /// `server` receives the `Sync` channel `req` from `client`.
145    const SYNC: &str = "ProtectionDomain client(10);\n\
146                        ProtectionDomain server(30);\n\
147                        Sync Chan req = client --> server;";
148
149    const MANDATORY: &str = "@bind(microkit.init) proc Init() { Skip; }\n\
150                             @bind(microkit.notified) proc Notified() { Skip; }\n";
151
152    /// `check_protected` on `server`, whose program is `MANDATORY` plus `extra`.
153    fn protected(extra: &str) -> Result<()> {
154        let server = format!("{MANDATORY}{extra}");
155        let client = MANDATORY;
156        let (tast, _) = built(SYNC, &[("client", client), ("server", &server)]).expect("builds");
157        let pd = PdId::new(1);
158        EntryPoints::resolve("server", &tast.bodies[pd].entries)?.check_protected(&tast.tenv, pd)
159    }
160
161    #[test]
162    fn a_sync_receiver_may_bind_protected() {
163        protected("@bind(microkit.protected) proc Serve() { req? -> Skip; }").unwrap();
164        protected("").unwrap();
165    }
166
167    #[test]
168    fn protected_needs_a_sync_channel_in() {
169        let env = project(&format!(
170            "{MANDATORY}@bind(microkit.protected) proc Serve() {{ Skip; }}"
171        ));
172        let pd = PdId::new(1);
173        let err = resolve(&env)
174            .and_then(|e| e.check_protected(&env.tenv, pd))
175            .unwrap_err()
176            .to_string();
177        assert!(err.contains("no `Sync` channel ends at it"), "got: {err}");
178    }
179
180    #[test]
181    fn resolve_lists_both_when_neither_is_bound() {
182        let env = project("proc P() { o2d? -> P(); }");
183        let err = resolve(&env).unwrap_err().to_string();
184        assert!(err.contains("microkit.init"), "got: {err}");
185        assert!(err.contains("microkit.notified"), "got: {err}");
186    }
187}