1use std::collections::{HashMap, HashSet};
18use std::fs::{self, File};
19use std::path::{Component, Path, PathBuf};
20use std::process::{Command, Stdio};
21
22use anyhow::{anyhow, bail, Context, Result};
23use microkit_tool::argparse::{Args, RequestedImageType};
24use microkit_tool::sdk::Sdk;
25use microkit_tool::{build::build_system, sdf::SystemDescription, sel4::Config};
26
27use crate::c_backend::generate;
28use crate::ccfg::System;
29use crate::foreign::{ForeignKind, ForeignModules, Link, INCLUDE_DIR};
30use crate::tast::Tast;
31
32use super::runtime;
33
34pub struct Image {
37 board: String,
38 profile: String,
39 args: Args,
40 sdk: Sdk,
41 pub config: Config,
43 includes: Vec<PathBuf>,
45}
46
47impl Image {
48 pub fn configure(
51 project: &Path,
52 board: String,
53 profile: String,
54 out: PathBuf,
55 includes: Vec<PathBuf>,
56 ) -> Result<Self> {
57 let build = project.join("build");
58 let args = Args {
59 sdf_path: PathBuf::new(),
60 board: board.clone(),
61 config: profile.clone(),
62 report_path: build.join("report.txt"),
63 capdl_json_path: None,
64 viper_output_dir: None,
65 output_path: out,
66 search_paths: vec![build],
67 requested_image_type: RequestedImageType::Unspecified,
68 override_kernel: None,
69 };
70 let sdk = Sdk::discover().unwrap();
71 let config = Config::build_kernel_config(&args, &sdk)
72 .map_err(|e| anyhow!("unsupported board/profile ({board}/{profile}): {e}"))?;
73 Ok(Image {
74 board,
75 profile,
76 args,
77 sdk,
78 config,
79 includes,
80 })
81 }
82
83 pub fn build(
87 &self,
88 project: &Path,
89 tast: &Tast,
90 ccfg: &System,
91 foreign: &ForeignModules,
92 system: &mut SystemDescription,
93 ) -> Result<()> {
94 let tenv = &tast.tenv;
95 let build = project.join("build");
96 let gen_dir = build.join("gen");
97 fs::create_dir_all(&gen_dir)
98 .with_context(|| format!("failed to create {}", gen_dir.display()))?;
99 let files = generate(tast, ccfg, foreign)?;
100 for f in &files {
101 f.write(&gen_dir)?;
102 }
103 eprintln!(
104 " \u{2713} Generated {} C file(s) in {}",
105 files.len(),
106 gen_dir.display()
107 );
108
109 let include = project.join(INCLUDE_DIR);
110 let mut include_dirs = vec![project, include.as_path(), gen_dir.as_path()];
111 include_dirs.extend(self.includes.iter().map(PathBuf::as_path));
112 let mut compiled = HashSet::new();
113 let mut pancake_units: HashMap<Vec<PathBuf>, PathBuf> = HashMap::new();
116 let mut unit_names = HashSet::new();
117 let filib = runtime::write_filib(&build)?;
119 let tools = Toolchain::from_env(&self.board, &self.profile)?;
120 let mem = tools.compile_runtime(&runtime::write_mem(&build)?)?;
122 let links = tenv
123 .pds
124 .iter_enumerated()
125 .flat_map(|(id, _)| foreign.linked(id));
126 let sources = project_sources(project, links)?;
127 let archive = tools.archive(&sources, project, &include_dirs, &build, &mut compiled)?;
128 for (id, pd) in tenv.pds.iter_enumerated() {
129 let files = foreign.linked(id);
130 let driver_sources = paired_driver_sources(files, project);
131 let pancake = pancake_sources(files, project);
132 let objects = if pancake.is_empty() {
133 Vec::new()
134 } else {
135 let object = if let Some(object) = pancake_units.get(&pancake) {
136 object.clone()
137 } else {
138 let base = pancake_unit_name(&pancake);
139 let mut unit = base.clone();
140 for n in 2.. {
141 if unit_names.insert(unit.clone()) {
142 break;
143 }
144 unit = format!("{base}-{n}");
145 }
146 let object =
147 compile_pancake(&unit, &pancake, &self.board, &include_dirs, &build)?;
148 pancake_units.insert(pancake.clone(), object.clone());
149 object
150 };
151 vec![object]
152 };
153 compile_c_file(
154 project,
155 &tools,
156 &gen_dir.join(format!("{}.c", pd.name)),
157 &include_dirs,
158 &build,
159 &driver_sources,
160 &objects,
161 archive.as_deref(),
162 &mem,
163 &filib,
164 &mut compiled,
165 )?;
166 }
167 generate_image(&self.config, system, &self.args, &self.sdk)
168 }
169}
170
171const HEADER_DIR_NAMES: &[&str] = &["include", "header", "headers", "c", "inc"];
174
175fn source_for_header(input: &Path, header_path: &Path) -> PathBuf {
193 let sibling = header_path.with_extension("c");
194 if input.join(&sibling).exists() {
195 return sibling;
196 }
197
198 if let Some(parent) = header_path.parent() {
199 if parent.file_name() == Some(std::ffi::OsStr::new("header")) {
200 let sibling_dir = parent.parent().unwrap_or_else(|| Path::new(""));
201 let stem = header_path.file_stem().unwrap_or_default();
202 let candidate = sibling_dir.join(stem).with_extension("c");
203 if input.join(&candidate).exists() {
204 return candidate;
205 }
206 }
207
208 let stem = header_path.file_stem().unwrap_or_default();
209 let nested = parent.join("src").join(stem).with_extension("c");
210 if input.join(&nested).exists() {
211 return nested;
212 }
213 }
214
215 let mut components: Vec<_> = header_path.components().collect();
216 if let Some(std::path::Component::Normal(top)) = components.first() {
217 if HEADER_DIR_NAMES.contains(&top.to_string_lossy().as_ref()) {
218 components[0] = std::path::Component::Normal(std::ffi::OsStr::new("src"));
219 let candidate: PathBuf = components.iter().collect::<PathBuf>().with_extension("c");
220 if input.join(&candidate).exists() {
221 return candidate;
222 }
223 }
224 }
225
226 sibling
227}
228
229fn paired_driver_sources(files: &[Link], input: &Path) -> Vec<PathBuf> {
233 let mut sources = Vec::new();
234 for file in files {
235 let path = &file.path;
236 let c = match file.kind {
237 ForeignKind::CHeader => input.join(source_for_header(input, path)),
238 ForeignKind::Pancake => {
240 let c = input.join(path.with_extension("c"));
241 if !c.exists() {
242 continue;
243 }
244 c
245 }
246 ForeignKind::CSource => continue,
248 };
249 if !sources.contains(&c) {
250 sources.push(c);
251 }
252 }
253 sources
254}
255
256fn pancake_sources(files: &[Link], input: &Path) -> Vec<PathBuf> {
258 let mut sources = Vec::new();
259 for file in files {
260 if file.kind == ForeignKind::Pancake {
261 let pnk = input.join(&file.path);
262 if !sources.contains(&pnk) {
263 sources.push(pnk);
264 }
265 }
266 }
267 sources
268}
269
270fn project_sources<'a>(
275 project: &Path,
276 links: impl Iterator<Item = &'a Link>,
277) -> Result<Vec<PathBuf>> {
278 let canonical = |p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
279 let taken: HashSet<PathBuf> = links
280 .filter_map(|link| match link.kind {
281 ForeignKind::CSource => Some(project.join(&link.path)),
282 ForeignKind::Pancake => Some(project.join(link.path.with_extension("c"))),
283 ForeignKind::CHeader => None,
284 })
285 .map(|p| canonical(&p))
286 .collect();
287 let mut sources = Vec::new();
288 c_files(project, &project.join("build"), &mut sources)?;
289 sources.retain(|s| !taken.contains(&canonical(s)));
290 sources.sort();
291 Ok(sources)
292}
293
294fn c_files(dir: &Path, skip: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
296 let entries = fs::read_dir(dir).with_context(|| format!("failed to read {}", dir.display()))?;
297 for entry in entries {
298 let entry = entry?;
299 let path = entry.path();
300 let kind = entry.file_type()?;
301 if kind.is_dir() {
302 if path != skip && !entry.file_name().to_string_lossy().starts_with('.') {
303 c_files(&path, skip, out)?;
304 }
305 } else if kind.is_file() && path.extension().is_some_and(|e| e == "c") {
306 out.push(path);
307 }
308 }
309 Ok(())
310}
311
312fn cpu_for(board: &str) -> &'static str {
314 match board {
315 "qemu_virt_aarch64" | "kria_k26" => "cortex-a53",
316 _ => "",
317 }
318}
319
320fn pancake_unit_name(sources: &[PathBuf]) -> String {
323 sources
324 .iter()
325 .map(|s| s.file_stem().unwrap_or_default().to_string_lossy())
326 .collect::<Vec<_>>()
327 .join("+")
328}
329
330fn compile_pancake(
337 unit: &str,
338 sources: &[PathBuf],
339 board: &str,
340 include_dirs: &[&Path],
341 out_dir: &Path,
342) -> Result<PathBuf> {
343 let gcc = match std::env::var("GCC") {
344 Ok(value) => PathBuf::from(value),
345 Err(err) => bail!("Could not read GCC environment variable: {err}"),
346 };
347 let Ok(cake) = std::env::var("CAKE_ML") else {
348 bail!(
349 "{unit}.pnk is Pancake, which needs the CakeML compiler: set CAKE_ML to a \
350 `cake` binary, rev 3440 or later (see CONTRIBUTING.md)"
351 );
352 };
353
354 let mut text = String::new();
355 for source in sources {
356 let src = fs::read_to_string(source)
357 .map_err(|e| anyhow::anyhow!("failed to read {}: {e}", source.display()))?;
358 text.push_str(&src);
359 if !text.ends_with('\n') {
360 text.push('\n');
361 }
362 }
363 let joined = out_dir.join(format!("{unit}.pnk"));
364 fs::write(&joined, text)?;
365
366 let preprocessed = out_dir.join(format!("{unit}.pnk.i"));
367 let mut cpp = Command::new(&gcc);
368 cpp.args(["-E", "-P", "-x", "c", "-nostdinc"]);
369 for dir in include_dirs {
370 cpp.arg(format!("-I{}", dir.display()));
371 }
372 if !cpp
373 .arg(&joined)
374 .arg("-o")
375 .arg(&preprocessed)
376 .status()?
377 .success()
378 {
379 bail!("{unit}.pnk: failed to preprocess");
380 }
381
382 let asm = out_dir.join(format!("{unit}.pnk.S"));
383 let compiled = Command::new(&cake)
384 .args(["--pancake", "--target=arm8", "--main_return=true"])
385 .stdin(File::open(&preprocessed)?)
386 .stdout(File::create(&asm)?)
387 .stderr(Stdio::piped())
388 .output()
389 .map_err(|e| anyhow::anyhow!("failed to run CAKE_ML ({cake}): {e}"))?;
390 if !compiled.status.success() {
391 let stdout = fs::read_to_string(&asm).unwrap_or_default();
393 let stderr = String::from_utf8_lossy(&compiled.stderr);
394 let detail: Vec<&str> = stderr.lines().chain(stdout.lines()).take(12).collect();
395 bail!(
396 "{unit}.pnk: cake failed to compile it:\n{}",
397 detail.join("\n")
398 );
399 }
400
401 let object = out_dir.join(format!("{unit}.pnk.o"));
402 let mut asm_cc = Command::new(&gcc);
403 let cpu = cpu_for(board);
404 if !cpu.is_empty() {
405 asm_cc.arg(format!("-mcpu={cpu}"));
406 }
407 if !asm_cc
408 .args(["-c", "-x", "assembler-with-cpp"])
409 .arg(&asm)
410 .arg("-o")
411 .arg(&object)
412 .status()?
413 .success()
414 {
415 bail!("{unit}.pnk: failed to assemble {}", asm.display());
416 }
417 Ok(object)
418}
419
420struct Toolchain {
423 cc: PathBuf,
424 ld: PathBuf,
425 board: String,
426 board_path: PathBuf,
427 debug: bool,
429}
430
431impl Toolchain {
432 fn from_env(board: &str, profile: &str) -> Result<Self> {
433 let cc = match std::env::var("GCC") {
434 Ok(value) => PathBuf::from(value),
435 Err(err) => bail!("Could not read GCC environment variable: {err}"),
436 };
437 let ld = match std::env::var("LD") {
438 Ok(value) => PathBuf::from(value),
439 Err(err) => bail!("Could not read LD environment variable: {err}"),
440 };
441 let sdk_dir = match std::env::var("MICROKIT_SDK") {
442 Ok(value) => PathBuf::from(value),
443 Err(err) => bail!("Could not read MICROKIT_SDK environment variable: {err}"),
444 };
445 let boards_path = sdk_dir.join("board");
446 if !boards_path.is_dir() {
447 bail!(
448 "SDK directory '{}' does not have a 'board' sub-directory.",
449 sdk_dir.display()
450 );
451 }
452 let board_path = boards_path.join(board).join(profile);
453 if !board_path.exists() {
454 bail!("board path '{}' does not exist.", board_path.display());
455 }
456 Ok(Toolchain {
457 cc,
458 ld,
459 board: board.to_string(),
460 board_path,
461 debug: profile == "debug",
462 })
463 }
464
465 fn compile_runtime(&self, source: &Path) -> Result<PathBuf> {
470 let object = source.with_extension("o");
471 let status = Command::new(&self.cc)
472 .arg(format!("-mcpu={}", cpu_for(&self.board)))
473 .arg("-mstrict-align")
474 .arg("-nostdlib")
475 .arg("-ffreestanding")
476 .arg("-O2")
477 .arg("-fno-tree-loop-distribute-patterns")
478 .arg("-Wall")
479 .arg("-Werror")
480 .arg(source)
481 .arg("-c")
482 .arg("-o")
483 .arg(&object)
484 .status()
485 .with_context(|| format!("failed to run {}", self.cc.display()))?;
486 if !status.success() {
487 bail!("failed to compile {}", source.display());
488 }
489 Ok(object)
490 }
491
492 fn compile(
496 &self,
497 source: &Path,
498 object: &Path,
499 include_dirs: &[&Path],
500 compiled: &mut HashSet<PathBuf>,
501 ) -> Result<()> {
502 if !compiled.insert(source.to_path_buf()) {
503 return Ok(());
504 }
505 if let Some(dir) = object.parent() {
506 fs::create_dir_all(dir)
507 .with_context(|| format!("failed to create {}", dir.display()))?;
508 }
509 let mut cc = Command::new(&self.cc);
510 cc.arg(format!("-mcpu={}", cpu_for(&self.board)))
511 .arg("-mstrict-align")
512 .arg("-nostdlib")
513 .arg("-ffreestanding")
514 .arg("-g")
515 .arg("-Wall")
516 .arg("-Wno-array-bounds")
517 .arg("-Wno-unused-variable")
518 .arg("-Wno-unused-function")
519 .arg("-Werror")
520 .arg(format!("-I{}/include", self.board_path.display()));
521 for dir in include_dirs {
522 cc.arg(format!("-I{}", dir.display()));
523 }
524 if self.debug {
525 cc.arg("-DFIC_DEBUG");
526 }
527 let status = cc
528 .arg(format!("-DBOARD_{}", self.board))
529 .arg(source)
530 .arg("-c")
531 .arg("-o")
532 .arg(object)
533 .status()
534 .with_context(|| format!("failed to run {}", self.cc.display()))?;
535 if !status.success() {
536 bail!("failed to compile {}", source.display());
537 }
538 Ok(())
539 }
540
541 fn archive(
545 &self,
546 sources: &[PathBuf],
547 project: &Path,
548 include_dirs: &[&Path],
549 out_dir: &Path,
550 compiled: &mut HashSet<PathBuf>,
551 ) -> Result<Option<PathBuf>> {
552 if sources.is_empty() {
553 return Ok(None);
554 }
555 let archive = out_dir.join("libproject.a");
556 match fs::remove_file(&archive) {
557 Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
558 return Err(e).with_context(|| format!("failed to remove {}", archive.display()));
559 }
560 _ => {}
561 }
562 let ar = runtime::sibling(&self.ld, "ar")?;
563 let mut command = Command::new(&ar);
564 command.arg("rcs").arg(&archive);
565 for source in sources {
566 let object = object_for(source, project, out_dir);
567 self.compile(source, &object, include_dirs, compiled)?;
568 command.arg(object);
569 }
570 let status = command
571 .status()
572 .with_context(|| format!("failed to run {}", ar.display()))?;
573 if !status.success() {
574 bail!(
575 "failed to archive the project's C into {}",
576 archive.display()
577 );
578 }
579 Ok(Some(archive))
580 }
581}
582
583fn object_for(source: &Path, project: &Path, out_dir: &Path) -> PathBuf {
587 let rel = source.strip_prefix(project).unwrap_or(source);
588 let rel: PathBuf = rel
589 .components()
590 .filter(|c| matches!(c, Component::Normal(_)))
591 .collect();
592 out_dir.join("obj").join(rel).with_extension("o")
593}
594
595#[allow(clippy::implicit_hasher, clippy::too_many_arguments)]
603fn compile_c_file(
604 project: &Path,
605 tools: &Toolchain,
606 file: &Path,
607 include_dirs: &[&Path],
608 out_dir: &Path,
609 extra_sources: &[PathBuf],
610 extra_objects: &[PathBuf],
611 archive: Option<&Path>,
612 mem: &Path,
613 filib: &Path,
614 compiled: &mut HashSet<PathBuf>,
615) -> Result<()> {
616 let stem = file.file_stem().unwrap().display().to_string();
617 let elf = out_dir.join(format!("{stem}.elf"));
618
619 let unit = out_dir.join(format!("{stem}.o"));
622 tools.compile(file, &unit, include_dirs, compiled)?;
623 let mut drivers = Vec::new();
624 for source in extra_sources {
625 let object = object_for(source, project, out_dir);
626 tools.compile(source, &object, include_dirs, compiled)?;
627 drivers.push(object);
628 }
629
630 let core = runtime::core(&unit, mem, filib, &tools.ld)?;
632 let mut ld = Command::new(&tools.ld);
633 ld.arg(format!("-L{}/lib", tools.board_path.display()))
634 .arg(&core)
635 .args(&drivers)
636 .args(extra_objects);
637 if let Some(archive) = archive {
639 ld.arg(archive);
640 }
641 let linked = ld
642 .arg("-lmicrokit")
643 .arg("-Tmicrokit.ld")
644 .arg("-o")
645 .arg(&elf)
646 .status()
647 .with_context(|| format!("failed to run {}", tools.ld.display()))?;
648
649 if !linked.success() {
650 bail!("failed to link {}", file.display());
651 }
652
653 Ok(())
654}
655
656fn generate_image(
663 kernel_config: &Config,
664 system: &mut SystemDescription,
665 args: &Args,
666 sdk: &Sdk,
667) -> Result<()> {
668 build_system(args, sdk, kernel_config, system).map_err(anyhow::Error::msg)
669}
670
671#[cfg(test)]
672mod tests {
673 use super::{object_for, pancake_unit_name};
674 use std::path::{Path, PathBuf};
675
676 #[test]
677 fn a_driver_object_is_named_by_its_path_not_its_stem() {
678 let (project, build) = (Path::new("/p"), Path::new("/p/build"));
679 assert_eq!(
680 object_for(Path::new("/p/c/copy.c"), project, build),
681 Path::new("/p/build/obj/c/copy.o")
682 );
683 assert_ne!(
684 object_for(Path::new("/p/a/x.c"), project, build),
685 object_for(Path::new("/p/b/x.c"), project, build)
686 );
687 assert_eq!(
688 object_for(Path::new("/lib/x.c"), project, build),
689 Path::new("/p/build/obj/lib/x.o")
690 );
691 }
692
693 #[test]
694 fn a_pancake_unit_is_named_after_its_sources_in_import_order() {
695 let unit = |paths: &[&str]| {
696 pancake_unit_name(&paths.iter().map(PathBuf::from).collect::<Vec<_>>())
697 };
698 assert_eq!(unit(&["demo/pingpong.pnk"]), "pingpong");
699 assert_eq!(unit(&["drv/uart.pnk", "timer.pnk"]), "uart+timer");
700 assert_eq!(unit(&["timer.pnk", "drv/uart.pnk"]), "timer+uart");
701 }
702}