boxlite 0.9.3

Embeddable virtual machine runtime for secure, isolated code execution
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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
use regex::Regex;
use sha2::{Digest, Sha256};
use std::cell::OnceCell;
use std::env;
use std::fs;
use std::io;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Cargo build-script facts shared across runtime preparation steps.
struct CargoBuildContext {
    manifest_dir: PathBuf,
    out_dir: PathBuf,
    // Resolve lazily so registry/prebuilt builds do not require a source workspace.
    workspace_root: OnceCell<Option<PathBuf>>,
    primary_package: bool,
}

impl CargoBuildContext {
    /// Capture the Cargo environment values this build script needs.
    fn new() -> Self {
        let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
        let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
        let primary_package = env::var_os("CARGO_PRIMARY_PACKAGE").is_some();

        Self {
            manifest_dir,
            out_dir,
            workspace_root: OnceCell::new(),
            primary_package,
        }
    }

    /// Return Cargo's build output directory.
    fn out_dir(&self) -> &Path {
        &self.out_dir
    }

    /// Return the source workspace root when this build is inside one.
    fn workspace_root(&self) -> Option<&Path> {
        self.workspace_root
            .get_or_init(|| Self::find_workspace_root(&self.manifest_dir))
            .as_deref()
    }

    /// Return true when BoxLite is being built by a downstream consumer.
    fn is_dependency_build(&self) -> bool {
        if self.primary_package {
            return false;
        }

        match Self::target_dir_for_workspace(self.workspace_root()) {
            Some(target_dir) => !self.out_dir.starts_with(target_dir),
            None => true,
        }
    }

    /// Resolve Cargo's target directory for the source workspace.
    fn target_dir_for_workspace(workspace_root: Option<&Path>) -> Option<PathBuf> {
        let workspace_root = workspace_root?;
        Some(
            env::var_os("CARGO_TARGET_DIR")
                .map(PathBuf::from)
                .map(|target_dir| {
                    if target_dir.is_absolute() {
                        target_dir
                    } else {
                        workspace_root.join(target_dir)
                    }
                })
                .unwrap_or_else(|| workspace_root.join("target")),
        )
    }

    /// Find the cargo workspace root by walking up from CARGO_MANIFEST_DIR.
    /// Looks for a Cargo.toml containing `[workspace]`.
    fn find_workspace_root(manifest_dir: &Path) -> Option<PathBuf> {
        let mut dir = manifest_dir;
        loop {
            let cargo_toml = dir.join("Cargo.toml");
            if cargo_toml.is_file()
                && fs::read_to_string(&cargo_toml)
                    .is_ok_and(|contents| contents.contains("[workspace]"))
            {
                return Some(dir.to_path_buf());
            }
            dir = match dir.parent() {
                Some(parent) => parent,
                None => {
                    println!(
                        "cargo:warning=BoxLite workspace root was not found from {}; source runtime embedding will be skipped unless a prebuilt runtime is available",
                        manifest_dir.display()
                    );
                    return None;
                }
            };
        }
    }
}

/// Copies all dynamic library files from source directory to destination.
/// Only copies files with library extensions (.dylib, .so, .so.*, .dll).
/// Preserves symlinks to avoid duplicating the same library multiple times.
fn copy_libs(source: &Path, dest: &Path) -> Result<(), String> {
    if !source.exists() {
        return Err(format!(
            "Source directory does not exist: {}",
            source.display()
        ));
    }

    fs::create_dir_all(dest).map_err(|e| {
        format!(
            "Failed to create destination directory {}: {}",
            dest.display(),
            e
        )
    })?;

    for entry in fs::read_dir(source).map_err(|e| {
        format!(
            "Failed to read source directory {}: {}",
            source.display(),
            e
        )
    })? {
        let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?;
        let source_path = entry.path();

        let file_name = source_path.file_name().ok_or("Failed to get filename")?;

        // Only process library files
        if !is_library_file(&source_path) {
            continue;
        }

        let dest_path = dest.join(file_name);

        // Check if source is a symlink
        let metadata = fs::symlink_metadata(&source_path).map_err(|e| {
            format!(
                "Failed to read metadata for {}: {}",
                source_path.display(),
                e
            )
        })?;

        if metadata.file_type().is_symlink() {
            // Skip symlinks - runtime linker uses the full versioned name embedded in the binary
            // (e.g., @rpath/libkrun.1.15.1.dylib, not @rpath/libkrun.dylib)
            // Symlinks are only needed during build-time linking
            continue;
        }

        if metadata.is_file() {
            // Regular file - remove existing file first (maybe read-only)
            if dest_path.exists() {
                fs::remove_file(&dest_path).map_err(|e| {
                    format!(
                        "Failed to remove existing file {}: {}",
                        dest_path.display(),
                        e
                    )
                })?;
            }

            // Copy the file
            fs::copy(&source_path, &dest_path).map_err(|e| {
                format!(
                    "Failed to copy {} -> {}: {}",
                    source_path.display(),
                    dest_path.display(),
                    e
                )
            })?;

            println!(
                "cargo:warning=Bundled library: {}",
                file_name.to_string_lossy()
            );
        }
    }

    Ok(())
}

/// Checks if a file is a dynamic library based on its extension.
fn is_library_file(path: &Path) -> bool {
    let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

    // macOS: .dylib
    if filename.ends_with(".dylib") {
        return true;
    }

    // Linux: .so or .so.VERSION
    if filename.contains(".so") {
        return true;
    }

    // Windows: .dll
    if filename.ends_with(".dll") {
        return true;
    }

    false
}

