hilt 0.1.0

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

use std::fmt::Write as _;
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant};

use crate::config::{HilConfig, UartBridge, RENODE_ARM64_IMAGE};
use crate::output::HilOutput;
use crate::platform::{CpuInit, ReplSource};

/// Env var that overrides container-runtime auto-detection.
pub const RUNTIME_ENV: &str = "HILT_CONTAINER_RUNTIME";

const CONTAINER_WORK: &str = "/hil";

/// Upstream Renode release the native `aarch64` image ([`RENODE_ARM64_IMAGE`])
/// is built from. There is no official arm64 Renode container, so `hilt` builds
/// one on demand from this release's `linux-arm64` portable (self-contained
/// .NET) tarball.
pub const RENODE_ARM64_VERSION: &str = "1.16.1";

/// `true` for the one image `hilt` manages itself: the locally-built native
/// arm64 Renode image, which needs an on-demand build and a `--platform` pin.
fn is_managed_arm64_image(image: &str) -> bool {
    image == RENODE_ARM64_IMAGE
}

/// `Containerfile` for the native `aarch64` Renode image. A slim Debian base
/// plus the upstream `linux-arm64` portable Renode (which bundles its own .NET
/// runtime), entrypoint-compatible with `antmicro/renode` (`/opt/renode/renode`).
fn renode_arm64_containerfile() -> String {
    let v = RENODE_ARM64_VERSION;
    format!(
        r#"FROM docker.io/library/debian:bookworm-slim
RUN apt-get update \
 && apt-get install -y --no-install-recommends libicu72 ca-certificates curl \
 && curl -fsSL -o /tmp/renode.tar.gz \
      https://github.com/renode/renode/releases/download/v{v}/renode-{v}.linux-arm64-portable-dotnet.tar.gz \
 && mkdir -p /opt && tar xzf /tmp/renode.tar.gz -C /opt && rm /tmp/renode.tar.gz \
 && ln -s /opt/renode_{v}-dotnet_portable /opt/renode \
 && apt-get purge -y curl && apt-get autoremove -y && rm -rf /var/lib/apt/lists/*
ENTRYPOINT ["/opt/renode/renode"]
"#
    )
}

/// Returns `true` if `image` already exists locally for `runtime`.
fn image_present(runtime: &str, image: &str) -> bool {
    command_succeeds(runtime, &["image", "inspect", image])
}

/// Builds the native `aarch64` Renode image if it is not already present.
///
/// Only the `hilt`-managed [`RENODE_ARM64_IMAGE`] is ever auto-built; any other
/// image (the amd64 default, or a user override) is left to the caller/registry.
/// Guarded by a process-wide `Once` so parallel tests neither race the build
/// nor pay a redundant `image inspect` per run.
///
/// # Panics
///
/// Panics if the image is missing and the build fails.
fn ensure_renode_image(runtime: &str, image: &str) {
    if !is_managed_arm64_image(image) {
        return;
    }
    static BUILD: std::sync::Once = std::sync::Once::new();
    BUILD.call_once(|| {
        if image_present(runtime, image) {
            return;
        }
        eprintln!("hilt: building native arm64 Renode image `{image}` (first run, one-time)…");
        // ponytail: pid-keyed dir; the Once serializes in-process racers,
        // cross-process first-run races are left to podman's per-tag locking.
        let dir = std::env::temp_dir().join(format!("hilt-renode-build-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("failed to create Renode image build dir");
        std::fs::write(dir.join("Containerfile"), renode_arm64_containerfile())
            .expect("failed to write Containerfile");
        let status = Command::new(runtime)
            .args(["build", "--platform", "linux/arm64", "-t", image, "-f"])
            .arg(dir.join("Containerfile"))
            .arg(&dir)
            .status()
            .expect("failed to invoke container build");
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            status.success(),
            "failed to build native arm64 Renode image `{image}`"
        );
    });
}

// ---------------------------------------------------------------------------
// Container runtime detection
// ---------------------------------------------------------------------------

/// Returns `true` if running `cmd` with `args` succeeds (exit status 0).
fn command_succeeds(cmd: &str, args: &[&str]) -> bool {
    Command::new(cmd)
        .args(args)
        .output()
        .is_ok_and(|o| o.status.success())
}

/// Finds the container runtime: `HILT_CONTAINER_RUNTIME`, else the first of
/// `podman`/`docker` that answers `--version`.
fn find_container_runtime() -> Option<String> {
    if let Ok(rt) = std::env::var(RUNTIME_ENV) {
        return Some(rt);
    }
    ["podman", "docker"]
        .iter()
        .find(|c| command_succeeds(c, &["--version"]))
        .map(ToString::to_string)
}

/// Detects the container runtime. Honors `HILT_CONTAINER_RUNTIME`, else tries
/// `podman` then `docker`.
///
/// # Panics
///
/// Panics if no container runtime is found.
#[must_use]
pub fn detect_container_runtime() -> String {
    find_container_runtime().expect("no container runtime found -- install podman or docker")
}

/// Returns `true` if a container runtime is available (non-panicking).
#[must_use]
pub fn container_runtime_available() -> bool {
    find_container_runtime().is_some()
}

/// Resolves a native Renode binary, in order: `HILT_RENODE_BIN`, then `renode`
/// on `PATH`, then `/opt/renode/renode` (the `antmicro/renode` image path).
#[must_use]
pub fn renode_bin() -> Option<PathBuf> {
    if let Some(p) = std::env::var_os("HILT_RENODE_BIN") {
        let p = PathBuf::from(p);
        if p.exists() {
            return Some(p);
        }
    }
    if command_succeeds("renode", &["--version"]) {
        return Some(PathBuf::from("renode"));
    }
    let opt = PathBuf::from("/opt/renode/renode");
    opt.exists().then_some(opt)
}

/// Returns `true` if a native Renode binary is available (for non-container
/// use, e.g. running inside a Renode-based image).
#[must_use]
pub fn renode_available() -> bool {
    renode_bin().is_some()
}

fn cleanup_container(runtime: &str, cidfile: &Path) {
    let Ok(cid) = std::fs::read_to_string(cidfile) else {
        return;
    };
    let cid = cid.trim();
    if cid.is_empty() {
        return;
    }
    let _ = Command::new(runtime).args(["rm", "-f", cid]).status();
}

// ---------------------------------------------------------------------------
// Host SocketCAN setup
// ---------------------------------------------------------------------------

/// Creates (or recreates) a virtual CAN interface with CAN-FD MTU.
///
/// # Panics
///
/// Panics if the interface cannot be created (typically needs root).
pub fn setup_vcan(iface: &str) {
    Command::new("modprobe").arg("vcan").status().ok();
    Command::new("ip")
        .args(["link", "del", iface])
        .status()
        .ok();
    let status = Command::new("ip")
        .args(["link", "add", "dev", iface, "type", "vcan"])
        .status()
        .expect("failed to create vcan interface");
    assert!(
        status.success(),
        "failed to create {iface} -- try with sudo or in a container"
    );
    Command::new("ip")
        .args(["link", "set", iface, "up", "mtu", "72"])
        .status()
        .expect("failed to bring up vcan interface");
}

/// Returns `true` if the given network interface exists.
#[must_use]
pub fn interface_available(iface: &str) -> bool {
    command_succeeds("ip", &["link", "show", iface])
}

// ---------------------------------------------------------------------------
// Process lifecycle
// ---------------------------------------------------------------------------

/// Runs a command with a hard timeout and a cleanup callback.
///
/// Captures stdout/stderr on background threads (so a chatty child can't
/// deadlock on a full pipe). If the deadline passes, the child is killed,
/// reaped, and then `cleanup` runs.
///
/// # Panics
///
/// Panics if the process cannot be spawned, polled, or reaped.
pub fn run_with_timeout_and_cleanup<F>(
    mut command: Command,
    timeout_secs: u32,
    cleanup: F,
) -> Output
where
    F: FnOnce(),
{
    command.stdout(Stdio::piped()).stderr(Stdio::piped());

    let mut child = command
        .spawn()
        .unwrap_or_else(|e| panic!("failed to spawn container runtime: {e}"));
    let mut stdout = child.stdout.take().expect("child stdout not captured");
    let mut stderr = child.stderr.take().expect("child stderr not captured");

    let stdout_thread = thread::spawn(move || {
        let mut buf = Vec::new();
        stdout
            .read_to_end(&mut buf)
            .unwrap_or_else(|e| panic!("failed to read child stdout: {e}"));
        buf
    });
    let stderr_thread = thread::spawn(move || {
        let mut buf = Vec::new();
        stderr
            .read_to_end(&mut buf)
            .unwrap_or_else(|e| panic!("failed to read child stderr: {e}"));
        buf
    });

    let deadline = Instant::now() + Duration::from_secs(timeout_secs.into());
    let status = loop {
        match child
            .try_wait()
            .unwrap_or_else(|e| panic!("failed to poll container runtime: {e}"))
        {
            Some(status) => break status,
            None if Instant::now() >= deadline => {
                let _ = child.kill();
                break child
                    .wait()
                    .unwrap_or_else(|e| panic!("failed to reap timed-out container runtime: {e}"));
            }
            None => thread::sleep(Duration::from_millis(100)),
        }
    };

    cleanup();

    let stdout = stdout_thread
        .join()
        .unwrap_or_else(|_| panic!("failed to join stdout reader"));
    let stderr = stderr_thread
        .join()
        .unwrap_or_else(|_| panic!("failed to join stderr reader"));

    Output {
        status,
        stdout,
        stderr,
    }
}

/// Runs a prepared Renode container command with `timeout_secs` plus a margin,
/// and a cleanup callback. Thin convenience over
/// [`run_with_timeout_and_cleanup`].
///
/// # Panics
///
/// Panics on the same conditions as [`run_with_timeout_and_cleanup`].
pub fn run_renode_container<F>(command: Command, timeout_secs: u32, cleanup: F) -> Output
where
    F: FnOnce(),
{
    run_with_timeout_and_cleanup(command, timeout_secs.saturating_add(50), cleanup)
}

// ---------------------------------------------------------------------------
// ELF introspection
// ---------------------------------------------------------------------------

/// Vector table and marker symbol extracted from a firmware ELF.
#[derive(Debug, Clone, Copy)]
pub struct ElfInfo {
    /// Vector table offset.
    pub vtor: u32,
    /// Initial stack pointer.
    pub sp: u32,
    /// Reset handler address (thumb bit cleared).
    pub pc: u32,
    /// Address of the marker symbol, if found.
    pub hook_addr: Option<u32>,
}

/// Extracts the vector table (`vtor`/`sp`/`pc`) and `marker` symbol address
/// from a firmware ELF using `rust-objdump` and `rust-nm`.
///
/// # Panics
///
/// Panics if `rust-objdump` is missing or the vector table cannot be read.
#[must_use]
pub fn extract_elf_info(firmware_elf: &Path, marker: &str) -> ElfInfo {
    let vt_output = Command::new("rust-objdump")
        .args(["-s", "-j", ".vector_table"])
        .arg(firmware_elf)
        .output()
        .expect("rust-objdump not found -- install via `rustup component add llvm-tools`");

    let stdout = String::from_utf8_lossy(&vt_output.stdout);
    let mut vtor = 0u32;
    let mut sp = 0u32;
    let mut pc = 0u32;
    for line in stdout.lines() {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 3 {
            continue;
        }
        let Ok(addr) = u32::from_str_radix(parts[0], 16) else {
            continue;
        };
        vtor = addr;
        sp = swap_endian_u32(parts[1]);
        pc = swap_endian_u32(parts[2]) & !1;
        break;
    }
    assert!(
        pc != 0,
        "failed to extract vector table from {}",
        firmware_elf.display()
    );

    ElfInfo {
        vtor,
        sp,
        pc,
        hook_addr: find_symbol_address(firmware_elf, marker),
    }
}

/// Returns the address of `symbol` in `firmware_elf`, via `rust-nm`.
#[must_use]
pub fn find_symbol_address(firmware_elf: &Path, symbol: &str) -> Option<u32> {
    let output = Command::new("rust-nm")
        .arg("--defined-only")
        .arg(firmware_elf)
        .output()
        .ok()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines() {
        let mut fields = line.split_whitespace();
        let addr_str = fields.next()?;
        let _type = fields.next();
        if fields.next() == Some(symbol) {
            return u32::from_str_radix(addr_str, 16).ok();
        }
    }
    None
}

fn swap_endian_u32(hex: &str) -> u32 {
    u32::from_le_bytes(u32::from_str_radix(hex, 16).unwrap_or(0).to_be_bytes())
}

// ---------------------------------------------------------------------------
// Renode script generation
// ---------------------------------------------------------------------------

/// One machine resolved to the concrete values the `.resc` generator needs.
struct ReadyMachine {
    name: String,
    elf_ref: String,
    repl_ref: String,
    mips: Option<u32>,
    can_connector: Option<&'static str>,
    init: CpuInit,
    info: Option<ElfInfo>,
    socketcan_bridge: bool,
    uart_bridge: Option<UartBridge>,
}

/// Renders a Renode `.resc` script for the given machines.
fn render_resc(
    machines: &[ReadyMachine],
    socketcan_iface: &str,
    stubs_ref: Option<&str>,
    timeout_secs: u32,
) -> String {
    let any_bridge = machines.iter().any(|m| m.socketcan_bridge);
    let hub = machines.len() > 1 || any_bridge;

    let mut s = String::from("using sysbus\n\n");
    if hub {
        s.push_str("emulation CreateCANHub \"canHub\" False\n\n");
    }

    for m in machines {
        let _ = writeln!(s, "mach create \"{}\"", m.name);
        let _ = writeln!(s, "machine LoadPlatformDescription @{}", m.repl_ref);
        if let Some(stubs) = stubs_ref {
            let _ = writeln!(s, "machine LoadPlatformDescription @{stubs}");
        }
        if let Some(mips) = m.mips {
            let _ = writeln!(s, "cpu PerformanceInMips {mips}");
        }
        let _ = writeln!(s, "sysbus LoadELF @{}", m.elf_ref);

        if m.init == CpuInit::VectorTable {
            if let Some(info) = m.info {
                let _ = writeln!(s, "cpu VectorTableOffset {:#010X}", info.vtor);
                let _ = writeln!(s, "cpu SP {:#010X}", info.sp);
                let _ = writeln!(s, "cpu PC {:#010X}", info.pc);
                if let Some(addr) = info.hook_addr {
                    let _ = writeln!(
                        s,
                        "cpu AddHook {addr:#010X} \"self.Log(LogLevel.Warning, 'HIL OK')\""
                    );
                }
            }
        }

        if hub {
            if let Some(connector) = m.can_connector {
                let _ = writeln!(s, "connector Connect {connector} canHub");
            }
            if m.socketcan_bridge {
                let _ = writeln!(s, "machine CreateSocketCANBridge \"{socketcan_iface}\"");
                let _ = writeln!(s, "connector Connect {socketcan_iface} canHub");
            }
        }

        // Expose the machine's UART to the host as a TCP server terminal. The
        // container port is published on the host by the runner. Bytes flow
        // raw; the firmware and host agree on any higher-level framing.
        if let Some(bridge) = &m.uart_bridge {
            let term = format!("{}_uart", m.name);
            // The trailing `false` suppresses Renode's Telnet IAC negotiation so
            // the terminal is a *raw* byte pipe. Without it, Renode greets each
            // client with Telnet option bytes (0xFF …) that corrupt binary
            // framing on the wire.
            let _ = writeln!(
                s,
                "emulation CreateServerSocketTerminal {} \"{term}\" false",
                bridge.host_port
            );
            let _ = writeln!(s, "connector Connect {} {term}", bridge.uart);
        }

        s.push_str("mach clear\n\n");
    }

    s.push_str("start\n");
    let _ = writeln!(
        s,
        "emulation RunFor \"00:{:02}:{:02}\"",
        timeout_secs / 60,
        timeout_secs % 60
    );
    s.push_str("quit\n");
    s
}

// ---------------------------------------------------------------------------
// Runner
// ---------------------------------------------------------------------------

/// Runs firmware in Renode inside a container, generating the platform
/// description(s) and `.resc` script from a [`HilConfig`].
pub struct RenodeRunner {
    config: HilConfig,
}

struct CleanupGuard(PathBuf);
impl Drop for CleanupGuard {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

impl RenodeRunner {
    /// Creates a runner from a configuration.
    #[must_use]
    pub fn new(config: HilConfig) -> Self {
        Self { config }
    }

    /// Borrows the configuration.
    #[must_use]
    pub fn config(&self) -> &HilConfig {
        &self.config
    }

    /// Runs the HIL test and returns the captured output.
    ///
    /// Uses a container when a runtime (podman/docker) is available, otherwise
    /// falls back to a native `renode` binary — so the same call works both
    /// from a container host and *inside* a Renode-based image. The work
    /// directory (and container, if any) are cleaned up automatically, even on
    /// timeout.
    ///
    /// # Panics
    ///
    /// Panics if a firmware ELF is missing, or if neither a container runtime
    /// nor a native Renode binary is found.
    #[must_use]
    pub fn run(&self) -> HilOutput {
        let work_dir = work_dir_for(&self.config);
        std::fs::create_dir_all(&work_dir).expect("failed to create HIL work dir");
        let _guard = CleanupGuard(work_dir.clone());

        let runtime = find_container_runtime();
        let use_container = runtime.is_some();
        let renode = if use_container { None } else { renode_bin() };
        assert!(
            use_container || renode.is_some(),
            "no HIL backend: install podman/docker, or a native renode \
             (HILT_RENODE_BIN, PATH, or /opt/renode/renode)"
        );

        // Where the work dir lives from the Renode process's point of view:
        // a bind mount in container mode, the real path natively.
        let repl_base = if use_container {
            CONTAINER_WORK.to_string()
        } else {
            work_dir.display().to_string()
        };

        // Resolve each machine, writing embedded .repls into the work dir.
        let mut ready = Vec::with_capacity(self.config.machines.len());
        let mut elf_paths = Vec::new();
        for m in &self.config.machines {
            let elf = m.firmware_elf.canonicalize().unwrap_or_else(|e| {
                panic!(
                    "firmware ELF not found at {}: {e}",
                    m.firmware_elf.display()
                )
            });
            elf_paths.push(elf.clone());

            let repl_ref = match m.platform.repl {
                ReplSource::ImagePath(p) => p.to_string(),
                ReplSource::Embedded(body) => {
                    let file = format!("{}.repl", m.name);
                    std::fs::write(work_dir.join(&file), body).expect("failed to write .repl");
                    format!("{repl_base}/{file}")
                }
            };

            let info = (m.platform.init == CpuInit::VectorTable)
                .then(|| extract_elf_info(&elf, &self.config.marker));

            ready.push(ReadyMachine {
                name: m.name.clone(),
                elf_ref: elf.display().to_string(),
                repl_ref,
                mips: m.platform.mips,
                can_connector: m.platform.can_connector,
                init: m.platform.init,
                info,
                socketcan_bridge: m.socketcan_bridge,
                uart_bridge: m.uart_bridge.clone(),
            });
        }

        // Resolve the optional stubs overlay (referenced by its real path).
        let stubs = self.config.stubs_repl.as_ref().map(|p| {
            p.canonicalize()
                .unwrap_or_else(|e| panic!("stubs REPL not found at {}: {e}", p.display()))
        });

        let resc = render_resc(
            &ready,
            &self.config.socketcan_iface,
            stubs.as_ref().map(|p| p.display().to_string()).as_deref(),
            self.config.timeout_secs,
        );
        std::fs::write(work_dir.join("test.resc"), &resc).expect("failed to write .resc");

        // UART-bridge ports must be distinct: each becomes one server-socket
        // terminal in Renode and one published host port.
        let mut uart_ports: Vec<u16> = self
            .config
            .machines
            .iter()
            .filter_map(|m| m.uart_bridge.as_ref().map(|b| b.host_port))
            .collect();
        uart_ports.sort_unstable();
        let unique = uart_ports.windows(2).all(|w| w[0] != w[1]);
        assert!(unique, "duplicate UART bridge host_port in config");

        let timeout = self.config.timeout_secs + 15;
        let output = if use_container {
            let runtime = runtime.expect("container backend resolved above");
            ensure_renode_image(&runtime, &self.config.image);
            let cidfile = work_dir.join("renode.cid");
            let relabel = if cfg!(target_os = "linux") { ",Z" } else { "" };

            let mut command = Command::new(&runtime);
            command.args(["run", "--rm"]);
            // The native arm64 image is single-arch; pin the platform so podman
            // doesn't try (and fail) to pull/run an amd64 variant on hosts where
            // amd64 is the default emulated target.
            if is_managed_arm64_image(&self.config.image) {
                command.args(["--platform", "linux/arm64"]);
            } else if cfg!(target_arch = "aarch64") {
                // An amd64 image on an arm64 host runs under qemu-user, where
                // .NET's write-xor-execute JIT segfaults; disabling it lets
                // Renode boot. Native runs don't need (or get) this.
                command.args(["-e", "DOTNET_EnableWriteXorExecute=0"]);
            }
            if self.config.needs_host_network() {
                // Under host networking, published ports are discarded (the
                // terminals bind directly on the host), so skip `-p`.
                command.arg("--network=host");
            } else {
                // Publish UART-bridge ports so host code reaches the
                // in-container terminals without host networking.
                for port in &uart_ports {
                    command.args(["-p".to_string(), format!("127.0.0.1:{port}:{port}")]);
                }
            }
            command.args([
                "--cidfile".to_string(),
                cidfile
                    .to_str()
                    .expect("cidfile path not UTF-8")
                    .to_string(),
                "--volume".to_string(),
                format!("{}:{CONTAINER_WORK}:ro{relabel}", work_dir.display()),
            ]);
            for elf in &elf_paths {
                command.arg("--volume");
                command.arg(format!("{}:{}:ro{relabel}", elf.display(), elf.display()));
            }
            if let Some(stubs) = &stubs {
                command.arg("--volume");
                command.arg(format!(
                    "{}:{}:ro{relabel}",
                    stubs.display(),
                    stubs.display()
                ));
            }
            command.args([
                "--entrypoint".to_string(),
                "/opt/renode/renode".to_string(),
                self.config.image.clone(),
                "--disable-xwt".to_string(),
                "--plain".to_string(),
                "-e".to_string(),
                format!("include @{CONTAINER_WORK}/test.resc"),
            ]);

            run_with_timeout_and_cleanup(command, timeout, || cleanup_container(&runtime, &cidfile))
        } else {
            let renode = renode.expect("native renode backend resolved above");
            let mut command = Command::new(renode);
            command
                .args(["--disable-xwt", "--plain"])
                .arg(work_dir.join("test.resc"));
            run_with_timeout_and_cleanup(command, timeout, || {})
        };

        HilOutput::new(
            String::from_utf8_lossy(&output.stdout).into_owned(),
            String::from_utf8_lossy(&output.stderr).into_owned(),
            output.status.code(),
        )
    }
}

/// Picks a work directory under the cargo target dir, unique per run.
///
/// Uniqueness matters beyond parallelism: two sequential runs in one process
/// (same pid, same platform tag) must NOT reuse a path — bind-remounting a
/// just-torn-down host dir into a fresh podman-machine container can wedge the
/// mount, hanging Renode before it even includes test.resc.
fn work_dir_for(config: &HilConfig) -> PathBuf {
    static RUN_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let seq = RUN_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let base = std::env::var_os("CARGO_TARGET_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            std::env::current_dir()
                .expect("failed to read current dir")
                .join("target")
        });
    let tag = config.machines.first().map_or("hil", |m| m.platform.name);
    base.join(format!("hil-{tag}-{}-{seq}", std::process::id()))
}

// ---------------------------------------------------------------------------
// Firmware building
// ---------------------------------------------------------------------------

/// Which cargo artifact a guest build produces.
#[derive(Debug, Clone)]
pub enum Artifact {
    /// A `[[bin]]` target (`--bin <name>`).
    Bin(String),
    /// An example (`--example <name>`), placed under `examples/`.
    Example(String),
}

/// Builds a cross-compiled guest firmware binary on demand.
///
/// Mirrors the cargo invocation a project would otherwise put in a `justfile`,
/// and returns the path to the resulting ELF. The build is skipped if the
/// output already exists, so repeated test runs are cheap.
#[derive(Debug, Clone)]
pub struct GuestBuild {
    /// Cargo package containing the artifact.
    pub package: String,
    /// The artifact to build.
    pub artifact: Artifact,
    /// Cross-compilation target triple, e.g. `thumbv7em-none-eabihf`.
    pub target: String,
    /// Features to enable.
    pub features: Vec<String>,
    /// Pass `--no-default-features`.
    pub no_default_features: bool,
    /// Build in release mode (default `true`).
    pub release: bool,
}

impl GuestBuild {
    /// A `[[bin]]` build for `package`.
    #[must_use]
    pub fn bin(package: impl Into<String>, name: impl Into<String>) -> Self {
        Self::new(package, Artifact::Bin(name.into()))
    }

    /// An `--example` build for `package`.
    #[must_use]
    pub fn example(package: impl Into<String>, name: impl Into<String>) -> Self {
        Self::new(package, Artifact::Example(name.into()))
    }

    fn new(package: impl Into<String>, artifact: Artifact) -> Self {
        Self {
            package: package.into(),
            artifact,
            target: String::new(),
            features: Vec::new(),
            no_default_features: false,
            release: true,
        }
    }

    /// Sets the cross-compilation target triple.
    #[must_use]
    pub fn target(mut self, target: impl Into<String>) -> Self {
        self.target = target.into();
        self
    }

    /// Sets the features to enable.
    #[must_use]
    pub fn features<I, S>(mut self, features: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.features = features.into_iter().map(Into::into).collect();
        self
    }

    /// Passes `--no-default-features`.
    #[must_use]
    pub fn no_default_features(mut self) -> Self {
        self.no_default_features = true;
        self
    }

    /// Builds in debug mode instead of release.
    #[must_use]
    pub fn debug(mut self) -> Self {
        self.release = false;
        self
    }

    /// The expected output ELF path for this build.
    #[must_use]
    pub fn output_path(&self) -> PathBuf {
        let target_root = std::env::var_os("CARGO_TARGET_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("target"));
        let profile = if self.release { "release" } else { "debug" };
        let mut dir = target_root.join(&self.target).join(profile);
        let name = match &self.artifact {
            Artifact::Bin(n) => n,
            Artifact::Example(n) => {
                dir = dir.join("examples");
                n
            }
        };
        dir.join(name)
    }

    /// Builds the artifact if needed and returns its ELF path.
    ///
    /// # Panics
    ///
    /// Panics if `cargo` cannot be invoked or the build fails.
    #[must_use]
    pub fn build(&self) -> PathBuf {
        let output = self.output_path();
        if output.exists() {
            return output;
        }

        let mut cmd = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()));
        cmd.args(["build", "-p", &self.package]);
        match &self.artifact {
            Artifact::Bin(n) => cmd.args(["--bin", n]),
            Artifact::Example(n) => cmd.args(["--example", n]),
        };
        if self.no_default_features {
            cmd.arg("--no-default-features");
        }
        if !self.features.is_empty() {
            cmd.args(["--features", &self.features.join(",")]);
        }
        if self.release {
            cmd.arg("--release");
        }
        if !self.target.is_empty() {
            cmd.args(["--target", &self.target]);
        }

        let status = cmd.status().expect("failed to invoke cargo");
        assert!(status.success(), "failed to build guest artifact");
        output
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn vt_info() -> ElfInfo {
        ElfInfo {
            vtor: 0x1000_0000,
            sp: 0x2004_2000,
            pc: 0x1000_0100,
            hook_addr: Some(0x1000_0200),
        }
    }

    fn vector_table_machine(name: &str) -> ReadyMachine {
        ReadyMachine {
            name: name.to_string(),
            elf_ref: "/abs/fw.elf".to_string(),
            repl_ref: format!("/hil/{name}.repl"),
            mips: None,
            can_connector: None,
            init: CpuInit::VectorTable,
            info: Some(vt_info()),
            socketcan_bridge: false,
            uart_bridge: None,
        }
    }

    fn board_machine(name: &str, bridge: bool) -> ReadyMachine {
        ReadyMachine {
            name: name.to_string(),
            elf_ref: format!("/abs/{name}.elf"),
            repl_ref: "platforms/boards/nucleo_h753zi.repl".to_string(),
            mips: Some(125),
            can_connector: Some("fdcan1"),
            init: CpuInit::Board,
            info: None,
            socketcan_bridge: bridge,
            uart_bridge: None,
        }
    }

    #[test]
    fn single_vector_table_resc_has_cpu_state_and_hook_no_hub() {
        let resc = render_resc(&[vector_table_machine("hil")], "vcan0", None, 10);
        assert!(resc.contains("mach create \"hil\""));
        assert!(resc.contains("LoadPlatformDescription @/hil/hil.repl"));
        assert!(resc.contains("cpu VectorTableOffset 0x10000000"));
        assert!(resc.contains("cpu SP 0x20042000"));
        assert!(resc.contains("cpu PC 0x10000100"));
        assert!(resc.contains("cpu AddHook 0x10000200"));
        assert!(resc.contains("HIL OK"));
        assert!(resc.contains("RunFor \"00:00:10\""));
        assert!(!resc.contains("canHub"));
    }

    #[test]
    fn multi_board_resc_builds_hub_and_connects_fdcan() {
        let machines = [
            board_machine("controller", true),
            board_machine("sensor", false),
        ];
        let resc = render_resc(&machines, "vcan0", None, 15);
        assert!(resc.contains("emulation CreateCANHub \"canHub\""));
        assert!(resc.contains("cpu PerformanceInMips 125"));
        assert!(resc.contains("connector Connect fdcan1 canHub"));
        assert!(resc.contains("machine CreateSocketCANBridge \"vcan0\""));
        assert!(resc.contains("connector Connect vcan0 canHub"));
        assert!(resc.contains("mach create \"controller\""));
        assert!(resc.contains("mach create \"sensor\""));
        // The non-bridge machine must not create a bridge.
        assert_eq!(resc.matches("CreateSocketCANBridge").count(), 1);
    }

    #[test]
    fn single_bridged_machine_still_gets_a_hub() {
        let resc = render_resc(&[board_machine("solo", true)], "vcan1", None, 20);
        assert!(resc.contains("CreateCANHub"));
        assert!(resc.contains("CreateSocketCANBridge \"vcan1\""));
        assert!(resc.contains("RunFor \"00:00:20\""));
    }

    #[test]
    fn uart_bridge_renders_server_terminal_and_connect() {
        let mut m = vector_table_machine("hil");
        m.uart_bridge = Some(UartBridge {
            host_port: 3456,
            uart: "sysbus.uart".to_string(),
        });
        let resc = render_resc(&[m], "vcan0", None, 10);
        assert!(resc.contains("emulation CreateServerSocketTerminal 3456 \"hil_uart\" false"));
        assert!(resc.contains("connector Connect sysbus.uart hil_uart"));
        // A lone UART bridge must not spin up a CAN hub.
        assert!(!resc.contains("canHub"));
    }

    #[test]
    fn stubs_overlay_is_loaded_per_machine() {
        let resc = render_resc(
            &[vector_table_machine("hil")],
            "vcan0",
            Some("/abs/stubs.repl"),
            5,
        );
        assert!(resc.contains("LoadPlatformDescription @/abs/stubs.repl"));
    }

    #[test]
    fn timeout_minutes_and_seconds_format() {
        let resc = render_resc(&[vector_table_machine("hil")], "vcan0", None, 125);
        assert!(resc.contains("RunFor \"00:02:05\""));
    }

    #[test]
    fn guest_build_output_paths() {
        let _guard = crate::test_env_lock();
        let saved = std::env::var("CARGO_TARGET_DIR").ok();
        std::env::remove_var("CARGO_TARGET_DIR");
        let bin = GuestBuild::bin("buspass", "hil_controller")
            .target("thumbv7em-none-eabihf")
            .output_path();
        assert!(bin.ends_with("target/thumbv7em-none-eabihf/release/hil_controller"));

        let ex = GuestBuild::example("tecla-rp2040", "hil_keyboard")
            .target("thumbv6m-none-eabi")
            .output_path();
        assert!(ex.ends_with("target/thumbv6m-none-eabi/release/examples/hil_keyboard"));

        let dbg = GuestBuild::bin("p", "b").target("t").debug().output_path();
        assert!(dbg.ends_with("target/t/debug/b"));

        if let Some(v) = saved {
            std::env::set_var("CARGO_TARGET_DIR", v);
        }
    }

    #[test]
    fn detect_runtime_honors_env() {
        let _guard = crate::test_env_lock();
        let saved = std::env::var(RUNTIME_ENV).ok();
        std::env::set_var(RUNTIME_ENV, "fake-runtime");
        assert_eq!(detect_container_runtime(), "fake-runtime");
        assert!(container_runtime_available());
        match saved {
            Some(v) => std::env::set_var(RUNTIME_ENV, v),
            None => std::env::remove_var(RUNTIME_ENV),
        }
    }

    #[test]
    fn interface_available_loopback_yes_bogus_no() {
        // `ip` may be absent on some hosts; only assert the negative there.
        if Command::new("ip").arg("-V").output().is_ok() {
            assert!(interface_available("lo"));
        }
        assert!(!interface_available("hilt_fake_iface_xyz"));
    }
}