ostool 0.30.1

A tool for operating system development
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! Build system configuration and Cargo integration.
//!
//! This module provides functionality for building operating system projects
//! using Cargo or custom build commands. It supports:
//!
//! - Configuring build options via TOML configuration files
//! - Running pre-build and post-build shell commands
//! - Automatic feature detection and configuration
//! - Multiple runner types (QEMU and U-Boot)
//!
//! # Example
//!
//! ```rust,no_run
//! use ostool::build::config::{BuildConfig, BuildSystem, Cargo};
//!
//! // Build configurations are typically loaded from TOML files
//! // See .build.toml for example configuration format
//! ```

use std::path::{Path, PathBuf};

use anyhow::{Context, bail};

use crate::{
    artifact::runtime::{
        RuntimeArtifactOptions, prepare_runtime_artifacts as prepare_runtime_artifact_outputs,
    },
    build::{
        cargo_pipeline::{CargoBuildInput, CargoBuildOutcome, CargoBuildPipeline},
        config::{BuildConfig, BuildSystem, Cargo, Custom},
    },
    invocation::{ActiveBuildContext, ActiveCargoBuild, ActiveCustomBuild, Invocation},
    project::{ProjectLayout, metadata, variables::VariableScope},
    run::{
        qemu::{QemuConfig, RunQemuOptions},
        uboot::UbootConfig,
    },
};

mod artifact_selector;
pub(crate) mod config_hooks;
pub(crate) mod config_loader;

/// Cargo pipeline implementation for building projects.
mod cargo_pipeline;

/// Build configuration types and structures.
pub mod config;

pub mod someboot;

/// Executable artifact information produced by a Cargo build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CargoBuildOutput {
    elf_path: PathBuf,
    cargo_artifact_dir: PathBuf,
}

impl CargoBuildOutput {
    fn new(elf_path: PathBuf, cargo_artifact_dir: PathBuf) -> Self {
        Self {
            elf_path,
            cargo_artifact_dir,
        }
    }

    /// Path to the executable ELF reported by Cargo.
    pub fn elf_path(&self) -> &Path {
        &self.elf_path
    }

    /// Directory containing the executable artifact reported by Cargo.
    pub fn cargo_artifact_dir(&self) -> &Path {
        &self.cargo_artifact_dir
    }
}

impl From<&CargoBuildOutcome> for CargoBuildOutput {
    fn from(outcome: &CargoBuildOutcome) -> Self {
        let resolved = outcome.resolved_artifact();
        Self::new(
            resolved.elf_path().to_path_buf(),
            resolved.cargo_artifact_dir().to_path_buf(),
        )
    }
}

/// Input for preparing runtime artifacts from an already built ELF.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeArtifactInput {
    elf_path: PathBuf,
    to_bin: bool,
    cargo_artifact_dir: Option<PathBuf>,
    strip_elf: bool,
}

impl RuntimeArtifactInput {
    /// Creates a runtime artifact input from an ELF path.
    pub fn new(elf_path: impl Into<PathBuf>, to_bin: bool) -> Self {
        Self {
            elf_path: elf_path.into(),
            to_bin,
            cargo_artifact_dir: None,
            strip_elf: false,
        }
    }

    /// Associates the input ELF with the Cargo artifact directory that produced it.
    pub fn with_cargo_artifact_dir(mut self, cargo_artifact_dir: impl Into<PathBuf>) -> Self {
        self.cargo_artifact_dir = Some(cargo_artifact_dir.into());
        self
    }

    /// Copies the input ELF into a stripped runtime `.elf` before preparing outputs.
    pub fn strip_elf(mut self, strip_elf: bool) -> Self {
        self.strip_elf = strip_elf;
        self
    }
}

/// Parameters for running a built Cargo artifact in QEMU.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CargoQemuRunnerArgs {
    /// Optional fully prepared QEMU runtime configuration.
    pub qemu: Option<QemuConfig>,
    /// Whether to enable debug mode (GDB server).
    pub debug: bool,
    /// Whether to dump the device tree blob.
    pub dtb_dump: bool,
}

