Skip to main content

fic/wfcheck/
protected.rs

1//! Where a `Sync` channel is received. Its send is a protected-procedure
2//! call, which the kernel answers by invoking the receiver's `protected`
3//! and waits on until it returns, so:
4//!
5//! - **Receive-headed**: every edge at the head of the `protected` graph is
6//!   an unguarded receive on a `Sync` channel, one per channel.
7//! - **Run to completion**: no other edge of it receives or awaits an IRQ,
8//!   since the caller waits while it runs.
9//! - **Only there**: `init` and `notified` never receive a `Sync` channel,
10//!   since its call does not notify.
11//! - **Not from `init`**: `init` never sends on one, as Lean's `Boot`
12//!   (`syncFree`): the model runs `init` committed, so a call from it would
13//!   block the callee.
14//!
15//! Errors, unlike [`super::wellformed`]'s: the C backend has no lowering
16//! for any of them.
17
18use crate::ast::ChannelKind;
19use crate::base::ChanId;
20use crate::ccfg::graph::{Ccfg, Edge, Label};
21use crate::ccfg::System;
22use crate::error::{Diagnostic, Diagnostics};
23use crate::tast::{Comm, Event, ProgramView, Tast};
24
25use super::wellformed::Graph;
26
27/// Every PD's `Sync` receives are its `protected` head, and its `protected`
28/// graph runs to completion.
29///
30/// # Errors
31///
32/// One diagnostic per finding.
33pub fn check_protected(tast: &Tast, system: &System) -> Result<(), Diagnostics> {
34    let mut errors = Vec::new();
35    for (pd, orchestration) in system.programs.iter_enumerated() {
36        let mut graph = Graph {
37            view: ProgramView::new(tast, pd),
38            file: &tast.tenv.pds[pd].fi,
39            found: Vec::new(),
40        };
41        for ccfg in [&orchestration.init, &orchestration.notified] {
42            for edge in &ccfg.edges {
43                graph.sync_outside_protected(edge);
44            }
45        }
46        for edge in &orchestration.init.edges {
47            graph.sync_in_init(edge);
48        }
49        if let Some(ccfg) = &orchestration.protected {
50            graph.protected(ccfg);
51        }
52        errors.append(&mut graph.found);
53    }
54    Diagnostics::finish(errors, ())
55}
56
57/// The channel `edge` receives on.
58fn received(edge: &Edge) -> Option<ChanId> {
59    match &edge.label {
60        Some(Label::Event(Event::Comm(Comm::Recv { chan, .. }))) => Some(*chan),
61        _ => None,
62    }
63}
64
65impl Graph<'_> {
66    /// `edge` is a `Sync` channel's receive.
67    fn sync_receive(&self, edge: &Edge) -> Option<ChanId> {
68        received(edge).filter(|c| self.view.chan(*c).kind == ChannelKind::SyncUni)
69    }
70
71    /// A `Sync` receive in `init` or `notified`.
72    fn sync_outside_protected(&mut self, edge: &Edge) {
73        if let Some(chan) = self.sync_receive(edge) {
74            let name = &self.view.chan(chan).name;
75            self.report(
76                edge.process,
77                self.event_span(edge),
78                &format!(
79                    "`{name}?` receives a `Sync` channel outside `microkit.protected`: its send is a \
80                     protected-procedure call, which only the `protected` process answers"
81                ),
82            );
83        }
84    }
85
86    /// A `Sync` send in `init`.
87    fn sync_in_init(&mut self, edge: &Edge) {
88        let Some(Label::Event(Event::Comm(Comm::Send { chan, .. }))) = &edge.label else {
89            return;
90        };
91        let ch = self.view.chan(*chan);
92        if ch.kind == ChannelKind::SyncUni {
93            let name = &ch.name;
94            self.report(
95                edge.process,
96                self.event_span(edge),
97                &format!(
98                    "`{name}!` calls on a `Sync` channel from `microkit.init`: `init` runs before \
99                     anything else and calls nothing; call from `notified` or `protected`"
100                ),
101            );
102        }
103    }
104
105    /// The `protected` graph: receive-headed on `Sync` channels, once each,
106    /// and no receive or IRQ await after.
107    fn protected(&mut self, ccfg: &Ccfg) {
108        let head: Vec<&Edge> = ccfg.edges.iter().filter(|e| e.src == ccfg.init).collect();
109        if head
110            .iter()
111            .any(|e| e.guard.is_some() || self.sync_receive(e).is_none())
112        {
113            let process = self
114                .view
115                .body()
116                .entries
117                .iter()
118                .find(|e| e.platform == "microkit" && e.entry == "protected")
119                .map(|e| e.process);
120            if let Some(process) = process {
121                let decl = &self.view.body().processes[process].sig;
122                self.found.push(Diagnostic::at(
123                    format!(
124                        "process `{}` bound to `microkit.protected` is not receive-headed: each path \
125                         at its head must begin with an unguarded receive on a `Sync` channel (`c?`) \
126                         — the kernel invokes it for that channel's call",
127                        decl.name
128                    ),
129                    decl.span.clone(),
130                    self.file,
131                ));
132            }
133        }
134        for (i, edge) in head.iter().enumerate() {
135            let Some(chan) = self.sync_receive(edge) else {
136                continue;
137            };
138            if head[..i].iter().any(|e| self.sync_receive(e) == Some(chan)) {
139                let name = &self.view.chan(chan).name;
140                self.report(
141                    edge.process,
142                    self.event_span(edge),
143                    &format!(
144                        "two branches of the protected head receive on `{name}?`: which one answers \
145                         the call is not decided — receive once, and decide by guards after"
146                    ),
147                );
148            }
149        }
150        for edge in ccfg
151            .edges
152            .iter()
153            .filter(|e| e.src != ccfg.init && e.blocks())
154        {
155            self.report(
156                edge.process,
157                self.event_span(edge),
158                "a receive or IRQ await after the head of `microkit.protected`: the caller waits \
159                 while it runs, so it runs to its end without waiting",
160            );
161        }
162    }
163}