ostool 0.18.0

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
//! Cargo build command builder and executor.
//!
//! This module provides the [`CargoBuilder`] type for constructing and executing
//! Cargo build commands with customizable options, environment variables, and
//! pre/post build hooks.

use std::{
    collections::HashMap,
    io::BufReader,
    path::{Path, PathBuf},
    process::Stdio,
};

use anyhow::{Context, anyhow, bail};
use cargo_metadata::{Message, PackageId};
use colored::Colorize;

use crate::{
    Tool,
    build::{
        config::{Cargo, CargoBuildProfile},
        someboot,
    },
    utils::{Command, PathResultExt},
};

#[derive(Debug, Clone)]
struct ResolvedCargoArtifact {
    elf_path: PathBuf,
    cargo_artifact_dir: PathBuf,
}

/// A builder for constructing and executing Cargo commands.
///
/// `CargoBuilder` provides a fluent API for configuring Cargo build or run
/// commands with custom arguments, environment variables, and build hooks.
///
/// This builder is an internal implementation detail used by [`Tool`].
pub struct CargoBuilder<'a> {
    tool: &'a mut Tool,
    config: &'a Cargo,
    command: String,
    extra_args: Vec<String>,
    extra_envs: HashMap<String, String>,
    skip_objcopy: bool,
    resolve_artifact_from_json: bool,
    resolved_artifact: Option<ResolvedCargoArtifact>,
    config_path: Option<PathBuf>,
}

impl<'a> CargoBuilder<'a> {
    /// Creates a new `CargoBuilder` for executing `cargo build`.
    ///
    /// # Arguments
    ///
    /// * `tool` - The tool context.
    /// * `config` - The Cargo build configuration.
    /// * `config_path` - Optional path to the configuration file.
    pub fn build(tool: &'a mut Tool, config: &'a Cargo, config_path: Option<PathBuf>) -> Self {
        Self {
            tool,
            config,
            command: "build".to_string(),
            extra_args: Vec::new(),
            extra_envs: HashMap::new(),
            skip_objcopy: false,
            resolve_artifact_from_json: true,
            resolved_artifact: None,
            config_path,
        }
    }

    /// Sets the debug mode for the build.
    ///
    /// When enabled, builds in debug mode and enables GDB server for QEMU.
    pub fn debug(self, debug: bool) -> Self {
        self.tool.config.debug = debug;
        self
    }

    /// Creates a build command using the context's stored config path.
    pub fn build_auto(tool: &'a mut Tool, config: &'a Cargo) -> Self {
        let config_path = tool.ctx.build_config_path.clone();
        Self::build(tool, config, config_path)
    }

    /// Sets whether to skip the objcopy step after building.
    pub fn skip_objcopy(mut self, skip: bool) -> Self {
        self.skip_objcopy = skip;
        self
    }

    /// Enables artifact path resolution from Cargo JSON messages.
    pub fn resolve_artifact_from_json(mut self, enable: bool) -> Self {
        self.resolve_artifact_from_json = enable;
        self
    }

    /// Executes the configured Cargo command.
    ///
    /// This runs pre-build commands, executes Cargo, handles output artifacts,
    /// and runs post-build commands.
    ///
    /// # Errors
    ///
    /// Returns an error if any step of the build process fails.
    pub async fn execute(mut self) -> anyhow::Result<()> {
        // 1. Pre-build commands
        self.run_pre_build_cmds()?;

        // 2. Build and run cargo
        self.run_cargo().await?;

        // 3. Handle output
        self.handle_output().await?;

        // 4. Post-build commands
        self.run_post_build_cmds()?;

        Ok(())
    }

    fn run_pre_build_cmds(&mut self) -> anyhow::Result<()> {
        for cmd in &self.config.pre_build_cmds {
            self.tool.shell_run_cmd(cmd)?;
        }
        Ok(())
    }

    async fn run_cargo(&mut self) -> anyhow::Result<()> {
        self.run_cargo_and_resolve_artifact().await
    }

    async fn run_cargo_and_resolve_artifact(&mut self) -> anyhow::Result<()> {
        let (target_pkg_id, default_run) = self.target_package_info()?;
        let mut cmd = self.build_cargo_command().await?;

        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::inherit());
        cmd.print_cmd();