/// Parameters for running a built Cargo artifact on real hardware via U-Boot.
#[derive(Debug, Clone, Default)]
pub struct CargoUbootRunnerArgs {
    /// Optional fully prepared U-Boot runtime configuration.
    pub uboot: Option<UbootConfig>,
}

/// Specifies the type of runner to use after building.
///
/// This enum determines how the built artifact will be executed,
/// through QEMU emulation or U-Boot on real hardware.
pub enum CargoRunnerKind {
    /// Run the built artifact in QEMU emulator.
    Qemu(Box<CargoQemuRunnerArgs>),
    /// Run the built artifact on real hardware via U-Boot.
    Uboot(Box<CargoUbootRunnerArgs>),
}

impl CargoRunnerKind {
    pub fn new_qemu(args: CargoQemuRunnerArgs) -> Self {
        Self::Qemu(Box::new(args))
    }

    pub fn new_uboot(args: CargoUbootRunnerArgs) -> Self {
        Self::Uboot(Box::new(args))
    }
}

/// CLI overrides for Cargo package and binary target selection.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct CargoSelector {
    package: Option<String>,
    bin: Option<String>,
    test: Option<String>,
}

impl CargoSelector {
    /// Creates a Cargo selector from optional CLI overrides.
    #[cfg(test)]
    pub(crate) fn new(package: Option<String>, bin: Option<String>, test: Option<String>) -> Self {
        Self { package, bin, test }
    }

    /// Returns whether no selector override was supplied.
    fn is_empty(&self) -> bool {
        self.package.is_none() && self.bin.is_none() && self.test.is_none()
    }
}

/// Applies Cargo selector overrides to a build configuration.
fn apply_cargo_selector(
    config: &mut config::BuildConfig,
    selector: &CargoSelector,
) -> anyhow::Result<()> {
    if selector.is_empty() {
        return Ok(());
    }

    let config::BuildSystem::Cargo(cargo_config) = &mut config.system else {
        bail!("--package/--bin/--test can only be used with system.Cargo build configs");
    };

    if let Some(package) = &selector.package {
        cargo_config.package = package.clone();
    }
    if let Some(bin) = &selector.bin {
        cargo_config.bin = Some(bin.clone());
        cargo_config.test = None;
    }
    if let Some(test) = &selector.test {
        cargo_config.bin = None;
        cargo_config.test = Some(test.clone());
    }
    Ok(())
}

pub(crate) fn activate_build_context(
    layout: &ProjectLayout,
    mut config: BuildConfig,
    config_path: Option<PathBuf>,
    selector: &CargoSelector,
) -> anyhow::Result<ActiveBuildContext> {
    apply_cargo_selector(&mut config, selector)?;
    match config.system {
        BuildSystem::Cargo(cargo) => {
            let variable_scope = cargo_variable_scope(layout, &cargo)?;
            Ok(ActiveBuildContext::Cargo(Box::new(ActiveCargoBuild::new(
                config_path,
                variable_scope,
            ))))
        }
        BuildSystem::Custom(_) => {
            let variable_scope =
                VariableScope::for_package(layout, layout.manifest_dir().to_path_buf());
            Ok(ActiveBuildContext::Custom(ActiveCustomBuild::new(
                config_path,
                variable_scope,
            )))
        }
    }
}

pub(crate) fn cargo_variable_scope(
    layout: &ProjectLayout,
    cargo: &Cargo,
) -> anyhow::Result<VariableScope> {
    let package_dir = metadata::package_manifest_dir(layout, &cargo.package)?;
    Ok(VariableScope::for_package(layout, package_dir))
}

/// Returns the default build configuration template.
pub fn default_build_config() -> config::BuildConfig {
    config::BuildConfig::default()
}

/// Loads a build configuration from a workspace-like directory.
///
/// This only parses the config file. Apply caller overrides first, then call
/// [`activate_build_config`] or a build/run helper with the final config.
pub async fn load_build_config_from_dir(
    invocation: &Invocation,
    dir: &Path,
    menu: bool,
) -> anyhow::Result<config::BuildConfig> {
    prepare_build_config(invocation, Some(dir.join(".build.toml")), menu).await
}

