axbuild 0.4.6

An OS build lib toolkit used by arceos
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
//! Shared QEMU test case asset orchestration.
//!
//! Main responsibilities:
//! - Decide whether a test case needs extra build or injection work
//! - Prepare case-scoped work directories, overlays, and auxiliary QEMU assets
//! - Dispatch C, shell, and Python case flows before rootfs content injection

use std::{
    fs,
    io::{Read, Seek, SeekFrom},
    path::{Path, PathBuf},
    sync::atomic::{AtomicU64, Ordering},
    time::Duration,
};

use anyhow::{Context, bail, ensure};
use ostool::{build::config::Cargo, run::qemu::QemuConfig};
use sha2::{Digest, Sha256};
use walkdir::WalkDir;

use super::build as case_builder;
use crate::context::AppContext;

const CASE_WORK_ROOT_NAME: &str = "qemu-cases";
const CASE_CACHE_DIR_NAME: &str = "cache";
const CASE_RUNS_DIR_NAME: &str = "runs";
/// Sub-directory under `cache_dir` that holds pre-injected rootfs images.
/// One image per cache key (`{sha256}.img`); present means ready to use.
const CASE_ROOTFS_CACHE_DIR_NAME: &str = "rootfs";
const CASE_STAGING_DIR_NAME: &str = "staging-root";
const CASE_BUILD_DIR_NAME: &str = "build";
const CASE_OVERLAY_DIR_NAME: &str = "overlay";
const CASE_COMMAND_WRAPPER_DIR_NAME: &str = "guest-bin";
const CASE_CROSS_BIN_DIR_NAME: &str = "cross-bin";
const CASE_CMAKE_TOOLCHAIN_FILE_NAME: &str = "cmake-toolchain.cmake";
const CASE_APK_CACHE_DIR_NAME: &str = "apk-cache";
const CASE_SH_DIR_NAME: &str = "sh";
const CASE_ROOTFS_COPY_NAME: &str = "case-rootfs.img";
const PYTHON_PIPELINE_CACHE_VERSION: &str = "python-apk-v1";
const RUST_PIPELINE_CACHE_VERSION: &str = "rust-cross-v1";
/// QEMU global snapshot flag — all disk writes go to a temporary file and are
/// never committed back to the image, keeping the source image pristine.
const QEMU_SNAPSHOT_ARG: &str = "-snapshot";

static CASE_RUN_ID: AtomicU64 = AtomicU64::new(0);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TestQemuCase {
    pub(crate) name: String,
    pub(crate) display_name: String,
    pub(crate) case_dir: PathBuf,
    pub(crate) qemu_config_path: PathBuf,
    pub(crate) test_commands: Vec<String>,
    pub(crate) subcases: Vec<TestQemuSubcase>,
}