/// Auto-discovers and bundles all dependencies from -sys crates.
///
/// Convention: Each -sys crate emits `cargo:{NAME}_BOXLITE_DEP=<path>`
/// which becomes `DEP_{LINKS}_{NAME}_BOXLITE_DEP` env var.
///
/// The path can be either:
/// - A directory: copies all library files (.dylib, .so, .dll) from it
/// - A file: copies that single file
///
/// Returns a list of (name, bundled_path) pairs.
fn bundle_boxlite_deps(runtime_dir: &Path) -> Vec<(String, PathBuf)> {
    // Pattern: DEP_{LINKS}_{NAME}_BOXLITE_DEP
    // Example: DEP_KRUN_LIBKRUN_BOXLITE_DEP -> libkrun (directory)
    // Example: DEP_E2FSPROGS_MKE2FS_BOXLITE_DEP -> mke2fs (file)
    let re = Regex::new(r"^DEP_[A-Z0-9]+_([A-Z0-9]+)_BOXLITE_DEP$").unwrap();

    let mut collected = Vec::new();

    for (key, source_path_str) in env::vars() {
        if let Some(caps) = re.captures(&key) {
            let name = caps[1].to_lowercase();
            let source_path = Path::new(&source_path_str);

            if !source_path.exists() {
                panic!("Dependency path does not exist: {}", source_path_str);
            }

            println!(
                "cargo:warning=Found dependency: {} at {}",
                name, source_path_str
            );

            if source_path.is_dir() {
                // Directory: copy library files
                match copy_libs(source_path, runtime_dir) {
                    Ok(()) => {
                        collected.push((name, runtime_dir.to_path_buf()));
                    }
                    Err(e) => {
                        panic!("Failed to copy {}: {}", name, e);
                    }
                }
            } else {
                // File: copy single file
                let file_name = source_path.file_name().expect("Failed to get filename");
                let dest_path = runtime_dir.join(file_name);

                if dest_path.exists() {
                    fs::remove_file(&dest_path).unwrap_or_else(|e| {
                        panic!("Failed to remove {}: {}", dest_path.display(), e)
                    });
                }

                fs::copy(source_path, &dest_path).unwrap_or_else(|e| {
                    panic!(
                        "Failed to copy {} -> {}: {}",
                        source_path.display(),
                        dest_path.display(),
                        e
                    )
                });

                println!("cargo:warning=Bundled: {}", file_name.to_string_lossy());
                collected.push((name, dest_path));
            }
        }
    }

    collected
}

/// Compiles seccomp JSON filters to BPF bytecode at build time.
///
/// This function:
/// 1. Determines the appropriate JSON filter based on target architecture
/// 2. Compiles the JSON to BPF bytecode using seccompiler
/// 3. Saves the binary filter to OUT_DIR/seccomp_filter.bpf
///
/// The compiled filter is embedded in the binary and deserialized at runtime,
/// providing zero-overhead syscall filtering.
#[cfg(target_os = "linux")]
fn compile_seccomp_filters() {
    use std::collections::HashMap;
    use std::convert::TryInto;
    use std::fs;
    use std::io::Cursor;

    let target = env::var("TARGET").expect("Missing TARGET env var");
    let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("Missing target arch");
    let out_dir = env::var("OUT_DIR").expect("Missing OUT_DIR");

    // Determine JSON path based on target
    let json_path = format!("resources/seccomp/{}.json", target);
    let json_path = if Path::new(&json_path).exists() {
        json_path
    } else {
        println!(
            "cargo:warning=No seccomp filter for {}, using unimplemented.json",
            target
        );
        "resources/seccomp/unimplemented.json".to_string()
    };

    // Compile JSON to BPF bytecode using seccompiler 0.5.0 API
    let bpf_path = format!("{}/seccomp_filter.bpf", out_dir);

    println!(
        "cargo:warning=Compiling seccomp filter: {} -> {}",
        json_path, bpf_path
    );

    // Read JSON file
    let json_content = fs::read(&json_path)
        .unwrap_or_else(|e| panic!("Failed to read seccomp JSON {}: {}", json_path, e));

    // Convert target_arch string to TargetArch enum
    let arch: seccompiler::TargetArch = target_arch
        .as_str()
        .try_into()
        .unwrap_or_else(|e| panic!("Unsupported target architecture {}: {:?}", target_arch, e));

    // Compile JSON to BpfMap using Cursor to satisfy Read trait
    let reader = Cursor::new(json_content);
    let bpf_map = seccompiler::compile_from_json(reader, arch).unwrap_or_else(|e| {
        panic!(
            "Failed to compile seccomp filters from {}: {}",
            json_path, e
        )
    });

    // Convert BpfMap (HashMap<String, Vec<sock_filter>>) to our format (HashMap<String, Vec<u64>>)
    // sock_filter is a C struct that is 8 bytes (u64) per instruction
    let mut converted_map: HashMap<String, Vec<u64>> = HashMap::new();
    for (thread_name, filter) in bpf_map {
        let instructions: Vec<u64> = filter
            .iter()
            .map(|instr| {
                // Convert sock_filter to u64
                // sock_filter is #[repr(C)] with fields: code(u16), jt(u8), jf(u8), k(u32)
                // Layout: [code:2][jt:1][jf:1][k:4] = 8 bytes total
                unsafe { std::mem::transmute_copy(instr) }
            })
            .collect();
        converted_map.insert(thread_name, instructions);
    }

    // Serialize converted map to binary using bincode
    // IMPORTANT: Use the same configuration as runtime deserialization (seccomp.rs)
    let bincode_config = bincode::config::standard().with_fixed_int_encoding();
    let serialized = bincode::encode_to_vec(&converted_map, bincode_config)
        .unwrap_or_else(|e| panic!("Failed to serialize BPF filters: {}", e));

    // Write to output file
    fs::write(&bpf_path, serialized)
        .unwrap_or_else(|e| panic!("Failed to write BPF filter to {}: {}", bpf_path, e));

    println!(
        "cargo:warning=Successfully compiled seccomp filter ({} bytes)",
        fs::metadata(&bpf_path).unwrap().len()
    );

    // Rerun if JSON changes
    println!("cargo:rerun-if-changed={}", json_path);
    println!("cargo:rerun-if-changed=resources/seccomp/");
}