/// Loads a build configuration from an explicit file path.
///
/// This only parses the config file. Apply caller overrides first, then call
/// [`activate_build_config`] or a build/run helper with the final config.
pub async fn load_build_config_from_path(
    invocation: &Invocation,
    path: &Path,
    menu: bool,
) -> anyhow::Result<config::BuildConfig> {
    prepare_build_config(invocation, Some(path.to_path_buf()), menu).await
}

/// Records the selected build configuration as active for variable expansion.
///
/// Pass `Some(path)` when `config` was loaded from a build config file so
/// relative Cargo extra config paths resolve against that file. Pass `None`
/// for in-memory build configs.
pub fn activate_build_config(
    invocation: &mut Invocation,
    config: &config::BuildConfig,
    config_path: Option<&Path>,
) -> anyhow::Result<()> {
    let active = activate_build_context(
        invocation.project_layout(),
        config.clone(),
        config_path.map(Path::to_path_buf),
        &CargoSelector::default(),
    )?;
    invocation.set_active_build(active);
    Ok(())
}

async fn prepare_build_config(
    invocation: &Invocation,
    config_path: Option<PathBuf>,
    menu: bool,
) -> anyhow::Result<BuildConfig> {
    let hooks = config_hooks::build_config_hooks(invocation.workspace_dir());
    config_loader::load_build_config(invocation.workspace_dir(), config_path, menu, &hooks).await
}

/// Builds the project using the specified build configuration.
///
/// `config_path` is the optional source path for `config`.
pub async fn build_with_config(
    invocation: &mut Invocation,
    config: &config::BuildConfig,
    config_path: Option<&Path>,
) -> anyhow::Result<()> {
    invocation.clear_debug_artifacts();
    activate_build_config(invocation, config, config_path)?;
    match &config.system {
        config::BuildSystem::Custom(custom) => build_custom(invocation, custom)?,
        config::BuildSystem::Cargo(cargo) => {
            cargo_build(invocation, cargo, config_path).await?;
        }
    }
    generate_build_analysis(invocation, config)
}

/// Runs the custom build command from a build configuration.
pub(crate) fn build_custom(invocation: &mut Invocation, config: &Custom) -> anyhow::Result<()> {
    let process_context = invocation.process_context()?;
    crate::process::shell_run_cmd(&process_context, &config.build_cmd)?;
    Ok(())
}

/// Prepares runtime ELF/BIN outputs from an already built artifact.
///
/// This is useful when a caller builds with [`cargo_build`], modifies the returned
/// ELF in place, and then wants QEMU, U-Boot, or board runners to consume the
/// updated artifact without rebuilding it.
pub fn prepare_runtime_artifact(
    invocation: &mut Invocation,
    input: RuntimeArtifactInput,
) -> anyhow::Result<()> {
    invocation.clear_debug_artifacts();
    let process_context = invocation.process_context()?;
    let prepared = prepare_runtime_artifact_outputs(
        &process_context,
        RuntimeArtifactOptions {
            elf_path: input.elf_path,
            to_bin: input.to_bin,
            bin_dir: invocation.bin_dir(),
            debug: invocation.options().debug(),
            cargo_artifact_dir: input.cargo_artifact_dir,
            strip_elf: input.strip_elf,
        },
    )?;
    invocation.apply_prepared_runtime_artifacts(prepared);
    Ok(())
}

/// Builds the project using Cargo and returns the executable artifact selected from Cargo output.
///
/// `config_path` is the optional `.build.toml` source path for `config`.
pub async fn cargo_build(
    invocation: &mut Invocation,
    config: &Cargo,
    config_path: Option<&Path>,
) -> anyhow::Result<CargoBuildOutput> {
    invocation.clear_debug_artifacts();
    activate_build_config(
        invocation,
        &BuildConfig {
            artifacts: Default::default(),
            system: BuildSystem::Cargo(Box::new(config.clone())),
        },
        config_path,
    )?;
    let debug = invocation.options().debug();
    let input = cargo_build_input(invocation, config, debug)?;
    let outcome = CargoBuildPipeline::build(input, config).execute().await?;
    apply_cargo_build_outcome(invocation, config, &outcome, false, debug)?;
    run_cargo_post_build_cmds(invocation, config)?;
    Ok(CargoBuildOutput::from(&outcome))
}

