Skip to main content

fic/ccfg/
message.rs

1//! Each typed `Sync` channel's message ([`messages`]): its value, by copy, in
2//! the message registers of the protected procedure call. A lowering, like
3//! the rings, so it is sized here; a value that does not fit is an error.
4//!
5//! The limit is seL4's: `microkit_mr_set` is `seL4_SetMR`, which writes the
6//! IPC buffer, and the kernel copies up to `seL4_MsgMaxLength` words, the
7//! first `seL4_FastMessageRegisters` (4 on `AArch64`) in registers.
8
9use serde::Serialize;
10
11use crate::ast::ChannelKind;
12use crate::base::{ChanId, IdVec};
13use crate::error::{Diagnostic, Diagnostics};
14use crate::tast::TyEnv;
15
16use super::ring::{bytes, named};
17
18/// seL4's `seL4_MsgMaxLength`: the words one message carries.
19pub const MAX_WORDS: u64 = 120;
20
21/// A message register's bytes.
22const WORD_BYTES: u64 = 8;
23
24/// `bytes` of value in `words` message registers.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
26pub struct Message {
27    /// The value's bytes, at least one.
28    pub bytes: u64,
29    /// ⌈bytes / 8⌉, 1 to [`MAX_WORDS`].
30    pub words: u64,
31}
32
33/// Every channel's message, `None` unless it is a `Sync Chan<T>`.
34///
35/// # Errors
36///
37/// A value with no bytes, or more than [`MAX_WORDS`] words, each at its
38/// channel.
39pub fn messages(tenv: &TyEnv) -> Result<IdVec<ChanId, Option<Message>>, Diagnostics> {
40    let mut errors = Vec::new();
41    let messages = tenv
42        .chans
43        .iter()
44        .map(|ch| {
45            let payload = ch
46                .payload
47                .as_ref()
48                .filter(|_| ch.kind == ChannelKind::SyncUni)?;
49            let size = bytes(tenv, payload);
50            let words = size.div_ceil(WORD_BYTES);
51            let name = named(tenv, payload);
52            let fault = if size == 0 {
53                Some(format!(
54                    "'{name}' has no bytes: a message carries at least one"
55                ))
56            } else if words > MAX_WORDS {
57                Some(format!(
58                    "'{name}' is {size} bytes, {words} message registers: a `Sync` channel's value \
59                     fits in seL4's {MAX_WORDS} ({} bytes)",
60                    MAX_WORDS * WORD_BYTES
61                ))
62            } else {
63                None
64            };
65            if let Some(m) = fault {
66                errors.push(Diagnostic::at(
67                    format!("channel '{}': {m}", ch.name),
68                    ch.span.clone(),
69                    tenv.file.clone(),
70                ));
71                return None;
72            }
73            Some(Message { bytes: size, words })
74        })
75        .collect();
76    Diagnostics::finish(errors, messages)
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use crate::base::Idx;
83    use crate::tast::env::built;
84
85    fn messages_of(decls: &str, ty: &str) -> Result<Option<Message>, String> {
86        let fis = format!(
87            "{decls}\nProtectionDomain a(1);\nProtectionDomain b(2);\n\
88             Sync Chan<{ty}> c = a --> b;"
89        );
90        let tenv = built(&fis, &[]).expect("builds").0.tenv;
91        messages(&tenv)
92            .map(|m| m[ChanId::new(0)])
93            .map_err(|d| d.0[0].message().to_owned())
94    }
95
96    #[test]
97    fn a_value_takes_its_words() {
98        let ok = |decls: &str, ty: &str, bytes: u64, words: u64| {
99            assert_eq!(
100                messages_of(decls, ty),
101                Ok(Some(Message { bytes, words })),
102                "{ty}"
103            );
104        };
105        ok("", "uint8", 1, 1);
106        ok("", "int64", 8, 1);
107        ok("struct Req { a: int32; b: int64; }", "Req", 16, 2);
108        // Past the 4 words seL4 passes in registers, the IPC buffer takes the rest.
109        ok("struct Five { w: int64[4]; x: uint8; }", "Five", 40, 5);
110        ok("struct Most { w: int64[120]; }", "Most", 960, 120);
111    }
112
113    #[test]
114    fn a_value_past_sel4s_message_is_rejected() {
115        let over = "struct Over { w: int64[120]; x: uint8; }";
116        let err = messages_of(over, "Over").unwrap_err();
117        assert!(
118            err.contains(
119                "channel 'c': 'Over' is 968 bytes, 121 message registers: a `Sync` channel's \
120                 value fits in seL4's 120 (960 bytes)"
121            ),
122            "{err}"
123        );
124    }
125
126    #[test]
127    fn an_untyped_sync_channel_has_no_message() {
128        let tenv = built(
129            "ProtectionDomain a(1);\nProtectionDomain b(2);\nSync Chan c = a --> b;",
130            &[],
131        )
132        .expect("builds")
133        .0
134        .tenv;
135        assert_eq!(messages(&tenv).unwrap()[ChanId::new(0)], None);
136    }
137}