#[cfg(not(target_os = "linux"))]
/// Skip seccomp filter generation on non-Linux targets.
fn compile_seccomp_filters() {
    // No-op on non-Linux platforms
    println!("cargo:warning=Seccomp compilation skipped (not Linux)");
}

/// Prebuilt runtime artifact state under OUT_DIR/runtime.
struct PrebuiltRuntime {
    runtime_dir: PathBuf,
}

impl PrebuiltRuntime {
    const FILE_MANIFEST: &'static str = ".boxlite-runtime-files";
    const TARBALL_NAME: &'static str = "boxlite-runtime.tar.gz";

    /// Create a handle for an extracted prebuilt runtime directory.
    fn new(runtime_dir: &Path) -> Self {
        Self {
            runtime_dir: runtime_dir.to_path_buf(),
        }
    }

    /// Return the generated file manifest path.
    fn manifest_path(&self) -> PathBuf {
        self.runtime_dir.join(Self::FILE_MANIFEST)
    }

    /// List runtime files and symlinks that came from the release artifact.
    fn scan_file_names(&self) -> io::Result<Vec<String>> {
        let mut files = Vec::new();
        for entry in fs::read_dir(&self.runtime_dir)? {
            let entry = entry?;
            let path = entry.path();
            let name = entry.file_name().to_string_lossy().to_string();
            if name == Self::FILE_MANIFEST || name == Self::TARBALL_NAME {
                continue;
            }

            let metadata = fs::symlink_metadata(&path)?;
            if metadata.is_file() || metadata.file_type().is_symlink() {
                files.push(name);
            }
        }
        files.sort();
        Ok(files)
    }

    /// Write the artifact-defined runtime file manifest.
    fn write_file_manifest(&self) -> io::Result<Vec<String>> {
        let files = self.scan_file_names()?;
        if files.is_empty() {
            return Err(io::Error::other(
                "prebuilt runtime did not contain any files",
            ));
        }

        let mut contents = String::new();
        for file in &files {
            contents.push_str(file);
            contents.push('\n');
        }
        // The release artifact defines the required runtime set; avoid OS-specific lists here.
        fs::write(self.manifest_path(), contents)?;
        Ok(files)
    }

    /// Read the artifact-defined runtime file manifest.
    fn read_file_manifest(&self) -> io::Result<Vec<String>> {
        let contents = fs::read_to_string(self.manifest_path())?;
        Ok(contents
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(ToOwned::to_owned)
            .collect())
    }

    /// Return user-facing reasons why the runtime cannot be embedded.
    fn incomplete_reasons(&self) -> Vec<String> {
        if !self.runtime_dir.exists() {
            return vec!["runtime directory missing".to_string()];
        }

        let files = match self.read_file_manifest() {
            Ok(files) => files,
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                return vec!["prebuilt runtime manifest missing".to_string()];
            }
            Err(e) => return vec![format!("failed to read prebuilt runtime manifest: {e}")],
        };

        if files.is_empty() {
            return vec!["prebuilt runtime manifest is empty".to_string()];
        }