/// Builds or imports the configured artifact and prepares the runtime outputs.
pub async fn prepare_with_config(
    invocation: &mut Invocation,
    config: &config::BuildConfig,
    config_path: Option<&Path>,
    debug: bool,
) -> anyhow::Result<()> {
    invocation.clear_debug_artifacts();
    activate_build_config(invocation, config, config_path)?;
    match &config.system {
        config::BuildSystem::Custom(custom) => {
            prepare_custom_runtime_artifacts(invocation, custom).await?;
        }
        config::BuildSystem::Cargo(cargo) => {
            prepare_cargo_runtime_artifacts(invocation, cargo, debug).await?;
        }
    }
    generate_build_analysis(invocation, config)
}

fn generate_build_analysis(
    invocation: &mut Invocation,
    config: &BuildConfig,
) -> anyhow::Result<()> {
    if !config.artifacts.analysis.is_enabled() {
        return Ok(());
    }
    let source = match &config.system {
        BuildSystem::Cargo(_) => invocation
            .runtime_artifacts()
            .cargo_source_elf()
            .context("Cargo build did not select an ELF for analysis")?
            .to_path_buf(),
        BuildSystem::Custom(custom) => {
            let path = PathBuf::from(&custom.elf_path);
            if path.is_absolute() {
                path
            } else {
                invocation.manifest_dir().join(path)
            }
        }
    };
    let artifacts = crate::artifact::analysis::generate(
        &invocation.process_context()?,
        &config.artifacts.analysis,
        &source,
    )?;
    invocation.replace_debug_artifacts(artifacts);
    Ok(())
}

async fn prepare_custom_runtime_artifacts(
    invocation: &mut Invocation,
    config: &Custom,
) -> anyhow::Result<()> {
    build_custom(invocation, config)?;
    let path = PathBuf::from(&config.elf_path);
    let path = if path.is_absolute() {
        path
    } else {
        invocation.manifest_dir().join(path)
    };
    invocation.prepare_elf_artifact(path, config.to_bin).await
}

async fn prepare_cargo_runtime_artifacts(
    invocation: &mut Invocation,
    config: &Cargo,
    debug: bool,
) -> anyhow::Result<()> {
    let input = cargo_build_input(invocation, config, debug)?;
    let outcome = CargoBuildPipeline::build(input, config)
        .skip_objcopy(true)
        .resolve_artifact_from_json(true)
        .execute()
        .await?;
    apply_cargo_build_outcome(invocation, config, &outcome, true, debug)?;
    run_cargo_post_build_cmds(invocation, config)?;
    Ok(())
}

/// Builds and runs the project using Cargo with the specified runner.
///
/// `config_path` is the optional `.build.toml` source path for `config`.
pub async fn cargo_run(
    invocation: &mut Invocation,
    config: &Cargo,
    config_path: Option<&Path>,
    runner: &CargoRunnerKind,
) -> anyhow::Result<()> {
    cargo_run_with_config(
        invocation,
        &BuildConfig {
            system: BuildSystem::Cargo(Box::new(config.clone())),
            artifacts: Default::default(),
        },
        config_path,
        runner,
    )
    .await
}

