Skip to main content

fic/microkit/
image.rs

1//! The image build, [`Image`].
2//!
3//! Each PD's program is the generated state machine. A `.c` import is
4//! `#include`d into the generated unit (single translation unit); a `.h`
5//! import is the separate-driver form: the unit includes the header and the
6//! paired sibling `.c` (`paired_driver_sources`) is compiled and linked
7//! alongside. Every other `.c` in the project goes into one archive,
8//! `build/libproject.a` (`project_sources`), linked after the PD's objects:
9//! ld takes only the members that define a symbol still missing, so a driver
10//! reaches the C it calls without the `.fi` importing it. Two archived files
11//! defining one symbol are no error: ld takes the first member it needs.
12//! Pancake sources become one object per distinct import set,
13//! linked into every PD that imports it (`compile_pancake`). `filib`, fic's
14//! PD runtime, is linked into every PD with the unit first, its ring calls
15//! hidden from the drivers and the Pancake (`runtime.rs`).
16
17use 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
34/// A Microkit image to build: the board, the build profile, and the kernel
35/// configuration they give.
36pub struct Image {
37    board: String,
38    profile: String,
39    args: Args,
40    sdk: Sdk,
41    /// The kernel configuration, which [`super::to_sdf`] reads.
42    pub config: Config,
43    /// Searched after the project's own include path (`fic -I`).
44    includes: Vec<PathBuf>,
45}
46
47impl Image {
48    /// The target for `board` and `profile`, the image written to `out`;
49    /// C is compiled with `includes` after the project's include path.
50    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    /// Generate each PD's C into `<project>/build/gen/`, compile it with its
84    /// drivers, its Pancake object and `filib`, and assemble the image from
85    /// `system`.
86    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        // `unit_names` keeps two import sets with the same stems
114        // (`a/x.pnk`, `b/x.pnk`) in separate files.
115        let mut pancake_units: HashMap<Vec<PathBuf>, PathBuf> = HashMap::new();
116        let mut unit_names = HashSet::new();
117        // Every PD prints through it.
118        let filib = runtime::write_filib(&build)?;
119        let tools = Toolchain::from_env(&self.board, &self.profile)?;
120        // C's memory routines, which every PD links too.
121        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
171/// Top-level directory names conventionally used to hold public headers,
172/// paired with a sibling `src/` directory holding the matching `.c`.
173const HEADER_DIR_NAMES: &[&str] = &["include", "header", "headers", "c", "inc"];
174
175/// Resolve a `.h` import path to its paired `.c` source path.
176///
177/// Tries, in order, and takes the first candidate that exists on disk
178/// under `input`:
179/// - Flat: the `.c` is a sibling of the `.h` (`eth.h` → `eth.c`).
180/// - `header/` subfolder: a `.h` living in a directory named `header` pairs
181///   with the `.c` in that directory's parent (`c/header/eth.h` → `c/eth.c`).
182/// - Nested `src/`: a `.h`'s own directory has a `src/` subdirectory holding
183///   the `.c` (`c/eth.h` → `c/src/eth.c`) — headers and sources share one
184///   top-level folder, split by a nested `src/`.
185/// - `<headerdir>/` + `src/` split: a `.h` whose *top-level* directory is a
186///   conventional header-dir name pairs with the `.c` in a sibling `src/`
187///   at the project root (`include/eth.h` → `src/eth.c`) — the
188///   common-C-practice split of interface from implementation.
189///
190/// Falls back to the flat sibling if none of the above exist, so a genuine
191/// missing-file error still names the path the user actually wrote.
192fn 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
229/// The `.c` sources linked beside a PD's unit: each `.h` import's pair (see
230/// [`source_for_header`]) and each `.pnk` import's FFI shims. A `.c` import
231/// is inlined into the unit instead.
232fn 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            // Its shims, one `ffi<name>` per `@<name>`, in a sibling `.c`.
239            ForeignKind::Pancake => {
240                let c = input.join(path.with_extension("c"));
241                if !c.exists() {
242                    continue;
243                }
244                c
245            }
246            // An inlined `.c` is `#include`d by the unit, not compiled apart.
247            ForeignKind::CSource => continue,
248        };
249        if !sources.contains(&c) {
250            sources.push(c);
251        }
252    }
253    sources
254}
255
256/// The `.pnk` files a PD imports, on disk, in import order.
257fn 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
270/// The project's own C for the archive: every `.c` under `project` but
271/// `build/` and dot-directories, less what a PD's unit or link takes
272/// already (a `.c` import, inlined; a `.pnk` import's shims). Sorted, so the
273/// archive is the same on every build.
274fn 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
294/// Every `.c` under `dir`, into `out`, but under `skip` and dot-directories.
295fn 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
312/// The `-mcpu` a board's cores take (empty: the compiler's default).
313fn cpu_for(board: &str) -> &'static str {
314    match board {
315        "qemu_virt_aarch64" | "kria_k26" => "cortex-a53",
316        _ => "",
317    }
318}
319
320/// The name a Pancake compilation unit's files take in `build/`: its
321/// sources' stems in import order, joined by `+` (`pingpong`, `uart+timer`).
322fn 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
330/// Compile one import set — a PD's Pancake imports — into one object, which
331/// every PD importing the same set links.
332///
333/// Concatenated first: `cml_main` and the `cml_*` pointers are global, so two
334/// Pancake objects in one ELF would clash. `--main_return=true` is what makes
335/// each `export fun` callable from C. `unit` names the files in `out_dir`.
336fn 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        // cake reports some errors on stdout, which went to the .S file.
392        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
420/// The cross compiler and linker (`$GCC`, `$LD`) and the board's directory
421/// in the SDK (`$MICROKIT_SDK`) every PD's C is built against.
422struct Toolchain {
423    cc: PathBuf,
424    ld: PathBuf,
425    board: String,
426    board_path: PathBuf,
427    /// The `debug` profile: units report a notification no arm took.
428    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    /// Compile fic's own runtime C, `source`, to an object beside it. At
466    /// `-O2`, whatever a project's C gets: every copy in a PD runs through
467    /// it. `-fno-tree-loop-distribute-patterns` keeps GCC from turning a
468    /// copying loop into a call to the routine it is the body of.
469    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    /// Compile `source` to `object`, unless `compiled` has it already —
493    /// driver TUs are commonly linked by several PDs. That holds only while
494    /// per-PD compilation stays uniform (same flags, no per-PD defines).
495    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    /// `<out_dir>/libproject.a` of `sources`, each its [`object_for`];
542    /// `None` when there are none. Rewritten whole, so a deleted source
543    /// leaves no member behind.
544    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
583/// A driver source's object: `<out_dir>/obj/` then its path in `project`
584/// (or its absolute path, outside it), so no two sources share one, nor
585/// one a PD's unit.
586fn 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/// Compile a PD's unit `file` and link it into a bare-metal ELF for the
596/// board, against the SDK's linker script.
597///
598/// `extra_sources` are the separate-driver `.c` files paired with a PD's `.h`
599/// imports (`eth.c` with `eth.h`), each compiled to its own [`object_for`]
600/// and linked beside `file`'s object, `<out_dir>/<stem>.o`; `extra_objects`
601/// are built elsewhere (the PD's Pancake); `archive` is the project's other C.
602#[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    // The generated unit to `<out_dir>/<pd>.o`, every paired driver source
620    // to its own path under `obj/`, all linked into the one ELF.
621    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    // The unit with the runtime first, its ring calls hidden from the rest.
631    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    // After every object, so ld knows what is still missing.
638    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
656/// Generate a bootable Microkit image from a system description and pre-built
657/// ELFs.
658///
659/// Delegates to [`microkit_tool::build`] (needs `$MICROKIT_SDK`), which packs
660/// the loader, the seL4 kernel and every PD ELF — located via `search_paths` —
661/// into `output`, with a build report at `report`.
662fn 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}