        let mut child = cmd
            .spawn()
            .context("failed to spawn cargo build command for artifact resolution")?;

        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| anyhow!("failed to capture cargo stdout for message parsing"))?;
        let reader = BufReader::new(stdout);

        let mut executable_artifacts: Vec<(String, ResolvedCargoArtifact)> = Vec::new();
        for message in Message::parse_stream(reader) {
            let message = message.context("failed to parse cargo JSON message stream")?;
            match message {
                Message::CompilerArtifact(artifact) => {
                    if artifact.package_id == target_pkg_id
                        && artifact.target.is_bin()
                        && let Some(executable) = artifact.executable
                    {
                        let elf_path = executable.into_std_path_buf();
                        let cargo_artifact_dir = elf_path
                            .parent()
                            .ok_or_else(|| {
                                anyhow!(
                                    "cargo reported executable without parent directory: {}",
                                    elf_path.display()
                                )
                            })?
                            .to_path_buf();
                        executable_artifacts.push((
                            artifact.target.name,
                            ResolvedCargoArtifact {
                                elf_path,
                                cargo_artifact_dir,
                            },
                        ));
                    }
                }
                Message::CompilerMessage(msg) => {
                    if let Some(rendered) = msg.message.rendered {
                        eprint!("{rendered}");
                    }
                }
                Message::TextLine(line) => {
                    println!("{line}");
                }
                _ => {}
            }
        }

        let status = child
            .wait()
            .context("failed waiting for cargo build process")?;
        if !status.success() {
            bail!("failed with status: {status}");
        }

        let resolved = select_executable_artifact(
            &executable_artifacts,
            self.config.bin.as_deref(),
            default_run.as_deref(),
            &self.config.package,
        )?;

        self.resolved_artifact = Some(resolved);
        Ok(())
    }

    async fn build_cargo_command(&mut self) -> anyhow::Result<Command> {
        let mut cmd = self.tool.command("cargo");

        cmd.arg(&self.command);

        for (k, v) in &self.config.env {
            println!("{}", format!("{k}={v}").cyan());
            cmd.env(k, v);
        }
        for (k, v) in &self.extra_envs {
            println!("{}", format!("{k}={v}").cyan());
            cmd.env(k, v);
        }

        // Extra config
        if let Some(extra_config_path) = self.cargo_extra_config().await? {
            cmd.arg("--config");
            cmd.arg(extra_config_path.display().to_string());
        }

        // Package and target
        cmd.arg("-p");
        cmd.arg(&self.config.package);
        if let Some(bin) = &self.config.bin {
            cmd.arg("--bin");
            cmd.arg(bin);
        }
        cmd.arg("--target");
        cmd.arg(&self.config.target);
        cmd.arg("-Z");
        cmd.arg("unstable-options");

        cmd.arg("--target-dir");
        cmd.arg(self.tool.build_dir().display().to_string());

        // Features
        let features = self.build_features();
        if !features.is_empty() {
            cmd.arg("--features");
            cmd.arg(features.join(","));
        }

        // Config args
        for arg in &self.config.args {
            cmd.arg(arg);
        }

        // Auto-detected args from someboot/build-info.toml
        let workspace_manifest = self.tool.workspace_dir().join("Cargo.toml");
        if workspace_manifest.exists() {
            let detected_args = someboot::detect_build_config_for_package(
                &workspace_manifest,
                &self.config.package,
                &features,
                &self.config.target,
            )
            .with_context(|| {
                format!(
                    "failed to detect someboot build config from {}",
                    workspace_manifest.display()
                )
            })?;
            for arg in detected_args {
                cmd.arg(arg);
            }
        }

        // Release mode
        if self.effective_profile() == CargoBuildProfile::Release {
            cmd.arg("--release");
        }

        cmd.arg("--message-format");
        cmd.arg("json-render-diagnostics");

        // Extra args
        for arg in &self.extra_args {
            cmd.arg(arg);
        }

        Ok(cmd)
    }

    /// Applies the resolved Cargo artifact to the legacy tool runtime state.
    async fn handle_output(&mut self) -> anyhow::Result<()> {
        let resolved = self.resolved_artifact.clone().ok_or_else(|| {
            anyhow!(
                "cargo build finished without a resolved executable artifact for package '{}' and target '{}'",
                self.config.package,
                self.config.target
            )
        })?;

        self.tool.set_elf_artifact_path(resolved.elf_path).await?;
        self.tool.ctx.artifacts.cargo_artifact_dir = Some(resolved.cargo_artifact_dir.clone());
        self.tool.ctx.artifacts.runtime_artifact_dir = Some(resolved.cargo_artifact_dir);

        if self.config.to_bin && !self.skip_objcopy {
            self.tool.objcopy_output_bin()?;
        }

        Ok(())
    }

    fn run_post_build_cmds(&mut self) -> anyhow::Result<()> {
        for cmd in &self.config.post_build_cmds {
            self.tool.shell_run_cmd(cmd)?;
        }
        Ok(())
    }

    fn target_package_info(&self) -> anyhow::Result<(PackageId, Option<String>)> {
        let metadata = self.tool.metadata()?;
        let Some(package) = metadata
            .packages
            .iter()
            .find(|pkg| pkg.name == self.config.package)
        else {
            bail!(
                "package '{}' not found in cargo metadata under {}",
                self.config.package,
                self.tool.manifest_dir().display()
            );
        };
        Ok((package.id.clone(), package.default_run.clone()))
    }

    fn build_features(&self) -> Vec<String> {
        let mut features = self.config.features.clone();
        if let Some(log_level) = self.log_level_feature() {
            features.push(log_level);
        }
        features
    }

    fn effective_profile(&self) -> CargoBuildProfile {
        self.config.profile.unwrap_or_else(|| {
            if self.tool.debug_enabled() {
                CargoBuildProfile::Debug
            } else {
                CargoBuildProfile::Release
            }
        })
    }

    fn log_level_feature(&self) -> Option<String> {
        let level = self.config.log.clone()?;

        let meta = self.tool.metadata().ok()?;
        let pkg = meta
            .packages
            .iter()
            .find(|p| p.name == self.config.package)?;

        let has_log = pkg.dependencies.iter().any(|dep| dep.name == "log");

        if has_log {
            Some(format!(
                "log/{}max_level_{}",
                if self.effective_profile() == CargoBuildProfile::Debug {
                    ""
                } else {
                    "release_"
                },
                format!("{:?}", level).to_lowercase()
            ))
        } else {
            None
        }
    }

    /// Resolves an optional extra Cargo config from a local path or URL.
    async fn cargo_extra_config(&self) -> anyhow::Result<Option<PathBuf>> {
        let s = match self.config.extra_config.as_ref() {
            Some(s) => s,
            None => return Ok(None),
        };

        // Check if it's a URL (starts with http:// or https://)
        if s.starts_with("http://") || s.starts_with("https://") {
            // Convert GitHub URL to raw content URL if needed
            let download_url = Self::convert_to_raw_url(s);

            // Download to temp directory
            match self.download_config_to_temp(&download_url).await {
                Ok(path) => Ok(Some(path)),
                Err(e) => {
                    eprintln!("Failed to download config from {}: {}", s, e);
                    Err(e)
                }
            }
        } else {
            // It's a local path
            let extra = Path::new(s);

            if extra.is_relative() {
                if let Some(ref config_path) = self.config_path {
                    let combined = config_path
                        .parent()
                        .ok_or_else(|| {
                            anyhow::anyhow!(
                                "invalid config path without parent: {}",
                                config_path.display()
                            )
                        })?
                        .join(extra);
                    Ok(Some(combined))
                } else {
                    Ok(Some(extra.to_path_buf()))
                }
            } else {
                Ok(Some(extra.to_path_buf()))
            }
        }
    }

    /// Convert GitHub URL to raw content URL
    /// Supports:
    /// - https://github.com/user/repo/blob/branch/path/file -> https://raw.githubusercontent.com/user/repo/branch/path/file
    /// - https://raw.githubusercontent.com/... (already raw, no change)
    /// - Other URLs: no change
    fn convert_to_raw_url(url: &str) -> String {
        // Already a raw URL
        if url.contains("raw.githubusercontent.com") || url.contains("raw.github.com") {
            return url.to_string();
        }

        // Convert github.com/user/repo/blob/... to raw.githubusercontent.com/user/repo/...
        if url.contains("github.com") && url.contains("/blob/") {
            let converted = url
                .replace("github.com", "raw.githubusercontent.com")
                .replace("/blob/", "/");
            println!("Converting GitHub URL to raw: {} -> {}", url, converted);
            return converted;
        }

        // Not a GitHub URL or already in correct format
        url.to_string()
    }

    async fn download_config_to_temp(&self, url: &str) -> anyhow::Result<PathBuf> {
        use std::time::SystemTime;

        println!("Downloading cargo config from: {}", url);

        // Get system temp directory
        let temp_dir = std::env::temp_dir();

        // Generate filename with timestamp
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Extract filename from URL or use default
        let url_path = url.split('/').next_back().unwrap_or("config.toml");
        let filename = format!("cargo_config_{}_{}", timestamp, url_path);
        let target_path = temp_dir.join(filename);

        // Create reqwest client
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {}", e))?;

        // Build request with User-Agent for GitHub
        let mut request = client.get(url);

        if url.contains("github.com") || url.contains("githubusercontent.com") {
            // GitHub requires User-Agent
            request = request.header("User-Agent", "ostool-cargo-downloader");
        }

        // Download the file
        let response = request
            .send()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to download from {}: {}", url, e))?;

        if !response.status().is_success() {
            return Err(anyhow::anyhow!("HTTP error {}: {}", response.status(), url));
        }

        let content = response
            .bytes()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to read response body: {}", e))?;

        // Write to temp file
        tokio::fs::write(&target_path, content)
            .await
            .with_path("failed to write downloaded cargo config", &target_path)
            .with_context(|| format!("while downloading cargo config from {url}"))?;

        println!("Config downloaded to: {}", target_path.display());

        Ok(target_path)
    }
}