/// Builds and runs Cargo with the complete configuration, including optional analysis.
///
/// Rejects custom build configurations. Analysis failures are returned before
/// starting the runner; [`cargo_run`] uses the default analysis configuration.
pub async fn cargo_run_with_config(
    invocation: &mut Invocation,
    config: &BuildConfig,
    config_path: Option<&Path>,
    runner: &CargoRunnerKind,
) -> anyhow::Result<()> {
    let BuildSystem::Cargo(cargo) = &config.system else {
        anyhow::bail!("cargo_run_with_config requires a Cargo build configuration");
    };
    let debug = matches!(runner, CargoRunnerKind::Qemu(args) if args.debug);
    prepare_with_config(invocation, config, config_path, debug).await?;

    match runner {
        CargoRunnerKind::Qemu(args) => {
            let qemu = match &args.qemu {
                Some(config) => config.clone(),
                None => crate::run::qemu::ensure_config_for_cargo(invocation, cargo).await?,
            };
            crate::run::qemu::run_qemu_with_debug(
                invocation,
                &qemu,
                RunQemuOptions {
                    dtb_dump: args.dtb_dump,
                },
                debug,
            )
            .await?;
        }
        CargoRunnerKind::Uboot(args) => {
            let uboot = match &args.uboot {
                Some(config) => config.clone(),
                None => crate::run::uboot::ensure_config_for_cargo(invocation, cargo).await?,
            };
            crate::run::uboot::run_uboot(invocation, &uboot).await?;
        }
    }

    Ok(())
}

fn cargo_build_input(
    invocation: &Invocation,
    config: &Cargo,
    debug: bool,
) -> anyhow::Result<CargoBuildInput> {
    Ok(CargoBuildInput::new(
        invocation.project_layout().clone(),
        invocation.process_context()?,
        invocation.build_dir(),
        invocation
            .state()
            .build_config_path()
            .map(std::path::Path::to_path_buf),
        debug,
        !config.disable_someboot_build_config,
    ))
}

fn apply_cargo_build_outcome(
    invocation: &mut Invocation,
    config: &Cargo,
    outcome: &CargoBuildOutcome,
    skip_objcopy: bool,
    debug: bool,
) -> anyhow::Result<()> {
    let resolved = outcome.resolved_artifact();
    let process_context = invocation.process_context()?;
    let prepared = prepare_runtime_artifact_outputs(
        &process_context,
        RuntimeArtifactOptions {
            elf_path: resolved.elf_path().to_path_buf(),
            to_bin: config.to_bin && !skip_objcopy,
            bin_dir: invocation.bin_dir(),
            debug,
            cargo_artifact_dir: Some(resolved.cargo_artifact_dir().to_path_buf()),
            strip_elf: false,
        },
    )?;
    invocation.apply_prepared_runtime_artifacts(prepared);
    Ok(())
}