        files
            .into_iter()
            .filter(|name| !self.runtime_dir.join(name).exists())
            .map(|name| format!("missing manifest entry {name}"))
            .collect()
    }

    /// Return true when every manifest-listed runtime file exists.
    fn is_complete(&self) -> bool {
        self.incomplete_reasons().is_empty()
    }

    /// Maps the host platform to the runtime artifact target name.
    /// Matches the naming convention from config.yml and build-runtime.yml.
    fn runtime_target() -> Option<&'static str> {
        let os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
        let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();

        match (os.as_str(), arch.as_str()) {
            ("macos", "aarch64") => Some("darwin-arm64"),
            ("linux", "x86_64") => Some("linux-x64-gnu"),
            ("linux", "aarch64") => Some("linux-arm64-gnu"),
            _ => None,
        }
    }

    /// Downloads a file from URL using curl.
    fn download_file(url: &str, dest: &Path) -> io::Result<()> {
        println!("cargo:warning=Downloading {}...", url);

        let output = Command::new("curl")
            .args(["-fsSL", "-o", dest.to_str().unwrap(), url])
            .output()?;

        if !output.status.success() {
            return Err(io::Error::other(format!(
                "curl failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        Ok(())
    }

    /// Extracts an entire tarball to the runtime directory.
    fn extract_tarball(&self, tarball: &Path) -> io::Result<()> {
        let status = Command::new("tar")
            .args([
                "-xzf",
                tarball.to_str().unwrap(),
                "-C",
                self.runtime_dir.to_str().unwrap(),
                "--strip-components=1",
            ])
            .status()?;

        if !status.success() {
            return Err(io::Error::other("tar extraction failed"));
        }

        Ok(())
    }

    /// Creates unversioned symlinks for versioned library files.
    ///
    /// Build-time linking (`-lkrun`) requires `libkrun.dylib` (unversioned),
    /// but the prebuilt tarball only contains versioned files like `libkrun.1.16.0.dylib`.
    /// This creates the symlinks that `make install` would normally create.
    ///
    /// Patterns:
    /// - macOS: `libfoo.1.2.3.dylib` → `libfoo.dylib`
    /// - Linux: `libfoo.so.1.2.3` → `libfoo.so`
    fn create_library_symlinks(&self) {
        // macOS: lib<name>.<version>.dylib → lib<name>.dylib
        // Linux: lib<name>.so.<version>    → lib<name>.so
        let re = Regex::new(r"^(lib\w+)\.(\d+\.)*\d+\.dylib$|^(lib\w+\.so)\.\d+(\.\d+)*$").unwrap();

        let entries: Vec<_> = fs::read_dir(&self.runtime_dir)
            .into_iter()
            .flatten()
            .filter_map(|e| e.ok())
            .collect();

        for entry in &entries {
            let filename = entry.file_name();
            let filename = filename.to_string_lossy();

            if let Some(caps) = re.captures(&filename) {
                // Group 1 = macOS base (e.g., "libkrun"), Group 3 = Linux base (e.g., "libkrun.so")
                let base = caps.get(1).or(caps.get(3)).map(|m| m.as_str());
                if let Some(base) = base {
                    let symlink_name = if caps.get(1).is_some() {
                        format!("{}.dylib", base)
                    } else {
                        base.to_string()
                    };

                    let symlink_path = self.runtime_dir.join(&symlink_name);
                    if !symlink_path.exists() {
                        #[cfg(unix)]
                        {
                            // Relative symlink: libkrun.dylib → libkrun.1.16.0.dylib
                            std::os::unix::fs::symlink(filename.as_ref(), &symlink_path).ok();
                            println!(
                                "cargo:warning=Created symlink: {} -> {}",
                                symlink_name, filename
                            );
                        }
                    }
                }
            }
        }
    }

    /// Downloads prebuilt runtime binaries from GitHub Releases.
    ///
    /// Called when BOXLITE_DEPS_STUB is set (i.e., -sys crates skipped their builds).
    /// Downloads the full `boxlite-runtime-v{version}-{target}.tar.gz` tarball which contains
    /// all native libraries (libkrun, libgvproxy, etc.) and tool binaries.
    fn download(&self) -> bool {
        if self.is_complete() {
            println!("cargo:warning=Prebuilt runtime already present, skipping download");
            return true;
        }

        let target = match Self::runtime_target() {
            Some(t) => t,
            None => {
                println!("cargo:warning=Unsupported platform for prebuilt download, skipping");
                return false;
            }
        };

        let version = env::var("CARGO_PKG_VERSION").unwrap();
        let default_url = format!(
            "https://github.com/boxlite-ai/boxlite/releases/download/v{version}/boxlite-runtime-v{version}-{target}.tar.gz"
        );

        println!("cargo:rerun-if-env-changed=BOXLITE_RUNTIME_URL");
        let url = env::var("BOXLITE_RUNTIME_URL").unwrap_or(default_url);

        fs::create_dir_all(&self.runtime_dir)
            .unwrap_or_else(|e| panic!("Failed to create runtime directory: {}", e));

        let tarball_path = self.runtime_dir.join(Self::TARBALL_NAME);

        match Self::download_file(&url, &tarball_path) {
            Ok(()) => {}
            Err(e) => {
                println!(
                    "cargo:warning=Failed to download prebuilt runtime from {}: {}",
                    url, e
                );
                println!("cargo:warning=Native libraries will not be available.");
                return false;
            }
        }

        match self.extract_tarball(&tarball_path) {
            Ok(()) => {
                // Clean up tarball before listing
                fs::remove_file(&tarball_path).ok();

                // Create unversioned symlinks for build-time linking
                self.create_library_symlinks();

                let files = match self.write_file_manifest() {
                    Ok(files) => files,
                    Err(e) => {
                        println!("cargo:warning=Failed to write runtime manifest: {}", e);
                        return false;
                    }
                };
                println!(
                    "cargo:warning=Downloaded prebuilt runtime v{}: [{}]",
                    version,
                    files.join(", ")
                );
                let incomplete = self.incomplete_reasons();
                if !incomplete.is_empty() {
                    println!(
                        "cargo:warning=Prebuilt runtime is incomplete: {}",
                        incomplete.join(", ")
                    );
                    return false;
                }
                true
            }
            Err(e) => {
                fs::remove_file(&tarball_path).ok();
                println!("cargo:warning=Failed to extract runtime tarball: {}", e);
                false
            }
        }
    }
}

/// How native dependencies are resolved.
///
/// Controlled by the `BOXLITE_DEPS_STUB` environment variable:
/// - unset  → `Source`:   build -sys crates from source, bundle outputs
/// - `1`    → `Stub`:     skip everything, for CI `cargo check`/`cargo clippy`
/// - `2`    → `Prebuilt`: skip -sys builds, download prebuilt from GitHub Releases
enum DepsMode {
    Source,
    Stub,
    Prebuilt,
}

impl DepsMode {
    /// Convert BOXLITE_DEPS_STUB into the native dependency resolution mode.
    fn from_env() -> Self {
        match env::var("BOXLITE_DEPS_STUB").ok().as_deref() {
            Some("2") => Self::Prebuilt,
            Some(_) => Self::Stub,
            None => Self::Source,
        }
    }
}

/// Auto-set BOXLITE_DEPS_STUB=2 when downloaded from a registry (crates.io).
/// Cargo adds .cargo_vcs_info.json to published packages.
fn auto_detect_registry() {
    if env::var("BOXLITE_DEPS_STUB").is_err() {
        let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
        if manifest_dir.join(".cargo_vcs_info.json").exists() {
            // SAFETY: build.rs is single-threaded; no concurrent env var access.
            unsafe { env::set_var("BOXLITE_DEPS_STUB", "2") };
        }
    }
}

// ── Embedded runtime manifest generation ────────────────────────────────

/// Embedded runtime manifest generator.
///
/// Lightweight handle that stores the runtime directory path.
/// Call `generate()` to scan the directory, write `embedded_manifest.rs`,
/// and emit content hashes via `cargo:rustc-env`.
struct EmbeddedManifest {
    runtime_dir: PathBuf,
}

impl EmbeddedManifest {
    /// Create a manifest generator for the given runtime directory.
    fn new(runtime_dir: &Path) -> Self {
        Self {
            runtime_dir: runtime_dir.to_path_buf(),
        }
    }

    /// Scan `runtime_dir` for regular files (skipping symlinks/directories).
    fn scan_entries(&self) -> Vec<(String, PathBuf, u32)> {
        let mut entries = Vec::new();
        if self.runtime_dir.exists() {
            for entry in fs::read_dir(&self.runtime_dir)
                .unwrap_or_else(|e| panic!("Failed to read runtime dir: {}", e))
            {
                let entry = entry.unwrap();
                let path = entry.path();
                let name = entry.file_name().to_string_lossy().to_string();
                if name == PrebuiltRuntime::FILE_MANIFEST {
                    continue;
                }

                let meta = fs::symlink_metadata(&path).unwrap();
                if !meta.is_file() {
                    continue;
                }

                let mode = Self::file_mode(&path);
                entries.push((name, path, mode));
            }
        }
        // Sort for deterministic code generation and hashing
        entries.sort_by(|a, b| a.0.cmp(&b.0));
        entries
    }

    // ── Private helpers ─────────────────────────────────────────────

    /// Write the generated manifest and emit its build metadata.
    fn emit_manifest(manifest_path: &Path, entries: &[(String, PathBuf, u32)]) {
        Self::write_manifest_rs(manifest_path, entries);
        Self::emit_content_hash(entries);
        if !entries.is_empty() {
            Self::log_summary(entries);
        }
    }

    /// Generate the Rust source included by runtime::embedded.
    fn write_manifest_rs(manifest_path: &Path, entries: &[(String, PathBuf, u32)]) {
        if entries.is_empty() {
            fs::write(
                manifest_path,
                "// Auto-generated by build.rs — no embedded files\n\
                 pub const MANIFEST: &[(&str, u32, &[u8])] = &[];\n",
            )
            .unwrap_or_else(|e| panic!("Failed to write empty manifest: {}", e));
            return;
        }

        let mut code = String::from("// Auto-generated by build.rs — do not edit\n");
        code.push_str("pub const MANIFEST: &[(&str, u32, &[u8])] = &[\n");
        for (name, path, mode) in entries {
            let abs = path.to_string_lossy().replace('\\', "/");
            code.push_str(&format!(
                "    (\"{}\", 0o{:o}, include_bytes!(\"{}\")),\n",
                name, mode, abs
            ));
            println!("cargo:rerun-if-changed={}", path.display());
        }
        code.push_str("];\n");

        fs::write(manifest_path, &code)
            .unwrap_or_else(|e| panic!("Failed to write embedded manifest: {}", e));
    }

    /// Hash manifest names, modes, and bytes for cache invalidation.
    fn emit_content_hash(entries: &[(String, PathBuf, u32)]) {
        let mut hasher = Sha256::new();
        for (name, path, mode) in entries {
            hasher.update(name.as_bytes());
            hasher.update(mode.to_le_bytes());
            let content = fs::read(path)
                .unwrap_or_else(|e| panic!("Failed to read {} for hashing: {}", path.display(), e));
            hasher.update(&content);
        }
        let hash = format!("{:x}", hasher.finalize());
        let prefix = &hash[..12];
        println!("cargo:rustc-env=BOXLITE_MANIFEST_HASH={}", prefix);
        println!(
            "cargo:rustc-env=BOXLITE_BUILD_PROFILE={}",
            env::var("PROFILE").unwrap()
        );
        println!("cargo:warning=Embedded manifest hash: {}", prefix);
    }

    /// Log the generated embedded runtime size summary.
    fn log_summary(entries: &[(String, PathBuf, u32)]) {
        let total_size: u64 = entries
            .iter()
            .map(|(_, p, _)| fs::metadata(p).map(|m| m.len()).unwrap_or(0))
            .sum();
        println!(
            "cargo:warning=Embedded runtime: {} files, {:.1} MB total",
            entries.len(),
            total_size as f64 / (1024.0 * 1024.0)
        );
    }

    /// Return the Unix permission bits to preserve in the generated manifest.
    fn file_mode(path: &Path) -> u32 {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::metadata(path)
                .map(|metadata| metadata.permissions().mode() & 0o777)
                .unwrap_or(0o644)
        }

        #[cfg(not(unix))]
        {
            let _ = path;
            0o644
        }
    }

    // ── Embedded manifest generation ────────────────────────────────

    /// Top-level entry point for embedded manifest generation.
    ///
    /// When `embedded-runtime` feature is enabled and deps are available (Source mode),
    /// finds pre-built shim/guest binaries, copies them to the runtime dir, and generates
    /// an `include_bytes!` manifest for all files in the runtime dir.
    ///
    /// When the feature is off or in Stub mode, generates an empty manifest.
    fn generate(&self, mode: &DepsMode, cargo: &CargoBuildContext) {
        let manifest_path = cargo.out_dir().join("embedded_manifest.rs");

        let enabled = env::var("CARGO_FEATURE_EMBEDDED_RUNTIME").is_ok();

        if !enabled || matches!(mode, DepsMode::Stub) {
            Self::emit_manifest(&manifest_path, &[]);
            return;
        }

        if matches!(mode, DepsMode::Prebuilt) {
            let entries = self.scan_entries();
            Self::emit_manifest(&manifest_path, &entries);
            return;
        }

        let prebuilt_runtime = PrebuiltRuntime::new(&self.runtime_dir);
        if cargo.is_dependency_build() && prebuilt_runtime.is_complete() {
            let entries = self.scan_entries();
            Self::emit_manifest(&manifest_path, &entries);
            return;
        }

        // Feature enabled: collect pre-built binaries into runtime_dir,
        // then generate include_bytes! for all files.
        let Some(workspace_root) = cargo.workspace_root() else {
            let entries = self.scan_entries();
            Self::emit_manifest(&manifest_path, &entries);
            return;
        };

        fs::create_dir_all(&self.runtime_dir)
            .unwrap_or_else(|e| panic!("Failed to create runtime directory: {}", e));

        let profile = env::var("PROFILE").unwrap();

        self.copy_prebuilt_binary(
            workspace_root,
            "boxlite-shim",
            &profile,
            Self::find_prebuilt_shim,
        );
        self.copy_prebuilt_binary(
            workspace_root,
            "boxlite-guest",
            &profile,
            Self::find_prebuilt_guest,
        );

        let entries = self.scan_entries();
        Self::emit_manifest(&manifest_path, &entries);
    }

    /// Copy a pre-built binary into the runtime directory.
    ///
    /// Always overwrites the destination to avoid stale binaries when the source
    /// is rebuilt. Emits `cargo:rerun-if-changed` for the source path so cargo
    /// re-runs build.rs when the binary changes.
    ///
    /// Uses the provided `finder` function to locate the binary. If not found,
    /// warns and skips — this happens when building boxlite-shim itself (the
    /// binary doesn't exist yet). The embedded manifest will simply omit it.
    fn copy_prebuilt_binary(
        &self,
        workspace_root: &Path,
        name: &str,
        profile: &str,
        finder: fn(&Path, &str) -> Option<PathBuf>,
    ) {
        let Some(source) = finder(workspace_root, profile) else {
            println!("cargo:warning={} not found, skipping embed", name);
            return;
        };

        // Re-run build.rs when the source binary changes.
        println!("cargo:rerun-if-changed={}", source.display());

        let dest = self.runtime_dir.join(name);
        fs::copy(&source, &dest).unwrap_or_else(|e| {
            panic!(
                "Failed to copy {} -> {}: {}",
                source.display(),
                dest.display(),
                e
            )
        });

        // Ensure boxlite-shim has the hypervisor entitlement on macOS. Cargo's
        // implicit bin-target rebuild (triggered by any `cargo test -p boxlite`)
        // produces an unsigned shim; without this step the embedded copy — and
        // therefore every integration test — would fail with
        // "Hypervisor.framework access denied".
        if name == "boxlite-shim" && cfg!(target_os = "macos") {
            sign_shim_with_entitlements(&dest);
        }

        println!(
            "cargo:warning=Embedded {}: {} ({:.1} MB)",
            name,
            source.display(),
            fs::metadata(&dest).map(|m| m.len()).unwrap_or(0) as f64 / (1024.0 * 1024.0)
        );
    }

    /// Find pre-built boxlite-shim binary for the given build profile.
    ///
    /// Search order:
    /// 1. Native: `target/{profile}/boxlite-shim` (macOS)
    /// 2. Linux gnu: `target/{arch}-unknown-linux-gnu/{profile}/boxlite-shim` (static glibc)
    fn find_prebuilt_shim(workspace_root: &Path, profile: &str) -> Option<PathBuf> {
        let target_dir = workspace_root.join("target");

        // Native path (macOS)
        let native = target_dir.join(profile).join("boxlite-shim");
        if native.is_file() {
            return Some(native);
        }

        // Linux gnu (static glibc — Go c-archive is incompatible with musl TLS)
        // Check matching architecture first to avoid picking wrong binary on
        // multi-arch machines.
        for arch in Self::preferred_arches() {
            let gnu = target_dir
                .join(format!("{}-unknown-linux-gnu", arch))
                .join(profile)
                .join("boxlite-shim");
            if gnu.is_file() {
                return Some(gnu);
            }
        }

        None
    }

    /// Find pre-built boxlite-guest binary for the given build profile.
    ///
    /// Checks matching architecture first to avoid picking wrong binary on
    /// multi-arch machines (e.g., x86_64 guest embedded into aarch64 build).
    fn find_prebuilt_guest(workspace_root: &Path, profile: &str) -> Option<PathBuf> {
        let target_dir = workspace_root.join("target");

        // Check matching architecture first, then fall back to others
        for arch in Self::preferred_arches() {
            let path = target_dir
                .join(format!("{}-unknown-linux-musl", arch))
                .join(profile)
                .join("boxlite-guest");
            if path.is_file() {
                return Some(path);
            }
        }

        None
    }

    /// Return architecture list with the build target's arch first.
    ///
    /// On multi-arch machines with both x86_64 and aarch64 binaries built,
    /// this ensures we pick the one matching the current build target.
    fn preferred_arches() -> Vec<&'static str> {
        let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
        match arch.as_str() {
            "aarch64" => vec!["aarch64", "x86_64"],
            "x86_64" => vec!["x86_64", "aarch64"],
            _ => vec!["x86_64", "aarch64"],
        }
    }
}

/// Sign a macOS binary with the hypervisor entitlement (ad-hoc).
///
/// `cargo test -p boxlite` implicitly rebuilds the `boxlite-shim` bin target,
/// which wipes whatever signature `scripts/build/sign.sh` put on it, so the
/// copy `copy_prebuilt_binary` made into the runtime dir would land unsigned
/// and every VM-dependent test would fail with "Hypervisor.framework access
/// denied". Doing the signing here makes the embed step self-sufficient.
fn sign_shim_with_entitlements(binary: &Path) {
    const ENTITLEMENTS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.hypervisor</key>
    <true/>
    <key>com.apple.security.cs.disable-library-validation</key>
    <true/>
</dict>
</plist>
"#;

    // codesign's --entitlements needs a real file path; pass a temp plist
    // written next to the binary.
    let plist_path = binary.with_file_name(format!(
        "{}.entitlements.plist",
        binary
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("shim")
    ));
    if let Err(e) = fs::write(&plist_path, ENTITLEMENTS) {
        println!(
            "cargo:warning=failed to write entitlements plist for {}: {}",
            binary.display(),
            e
        );
        return;
    }

    let output = Command::new("codesign")
        .args([
            "-s",
            "-",
            "--force",
            "--entitlements",
            plist_path
                .to_str()
                .expect("entitlements path must be UTF-8"),
            binary.to_str().expect("shim path must be valid UTF-8"),
        ])
        .output();

    let _ = fs::remove_file(&plist_path);

    match output {
        Ok(out) if out.status.success() => {
            println!(
                "cargo:warning=Signed {} with hypervisor entitlement",
                binary.display()
            );
        }
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr);
            println!(
                "cargo:warning=codesign on {} failed ({}): {}",
                binary.display(),
                out.status,
                stderr.trim()
            );
        }
        Err(e) => {
            println!(
                "cargo:warning=codesign could not be spawned for {}: {}",
                binary.display(),
                e
            );
        }
    }
}
/// Computes and embeds the `boxlite-guest` binary hash.
///
/// Search order:
/// 1. Direct build output: `target/{target-triple}/{profile}/boxlite-guest`
/// 2. `runtime_dir` (OUT_DIR/runtime/ — for prebuilt mode)
///
/// IMPORTANT: The source binary (direct build output) must be checked FIRST because
/// this runs before embedded manifest generation in main(). The OUT_DIR/runtime/ copy
/// may be from a previous build and stale when the guest binary was rebuilt.
///
/// If the binary isn't found, silently skips — runtime will compute the hash as fallback.
struct GuestBinaryHash<'a> {
    runtime_dir: &'a Path,
    mode: &'a DepsMode,
    cargo: &'a CargoBuildContext,
}

