Skip to main content

fic/rast/
system.rs

1//! Resolving the `.fis` declarations: channels, structs, consts and the
2//! `System =` composition, into the [`Env`]. Memory regions and protection domains name
3//! nothing, so `Env` holds the AST's own nodes for them.
4//!
5//! Each declaration is validated as it resolves, by `validation.rs`'s
6//! rules; once the structs are in, the walk checks none contains itself.
7//!
8//! A channel names its endpoint PDs and its buffer's region by id, and each
9//! endpoint carries its channel id in that PD, which `mkids.rs` allocated. A
10//! buffer is declared with its channel, and so are its mappings, one at
11//! each end, built into [`Env::mappings`] as the channel is; `vaddr.rs`
12//! gives them their vaddrs once every program is resolved. A mapping is one node whether a channel's buffer
13//! implies it or a program writes it ([`Mapping`], `base`'s), and
14//! `program.rs` adds the written ones to the same arena after.
15
16use std::collections::HashMap;
17use std::ops::Range;
18
19use crate::ast;
20use crate::base::{Buffer, ChannelEnd, Composition, Idx, Mapping, PdId};
21#[cfg(test)]
22use crate::base::{ChanId, ConstId, Endpoint, MrId, StructId, TypeRef, VarRef};
23use crate::error::Diagnostic;
24
25use super::env::{array_len, type_ref, Names};
26use super::mkids::Ids;
27use super::validation;
28use super::{Channel, Env};
29
30/// Resolve the system's objects into `env`, which holds the data layer
31/// already: its memory regions, protection domains (their IRQ ids),
32/// channels and composition, each validated as it resolves.
33pub(super) fn resolve_system(
34    system: &ast::System,
35    names: &Names<'_>,
36    ids: &Ids,
37    env: &mut Env,
38    errors: &mut Vec<Diagnostic>,
39) {
40    let file = system.filename.as_str();
41    // A PD's id is its position, and there are only `PdId::MAX + 1`.
42    if let Some(decl) = system.protection_domains.get(PdId::MAX.index() + 1) {
43        errors.push(Diagnostic::at(
44            format!(
45                "protection domain '{}' is one too many: at most {} protection domains",
46                decl.name,
47                PdId::MAX.index() + 1
48            ),
49            decl.span.clone(),
50            file,
51        ));
52    }
53    env.irq_ids = (0..system.protection_domains.len())
54        .map(|pd| ids.irqs.get(&PdId::new(pd)).copied())
55        .collect();
56    for mr in &system.memory_regions {
57        env.mrs.push(mr.clone());
58    }
59    let mut irqs = HashMap::new();
60    for pd in &system.protection_domains {
61        report(validation::irq(pd, &mut irqs), file, errors);
62        env.pds.push(pd.clone());
63    }
64    for (index, ch) in system.channels.iter().enumerate() {
65        // An end with no id overflowed its PD, which `mkids.rs` reported.
66        let ends = ids.ends.get(&index).copied().unwrap_or_default();
67        match channel(ch, names, ends, env) {
68            Ok(chan) => {
69                report(validation::channel(ch, &chan, env), file, errors);
70                env.chans.push(chan);
71            }
72            Err(faults) => report(faults, file, errors),
73        }
74    }
75    if let Some(decl) = &system.system {
76        let pds: Vec<_> = decl
77            .pds
78            .iter()
79            .map(|(name, offset)| pd(name, names).map_err(|m| (m, *offset..offset + name.len())))
80            .collect();
81        if pds.iter().all(Result::is_ok) {
82            env.composition = Some(Composition {
83                pds: pds.into_iter().flatten().collect(),
84                span: decl.span.clone(),
85            });
86        } else {
87            report(
88                pds.into_iter().filter_map(Result::err).collect(),
89                file,
90                errors,
91            );
92        }
93    }
94}
95
96/// A message and the span it is reported at.
97pub(super) type Fault = (String, Range<usize>);
98
99/// Report each fault in `file`.
100pub(super) fn report(faults: Vec<Fault>, file: &str, errors: &mut Vec<Diagnostic>) {
101    for (message, span) in faults {
102        errors.push(Diagnostic::at(message, span, file));
103    }
104}
105
106/// A channel, its ends resolved and its buffer, if it has one, mapped at
107/// both ends into `env.mappings`.
108fn channel(
109    ch: &ast::ChannelDecl,
110    names: &Names<'_>,
111    (sender_id, receiver_id): (u32, u32),
112    env: &mut Env,
113) -> Result<Channel, Vec<Fault>> {
114    let end =
115        |name: &str, offset: usize| pd(name, names).map_err(|m| (m, offset..offset + name.len()));
116    let sender = end(&ch.sender, ch.sender_offset);
117    let receiver = end(&ch.receiver, ch.receiver_offset);
118    let buffer = match &ch.buffer {
119        None => Ok(None),
120        Some(b) => (|| {
121            let region = *names
122                .mrs
123                .get(b.region.as_str())
124                .ok_or_else(|| format!("memory region '{}' is not declared", b.region))?;
125            let payload = type_ref(&b.payload, names)?;
126            let capacity = b
127                .capacity
128                .as_ref()
129                .map(|n| array_len(n, names))
130                .transpose()?;
131            Ok(Some((region, payload, capacity)))
132        })()
133        .map_err(|m: String| (m, ch.span.clone())),
134    };
135    let payload = ch
136        .payload
137        .as_ref()
138        .map(|t| type_ref(t, names))
139        .transpose()
140        .map_err(|m| (m, ch.span.clone()));
141    let (sender, receiver, buffer, payload) = match (sender, receiver, buffer, payload) {
142        (Ok(s), Ok(r), Ok(b), Ok(p)) => (s, r, b, p),
143        (s, r, b, p) => {
144            return Err([s.err(), r.err(), b.err(), p.err()]
145                .into_iter()
146                .flatten()
147                .collect())
148        }
149    };
150    let sender = ChannelEnd {
151        pd: sender,
152        id: sender_id,
153    };
154    let receiver = ChannelEnd {
155        pd: receiver,
156        id: receiver_id,
157    };
158    let buffer = buffer.map(|(region, payload, capacity)| {
159        let decl = &env.mrs[region];
160        let mapping = |end: ChannelEnd| Mapping {
161            pd: end.pd,
162            name: decl.name.clone(),
163            region,
164            // Allocated once every program is resolved (`vaddr.rs`).
165            vaddr: 0,
166            pinned: false,
167            perms: Buffer::PERMS,
168            cached: true,
169            label: decl.security_label,
170            paddr_read: false,
171            span: ch.span.clone(),
172        };
173        let (at_sender, at_receiver) = (mapping(sender), mapping(receiver));
174        Buffer {
175            region,
176            payload,
177            capacity,
178            sender: env.mappings.push(at_sender),
179            receiver: env.mappings.push(at_receiver),
180        }
181    });
182    Ok(Channel {
183        name: ch.name.clone(),
184        kind: ch.kind,
185        sender,
186        receiver,
187        buffer,
188        payload,
189        span: ch.span.clone(),
190    })
191}
192
193fn pd(name: &str, names: &Names<'_>) -> Result<PdId, String> {
194    names
195        .pds
196        .get(name)
197        .copied()
198        .ok_or_else(|| format!("protection domain '{name}' is not declared"))
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use crate::base::{ArrayLen, Idx};
205    use crate::rast::env::built;
206    use crate::rast::ExprKind;
207
208    const FIS: &str = "struct Slot { seq: uint16; data: byte[N]; }
209        const N: int = 4;
210        const M: int = N * 2;
211        MemoryRegion ring(0x1000);
212        ProtectionDomain a(1);
213        ProtectionDomain b(2);
214        Chan c = a --> b via ring<Slot>;
215        System = a ||| b;";
216
217    #[test]
218    fn a_buffer_is_mapped_at_each_end() {
219        let env = built(FIS, &[]).expect("builds").0.env;
220        let ch = &env.chans[ChanId::new(0)];
221        assert_eq!((ch.sender.pd, ch.receiver.pd), (PdId::new(0), PdId::new(1)));
222        let buffer = ch.buffer.as_ref().expect("buffered");
223        assert_eq!(buffer.region, MrId::new(0));
224        for (end, pd) in [(Endpoint::Sender, 0), (Endpoint::Receiver, 1)] {
225            let m = &env.mappings[buffer.mapping(end)];
226            assert_eq!((m.name.as_str(), m.region), ("ring", MrId::new(0)));
227            assert_eq!(
228                (m.pd, m.perms, m.cached),
229                (PdId::new(pd), Buffer::PERMS, true)
230            );
231            assert_ne!(m.vaddr, 0);
232        }
233        assert_eq!(buffer.payload, TypeRef::Struct(StructId::new(0)));
234    }
235
236    #[test]
237    fn types_and_consts_name_their_declarations() {
238        let env = built(FIS, &[]).expect("builds").0.env;
239        let data = &env.structs[StructId::new(0)].fields[1];
240        assert!(matches!(
241            data.ty,
242            TypeRef::Array { len: ArrayLen::Const(c), .. } if c == ConstId::new(0)
243        ));
244        let ExprKind::Binary { lhs, .. } = &env.consts[ConstId::new(1)].value.kind else {
245            panic!("M is N * 2");
246        };
247        assert!(matches!(lhs.kind, ExprKind::Var(VarRef::Const(c)) if c == ConstId::new(0)));
248    }
249
250    #[test]
251    fn composition_lists_its_pds() {
252        let env = built(FIS, &[]).expect("builds").0.env;
253        let composition = env.composition.expect("written");
254        assert_eq!(composition.pds, vec![PdId::new(0), PdId::new(1)]);
255    }
256
257    #[test]
258    fn an_undeclared_name_is_reported_where_it_is_written() {
259        // The data layer's faults stop the build before the system's.
260        let fis = "struct S { a: Ghost; b: Phantom[2]; }";
261        let err = built(fis, &[]).expect_err("rejected");
262        let at: Vec<(&str, &str)> = err
263            .0
264            .iter()
265            .map(|d| (d.message(), fis[d.span().start..].trim_start()))
266            .collect();
267        for (message, written) in [
268            ("struct 'Ghost' is not declared", "a: Ghost"),
269            ("struct 'Phantom' is not declared", "b: Phantom"),
270        ] {
271            assert!(
272                at.iter()
273                    .any(|(m, s)| m.contains(message) && s.starts_with(written)),
274                "`{message}` not at `{written}` in {at:#?}"
275            );
276        }
277        let fis = "struct S { a: uint8; }
278            MemoryRegion ring(0x1000);
279            ProtectionDomain a(1);
280            Chan c = a --> nobody;
281            Chan d = ghost --> a via nowhere<S>;
282            System = a ||| missing;";
283        let err = built(fis, &[]).expect_err("rejected");
284        let at: Vec<(&str, &str)> = err
285            .0
286            .iter()
287            .map(|d| (d.message(), fis[d.span().start..].trim_start()))
288            .collect();
289        for (message, written) in [
290            ("protection domain 'nobody' is not declared", "nobody"),
291            ("protection domain 'ghost' is not declared", "ghost"),
292            ("memory region 'nowhere' is not declared", "Chan d"),
293            ("protection domain 'missing' is not declared", "missing"),
294        ] {
295            assert!(
296                at.iter()
297                    .any(|(m, s)| m.contains(message) && s.starts_with(written)),
298                "`{message}` not at `{written}` in {at:#?}"
299            );
300        }
301    }
302
303    #[test]
304    fn an_unbuffered_channel_maps_nothing() {
305        let env = built(
306            "ProtectionDomain a(1); ProtectionDomain b(2); Chan c = a <-> b;",
307            &[],
308        )
309        .expect("builds")
310        .0
311        .env;
312        let ch = &env.chans[ChanId::new(0)];
313        assert!(ch.buffer.is_none());
314    }
315}