impl TestQemuCase {
    pub(crate) fn is_grouped(&self) -> bool {
        !self.test_commands.is_empty()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TestQemuSubcaseKind {
    C,
    Rust,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TestQemuSubcase {
    pub(crate) name: String,
    pub(crate) case_dir: PathBuf,
    pub(crate) kind: TestQemuSubcaseKind,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GroupedCaseRunnerConfig {
    pub(crate) runner_name: String,
    pub(crate) runner_path: String,
    pub(crate) begin_marker: String,
    pub(crate) passed_marker: String,
    pub(crate) failed_marker: String,
    pub(crate) all_passed_marker: String,
    pub(crate) all_failed_marker: String,
    pub(crate) success_regex: String,
    pub(crate) fail_regex: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CaseScriptEnvConfig {
    pub(crate) staging_root: String,
    pub(crate) case_dir: String,
    pub(crate) case_c_dir: String,
    pub(crate) case_work_dir: String,
    pub(crate) case_build_dir: String,
    pub(crate) case_overlay_dir: String,
}

pub(crate) type GuestPackageEnvPrepareFn = fn(&Path) -> anyhow::Result<Vec<(String, String)>>;

#[derive(Debug, Clone)]
pub(crate) struct CaseAssetConfig {
    pub(crate) grouped_runner: GroupedCaseRunnerConfig,
    pub(crate) script_env: CaseScriptEnvConfig,
    pub(crate) cache_env_vars: Vec<String>,
    pub(crate) prepare_staging_root: fn(&Path) -> anyhow::Result<()>,
    pub(crate) prepare_guest_package_env: Option<GuestPackageEnvPrepareFn>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PreparedCaseAssets {
    /// Path of the rootfs image that QEMU should boot from.  For cases without
    /// pipeline injection this points directly to the shared source image; for
    /// cases that need injection it points to the per-case temporary copy.
    pub(crate) rootfs_path: PathBuf,
    pub(crate) extra_qemu_args: Vec<String>,
    /// Path of the temporary per-case rootfs copy to remove after the QEMU run,
    /// or `None` when the shared image was used directly (no injection needed).
    pub(crate) rootfs_copy_to_remove: Option<PathBuf>,
    pub(crate) run_dir_to_remove: Option<PathBuf>,
    pub(crate) pipeline: CasePipeline,
    pub(crate) cache_hit: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PreparedCaseAssetParts {
    pub(crate) extra_qemu_args: Vec<String>,
    pub(crate) rootfs_path: PathBuf,
    pub(crate) rootfs_copy_to_remove: Option<PathBuf>,
    pub(crate) run_dir_to_remove: Option<PathBuf>,
    pub(crate) pipeline: CasePipeline,
    pub(crate) cache_hit: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CasePipeline {
    Plain,
    Grouped,
    C,
    Sh,
    Python,
    Rust,
}

impl CasePipeline {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Plain => "plain",
            Self::Grouped => "grouped",
            Self::C => "c",
            Self::Sh => "sh",
            Self::Python => "python",
            Self::Rust => "rust",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CaseAssetLayout {
    pub(crate) work_dir: PathBuf,
    pub(crate) run_dir: PathBuf,
    pub(crate) cache_dir: PathBuf,
    /// Directory holding pre-injected rootfs cache images (`{hash}.img`).
    pub(crate) rootfs_cache_dir: PathBuf,
    pub(crate) staging_root: PathBuf,
    pub(crate) build_dir: PathBuf,
    pub(crate) overlay_dir: PathBuf,
    pub(crate) command_wrapper_dir: PathBuf,
    pub(crate) cross_bin_dir: PathBuf,
    pub(crate) cmake_toolchain_file: PathBuf,
    pub(crate) apk_cache_dir: PathBuf,
    /// Per-case copy of the shared rootfs image, used only when the case needs
    /// pipeline injection (C / shell / Python / grouped).  For plain cases no
    /// copy is created and QEMU's `-snapshot` flag keeps the shared image clean.
    pub(crate) case_rootfs_copy: PathBuf,
}

/// Resolves the workspace target directory used for a test build target.
pub(crate) fn resolve_target_dir(workspace_root: &Path, target: &str) -> anyhow::Result<PathBuf> {
    Ok(workspace_root.join("target").join(target))
}

/// Prepares any case-specific rootfs assets required by a QEMU test.
///
/// QEMU's `-snapshot` flag is always included in the returned
/// `extra_qemu_args` so that guest writes never persist to any image file.
/// A per-case rootfs copy is created only when the case requires pre-boot
/// injection (C / shell / Python / grouped pipelines); plain cases boot
/// directly from the shared image.
pub(crate) async fn prepare_case_assets(
    workspace_root: &Path,
    arch: &str,
    target: &str,
    case: &TestQemuCase,
    rootfs_path: PathBuf,
    config: CaseAssetConfig,
) -> anyhow::Result<PreparedCaseAssets> {
    let workspace_root = workspace_root.to_path_buf();
    let arch = arch.to_string();
    let target = target.to_string();
    let case = case.clone();
    let config = config.clone();
    let parts = tokio::task::spawn_blocking(move || {
        prepare_case_assets_sync(
            &workspace_root,
            &arch,
            &target,
            &case,
            &rootfs_path,
            &config,
        )
    })
    .await
    .context("qemu test case asset task failed")??;

    Ok(PreparedCaseAssets {
        rootfs_path: parts.rootfs_path,
        extra_qemu_args: parts.extra_qemu_args,
        rootfs_copy_to_remove: parts.rootfs_copy_to_remove,
        run_dir_to_remove: parts.run_dir_to_remove,
        pipeline: parts.pipeline,
        cache_hit: parts.cache_hit,
    })
}

/// Returns the shell-script source directory for a QEMU test case.
pub(crate) fn case_sh_source_dir(case: &TestQemuCase) -> PathBuf {
    case.case_dir.join(CASE_SH_DIR_NAME)
}

/// Returns the Python source directory for a QEMU test case.
pub(crate) fn case_python_source_dir(case: &TestQemuCase) -> PathBuf {
    case_builder::case_python_source_dir(case)
}

/// Builds the working directory layout used for a QEMU case asset run.
pub(crate) fn case_asset_layout(
    workspace_root: &Path,
    target: &str,
    case_name: &str,
) -> anyhow::Result<CaseAssetLayout> {
    let target_dir = resolve_target_dir(workspace_root, target)?;
    let work_dir = target_dir.join(CASE_WORK_ROOT_NAME).join(case_name);
    let run_dir = work_dir.join(CASE_RUNS_DIR_NAME).join(next_case_run_id());
    let cache_dir = work_dir.join(CASE_CACHE_DIR_NAME);

    Ok(CaseAssetLayout {
        staging_root: run_dir.join(CASE_STAGING_DIR_NAME),
        build_dir: run_dir.join(CASE_BUILD_DIR_NAME),
        overlay_dir: run_dir.join(CASE_OVERLAY_DIR_NAME),
        command_wrapper_dir: run_dir.join(CASE_COMMAND_WRAPPER_DIR_NAME),
        cross_bin_dir: run_dir.join(CASE_CROSS_BIN_DIR_NAME),
        cmake_toolchain_file: run_dir.join(CASE_CMAKE_TOOLCHAIN_FILE_NAME),
        apk_cache_dir: cache_dir.join(CASE_APK_CACHE_DIR_NAME),
        rootfs_cache_dir: cache_dir.join(CASE_ROOTFS_CACHE_DIR_NAME),
        case_rootfs_copy: run_dir.join(CASE_ROOTFS_COPY_NAME),
        cache_dir,
        run_dir,
        work_dir,
    })
}

/// Copies the shared rootfs image to a per-case working path.
///
/// The copy is always refreshed from the shared source so that leftover QEMU
/// guest writes from a previous run do not affect the current execution.
pub(crate) fn copy_shared_rootfs_for_case(
    shared_rootfs: &Path,
    layout: &CaseAssetLayout,
) -> anyhow::Result<()> {
    copy_file_fast(shared_rootfs, &layout.case_rootfs_copy)?;
    Ok(())
}

/// Removes the per-case rootfs copy after a test run completes, if one was
/// created.  Pass `None` when no copy was made (plain cases that boot from the
/// shared image directly).
///
/// The work directory (CMake build cache, APK cache, etc.) is intentionally
/// kept; only the large rootfs image is removed.  Failures are logged as
/// warnings so that a stale copy never masks an actual test failure.
pub(crate) fn remove_case_rootfs_copy(path: Option<&Path>) {
    let Some(path) = path else { return };
    if path.exists()
        && let Err(e) = fs::remove_file(path)
    {
        eprintln!(
            "warning: failed to remove case rootfs copy `{}`: {e}",
            path.display()
        );
    }
}

pub(crate) fn remove_case_run_dir(path: Option<&Path>) {
    let Some(path) = path else { return };
    if path.exists()
        && let Err(e) = fs::remove_dir_all(path)
    {
        eprintln!(
            "warning: failed to remove case run directory `{}`: {e}",
            path.display()
        );
    }
}

/// Performs the synchronous part of QEMU case asset preparation.
///
/// Returns `(extra_qemu_args, rootfs_path, rootfs_copy_to_remove)` where:
/// - `extra_qemu_args` always contains `-snapshot` so QEMU guest writes never
///   persist to any image file.
/// - `rootfs_path` is the image QEMU should boot from — the shared source
///   image for plain cases, or a fresh per-case copy for pipeline cases.
/// - `rootfs_copy_to_remove` is `Some(copy_path)` when a copy was created and
///   must be deleted after the run, `None` for plain cases.
pub(crate) fn prepare_case_assets_sync(
    workspace_root: &Path,
    arch: &str,
    target: &str,
    case: &TestQemuCase,
    shared_rootfs: &Path,
    config: &CaseAssetConfig,
) -> anyhow::Result<PreparedCaseAssetParts> {
    let pipeline = resolve_case_pipeline(case)?;

    // Pipeline cases need per-case layout for injection work; plain cases boot
    // directly from the shared image without any layout.
    let needs_injection = pipeline != CasePipeline::Plain;
    let layout = if needs_injection {
        Some(case_asset_layout(
            workspace_root,
            target,
            &case.display_name,
        )?)
    } else {
        None
    };

    let (case_rootfs, rootfs_copy_to_remove, run_dir_to_remove, cache_hit) = if needs_injection {
        let layout = layout.as_ref().expect("layout created above for injection");

        // Compute the cache key once and derive the cached rootfs image path.
        // The cached image is the post-injection rootfs — ready for QEMU to boot
        // from directly.  On a cache hit we skip inject_overlay entirely, which
        // is the dominant cost for Python/C pipeline cases.
        let rootfs_cache_img =
            rootfs_cache_image_path(layout, arch, target, pipeline, case, shared_rootfs, config)?;

        fs::create_dir_all(&layout.run_dir)
            .with_context(|| format!("failed to create {}", layout.run_dir.display()))?;

        let cache_hit = if is_valid_rootfs_cache_image(&rootfs_cache_img) {
            // Cache HIT: copy/reflink the cached post-injection image.
            // No need to copy shared_rootfs, build an overlay, or run inject_overlay.
            copy_file_fast(&rootfs_cache_img, &layout.case_rootfs_copy)?;
            true
        } else {
            // Cache MISS: full pipeline build, then save result to cache.
            copy_shared_rootfs_for_case(shared_rootfs, layout)?;
            let copy = &layout.case_rootfs_copy;
            match pipeline {
                CasePipeline::Grouped => case_builder::prepare_grouped_case_assets_sync(
                    arch, case, copy, layout, config,
                )?,
                CasePipeline::C => {
                    case_builder::prepare_c_case_assets_sync(arch, case, copy, layout, config)?
                }
                CasePipeline::Sh => prepare_sh_case_assets_sync(case, copy, layout)?,
                CasePipeline::Python => {
                    case_builder::prepare_python_case_assets_sync(arch, case, copy, layout, config)?
                }
                CasePipeline::Rust => {
                    case_builder::prepare_rust_case_assets_sync(arch, case, copy, layout, config)?
                }
                CasePipeline::Plain => unreachable!("plain cases do not prepare injection assets"),
            }
            // Save the post-injection rootfs to cache so future runs can skip
            // the overlay build and inject_overlay steps entirely.
            save_rootfs_cache_image(&layout.case_rootfs_copy, &rootfs_cache_img)?;
            false
        };

        let copy = layout.case_rootfs_copy.clone();
        (
            copy.clone(),
            Some(copy),
            Some(layout.run_dir.clone()),
            cache_hit,
        )
    } else {
        // No injection needed — boot directly from the shared image.
        // QEMU's -snapshot (below) ensures the shared image is never modified
        // by guest writes, so no copy is required at all.
        (shared_rootfs.to_path_buf(), None, None, false)
    };

    // -snapshot is always passed: all QEMU guest writes go to a temporary file
    // that QEMU auto-deletes on exit, keeping both the shared image and any
    // injection copy pristine after the run.
    let extra_qemu_args = vec![QEMU_SNAPSHOT_ARG.to_string()];

    Ok(PreparedCaseAssetParts {
        extra_qemu_args,
        rootfs_path: case_rootfs,
        rootfs_copy_to_remove,
        run_dir_to_remove,
        pipeline,
        cache_hit,
    })
}

pub(crate) fn resolve_case_pipeline(case: &TestQemuCase) -> anyhow::Result<CasePipeline> {
    let mut pipelines = Vec::new();
    if case.is_grouped() {
        pipelines.push(CasePipeline::Grouped);
    }
    if case_builder::case_c_source_dir(case).is_dir() {
        pipelines.push(CasePipeline::C);
    }
    if case_sh_source_dir(case).is_dir() {
        pipelines.push(CasePipeline::Sh);
    }
    if case_python_source_dir(case).is_dir() {
        pipelines.push(CasePipeline::Python);
    }
    if case_builder::case_rust_source_dir(case).is_dir() {
        pipelines.push(CasePipeline::Rust);
    }

    if pipelines.len() > 1 {
        bail!(
            "qemu case `{}` defines multiple asset pipelines: {}",
            case.name,
            pipelines
                .iter()
                .map(|pipeline| pipeline.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        );
    }

    Ok(pipelines.into_iter().next().unwrap_or(CasePipeline::Plain))
}

fn next_case_run_id() -> String {
    let sequence = CASE_RUN_ID.fetch_add(1, Ordering::Relaxed);
    format!("{}-{sequence}", std::process::id())
}

fn rootfs_cache_image_path(
    layout: &CaseAssetLayout,
    arch: &str,
    target: &str,
    pipeline: CasePipeline,
    case: &TestQemuCase,
    shared_rootfs: &Path,
    config: &CaseAssetConfig,
) -> anyhow::Result<PathBuf> {
    let key = case_asset_cache_key(arch, target, pipeline, case, shared_rootfs, config)?;
    Ok(layout.rootfs_cache_dir.join(format!("{key}.img")))
}

fn rootfs_cache_write_enabled() -> bool {
    if std::env::var_os("AXBUILD_DISABLE_ROOTFS_CACHE").is_some() {
        return false;
    }
    std::env::var_os("CI").is_none()
}

fn is_no_space_left(err: &anyhow::Error) -> bool {
    err.chain().any(|cause| {
        cause
            .downcast_ref::<std::io::Error>()
            .and_then(|e| e.raw_os_error())
            == Some(28)
    })
}

fn save_rootfs_cache_image(src: &Path, dst: &Path) -> anyhow::Result<()> {
    if !rootfs_cache_write_enabled() {
        return Ok(());
    }
    let parent = dst
        .parent()
        .ok_or_else(|| anyhow::anyhow!("rootfs cache path has no parent: {}", dst.display()))?;
    fs::create_dir_all(parent)
        .with_context(|| format!("failed to create rootfs cache dir {}", parent.display()))?;
    let temp = parent.join(format!(
        ".{}.{}.tmp",
        dst.file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("rootfs-cache"),
        next_case_run_id()
    ));
    if let Err(err) = copy_file_fast(src, &temp) {
        let _ = fs::remove_file(&temp);
        if is_no_space_left(&err) {
            return Ok(());
        }
        return Err(err);
    }
    match fs::rename(&temp, dst) {
        Ok(()) => Ok(()),
        Err(err) if dst.is_file() => {
            let _ = fs::remove_file(&temp);
            if is_valid_rootfs_cache_image(dst) {
                Ok(())
            } else {
                Err(err).with_context(|| {
                    format!("failed to install rootfs cache image {}", dst.display())
                })
            }
        }
        Err(err) => {
            let _ = fs::remove_file(&temp);
            Err(err)
                .with_context(|| format!("failed to install rootfs cache image {}", dst.display()))
        }
    }
}

/// Returns `true` when a rootfs cache image file exists and has a plausible
/// size.  Files smaller than 1 MiB are treated as corrupt/incomplete and will
/// trigger a cache-miss rebuild.
fn is_valid_rootfs_cache_image(path: &Path) -> bool {
    const MIN_SIZE: u64 = 1024 * 1024;
    path.is_file()
        && path
            .metadata()
            .map(|m| m.len() >= MIN_SIZE)
            .unwrap_or(false)
}

/// Copies `src` to `dst`, preferring a copy-on-write reflink when the
/// filesystem supports it so that ~1 GiB rootfs images are duplicated in
/// near-zero time on btrfs / XFS.
///
/// On Linux this delegates to `cp --reflink=auto` and falls back to a regular
/// `fs::copy` if that fails (e.g. on ext4 or when `cp` is too old).  On other
/// platforms only `fs::copy` is used.
fn copy_file_fast(src: &Path, dst: &Path) -> anyhow::Result<()> {
    #[cfg(target_os = "linux")]
    {
        // `cp --reflink=auto` tries FICLONE ioctl first; if the filesystem
        // does not support it the command falls back to a regular copy, so
        // this is always safe to try.
        let status = std::process::Command::new("cp")
            .arg("--reflink=auto")
            .arg(src)
            .arg(dst)
            .status();
        if let Ok(status) = status {
            if status.success() {
                return Ok(());
            }
            // cp reported an error — remove any partial destination file so
            // the fs::copy fallback below starts with a clean slate.
            let _ = fs::remove_file(dst);
        }
        // Fall through to regular copy on any failure (cp not available,
        // unsupported flag, or a non-CoW error we cannot distinguish).
    }
    fs::copy(src, dst)
        .with_context(|| format!("failed to copy {} to {}", src.display(), dst.display()))?;
    Ok(())
}

fn case_asset_cache_key(
    arch: &str,
    target: &str,
    pipeline: CasePipeline,
    case: &TestQemuCase,
    shared_rootfs: &Path,
    config: &CaseAssetConfig,
) -> anyhow::Result<String> {
    let mut hasher = Sha256::new();
    hash_token(&mut hasher, "v3");
    hash_token(&mut hasher, arch);
    hash_token(&mut hasher, target);
    hash_token(&mut hasher, case.display_name.as_str());
    hash_token(&mut hasher, pipeline.as_str());
    for var in &config.cache_env_vars {
        hash_token(&mut hasher, var);
        hash_token(&mut hasher, std::env::var(var).unwrap_or_default().as_str());
    }
    // Only the C pipeline uses the CMake toolchain template; include it in the
    // key only when relevant so that changes to the template don't invalidate
    // caches for unrelated pipelines.
    if pipeline == CasePipeline::C {
        hash_token(&mut hasher, include_str!("cmake-toolchain.cmake.in"));
    }
    if pipeline == CasePipeline::Python {
        hash_token(&mut hasher, PYTHON_PIPELINE_CACHE_VERSION);
    }
    if pipeline == CasePipeline::Rust {
        hash_token(&mut hasher, RUST_PIPELINE_CACHE_VERSION);
    }

    hash_rootfs_fingerprint(&mut hasher, shared_rootfs)?;
    hash_tree(&mut hasher, &case.case_dir)?;
    if !case.qemu_config_path.starts_with(&case.case_dir) && case.qemu_config_path.is_file() {
        hash_file(&mut hasher, &case.qemu_config_path)?;
    }

    Ok(format!("{:x}", hasher.finalize()))
}

fn hash_tree(hasher: &mut Sha256, root: &Path) -> anyhow::Result<()> {
    let mut files = WalkDir::new(root)
        .follow_links(false)
        .into_iter()
        .collect::<Result<Vec<_>, _>>()
        .with_context(|| format!("failed to walk {}", root.display()))?;
    files.sort_by_key(|entry| entry.path().to_path_buf());

    for entry in files {
        let path = entry.path();
        if path == root || !entry.file_type().is_file() {
            continue;
        }
        let rel = path.strip_prefix(root).unwrap_or(path);
        hash_token(hasher, rel.to_string_lossy().as_ref());
        hash_file(hasher, path)?;
    }
    Ok(())
}

fn hash_rootfs_fingerprint(hasher: &mut Sha256, path: &Path) -> anyhow::Result<()> {
    let metadata =
        fs::metadata(path).with_context(|| format!("failed to stat {}", path.display()))?;
    let len = metadata.len();
    hash_token(hasher, &len.to_string());

    let mut file =
        fs::File::open(path).with_context(|| format!("failed to open {}", path.display()))?;
    hash_file_window(hasher, &mut file, 0, len)?;
    if len > 0 {
        hash_file_window(hasher, &mut file, len / 2, len)?;
        hash_file_window(hasher, &mut file, len.saturating_sub(1024 * 1024), len)?;
    }
    Ok(())
}

fn hash_file_window(
    hasher: &mut Sha256,
    file: &mut fs::File,
    offset: u64,
    file_len: u64,
) -> anyhow::Result<()> {
    let read_len = (file_len.saturating_sub(offset)).min(1024 * 1024);
    hash_token(hasher, &format!("{offset}:{read_len}"));
    file.seek(SeekFrom::Start(offset))
        .with_context(|| format!("failed to seek rootfs fingerprint window at offset {offset}"))?;

    let mut remaining = read_len;
    let mut buf = [0_u8; 8192];
    while remaining > 0 {
        let limit = remaining.min(buf.len() as u64) as usize;
        let read = file
            .read(&mut buf[..limit])
            .context("failed to read rootfs fingerprint window")?;
        if read == 0 {
            break;
        }
        hasher.update(&buf[..read]);
        remaining -= read as u64;
    }
    Ok(())
}

fn hash_file(hasher: &mut Sha256, path: &Path) -> anyhow::Result<()> {
    let mut file =
        fs::File::open(path).with_context(|| format!("failed to open {}", path.display()))?;
    let mut buf = [0_u8; 8192];
    loop {
        let read = file
            .read(&mut buf)
            .with_context(|| format!("failed to read {}", path.display()))?;
        if read == 0 {
            break;
        }
        hasher.update(&buf[..read]);
    }
    Ok(())
}

fn hash_token(hasher: &mut Sha256, value: &str) {
    hasher.update(value.len().to_le_bytes());
    hasher.update(value.as_bytes());
}

pub(crate) fn apply_grouped_qemu_config(
    qemu: &mut QemuConfig,
    case: &TestQemuCase,
    config: &GroupedCaseRunnerConfig,
) {
    if !case.is_grouped() {
        return;
    }

    qemu.shell_init_cmd = Some(config.runner_path.clone());
    qemu.success_regex = vec![config.success_regex.clone()];
    if !qemu
        .fail_regex
        .iter()
        .any(|regex| regex == &config.fail_regex)
    {
        qemu.fail_regex.push(config.fail_regex.clone());
    }
}

pub(crate) async fn run_qemu_with_prepared_case_assets(
    app: &mut AppContext,
    cargo: &Cargo,
    qemu: QemuConfig,
    qemu_config_path: &Path,
    prepared_assets: PreparedCaseAssets,
    prepare_elapsed: Duration,
) -> anyhow::Result<()> {
    println!(
        "  prepare assets: {:.2?} (pipeline={}, cache={})",
        prepare_elapsed,
        prepared_assets.pipeline.as_str(),
        if prepared_assets.cache_hit {
            "hit"
        } else {
            "miss"
        }
    );
    println!(
        "  qemu config: {} (timeout={})",
        qemu_config_path.display(),
        super::qemu::qemu_timeout_summary(&qemu)
    );
    println!("  rootfs: {}", prepared_assets.rootfs_path.display());

    let qemu_started = std::time::Instant::now();
    let result = app.run_qemu(cargo, qemu).await;
    println!("  qemu run: {:.2?}", qemu_started.elapsed());

    remove_case_rootfs_copy(prepared_assets.rootfs_copy_to_remove.as_deref());
    remove_case_run_dir(prepared_assets.run_dir_to_remove.as_deref());
    result
}

pub(crate) fn write_grouped_case_runner_script(
    overlay_dir: &Path,
    test_commands: &[String],
    config: &GroupedCaseRunnerConfig,
) -> anyhow::Result<()> {
    ensure!(
        !test_commands.is_empty(),
        "grouped qemu case has no test commands"
    );

    let dest_dir = overlay_dir.join("usr/bin");
    fs::create_dir_all(&dest_dir)
        .with_context(|| format!("failed to create {}", dest_dir.display()))?;
    let runner_path = dest_dir.join(&config.runner_name);

    let mut body = String::new();
    body.push_str("failed=0\n");
    for command in test_commands {
        let quoted = shell_single_quote(command);
        let begin = shell_single_quote(&format!("{}: {command}", config.begin_marker));
        let passed = shell_single_quote(&format!("{}: {command}", config.passed_marker));
        let failed = shell_single_quote(&format!("{}: {command}", config.failed_marker));
        body.push_str(&format!(
            "printf '%s\\n' {begin}\nif sh -c {quoted}; then\n\tprintf '%s\\n' \
             {passed}\nelse\n\tstatus=$?\n\tprintf '%s status=%s\\n' {failed} \
             \"$status\"\n\tfailed=1\nfi\n"
        ));
    }
    let all_passed = shell_single_quote(&config.all_passed_marker);
    let all_failed = shell_single_quote(&config.all_failed_marker);
    body.push_str(&format!(
        "if [ \"$failed\" -eq 0 ]; then\n\tprintf '%s\\n' {all_passed}\n\texit 0\nfi\nprintf \
         '%s\\n' {all_failed}\nexit 1\n"
    ));

    write_executable_script(&runner_path, &body)
}

/// Prepares overlay assets for a shell-based QEMU test case.
pub(crate) fn prepare_sh_case_assets_sync(
    case: &TestQemuCase,
    case_rootfs: &Path,
    layout: &CaseAssetLayout,
) -> anyhow::Result<()> {
    let sh_dir = case_sh_source_dir(case);
    ensure!(
        sh_dir.is_dir(),
        "sh directory not found at `{}`",
        sh_dir.display()
    );

    reset_dir(&layout.overlay_dir)?;

    let dest_dir = layout.overlay_dir.join("usr/bin");
    fs::create_dir_all(&dest_dir)
        .with_context(|| format!("failed to create {}", dest_dir.display()))?;

    let mut entries = fs::read_dir(&sh_dir)
        .with_context(|| format!("failed to read {}", sh_dir.display()))?
        .collect::<Result<Vec<_>, _>>()
        .with_context(|| format!("failed to read {}", sh_dir.display()))?;
    entries.sort_by_key(|e| e.file_name());

    for entry in entries {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let dest = dest_dir.join(entry.file_name());
        fs::copy(&path, &dest)
            .with_context(|| format!("failed to copy {} to {}", path.display(), dest.display()))?;
        make_executable(&dest)?;
    }

    crate::rootfs::inject::inject_overlay(case_rootfs, &layout.overlay_dir)
}

/// Resets a directory to an empty existing state.
pub(crate) fn reset_dir(path: &Path) -> anyhow::Result<()> {
    if path.exists() {
        fs::remove_dir_all(path).with_context(|| format!("failed to remove {}", path.display()))?;
    }
    fs::create_dir_all(path).with_context(|| format!("failed to create {}", path.display()))
}

fn write_executable_script(path: &Path, body: &str) -> anyhow::Result<()> {
    fs::write(path, format!("#!/bin/sh\nset -u\n{body}"))
        .with_context(|| format!("failed to write {}", path.display()))?;
    make_executable(path)
}

fn make_executable(_path: &Path) -> anyhow::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(_path)
            .with_context(|| format!("failed to stat {}", _path.display()))?
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(_path, perms)
            .with_context(|| format!("failed to chmod {}", _path.display()))?;
    }
    Ok(())
}

fn shell_single_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

#[cfg(test)]
mod tests {
    use std::{
        env,
        ffi::{OsStr, OsString},
        fs,
        sync::{LazyLock, Mutex},
    };

    use tempfile::tempdir;

    use super::*;

    static ENV_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

    struct TempEnvVar {
        key: &'static str,
        original: Option<OsString>,
    }

    impl TempEnvVar {
        fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
            let original = env::var_os(key);
            unsafe {
                env::set_var(key, value);
            }
            Self { key, original }
        }

        fn unset(key: &'static str) -> Self {
            let original = env::var_os(key);
            unsafe {
                env::remove_var(key);
            }
            Self { key, original }
        }
    }

    impl Drop for TempEnvVar {
        fn drop(&mut self) {
            match self.original.as_ref() {
                Some(value) => unsafe {
                    env::set_var(self.key, value);
                },
                None => unsafe {
                    env::remove_var(self.key);
                },
            }
        }
    }

    fn fake_config() -> CaseAssetConfig {
        CaseAssetConfig {
            grouped_runner: GroupedCaseRunnerConfig {
                runner_name: "suite-run-case-tests".to_string(),
                runner_path: "/usr/bin/suite-run-case-tests".to_string(),
                begin_marker: "SUITE_GROUPED_TEST_BEGIN".to_string(),
                passed_marker: "SUITE_GROUPED_TEST_PASSED".to_string(),
                failed_marker: "SUITE_GROUPED_TEST_FAILED".to_string(),
                all_passed_marker: "SUITE_GROUPED_TESTS_PASSED".to_string(),
                all_failed_marker: "SUITE_GROUPED_TESTS_FAILED".to_string(),
                success_regex: r"(?m)^SUITE_GROUPED_TESTS_PASSED\s*$".to_string(),
                fail_regex: r"(?m)^SUITE_GROUPED_TEST_FAILED:".to_string(),
            },
            script_env: CaseScriptEnvConfig {
                staging_root: "SUITE_STAGING_ROOT".to_string(),
                case_dir: "SUITE_CASE_DIR".to_string(),
                case_c_dir: "SUITE_CASE_C_DIR".to_string(),
                case_work_dir: "SUITE_CASE_WORK_DIR".to_string(),
                case_build_dir: "SUITE_CASE_BUILD_DIR".to_string(),
                case_overlay_dir: "SUITE_CASE_OVERLAY_DIR".to_string(),
            },
            cache_env_vars: Vec::new(),
            prepare_staging_root: |_| Ok(()),
            prepare_guest_package_env: None,
        }
    }

    fn fake_case(root: &Path, name: &str) -> TestQemuCase {
        let case_dir = root.join("test-suite/example/default").join(name);
        fs::create_dir_all(&case_dir).unwrap();
        TestQemuCase {
            name: name.to_string(),
            display_name: name.to_string(),
            case_dir: case_dir.clone(),
            qemu_config_path: case_dir.join("qemu-aarch64.toml"),
            test_commands: Vec::new(),
            subcases: Vec::new(),
        }
    }

    #[test]
    fn resolve_target_dir_uses_workspace_target_directory() {
        let root = tempdir().unwrap();
        let dir = resolve_target_dir(root.path(), "x86_64-unknown-none").unwrap();

        assert_eq!(dir, root.path().join("target/x86_64-unknown-none"));
    }

    #[tokio::test]
    async fn prepare_case_assets_plain_case_uses_shared_rootfs_with_snapshot() {
        let root = tempdir().unwrap();
        let target_dir = root.path().join("target/x86_64-unknown-none");
        let rootfs_dir = root.path().join("tmp/axbuild/rootfs");
        fs::create_dir_all(&target_dir).unwrap();
        fs::create_dir_all(&rootfs_dir).unwrap();
        let shared_img = rootfs_dir.join("rootfs-x86_64-alpine.img");
        fs::write(&shared_img, b"rootfs").unwrap();
        let case = fake_case(root.path(), "smoke");

        let assets = prepare_case_assets(
            root.path(),
            "x86_64",
            "x86_64-unknown-none",
            &case,
            shared_img.clone(),
            fake_config(),
        )
        .await
        .unwrap();

        // Plain case (no pipeline): rootfs_path must point to the shared image
        // directly — no per-case copy is created.
        assert_eq!(assets.rootfs_path, shared_img);
        assert!(assets.rootfs_copy_to_remove.is_none());
        // -snapshot must always be present so QEMU guest writes never dirty
        // the shared image.
        assert!(assets.extra_qemu_args.contains(&"-snapshot".to_string()));
        // The shared image must be unmodified.
        assert_eq!(fs::read(&shared_img).unwrap(), b"rootfs");
    }

    #[test]
    fn grouped_runner_script_runs_all_commands_and_reports_summary() {
        let root = tempdir().unwrap();
        let overlay = root.path().join("overlay");
        let commands = vec![
            "/usr/bin/alpha".to_string(),
            "/usr/bin/beta --flag".to_string(),
        ];

        let config = fake_config();
        write_grouped_case_runner_script(&overlay, &commands, &config.grouped_runner).unwrap();

        let runner = overlay.join("usr/bin/suite-run-case-tests");
        let content = fs::read_to_string(&runner).unwrap();
        assert!(content.contains("SUITE_GROUPED_TEST_BEGIN: /usr/bin/alpha"));
        assert!(content.contains("SUITE_GROUPED_TEST_FAILED: /usr/bin/beta --flag"));
        assert!(content.contains("SUITE_GROUPED_TESTS_PASSED"));
    }

    #[test]
    fn save_rootfs_cache_image_is_noop_in_ci() {
        let _lock = ENV_LOCK.lock().unwrap();
        let _ci = TempEnvVar::set("CI", "1");
        let _disable = TempEnvVar::unset("AXBUILD_DISABLE_ROOTFS_CACHE");

        let root = tempdir().unwrap();
        let src = root.path().join("src.img");
        let dst = root.path().join("cache/rootfs.img");
        fs::write(&src, vec![0_u8; 1024 * 1024]).unwrap();

        save_rootfs_cache_image(&src, &dst).unwrap();
        assert!(!dst.exists());
    }

    #[test]
    fn save_rootfs_cache_image_writes_when_enabled() {
        let _lock = ENV_LOCK.lock().unwrap();
        let _ci = TempEnvVar::unset("CI");
        let _disable = TempEnvVar::unset("AXBUILD_DISABLE_ROOTFS_CACHE");

        let root = tempdir().unwrap();
        let src = root.path().join("src.img");
        let dst = root.path().join("cache/rootfs.img");
        fs::write(&src, vec![1_u8; 1024 * 1024]).unwrap();

        save_rootfs_cache_image(&src, &dst).unwrap();
        assert!(dst.is_file());
        assert_eq!(fs::read(&dst).unwrap().len(), 1024 * 1024);
    }
}