impl<'a> GuestBinaryHash<'a> {
    /// Create a guest binary hash emitter.
    fn new(runtime_dir: &'a Path, mode: &'a DepsMode, cargo: &'a CargoBuildContext) -> Self {
        Self {
            runtime_dir,
            mode,
            cargo,
        }
    }

    /// Emit BOXLITE_GUEST_HASH when a guest binary is available.
    fn emit(&self) {
        let Some(guest_path) = self.guest_path() else {
            println!("cargo:warning=boxlite-guest not found, skipping compile-time hash");
            return;
        };

        match Self::sha256_file(&guest_path) {
            Ok(hash) => {
                println!("cargo:rustc-env=BOXLITE_GUEST_HASH={}", hash);
                println!("cargo:rerun-if-changed={}", guest_path.display());
                println!(
                    "cargo:warning=Embedded guest hash: {}... (from {})",
                    &hash[..12],
                    guest_path.display()
                );
            }
            Err(e) => {
                println!(
                    "cargo:warning=Failed to hash boxlite-guest at {}: {}",
                    guest_path.display(),
                    e
                );
            }
        }
    }

    /// Pick the best available guest binary for hashing.
    fn guest_path(&self) -> Option<PathBuf> {
        let profile = env::var("PROFILE").unwrap_or_else(|_| "debug".to_string());
        self.source_guest_path(&profile)
            .or_else(|| self.runtime_guest_path())
    }