fn select_executable_artifact(
    executable_artifacts: &[(String, ResolvedCargoArtifact)],
    explicit_bin: Option<&str>,
    default_run: Option<&str>,
    package: &str,
) -> anyhow::Result<ResolvedCargoArtifact> {
    if let Some(bin) = explicit_bin {
        return executable_artifacts
            .iter()
            .rev()
            .find(|(name, _)| name == bin)
            .map(|(_, artifact)| artifact.clone())
            .ok_or_else(|| {
                anyhow!(
                    "binary target `{bin}` was not built for package `{package}`; check system.Cargo.bin or --bin"
                )
            });
    }

    if executable_artifacts.is_empty() {
        bail!(
            "no executable bin artifact found in cargo JSON output for package `{package}`; ostool currently resolves only Cargo bin targets"
        );
    }

    if let Some((_, artifact)) = executable_artifacts
        .iter()
        .rev()
        .find(|(name, _)| name == package)
    {
        return Ok(artifact.clone());
    }

    if let Some(default_bin) = default_run
        && let Some((_, artifact)) = executable_artifacts
            .iter()
            .rev()
            .find(|(name, _)| name == default_bin)
    {
        return Ok(artifact.clone());
    }

    if executable_artifacts.len() == 1 {
        return Ok(executable_artifacts[0].1.clone());
    }

    let bins = executable_artifacts
        .iter()
        .map(|(name, _)| name.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    bail!(
        "package `{package}` has multiple binary targets ({bins}); pass system.Cargo.bin or --bin"
    )
}

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

    use super::{CargoBuilder, ResolvedCargoArtifact, select_executable_artifact};
    use crate::{
        Tool, ToolConfig,
        build::config::{Cargo, CargoBuildProfile},
    };

    fn artifact(name: &str) -> ResolvedCargoArtifact {
        let cargo_artifact_dir = PathBuf::from("/tmp/ostool-target/debug");
        ResolvedCargoArtifact {
            elf_path: cargo_artifact_dir.join(name),
            cargo_artifact_dir,
        }
    }

    fn select(
        artifacts: &[(String, ResolvedCargoArtifact)],
        explicit_bin: Option<&str>,
        default_run: Option<&str>,
        package: &str,
    ) -> anyhow::Result<ResolvedCargoArtifact> {
        select_executable_artifact(artifacts, explicit_bin, default_run, package)
    }

    #[test]
    fn select_executable_artifact_uses_explicit_bin_first() {
        let artifacts = vec![
            ("kernel".to_string(), artifact("kernel")),
            ("kernel-qemu".to_string(), artifact("kernel-qemu")),
        ];

        let selected = select(&artifacts, Some("kernel-qemu"), None, "kernel").unwrap();

        assert_eq!(
            selected.elf_path,
            Path::new("/tmp/ostool-target/debug/kernel-qemu")
        );
    }

    #[test]
    fn select_executable_artifact_errors_when_explicit_bin_was_not_built() {
        let artifacts = vec![("kernel".to_string(), artifact("kernel"))];

        let err = select(&artifacts, Some("missing-bin"), None, "kernel").unwrap_err();

        assert!(
            err.to_string()
                .contains("binary target `missing-bin` was not built")
        );
    }

    #[test]
    fn select_executable_artifact_prefers_package_name_before_default_run() {
        let artifacts = vec![
            ("helper".to_string(), artifact("helper")),
            ("kernel".to_string(), artifact("kernel")),
        ];

        let selected = select(&artifacts, None, Some("helper"), "kernel").unwrap();

        assert_eq!(
            selected.elf_path,
            Path::new("/tmp/ostool-target/debug/kernel")
        );
    }

    #[test]
    fn select_executable_artifact_uses_default_run_without_package_name_binary() {
        let artifacts = vec![
            ("helper".to_string(), artifact("helper")),
            ("boot-test".to_string(), artifact("boot-test")),
        ];

        let selected = select(&artifacts, None, Some("boot-test"), "kernel").unwrap();

        assert_eq!(
            selected.elf_path,
            Path::new("/tmp/ostool-target/debug/boot-test")
        );
    }

    #[test]
    fn select_executable_artifact_uses_single_binary_as_fallback() {
        let artifacts = vec![("helper".to_string(), artifact("helper"))];

        let selected = select(&artifacts, None, None, "kernel").unwrap();

        assert_eq!(
            selected.elf_path,
            Path::new("/tmp/ostool-target/debug/helper")
        );
    }

    #[test]
    fn select_executable_artifact_errors_on_empty_cargo_output() {
        let err = select(&[], None, None, "kernel").unwrap_err();

        assert!(err.to_string().contains("no executable bin artifact found"));
    }

    #[test]
    fn select_executable_artifact_errors_on_ambiguous_multiple_binaries() {
        let artifacts = vec![
            ("kernel-qemu".to_string(), artifact("kernel-qemu")),
            ("kernel-uboot".to_string(), artifact("kernel-uboot")),
        ];

        let err = select(&artifacts, None, None, "kernel").unwrap_err();

        let rendered = err.to_string();
        assert!(rendered.contains("multiple binary targets"));
        assert!(rendered.contains("kernel-qemu"));
        assert!(rendered.contains("kernel-uboot"));
    }

    /// Verifies resolved Cargo artifacts are recorded into runtime state.
    ///
    /// This covers post-resolution Tool state, not serde/config loading.
    #[tokio::test]
    async fn handle_output_records_runtime_artifact_state_without_objcopy() {
        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 {
            env: HashMap::new(),
            target: "aarch64-unknown-none".into(),
            package: "kernel".into(),
            bin: None,
            features: vec![],
            log: None,
            extra_config: None,
            profile: Some(CargoBuildProfile::Debug),
            args: vec![],
            pre_build_cmds: vec![],
            post_build_cmds: vec![],
            to_bin: true,
        };

        let mut tool = Tool::new(ToolConfig {
            manifest: Some(temp.path().to_path_buf()),
            ..Default::default()
        })
        .unwrap();

        let mut builder = CargoBuilder::build(&mut tool, &config, None).skip_objcopy(true);
        builder.resolved_artifact = Some(ResolvedCargoArtifact {
            elf_path: elf_path.clone(),
            cargo_artifact_dir: cargo_artifact_dir.clone(),
        });
        builder.handle_output().await.unwrap();
        drop(builder);

        let expected_elf = elf_path.canonicalize().unwrap();
        assert_eq!(tool.ctx.artifacts.elf.as_ref(), Some(&expected_elf));
        assert!(tool.ctx.artifacts.bin.is_none());
        assert_eq!(
            tool.ctx.artifacts.cargo_artifact_dir.as_ref(),
            Some(&cargo_artifact_dir)
        );
        assert_eq!(
            tool.ctx.artifacts.runtime_artifact_dir.as_ref(),
            Some(&cargo_artifact_dir)
        );
        assert!(tool.ctx.arch.is_some());
    }
}