1use std::ops::Range;
6use std::path::Path;
7use std::sync::Arc;
8
9use anyhow::Result;
10use microkit_tool::sdf::{parse, SdfAttribute, SdfLocation, SdfNode, SystemDescription};
11use microkit_tool::sel4::Config;
12
13use crate::ast::{ChannelKind, MemoryRegionDecl, ProtectionDomainDecl};
14use crate::base::Mapping;
15use crate::error::Diagnostics;
16use crate::tast::{Channel, TyEnv};
17
18#[derive(Clone)]
20pub struct FiduciaNode {
21 pub(crate) tag_name: Arc<str>,
22 pub(crate) children: Vec<FiduciaNode>,
23 pub(crate) range: Range<SdfLocation>,
24 pub(crate) attributes: Vec<SdfAttribute>,
25}
26
27impl<'a> SdfNode<'a> for FiduciaNode {
28 fn children(&self) -> Box<dyn Iterator<Item = Box<dyn SdfNode<'a> + 'a>> + 'a> {
29 Box::new(
30 self.children
31 .clone()
32 .into_iter()
33 .map(|c| Box::new(c) as Box<dyn SdfNode>),
34 )
35 }
36 fn range(&self) -> std::ops::Range<microkit_tool::sdf::SdfLocation> {
37 self.range.clone()
38 }
39 fn attributes(&self) -> Vec<microkit_tool::sdf::SdfAttribute> {
40 self.attributes.clone()
41 }
42 fn attribute(&self, name: &str) -> Option<&str> {
43 self.attributes
44 .iter()
45 .find(|a| a.name.as_ref() == name)
46 .map(|a| a.value.as_ref())
47 }
48 fn tag_name(&self) -> &str {
49 self.tag_name.as_ref()
50 }
51}
52
53pub fn to_sdf(config: &Config, tenv: &TyEnv) -> Result<SystemDescription, Diagnostics> {
58 let mut root = FiduciaNode {
59 tag_name: Arc::from("root"),
60 children: vec![],
61 attributes: vec![],
62 range: Range {
63 start: SdfLocation { row: 0, col: 0 },
64 end: SdfLocation { row: 0, col: 0 },
65 },
66 };
67
68 for mr in tenv.mrs.iter() {
69 sdf_memory_region(&mut root, mr);
70 }
71 for (id, pd) in tenv.pds.iter_enumerated() {
72 sdf_protection_domain(&mut root, tenv.irq_ids[id], pd);
73 }
74 for ch in tenv.chans.iter() {
75 sdf_channel(&mut root, tenv, ch);
76 }
77
78 for mapping in tenv.mappings.iter() {
79 let pd_name = &tenv.pds[mapping.pd].name;
80 let region = &tenv.mrs[mapping.region].name;
81 sdf_memory_map(&mut root, pd_name, region, mapping);
82 if mapping.paddr_read {
83 sdf_paddr_setvar(&mut root, pd_name, region, mapping);
84 }
85 }
86
87 Ok(parse(Path::new(""), &root, config, &vec![]).unwrap())
88}
89
90fn sdf_memory_region(root: &mut FiduciaNode, decl: &MemoryRegionDecl) {
91 let location = SdfLocation { row: 0, col: 0 };
92 let mut node = FiduciaNode {
93 tag_name: Arc::from("memory_region"),
94 children: vec![],
95 attributes: vec![
96 SdfAttribute {
97 name: Arc::from("name"),
98 value: Arc::from(decl.name.as_str()),
99 location,
100 },
101 SdfAttribute {
102 name: Arc::from("size"),
103 value: Arc::from(decl.size.value().to_string()),
104 location,
105 },
106 SdfAttribute {
107 name: Arc::from("page_size"),
108 value: Arc::from(decl.page_size.to_string_number()),
109 location,
110 },
111 ],
112 range: Range {
113 start: location,
114 end: location,
115 },
116 };
117 if let Some(a) = decl.phys_addr {
118 node.attributes.push(SdfAttribute {
119 name: Arc::from("phys_addr"),
120 value: Arc::from(a.to_hex_grouped().as_str()),
121 location,
122 });
123 }
124 root.children.push(node);
125}
126
127fn sdf_protection_domain(root: &mut FiduciaNode, irq_id: Option<u32>, decl: &ProtectionDomainDecl) {
128 let program_name = format!("{}.elf", decl.name);
129 let program_image = Path::new(&program_name).to_path_buf();
130
131 let location = SdfLocation { row: 0, col: 0 };
132 let mut node = FiduciaNode {
133 tag_name: Arc::from("protection_domain"),
134 attributes: vec![
135 SdfAttribute {
136 name: Arc::from("name"),
137 value: Arc::from(decl.name.as_str()),
138 location,
139 },
140 SdfAttribute {
141 name: Arc::from("priority"),
142 value: Arc::from(decl.priority.to_string()),
143 location,
144 },
145 SdfAttribute {
146 name: Arc::from("budget"),
147 value: Arc::from(decl.budget.to_string()),
148 location,
149 },
150 SdfAttribute {
151 name: Arc::from("period"),
152 value: Arc::from(decl.period.to_string()),
153 location,
154 },
155 ],
156 children: vec![FiduciaNode {
157 tag_name: Arc::from("program_image"),
158 children: vec![],
159 range: Range {
160 start: location,
161 end: location,
162 },
163 attributes: vec![SdfAttribute {
164 name: Arc::from("path"),
165 value: Arc::from(program_image.to_string_lossy()),
166 location,
167 }],
168 }],
169 range: Range {
170 start: location,
171 end: location,
172 },
173 };
174
175 if let (Some(irq), Some(id)) = (decl.irq, irq_id) {
176 node.children.push(FiduciaNode {
177 tag_name: Arc::from("irq"),
178 children: vec![],
179 attributes: vec![
180 SdfAttribute {
181 name: Arc::from("irq"),
182 value: Arc::from(irq.to_string()),
183 location,
184 },
185 SdfAttribute {
186 name: Arc::from("id"),
187 value: Arc::from(id.to_string()),
188 location,
189 },
190 ],
191 range: Range {
192 start: location,
193 end: location,
194 },
195 });
196 }
197
198 root.children.push(node);
199}
200
201fn sdf_channel(root: &mut FiduciaNode, tenv: &TyEnv, decl: &Channel) {
202 let is_sync = matches!(decl.kind, ChannelKind::SyncUni);
203 let sender = tenv.pds[decl.sender.pd].name.as_str();
204 let receiver = tenv.pds[decl.receiver.pd].name.as_str();
205
206 let location = SdfLocation { row: 0, col: 0 };
207
208 let node = FiduciaNode {
209 tag_name: Arc::from("channel"),
210 children: vec![
211 FiduciaNode {
212 tag_name: Arc::from("end"),
213 children: vec![],
214 attributes: vec![
215 SdfAttribute {
216 name: Arc::from("pd"),
217 value: Arc::from(sender),
218 location,
219 },
220 SdfAttribute {
221 name: Arc::from("id"),
222 value: Arc::from(decl.sender.id.to_string()),
223 location,
224 },
225 SdfAttribute {
226 name: Arc::from("pp"),
227 value: Arc::from(is_sync.to_string()),
228 location,
229 },
230 ],
231 range: Range {
232 start: location,
233 end: location,
234 },
235 },
236 FiduciaNode {
237 tag_name: Arc::from("end"),
238 children: vec![],
239 attributes: vec![
240 SdfAttribute {
241 name: Arc::from("pd"),
242 value: Arc::from(receiver),
243 location,
244 },
245 SdfAttribute {
246 name: Arc::from("id"),
247 value: Arc::from(decl.receiver.id.to_string()),
248 location,
249 },
250 SdfAttribute {
251 name: Arc::from("pp"),
252 value: Arc::from("false".to_string()),
253 location,
254 },
255 ],
256 range: Range {
257 start: location,
258 end: location,
259 },
260 },
261 ],
262 attributes: vec![],
263 range: Range {
264 start: location,
265 end: location,
266 },
267 };
268
269 root.children.push(node);
270}
271
272fn sdf_memory_map(root: &mut FiduciaNode, pd_name: &str, region: &str, decl: &Mapping) {
273 let addr = decl.vaddr;
274
275 let location = SdfLocation { row: 0, col: 0 };
276 let node = FiduciaNode {
277 tag_name: Arc::from("map"),
278 children: vec![],
279 attributes: vec![
280 SdfAttribute {
281 name: Arc::from("mr"),
282 value: Arc::from(region),
283 location,
284 },
285 SdfAttribute {
286 name: Arc::from("vaddr"),
287 value: Arc::from(addr.to_string()),
288 location,
289 },
290 SdfAttribute {
291 name: Arc::from("perms"),
292 value: Arc::from(decl.perms.to_string()),
293 location,
294 },
295 SdfAttribute {
296 name: Arc::from("cached"),
297 value: Arc::from(decl.cached.to_string()),
298 location,
299 },
300 ],
301 range: Range {
302 start: location,
303 end: location,
304 },
305 };
306
307 let pd_node = root
308 .children
309 .iter_mut()
310 .filter(|a| a.tag_name() == "protection_domain")
311 .find(|a| a.attribute("name").unwrap() == pd_name)
312 .unwrap();
313
314 pd_node.children.push(node);
315}
316
317fn sdf_paddr_setvar(root: &mut FiduciaNode, pd_name: &str, region: &str, decl: &Mapping) {
322 let location = SdfLocation { row: 0, col: 0 };
323 let node = FiduciaNode {
324 tag_name: Arc::from("setvar"),
325 children: vec![],
326 attributes: vec![
327 SdfAttribute {
328 name: Arc::from("symbol"),
329 value: Arc::from(format!("{}_paddr", decl.name)),
330 location,
331 },
332 SdfAttribute {
333 name: Arc::from("region_paddr"),
334 value: Arc::from(region),
335 location,
336 },
337 ],
338 range: Range {
339 start: location,
340 end: location,
341 },
342 };
343 root.children
344 .iter_mut()
345 .filter(|a| a.tag_name() == "protection_domain")
346 .find(|a| a.attribute("name").unwrap() == pd_name)
347 .unwrap()
348 .children
349 .push(node);
350}
351
352#[cfg(test)]
353mod tests {
354 use crate::foreign::ForeignModules;
355 use std::path::PathBuf;
356
357 use microkit_tool::argparse::Args;
358 use microkit_tool::sdk::Sdk;
359
360 use super::*;
361 use crate::base::{ChanId, Idx};
362 use crate::frontend::{data_layer, front_end};
363 use crate::rast::env::ast_of;
364 use crate::tast::env::built;
365
366 fn config() -> Config {
367 let sdk = Sdk::discover().unwrap();
368 let args = Args {
369 sdf_path: PathBuf::new(),
370 board: "qemu_virt_aarch64".to_string(),
371 config: "debug".to_string(),
372 report_path: PathBuf::new(),
373 capdl_json_path: None,
374 viper_output_dir: None,
375 output_path: PathBuf::new(),
376 search_paths: vec![],
377 requested_image_type: microkit_tool::argparse::RequestedImageType::Unspecified,
378 override_kernel: None,
379 };
380 Config::build_kernel_config(&args, &sdk).unwrap()
381 }
382
383 #[test]
384 fn test_sdf_memory_region() {
385 let config = config();
386 let tenv = built(
387 "ProtectionDomain pd1(100, 32, 1000, 100000);Low MemoryRegion mr1(0x1000);",
388 &[],
389 )
390 .expect("builds")
391 .0
392 .tenv;
393 let sdf = to_sdf(&config, &tenv).unwrap();
394
395 assert_eq!(sdf.memory_regions.len(), 1);
396 assert_eq!(sdf.memory_regions[0].name, "mr1");
397 assert_eq!(sdf.memory_regions[0].page_count, 1);
398 }
399
400 #[test]
401 fn test_sdf_protection_domain() {
402 let config = config();
403 let tenv = built("ProtectionDomain pd1(100, 32, 1000, 100000);", &[])
404 .expect("builds")
405 .0
406 .tenv;
407 let sdf = to_sdf(&config, &tenv).unwrap();
408
409 assert_eq!(sdf.protection_domains.len(), 1);
410 assert_eq!(sdf.protection_domains[0].name, "pd1");
411 assert_eq!(sdf.protection_domains[0].sched_params.priority, 100);
412 assert_eq!(sdf.protection_domains[0].sched_params.budget, 1000);
413 assert_eq!(sdf.protection_domains[0].sched_params.period, 100_000);
414 }
415
416 #[test]
417 fn test_sdf_channel() {
418 let config = config();
419 let tenv = built(
420 "ProtectionDomain pd1(100);\nProtectionDomain pd2(200);\nChan ch1 = pd1 <-> pd2;",
421 &[],
422 )
423 .expect("builds")
424 .0
425 .tenv;
426 let sdf = to_sdf(&config, &tenv).unwrap();
427
428 assert_eq!(sdf.protection_domains.len(), 2);
429 assert_eq!(sdf.channels.len(), 1);
430 assert_eq!(sdf.channels[0].end_a.pd, 0);
431 assert_eq!(sdf.channels[0].end_b.pd, 1);
432 }
433
434 #[test]
435 fn test_sdf_sync_channel() {
436 let config = config();
437 let tenv = built(
438 "ProtectionDomain pd1(100);\nProtectionDomain pd2(200);\nSync Chan ch1 = pd1 --> pd2;",
439 &[],
440 )
441 .expect("builds")
442 .0
443 .tenv;
444 let sdf = to_sdf(&config, &tenv).unwrap();
445
446 assert_eq!(sdf.channels.len(), 1);
447 assert!(
448 sdf.channels[0].end_a.pp,
449 "Sync channel end should have pp=true"
450 );
451 assert!(
452 !sdf.channels[0].end_b.pp,
453 "Sync channel end should have pp=false"
454 );
455 }
456
457 #[test]
458 fn test_sdf_memory_mapping() {
459 let config = config();
460 let tenv = built(
461 "ProtectionDomain pd1(100, 32, 1000, 100000);\nLow MemoryRegion mr1(0x1000);",
462 &[("pd1", r#"Low Mapping buffer(mr1, "rw", false);"#)],
463 )
464 .expect("builds")
465 .0
466 .tenv;
467 let sdf = to_sdf(&config, &tenv).unwrap();
468
469 assert_eq!(sdf.protection_domains[0].maps.len(), 1);
470 assert_eq!(sdf.protection_domains[0].maps[0].mr, "mr1");
471 assert!(!sdf.protection_domains[0].maps[0].cached);
472 assert_eq!(sdf.protection_domains[0].maps[0].perms, 0b11);
473 }
474
475 #[test]
476 fn test_sdf_paddr_setvar_only_when_read() {
477 let config = config();
478 let sdf_of = |fi: &str| {
479 let program = format!(
482 "{fi}\n@bind(microkit.init) proc Init() {{ Skip; }}\n\
483 @bind(microkit.notified) proc Notified() {{ irq?32 -> Notified(); }}"
484 );
485 let rawast = ast_of(
486 "ProtectionDomain pd1(100, 32, 1000, 100000);\nLow MemoryRegion mr1(0x1000);",
487 &[("pd1", &program)],
488 );
489 let (env, tenv) = data_layer(&rawast).unwrap();
490 let front = front_end(&rawast, &mut ForeignModules::new(), env, tenv).unwrap();
491 to_sdf(&config, &front.tenv).unwrap()
492 };
493 let paddr = |sdf: &SystemDescription| -> Vec<(String, String)> {
495 sdf.protection_domains[0]
496 .setvars
497 .iter()
498 .map(|sv| (sv.symbol.clone(), format!("{:?}", sv.kind)))
499 .filter(|(_, kind)| kind.starts_with("Paddr"))
500 .collect()
501 };
502
503 let read = sdf_of(
504 "Low Mapping buffer(mr1, \"rw\", false);\nx: Address;\nevt a: x = buffer.paddr;",
505 );
506 let setvars = paddr(&read);
507 assert_eq!(setvars.len(), 1, "{setvars:?}");
508 assert_eq!(setvars[0].0, "buffer_paddr");
509 assert!(setvars[0].1.contains("\"mr1\""), "{setvars:?}");
510
511 let unread = sdf_of("Low Mapping buffer(mr1, \"rw\", false);");
512 assert!(paddr(&unread).is_empty(), "{:?}", paddr(&unread));
513 }
514
515 #[test]
516 fn test_sdf_mapping_has_no_address_setvars() {
517 let config = config();
518 let tenv = built(
519 "ProtectionDomain pd1(100);\nLow MemoryRegion mr1(0x1000);",
520 &[("pd1", r#"Low Mapping buffer(mr1, 0x2_000_000, "rw");"#)],
521 )
522 .expect("builds")
523 .0
524 .tenv;
525 let sdf = to_sdf(&config, &tenv).unwrap();
526
527 assert!(
529 sdf.protection_domains[0].setvars.is_empty(),
530 "{:?}",
531 sdf.protection_domains[0].setvars
532 );
533 }
534
535 #[test]
536 fn buffer_region_mapped_into_both_endpoints() {
537 let config = config();
538 let tenv = built(
539 "MemoryRegion ring(0x1000);\n\
540 ProtectionDomain a(10);\n\
541 ProtectionDomain b(20);\n\
542 Chan c = a --> b via ring<byte>;",
543 &[],
544 )
545 .expect("builds")
546 .0
547 .tenv;
548 let sdf = to_sdf(&config, &tenv).unwrap();
549 let ch = &tenv.chans[ChanId::new(0)];
550 let buffer = ch.buffer.as_ref().expect("buffered");
551 let end_vaddr = |name: &str| {
552 [(ch.sender, &buffer.sender), (ch.receiver, &buffer.receiver)]
553 .into_iter()
554 .find(|(end, _)| tenv.pds[end.pd].name == name)
555 .map(|(_, m)| tenv.mappings[*m].vaddr)
556 .unwrap()
557 };
558
559 for pd in &sdf.protection_domains {
560 let map = pd
561 .maps
562 .iter()
563 .find(|m| m.mr == "ring")
564 .unwrap_or_else(|| panic!("{}: buffer region not mapped", pd.name));
565 assert_eq!(map.vaddr, end_vaddr(&pd.name));
566 let symbols: Vec<&str> = pd.setvars.iter().map(|s| s.symbol.as_str()).collect();
567 assert!(!symbols.contains(&"ring_vaddr"), "{}: {symbols:?}", pd.name);
568 }
569 }
570}