fn run_cargo_post_build_cmds(invocation: &mut Invocation, config: &Cargo) -> anyhow::Result<()> {
    let process_context = invocation.process_context()?;
    for cmd in &config.post_build_cmds {
        crate::process::shell_run_cmd(&process_context, cmd)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::{fs, path::PathBuf};

    use crate::{
        build::{
            artifact_selector::ResolvedCargoArtifact,
            cargo_pipeline::CargoBuildOutcome,
            config::{BuildConfig, BuildSystem, Cargo, CargoBuildProfile, Custom},
        },
        invocation::{Invocation, InvocationOptions},
        project::resolve_project_layout,
    };

    use super::{
        CargoBuildOutput, CargoSelector, RuntimeArtifactInput, activate_build_config,
        activate_build_context, apply_cargo_build_outcome, build_with_config,
        prepare_runtime_artifact,
    };

    #[test]
    fn apply_cargo_build_outcome_records_runtime_artifact_state() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join("Cargo.toml"),
            "[package]\nname = \"kernel\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("src/main.rs"), "fn main() {}\n").unwrap();

        let cargo_artifact_dir = temp.path().join("target/aarch64/debug");
        fs::create_dir_all(&cargo_artifact_dir).unwrap();
        let elf_path = cargo_artifact_dir.join("kernel");
        fs::copy(std::env::current_exe().unwrap(), &elf_path).unwrap();

        let config = Cargo {
            target: "aarch64-unknown-none".into(),
            package: "kernel".into(),
            profile: Some(CargoBuildProfile::Debug),
            to_bin: true,
            ..Default::default()
        };
        let mut invocation = Invocation::new(InvocationOptions::new(
            Some(temp.path().to_path_buf()),
            None,
            None,
            false,
        ))
        .unwrap();
        let outcome = CargoBuildOutcome::new(ResolvedCargoArtifact::new(
            elf_path.clone(),
            cargo_artifact_dir.clone(),
        ));

        apply_cargo_build_outcome(&mut invocation, &config, &outcome, true, false).unwrap();

        let expected_elf = elf_path.canonicalize().unwrap();
        assert_eq!(
            invocation.runtime_artifacts().elf(),
            Some(expected_elf.as_path())
        );
        assert!(invocation.runtime_artifacts().bin().is_none());
        assert_eq!(
            invocation.runtime_artifacts().cargo_artifact_dir(),
            Some(cargo_artifact_dir.as_path())
        );
        assert_eq!(
            invocation.runtime_artifacts().cargo_source_artifact_dir(),
            Some(cargo_artifact_dir.as_path())
        );
        assert_eq!(
            invocation.runtime_artifacts().cargo_source_elf(),
            Some(expected_elf.as_path())
        );
        assert_eq!(
            invocation.runtime_artifacts().runtime_artifact_dir(),
            Some(cargo_artifact_dir.as_path())
        );
        assert!(invocation.runtime_artifacts().debug_artifacts().is_empty());
        assert!(invocation.runtime_arch().is_some());
    }

    #[test]
    fn cargo_build_output_exposes_resolved_artifact_paths() {
        let cargo_artifact_dir = PathBuf::from("target/aarch64/release");
        let elf_path = cargo_artifact_dir.join("kernel");
        let outcome = CargoBuildOutcome::new(ResolvedCargoArtifact::new(
            elf_path.clone(),
            cargo_artifact_dir.clone(),
        ));

        let output = CargoBuildOutput::from(&outcome);

        assert_eq!(output.elf_path(), elf_path.as_path());
        assert_eq!(output.cargo_artifact_dir(), cargo_artifact_dir.as_path());
    }

    #[test]
    fn prepare_runtime_artifact_records_external_artifact_state() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join("Cargo.toml"),
            "[package]\nname = \"kernel\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("src/main.rs"), "fn main() {}\n").unwrap();

        let cargo_artifact_dir = temp.path().join("target/aarch64/debug");
        fs::create_dir_all(&cargo_artifact_dir).unwrap();
        let elf_path = cargo_artifact_dir.join("kernel");
        fs::copy(std::env::current_exe().unwrap(), &elf_path).unwrap();

        let mut invocation = Invocation::new(InvocationOptions::new(
            Some(temp.path().to_path_buf()),
            None,
            None,
            false,
        ))
        .unwrap();

        prepare_runtime_artifact(
            &mut invocation,
            RuntimeArtifactInput::new(&elf_path, false)
                .with_cargo_artifact_dir(cargo_artifact_dir.clone())
                .strip_elf(true),
        )
        .unwrap();

        let expected_elf = elf_path.canonicalize().unwrap();
        assert_eq!(
            invocation.runtime_artifacts().elf(),
            Some(elf_path.with_extension("elf").as_path())
        );
        assert!(invocation.runtime_artifacts().bin().is_none());
        assert_eq!(
            invocation.runtime_artifacts().cargo_artifact_dir(),
            Some(cargo_artifact_dir.as_path())
        );
        assert_eq!(
            invocation.runtime_artifacts().cargo_source_artifact_dir(),
            Some(cargo_artifact_dir.as_path())
        );
        assert_eq!(
            invocation.runtime_artifacts().cargo_source_elf(),
            Some(expected_elf.as_path())
        );
        assert!(invocation.runtime_arch().is_some());
    }

    #[tokio::test]
    async fn custom_build_only_does_not_prepare_runtime_artifacts() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join("Cargo.toml"),
            "[package]\nname = \"kernel\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("src/main.rs"), "fn main() {}\n").unwrap();
        let marker = temp.path().join("custom-build-ran");
        let mut invocation = Invocation::new(InvocationOptions::new(
            Some(temp.path().to_path_buf()),
            None,
            None,
            false,
        ))
        .unwrap();
        let mut stale = crate::artifact::state::DebugArtifactRegistry::default();
        stale.register(
            crate::artifact::state::DebugArtifactKind::Symbols,
            temp.path().join("old.symbols"),
        );
        invocation.replace_debug_artifacts(stale);
        let config = BuildConfig {
            artifacts: Default::default(),
            system: BuildSystem::Custom(Custom {
                build_cmd: format!("printf built > {}", marker.display()),
                elf_path: "target/kernel.elf".into(),
                to_bin: true,
            }),
        };

        build_with_config(&mut invocation, &config, None)
            .await
            .unwrap();

        assert_eq!(fs::read_to_string(marker).unwrap(), "built");
        assert!(invocation.runtime_artifacts().elf().is_none());
        assert!(invocation.runtime_artifacts().bin().is_none());
        assert!(invocation.runtime_arch().is_none());
        assert!(invocation.runtime_artifacts().debug_artifacts().is_empty());
    }

    #[test]
    fn activate_build_context_applies_cargo_selector_and_scope() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join("Cargo.toml"),
            "[package]\nname = \"kernel\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("src/bin")).unwrap();
        fs::write(temp.path().join("src/main.rs"), "fn main() {}\n").unwrap();
        fs::write(temp.path().join("src/bin/kernel-qemu.rs"), "fn main() {}\n").unwrap();
        let layout = resolve_project_layout(Some(temp.path().to_path_buf())).unwrap();
        let config_path = temp.path().join(".build.toml");
        let config = BuildConfig {
            artifacts: Default::default(),
            system: BuildSystem::Cargo(Box::new(Cargo {
                package: "placeholder".into(),
                ..Default::default()
            })),
        };

        let active = activate_build_context(
            &layout,
            config,
            Some(config_path.clone()),
            &CargoSelector::new(Some("kernel".into()), Some("kernel-qemu".into()), None),
        )
        .unwrap();

        let crate::invocation::ActiveBuildContext::Cargo(active) = active else {
            panic!("expected active Cargo build");
        };
        assert_eq!(active.config_path(), Some(config_path.as_path()));
        assert_eq!(active.variable_scope().package_dir(), temp.path());
    }

    #[test]
    fn activate_build_config_uses_explicit_path_and_clears_absent_path() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join("Cargo.toml"),
            "[package]\nname = \"kernel\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("src/main.rs"), "fn main() {}\n").unwrap();
        let mut invocation = Invocation::new(InvocationOptions::new(
            Some(temp.path().to_path_buf()),
            None,
            None,
            false,
        ))
        .unwrap();
        let config = BuildConfig {
            artifacts: Default::default(),
            system: BuildSystem::Cargo(Box::new(Cargo {
                package: "kernel".into(),
                ..Default::default()
            })),
        };
        let config_path = temp.path().join(".build.toml");

        activate_build_config(&mut invocation, &config, Some(&config_path)).unwrap();
        assert_eq!(
            invocation.state().build_config_path(),
            Some(config_path.as_path())
        );

        activate_build_config(&mut invocation, &config, None).unwrap();
        assert!(invocation.state().build_config_path().is_none());
    }

    #[test]
    fn activate_build_context_rejects_selector_for_custom_build() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join("Cargo.toml"),
            "[package]\nname = \"kernel\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        fs::create_dir_all(temp.path().join("src")).unwrap();
        fs::write(temp.path().join("src/main.rs"), "fn main() {}\n").unwrap();
        let layout = resolve_project_layout(Some(temp.path().to_path_buf())).unwrap();
        let config = BuildConfig {
            artifacts: Default::default(),
            system: BuildSystem::Custom(Custom {
                build_cmd: "make".into(),
                elf_path: "target/kernel.elf".into(),
                to_bin: true,
            }),
        };

        let err = activate_build_context(
            &layout,
            config,
            None,
            &CargoSelector::new(Some("kernel".into()), None, None),
        )
        .unwrap_err();

        assert!(
            err.to_string()
                .contains("--package/--bin/--test can only be used with system.Cargo")
        );
    }
}