    /// Find the workspace-built guest binary in source builds.
    fn source_guest_path(&self, profile: &str) -> Option<PathBuf> {
        if !matches!(self.mode, DepsMode::Source) {
            return None;
        }

        let workspace_root = self.cargo.workspace_root()?;
        EmbeddedManifest::find_prebuilt_guest(workspace_root, profile)
    }

    /// Find the guest binary already copied into OUT_DIR/runtime.
    fn runtime_guest_path(&self) -> Option<PathBuf> {
        let path = self.runtime_dir.join("boxlite-guest");
        path.is_file().then_some(path)
    }

    /// Compute SHA256 hex digest of a file.
    fn sha256_file(path: &Path) -> io::Result<String> {
        let mut file = fs::File::open(path)?;
        let mut hasher = Sha256::new();
        let mut buffer = vec![0u8; 64 * 1024];
        loop {
            let n = file.read(&mut buffer)?;
            if n == 0 {
                break;
            }
            hasher.update(&buffer[..n]);
        }
        Ok(format!("{:x}", hasher.finalize()))
    }
}

/// Collects all FFI dependencies into a single runtime directory.
/// This directory can be used by downstream crates (e.g., Python SDK) to
/// bundle all required libraries and binaries together.
fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-env-changed=BOXLITE_DEPS_STUB");

    auto_detect_registry();

    // Compile KVM smoke test helper (C, Linux only).
    // Rust's libc::ioctl() variadic FFI has ABI issues with some KVM ioctls
    // on nested virtualization, so the smoke test is implemented in C.
    #[cfg(target_os = "linux")]
    {
        println!("cargo:rerun-if-changed=src/kvm_smoke.c");
        cc::Build::new()
            .file("src/kvm_smoke.c")
            .compile("kvm_smoke");
    }

    // Compile seccomp filters at build time (fast, required for include_bytes!())
    compile_seccomp_filters();

    let cargo = CargoBuildContext::new();
    let mode = DepsMode::from_env();

    let runtime_dir = cargo.out_dir().join("runtime");
    let prebuilt_runtime = PrebuiltRuntime::new(&runtime_dir);

    match &mode {
        DepsMode::Stub => {
            // Check-only mode: skip dependency bundling but still generate
            // the embedded manifest (needed for env!() macros in embedded.rs)
            println!("cargo:warning=BOXLITE_DEPS_STUB=1: skipping dependency bundling");
            println!("cargo:runtime_dir=/nonexistent");
            EmbeddedManifest::new(&runtime_dir).generate(&mode, &cargo);
            return;
        }
        DepsMode::Prebuilt => {
            // Download prebuilt runtime from GitHub Releases
            println!("cargo:warning=BOXLITE_DEPS_STUB=2: downloading prebuilt runtime");
            fs::create_dir_all(&runtime_dir)
                .unwrap_or_else(|e| panic!("Failed to create runtime directory: {}", e));
            if !prebuilt_runtime.download() {
                panic!(
                    "Failed to prepare complete prebuilt BoxLite runtime in {}",
                    runtime_dir.display()
                );
            }
            // Embed runtime directory for compile-time fallback by RuntimeBinaryFinder.
            // Runtime override remains BOXLITE_RUNTIME_DIR (read via std::env::var).
            // Compile-time embed is only needed in prebuilt mode.
            println!(
                "cargo:rustc-env=BOXLITE_RUNTIME_DIR={}",
                runtime_dir.display()
            );
        }
        DepsMode::Source => {
            // Normal: -sys crates built from source, bundle outputs
            fs::create_dir_all(&runtime_dir)
                .unwrap_or_else(|e| panic!("Failed to create runtime directory: {}", e));
            let collected = bundle_boxlite_deps(&runtime_dir);
            if !collected.is_empty() {
                let names: Vec<_> = collected.iter().map(|(name, _)| name.as_str()).collect();
                println!("cargo:warning=Bundled: {}", names.join(", "));
            }
            if env::var("CARGO_FEATURE_EMBEDDED_RUNTIME").is_ok()
                && cargo.is_dependency_build()
                && !prebuilt_runtime.is_complete()
            {
                let incomplete = prebuilt_runtime.incomplete_reasons();
                println!(
                    "cargo:warning=Dependency build has incomplete runtime [{}]; downloading prebuilt runtime",
                    incomplete.join(", ")
                );
                if !prebuilt_runtime.download() {
                    panic!(
                        "Failed to prepare complete prebuilt BoxLite runtime in {}",
                        runtime_dir.display()
                    );
                }
            }
        }
    };

    // Tell the linker where to find the bundled libraries.
    println!("cargo:rustc-link-search=native={}", runtime_dir.display());

    // libkrun is a Rust staticlib that embeds its own copy of std.
    // When linked into Rust test/bin targets, std symbols conflict.
    // Applied to both test and bin targets.
    #[cfg(target_os = "linux")]
    println!("cargo:rustc-link-arg-tests=-Wl,--allow-multiple-definition");
    #[cfg(target_os = "linux")]
    println!("cargo:rustc-link-arg-bins=-Wl,--allow-multiple-definition");

    // Expose the runtime directory to downstream crates (e.g., Python SDK)
    println!("cargo:runtime_dir={}", runtime_dir.display());

    // Compute and embed guest binary hash at compile time (best-effort).
    // Falls back to runtime computation if the binary isn't available yet.
    GuestBinaryHash::new(&runtime_dir, &mode, &cargo).emit();

    // Generate embedded runtime manifest (include_bytes! for self-contained SDKs)
    EmbeddedManifest::new(&runtime_dir).generate(&mode, &cargo);

    // Set rpath for boxlite-shim
    #[cfg(target_os = "macos")]
    println!("cargo:rustc-link-arg=-Wl,-rpath,@loader_path");
    #[cfg(target_os = "linux")]
    println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN");
}