hilt 0.2.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
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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
//! Renode container orchestration: script generation, process lifecycle,
//! ELF introspection, host SocketCAN setup, and firmware building.

use std::fmt::Write as _;
use std::io::{ErrorKind, Read};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::sync::{Mutex, PoisonError};
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";

/// `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])
}

/// Ensures `image` is present locally, building it (the `hilt`-managed
/// [`RENODE_ARM64_IMAGE`]) or pulling it (anything else) if not. Always
/// called before the wall-clock timer starts, so a slow first-run pull/build
/// never eats into a run's timeout budget.
///
/// Remembered per process, so parallel tests neither race the same
/// build/pull nor pay a redundant `image inspect` per run.
///
/// # Panics
///
/// Panics if the image is missing and the build or pull fails.
fn ensure_renode_image(runtime: &str, image: &str) {
    // ponytail: one mutex serializes all images, not just the one being
    // ensured -- fine since this only does real work once per image per
    // process (cached after). Cross-process first-run races are left to
    // podman's per-tag locking.
    static ENSURED: Mutex<Vec<String>> = Mutex::new(Vec::new());
    let mut ensured = ENSURED.lock().unwrap_or_else(PoisonError::into_inner);
    if ensured.iter().any(|i| i == image) {
        return;
    }
    if image_present(runtime, image) {
        // Already local.
    } else if image == RENODE_ARM64_IMAGE {
        eprintln!("hilt: building native arm64 Renode image `{image}` (first run, one-time)…");
        // ponytail: pid-keyed dir; the mutex serializes in-process racers.
        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}`"
        );
    } else {
        eprintln!("hilt: pulling Renode image `{image}` (first run, one-time)…");
        let status = Command::new(runtime)
            .args(["pull", image])
            .status()
            .expect("failed to invoke container pull");
        assert!(status.success(), "failed to pull Renode image `{image}`");
    }
    ensured.push(image.to_string());
}

// ---------------------------------------------------------------------------
// 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 mut rm = Command::new(runtime);
    rm.args(["rm", "-f", cid]);
    // A killed run leaves the container up; podman's `rm -f` would first wait
    // out a 10 s graceful stop (docker's already SIGKILLs).
    if runtime.contains("podman") {
        rm.args(["-t", "0"]);
    }
    // `rm` echoes the id; keep it out of the test's output.
    let _ = rm.stdout(Stdio::null()).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 wall-clock timeout and a cleanup callback.
///
/// Captures stdout/stderr on background threads (so a chatty child can't
/// deadlock on a full pipe). If `wall_timeout_secs` passes before the child
/// exits, it is killed, reaped, and the second return value is `true`; then
/// `cleanup` runs either way.
///
/// # Panics
///
/// Panics if the process cannot be spawned, polled, or reaped.
pub fn run_with_timeout_and_cleanup<F>(
    command: Command,
    wall_timeout_secs: u32,
    cleanup: F,
) -> (Output, bool)
where
    F: FnOnce(),
{
    let deadline = Instant::now() + Duration::from_secs(wall_timeout_secs.into());
    Captured::spawn(command).finish(deadline, cleanup)
}

/// A spawned child whose stdout/stderr are drained on background threads (so
/// a chatty child can't deadlock on a full pipe).
struct Captured {
    child: Child,
    stdout: thread::JoinHandle<Vec<u8>>,
    stderr: thread::JoinHandle<Vec<u8>>,
}

impl Captured {
    fn spawn(mut command: Command) -> Self {
        command.stdout(Stdio::piped()).stderr(Stdio::piped());
        let mut child = command
            .spawn()
            .unwrap_or_else(|e| panic!("failed to spawn container runtime: {e}"));
        let stdout = drain(
            child.stdout.take().expect("child stdout not captured"),
            "stdout",
        );
        let stderr = drain(
            child.stderr.take().expect("child stderr not captured"),
            "stderr",
        );
        Self {
            child,
            stdout,
            stderr,
        }
    }

    /// Waits for the child to exit, killing it once `deadline` passes (then
    /// reporting `true`), runs `cleanup`, and collects the output.
    fn finish(mut self, deadline: Instant, cleanup: impl FnOnce()) -> (Output, bool) {
        let mut timed_out = false;
        let status = loop {
            match self
                .child
                .try_wait()
                .unwrap_or_else(|e| panic!("failed to poll container runtime: {e}"))
            {
                Some(status) => break status,
                None if Instant::now() >= deadline => {
                    timed_out = true;
                    let _ = self.child.kill();
                    break self.child.wait().unwrap_or_else(|e| {
                        panic!("failed to reap timed-out container runtime: {e}")
                    });
                }
                None => thread::sleep(Duration::from_millis(100)),
            }
        };

        cleanup();

        let join = |h: thread::JoinHandle<Vec<u8>>| {
            h.join()
                .unwrap_or_else(|_| panic!("failed to join output reader"))
        };
        (
            Output {
                status,
                stdout: join(self.stdout),
                stderr: join(self.stderr),
            },
            timed_out,
        )
    }
}

fn drain(mut pipe: impl Read + Send + 'static, name: &'static str) -> thread::JoinHandle<Vec<u8>> {
    thread::spawn(move || {
        let mut buf = Vec::new();
        pipe.read_to_end(&mut buf)
            .unwrap_or_else(|e| panic!("failed to read child {name}: {e}"));
        buf
    })
}

/// Runs a prepared Renode container command and a cleanup callback, with the
/// same wall-clock budget [`RenodeRunner::run`] derives from a simulated-time
/// `timeout_secs` (see [`HilConfig::wall_timeout_secs`]). 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, bool)
where
    F: FnOnce(),
{
    run_with_timeout_and_cleanup(
        command,
        crate::config::default_wall_timeout(timeout_secs),
        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>,
    /// Address of the fail-marker symbol, if found.
    pub fail_addr: Option<u32>,
    /// Address of the Rust panic handler (`rust_begin_unwind`), if found.
    pub panic_addr: Option<u32>,
}

/// Extracts the vector table (`vtor`/`sp`/`pc`) and the `marker`,
/// `fail_marker`, and panic-handler symbol addresses from a firmware ELF.
/// Pure Rust: the `.vector_table` section and symbol table are read directly.
///
/// # Panics
///
/// Panics if the ELF cannot be read or has no `.vector_table` section.
#[must_use]
pub fn extract_elf_info(firmware_elf: &Path, marker: &str, fail_marker: &str) -> ElfInfo {
    let elf = std::fs::read(firmware_elf)
        .unwrap_or_else(|e| panic!("failed to read {}: {e}", firmware_elf.display()));
    let (vtor, sp, pc) = elf_vector_table(&elf).unwrap_or_else(|| {
        panic!(
            "failed to extract vector table from {}",
            firmware_elf.display()
        )
    });
    ElfInfo {
        vtor,
        sp,
        pc,
        hook_addr: elf_symbol(&elf, marker),
        fail_addr: elf_symbol(&elf, fail_marker),
        // `#[panic_handler]` is exported as `rust_begin_unwind`: verbatim
        // under legacy mangling, `_RNv..17rust_begin_unwind` under v0.
        panic_addr: elf_symbol_by(&elf, |n| {
            n == b"rust_begin_unwind" || n.ends_with(b"17rust_begin_unwind")
        }),
    }
}

/// Returns the address of the defined `symbol` in `firmware_elf` (thumb bit
/// cleared for functions), or `None` if the file is unreadable, not a
/// little-endian ELF32, or lacks the symbol.
#[must_use]
pub fn find_symbol_address(firmware_elf: &Path, symbol: &str) -> Option<u32> {
    elf_symbol(&std::fs::read(firmware_elf).ok()?, symbol)
}

// Minimal little-endian ELF32 reader: just enough for section lookup and the
// symbol table. Every read is bounds-checked, so a malformed file yields
// `None` rather than a panic.
fn le_u16(d: &[u8], off: usize) -> Option<u16> {
    Some(u16::from_le_bytes(d.get(off..off + 2)?.try_into().ok()?))
}

fn le_u32(d: &[u8], off: usize) -> Option<u32> {
    Some(u32::from_le_bytes(d.get(off..off + 4)?.try_into().ok()?))
}

/// NUL-terminated string at `off`.
fn c_str(d: &[u8], off: usize) -> Option<&[u8]> {
    let s = d.get(off..)?;
    Some(&s[..s.iter().position(|&b| b == 0)?])
}

/// ELF32 section header fields `hilt` reads.
struct Section {
    name: usize,
    kind: u32,
    addr: u32,
    offset: usize,
    size: usize,
    link: usize,
}

fn elf_sections(d: &[u8]) -> Option<Vec<Section>> {
    // Magic, ELFCLASS32, ELFDATA2LSB.
    if d.get(..6)? != b"\x7fELF\x01\x01" {
        return None;
    }
    let shoff = le_u32(d, 0x20)? as usize;
    let shentsize = usize::from(le_u16(d, 0x2E)?);
    (0..usize::from(le_u16(d, 0x30)?))
        .map(|i| {
            let h = shoff + i * shentsize;
            Some(Section {
                name: le_u32(d, h)? as usize,
                kind: le_u32(d, h + 4)?,
                addr: le_u32(d, h + 12)?,
                offset: le_u32(d, h + 16)? as usize,
                size: le_u32(d, h + 20)? as usize,
                link: le_u32(d, h + 24)? as usize,
            })
        })
        .collect()
}

/// `(vtor, sp, pc)` from the `.vector_table` section: its load address and
/// first two words (initial SP, reset vector with the thumb bit cleared).
fn elf_vector_table(d: &[u8]) -> Option<(u32, u32, u32)> {
    let sections = elf_sections(d)?;
    let names = sections.get(usize::from(le_u16(d, 0x32)?))?;
    let vt = sections
        .iter()
        .find(|s| c_str(d, names.offset + s.name) == Some(b".vector_table"))?;
    let pc = le_u32(d, vt.offset + 4)? & !1;
    (pc != 0).then_some((vt.addr, le_u32(d, vt.offset)?, pc))
}

/// Address of the defined (non-`SHN_UNDEF`) `symbol` in `.symtab`.
fn elf_symbol(d: &[u8], symbol: &str) -> Option<u32> {
    elf_symbol_by(d, |name| name == symbol.as_bytes())
}

/// Address of the first defined `.symtab` symbol whose name matches.
fn elf_symbol_by(d: &[u8], matches: impl Fn(&[u8]) -> bool) -> Option<u32> {
    const SHT_SYMTAB: u32 = 2;
    const STT_FUNC: u8 = 2;
    let sections = elf_sections(d)?;
    let symtab = sections.iter().find(|s| s.kind == SHT_SYMTAB)?;
    let strtab = sections.get(symtab.link)?;
    (0..symtab.size / 16).find_map(|i| {
        let e = symtab.offset + i * 16;
        let name = c_str(d, strtab.offset + le_u32(d, e)? as usize)?;
        if !matches(name) || le_u16(d, e + 14)? == 0 {
            return None;
        }
        let value = le_u32(d, e + 4)?;
        // Thumb function symbols carry the interworking bit; hooks want the
        // instruction address.
        Some(if d.get(e + 12)? & 0xF == STT_FUNC {
            value & !1
        } else {
            value
        })
    })
}

// ---------------------------------------------------------------------------
// 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>,
    /// Vector-table state and hook addresses; `Some` only for
    /// [`CpuInit::VectorTable`] platforms.
    info: Option<ElfInfo>,
    socketcan_bridge: bool,
    uart_bridge: Option<UartBridge>,
    uart: Option<&'static str>,
}

/// 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 hub = machines.len() > 1 || machines.iter().any(|m| m.socketcan_bridge);
    // Reaching a marker ends the run at once (`monitor.Parse` quits Renode
    // from inside the hook) instead of idling out the rest of `RunFor`. Pass
    // only ends a lone machine with no host bridge: other machines may still
    // be mid-test, and a bridged host may still be talking to the firmware.
    const QUIT: &str = "; monitor.Parse('quit')";
    let host_bridged = machines
        .iter()
        .any(|m| m.socketcan_bridge || m.uart_bridge.is_some());
    let pass_quit = if machines.len() == 1 && !host_bridged {
        QUIT
    } else {
        ""
    };

    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);
        // Headless (`--disable-xwt`), the analyzer logs each UART line to
        // stdout, where `HilOutput::uart` picks it up.
        if let Some(uart) = m.uart {
            let _ = writeln!(s, "showAnalyzer {uart}");
        }

        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'){pass_quit}\""
                );
            }
            for (addr, what) in [(info.fail_addr, "fail marker"), (info.panic_addr, "panic")] {
                if let Some(addr) = addr {
                    let _ = writeln!(
                        s,
                        "cpu AddHook {addr:#010X} \"self.Log(LogLevel.Error, 'HIL FAIL ({what})'){QUIT}\""
                    );
                }
            }
        }

        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 \"{}\"", format_run_for(timeout_secs));
    s.push_str("quit\n");
    s
}

/// `total_secs` as a Renode `emulation RunFor` duration, `HH:MM:SS` (hours
/// carry past 59 minutes).
pub(crate) fn format_run_for(total_secs: u32) -> String {
    format!(
        "{:02}:{:02}:{:02}",
        total_secs / 3600,
        (total_secs % 3600) / 60,
        total_secs % 60
    )
}

// ---------------------------------------------------------------------------
// 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 to completion and returns the captured output.
    /// Shorthand for [`spawn`](Self::spawn) then [`RunningHil::wait`].
    ///
    /// 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 {
        self.spawn().wait()
    }

    /// Starts the HIL run in the background and returns a handle to it, for
    /// tests that talk to the firmware while it runs (e.g. over a UART
    /// bridge via [`RunningHil::connect_uart`]). The run ends when Renode
    /// finishes, the wall-clock timeout hits, or the handle is killed or
    /// dropped; all of these clean up the container and work directory.
    ///
    /// # Panics
    ///
    /// Same conditions as [`run`](Self::run), plus duplicate non-zero UART
    /// bridge ports.
    #[must_use]
    pub fn spawn(&self) -> RunningHil {
        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();

        // 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()
        };

        // UART bridges, per machine: `(renode_port, host_port)`. Fixed ports
        // are used 1:1 and must be distinct. Port 0 in container mode gets a
        // private in-container port, published on an ephemeral host port the
        // runtime picks (host_port 0 = ask it later, race-free); elsewhere
        // Renode binds the host directly, so a free port is picked up front.
        let bridge_ports = assign_bridge_ports(
            self.config
                .machines
                .iter()
                .map(|m| m.uart_bridge.as_ref().map(|b| b.host_port)),
            use_container && !self.config.needs_host_network(),
        );

        // 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();
        let mut uart_ports = Vec::new();
        for (m, ports) in self.config.machines.iter().zip(&bridge_ports) {
            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, &self.config.fail_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,
                info,
                socketcan_bridge: m.socketcan_bridge,
                uart_bridge: m
                    .uart_bridge
                    .as_ref()
                    .zip(*ports)
                    .map(|(b, (renode, host))| {
                        uart_ports.push((m.name.clone(), renode, host));
                        UartBridge {
                            host_port: renode,
                            uart: b.uart.clone(),
                        }
                    }),
                uart: m.platform.uart,
            });
        }

        // 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");

        let wall_timeout = self.config.resolved_wall_timeout_secs();
        let (command, container) = if let Some(runtime) = runtime {
            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 self.config.image == RENODE_ARM64_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 (_, renode, host) in &uart_ports {
                    let host = if *host == 0 {
                        String::new()
                    } else {
                        host.to_string()
                    };
                    command.arg("-p").arg(format!("127.0.0.1:{host}:{renode}"));
                }
            }
            command
                .arg("--cidfile")
                .arg(&cidfile)
                .arg("--volume")
                .arg(format!(
                    "{}:{CONTAINER_WORK}:ro{relabel}",
                    work_dir.display()
                ));
            // ELFs and the stubs overlay are mounted at their host paths.
            for p in elf_paths.iter().chain(&stubs) {
                command
                    .arg("--volume")
                    .arg(format!("{0}:{0}:ro{relabel}", p.display()));
            }
            command
                .args(["--entrypoint", "/opt/renode/renode"])
                .arg(&self.config.image)
                .args(["--disable-xwt", "--plain", "-e"])
                .arg(format!("include @{CONTAINER_WORK}/test.resc"));

            (command, Some((runtime, cidfile)))
        } else {
            let renode = renode_bin().expect(
                "no HIL backend: install podman/docker, or a native renode \
                 (HILT_RENODE_BIN, PATH, or /opt/renode/renode)",
            );
            let mut command = Command::new(renode);
            command
                .args(["--disable-xwt", "--plain"])
                .arg(work_dir.join("test.resc"));
            (command, None)
        };

        RunningHil {
            deadline: Instant::now() + Duration::from_secs(wall_timeout.into()),
            proc: Mutex::new(Some(Captured::spawn(command))),
            container,
            uart_ports,
            _work_dir: guard,
        }
    }
}

/// A HIL run in progress, from [`RenodeRunner::spawn`].
///
/// Finish it with [`wait`](Self::wait) or [`kill`](Self::kill); dropping it
/// (e.g. when a test panics) kills Renode and cleans up the same way.
pub struct RunningHil {
    proc: Mutex<Option<Captured>>,
    deadline: Instant,
    /// `(runtime, cidfile)` in container mode, for port queries and teardown.
    container: Option<(String, PathBuf)>,
    /// `(machine, renode_port, host_port)`; host port 0 = ask the runtime.
    uart_ports: Vec<(String, u16, u16)>,
    _work_dir: CleanupGuard,
}

impl RunningHil {
    /// Waits for the run to end (or hit its wall-clock timeout) and returns
    /// its output.
    ///
    /// # Panics
    ///
    /// Panics if the Renode process cannot be polled or reaped.
    #[must_use]
    pub fn wait(mut self) -> HilOutput {
        self.finish(false)
    }

    /// Stops the run now -- kills Renode and removes its container -- and
    /// returns the output captured so far. [`HilOutput::timed_out`] is
    /// `false` for a kill.
    ///
    /// # Panics
    ///
    /// Panics if the Renode process cannot be reaped.
    #[must_use]
    pub fn kill(mut self) -> HilOutput {
        self.finish(true)
    }

    /// Host TCP port of `machine`'s UART bridge. For a bridge configured with
    /// port 0 this is the ephemeral port the container runtime picked, which
    /// is queried (with retries) once the container exists.
    ///
    /// # Panics
    ///
    /// Panics if `machine` has no UART bridge, or Renode exits or hits the
    /// wall-clock timeout before the port is known.
    #[must_use]
    pub fn uart_port(&self, machine: &str) -> u16 {
        let &(_, renode_port, host_port) = self
            .uart_ports
            .iter()
            .find(|(m, ..)| m == machine)
            .unwrap_or_else(|| panic!("machine `{machine}` has no UART bridge"));
        if host_port != 0 {
            return host_port;
        }
        let (runtime, cidfile) = self
            .container
            .as_ref()
            .expect("runtime-published ports only exist in container mode");
        self.poll(
            &format!("the runtime to publish machine `{machine}`'s UART port"),
            || {
                let cid = std::fs::read_to_string(cidfile).ok()?;
                let out = Command::new(runtime)
                    .args(["port", cid.trim(), &format!("{renode_port}/tcp")])
                    .output()
                    .ok()?;
                parse_published_port(&String::from_utf8_lossy(&out.stdout))
            },
        )
    }

    /// Connects to `machine`'s UART bridge, retrying until Renode's terminal
    /// actually accepts. The stream is a raw byte pipe to the firmware's
    /// serial line.
    ///
    /// # Panics
    ///
    /// Panics if `machine` has no UART bridge, or Renode exits or hits the
    /// wall-clock timeout before the terminal accepts.
    #[must_use]
    pub fn connect_uart(&self, machine: &str) -> TcpStream {
        let port = self.uart_port(machine);
        self.poll(
            &format!("machine `{machine}`'s UART terminal on port {port} to accept"),
            || {
                let stream = TcpStream::connect(("127.0.0.1", port)).ok()?;
                terminal_accepted(&stream).then_some(stream)
            },
        )
    }

    /// Retries `f` every 100 ms until it yields a value.
    fn poll<T>(&self, what: &str, mut f: impl FnMut() -> Option<T>) -> T {
        loop {
            if let Some(v) = f() {
                return v;
            }
            let exited = self
                .proc
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .as_mut()
                .is_none_or(|p| !matches!(p.child.try_wait(), Ok(None)));
            assert!(!exited, "Renode exited while waiting for {what}");
            assert!(
                Instant::now() < self.deadline,
                "wall-clock timeout while waiting for {what}"
            );
            thread::sleep(Duration::from_millis(100));
        }
    }

    fn finish(&mut self, kill: bool) -> HilOutput {
        let proc = self
            .proc
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
            .expect("HIL run already finished");
        let deadline = if kill { Instant::now() } else { self.deadline };
        let (output, timed_out) = proc.finish(deadline, || {
            if let Some((runtime, cidfile)) = &self.container {
                cleanup_container(runtime, cidfile);
            }
        });
        HilOutput::new(
            String::from_utf8_lossy(&output.stdout).into_owned(),
            String::from_utf8_lossy(&output.stderr).into_owned(),
            output.status.code(),
            timed_out && !kill,
        )
    }
}

impl Drop for RunningHil {
    fn drop(&mut self) {
        let running = self
            .proc
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner)
            .is_some();
        if running {
            let _ = self.finish(true);
        }
    }
}

/// Resolves each machine's UART bridge (`None` = no bridge) to
/// `(renode_port, host_port)`: fixed ports map 1:1; port 0 gets a private
/// in-container port with host port 0 ("ask the runtime") when the runtime
/// publishes, else a free local port.
///
/// # Panics
///
/// Panics on duplicate non-zero ports.
fn assign_bridge_ports(
    requested: impl Iterator<Item = Option<u16>> + Clone,
    runtime_publishes: bool,
) -> Vec<Option<(u16, u16)>> {
    let mut fixed: Vec<u16> = requested.clone().flatten().filter(|&p| p != 0).collect();
    fixed.sort_unstable();
    let unique = fixed.windows(2).all(|w| w[0] != w[1]);
    assert!(unique, "duplicate UART bridge host_port in config");
    let mut next_private = 3456;
    requested
        .map(|port| {
            Some(match port? {
                0 if runtime_publishes => {
                    while fixed.contains(&next_private) {
                        next_private += 1;
                    }
                    next_private += 1;
                    (next_private - 1, 0)
                }
                0 => {
                    let port = free_local_port();
                    (port, port)
                }
                port => (port, port),
            })
        })
        .collect()
}

/// Parses `<runtime> port` output (`127.0.0.1:45067`, possibly several
/// lines, IPv6 `[::1]:45067`) into the first host port.
fn parse_published_port(out: &str) -> Option<u16> {
    out.lines()
        .find_map(|l| l.trim().rsplit(':').next()?.parse().ok())
}

/// Container port forwarders (podman's rootlessport/gvproxy, docker-proxy)
/// accept a connection before anything listens behind them, then hang up
/// (~200 ms on podman/macOS); a live Renode terminal just stays open. So
/// peek briefly: EOF or reset means "not yet".
// ponytail: fixed 500 ms probe; a forwarder slower than that to hang up
// would pass as live -- lengthen the probe if that shows up.
fn terminal_accepted(stream: &TcpStream) -> bool {
    stream
        .set_read_timeout(Some(Duration::from_millis(500)))
        .is_ok()
        && match stream.peek(&mut [0]) {
            Ok(n) => n > 0,
            Err(e) => matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut),
        }
        && stream.set_read_timeout(None).is_ok()
}

/// A currently free localhost TCP port, for bridges Renode binds directly.
// ponytail: racy (the port is released before Renode binds it); only used
// off the container-publishing path, where the runtime can't pick for us.
fn free_local_port() -> u16 {
    TcpListener::bind("127.0.0.1:0")
        .and_then(|l| l.local_addr())
        .map(|a| a.port())
        .expect("failed to pick a free local port")
}

/// 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.
#[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,
    /// `Cargo.toml` of the package, for firmware outside the current
    /// workspace (`--manifest-path`).
    pub manifest_path: Option<PathBuf>,
}

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,
            manifest_path: None,
        }
    }

    /// 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
    }

    /// Builds the package from `path` (its `Cargo.toml`), e.g. firmware kept
    /// in its own workspace next to the host tests.
    #[must_use]
    pub fn manifest_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.manifest_path = Some(path.into());
        self
    }

    /// Builds the artifact and returns its ELF path.
    ///
    /// Always invokes `cargo build` (a no-op incremental rebuild is cheap and
    /// correct; skipping it risks testing a stale ELF after firmware edits).
    /// The path is read out of cargo's own `--message-format=json` stream
    /// rather than guessed, so it's correct in workspaces too (cargo test's
    /// cwd is the package dir, not the workspace root `target/` a guess would
    /// assume).
    ///
    /// Strips env vars the outer (host) cargo invocation may have set but
    /// that would break this nested cross build: `RUSTFLAGS` /
    /// `CARGO_ENCODED_RUSTFLAGS` / `CARGO_BUILD_RUSTFLAGS` and coverage instrumentation
    /// (`LLVM_PROFILE_FILE`, `CARGO_LLVM_COV*`) target the host build, not
    /// the cross-compiled guest; `CARGO_BUILD_TARGET` and `RUSTC_WRAPPER`
    /// would override or reinterpret this build's own `--target`/toolchain.
    ///
    /// # Panics
    ///
    /// Panics if `cargo` cannot be invoked, the build fails, or its output
    /// doesn't report an executable for the requested artifact.
    #[must_use]
    pub fn build(&self) -> PathBuf {
        let mut cmd = Command::new(std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()));
        for var in [
            "RUSTFLAGS",
            "CARGO_ENCODED_RUSTFLAGS",
            "CARGO_BUILD_RUSTFLAGS",
            "CARGO_BUILD_TARGET",
            "RUSTC_WRAPPER",
            "LLVM_PROFILE_FILE",
            "CARGO_LLVM_COV",
            "CARGO_LLVM_COV_TARGET_DIR",
            "CARGO_LLVM_COV_SHOW_ENV",
        ] {
            cmd.env_remove(var);
        }
        cmd.args(["build", "-p", &self.package, "--message-format=json"]);
        if let Some(manifest) = &self.manifest_path {
            cmd.arg("--manifest-path").arg(manifest);
        }
        let target_name = match &self.artifact {
            Artifact::Bin(n) => {
                cmd.args(["--bin", n]);
                n
            }
            Artifact::Example(n) => {
                cmd.args(["--example", n]);
                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 output = cmd.output().expect("failed to invoke cargo");
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success(),
            "failed to build guest artifact:\n{stdout}\n{}",
            String::from_utf8_lossy(&output.stderr)
        );

        find_executable(&stdout, target_name).unwrap_or_else(|| {
            panic!("cargo build did not report an executable for artifact `{target_name}`")
        })
    }
}

/// Extracts the executable path cargo built for `target_name` out of a
/// `cargo build --message-format=json` stdout stream: the `"executable"`
/// field of the `compiler-artifact` message whose `target.name` matches.
fn find_executable(json_stdout: &str, target_name: &str) -> Option<PathBuf> {
    json_stdout
        .lines()
        .filter(|line| line.contains("\"reason\":\"compiler-artifact\""))
        .find(|line| json_str_field(line, "name").as_deref() == Some(target_name))
        .and_then(|line| json_str_field(line, "executable"))
        .map(PathBuf::from)
}

/// Extracts the value of a `"key":"value"` JSON string field from `line`,
/// unescaping `\"`, `\\`, and a handful of common escapes. Zero-dependency
/// stand-in for a real JSON parser -- good enough for cargo's own
/// single-line, ASCII-safe `--message-format=json` output.
fn json_str_field(line: &str, key: &str) -> Option<String> {
    let pat = format!("\"{key}\":\"");
    let rest = &line[line.find(&pat)? + pat.len()..];
    let mut out = String::new();
    let mut chars = rest.chars();
    while let Some(c) = chars.next() {
        match c {
            '"' => return Some(out),
            '\\' => match chars.next()? {
                '"' => out.push('"'),
                '\\' => out.push('\\'),
                '/' => out.push('/'),
                'n' => out.push('\n'),
                't' => out.push('\t'),
                other => out.push(other),
            },
            other => out.push(other),
        }
    }
    None
}

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

    /// Hand-assembled little-endian ELF32: a `.vector_table` at 0x1000_0100
    /// and a symtab holding a thumb function, an odd-addressed data byte, and
    /// an undefined symbol.
    fn tiny_elf() -> Vec<u8> {
        let shstrtab = b"\0.vector_table\0.symtab\0.strtab\0.shstrtab\0";
        let strtab = b"\0hil_marker\0BYTE\0undef\0";
        let vt = [0x2004_0000u32, 0x1000_01C1];
        let sym = |name: u32, value: u32, info: u8, shndx: u16| {
            let mut e = Vec::new();
            e.extend(name.to_le_bytes());
            e.extend(value.to_le_bytes());
            e.extend(0u32.to_le_bytes());
            e.extend([info, 0]);
            e.extend(shndx.to_le_bytes());
            e
        };
        let symtab = [
            sym(0, 0, 0, 0),
            sym(1, 0x1000_029B, 0x12, 1),  // GLOBAL FUNC, thumb bit set
            sym(12, 0x2000_0003, 0x11, 1), // GLOBAL OBJECT, odd address
            sym(17, 0x1234, 0x10, 0),      // SHN_UNDEF
        ]
        .concat();

        let vt_off = 52u32;
        let sym_off = vt_off + 8;
        let str_off = sym_off + symtab.len() as u32;
        let shstr_off = str_off + strtab.len() as u32;
        let sh_off = shstr_off + shstrtab.len() as u32;

        let mut d = vec![0x7F, b'E', b'L', b'F', 1, 1, 1];
        d.resize(16, 0);
        d.extend([2, 0, 40, 0]); // ET_EXEC, EM_ARM
        d.extend(1u32.to_le_bytes());
        d.extend([0u32, 0, sh_off, 0].iter().flat_map(|w| w.to_le_bytes()));
        d.extend([52u16, 0, 0, 40, 5, 4].iter().flat_map(|h| h.to_le_bytes()));
        d.extend(vt.iter().flat_map(|w| w.to_le_bytes()));
        d.extend(&symtab);
        d.extend(strtab);
        d.extend(shstrtab);
        // name, type, flags, addr, offset, size, link, info, align, entsize
        let sections: [[u32; 10]; 5] = [
            [0; 10],
            [1, 1, 2, 0x1000_0100, vt_off, 8, 0, 0, 4, 0],
            [15, 2, 0, 0, sym_off, symtab.len() as u32, 3, 1, 4, 16],
            [23, 3, 0, 0, str_off, strtab.len() as u32, 0, 0, 1, 0],
            [31, 3, 0, 0, shstr_off, shstrtab.len() as u32, 0, 0, 1, 0],
        ];
        d.extend(sections.iter().flatten().flat_map(|w| w.to_le_bytes()));
        d
    }

    #[test]
    fn bridge_ports_fixed_ephemeral_and_none() {
        // Runtime publishes: port 0 gets a private port skipping fixed ones.
        let ports = assign_bridge_ports([Some(3456), None, Some(0), Some(0)].into_iter(), true);
        assert_eq!(
            ports,
            vec![Some((3456, 3456)), None, Some((3457, 0)), Some((3458, 0))]
        );
        // Native / host network: port 0 becomes a concrete free local port.
        let ports = assign_bridge_ports([Some(0), Some(4000)].into_iter(), false);
        let (renode, host) = ports[0].unwrap();
        assert!(renode != 0 && renode == host);
        assert_eq!(ports[1], Some((4000, 4000)));
    }

    #[test]
    #[should_panic(expected = "duplicate UART bridge host_port")]
    fn bridge_ports_reject_duplicates() {
        let _ = assign_bridge_ports([Some(5000), Some(0), Some(5000)].into_iter(), true);
    }

    #[test]
    fn published_port_parsing() {
        assert_eq!(parse_published_port("127.0.0.1:45067\n"), Some(45067));
        assert_eq!(
            parse_published_port("0.0.0.0:32768\n[::]:32768\n"),
            Some(32768)
        );
        assert_eq!(parse_published_port("[::1]:4000"), Some(4000));
        assert_eq!(parse_published_port(""), None);
        assert_eq!(parse_published_port("Error: no such container"), None);
    }

    #[test]
    fn elf_reader_vector_table_and_symbols() {
        let d = tiny_elf();
        assert_eq!(
            elf_vector_table(&d),
            Some((0x1000_0100, 0x2004_0000, 0x1000_01C0))
        );
        assert_eq!(elf_symbol(&d, "hil_marker"), Some(0x1000_029A));
        assert_eq!(elf_symbol(&d, "BYTE"), Some(0x2000_0003));
        assert_eq!(elf_symbol(&d, "undef"), None);
        assert_eq!(elf_symbol(&d, "missing"), None);
        // Truncated or non-ELF input is `None`, never a panic.
        assert_eq!(elf_symbol(&d[..200], "hil_marker"), None);
        assert_eq!(elf_vector_table(b"not an elf"), None);
    }

    #[test]
    fn elf_reader_file_api() {
        let path = std::env::temp_dir().join(format!("hilt-tiny-{}.elf", std::process::id()));
        std::fs::write(&path, tiny_elf()).unwrap();
        let info = extract_elf_info(&path, "hil_marker", "hil_fail");
        assert_eq!(
            (info.vtor, info.sp, info.pc, info.hook_addr),
            (0x1000_0100, 0x2004_0000, 0x1000_01C0, Some(0x1000_029A))
        );
        assert_eq!(extract_elf_info(&path, "nope", "nope").hook_addr, None);
        let _ = std::fs::remove_file(&path);
        assert_eq!(find_symbol_address(&path, "hil_marker"), None);
    }

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

    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,
            info: Some(vt_info()),
            socketcan_bridge: false,
            uart_bridge: None,
            uart: 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"),
            info: None,
            socketcan_bridge: bridge,
            uart_bridge: None,
            uart: 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'); monitor.Parse('quit')"));
        assert!(resc.contains(
            "cpu AddHook 0x10000210 \"self.Log(LogLevel.Error, 'HIL FAIL (fail marker)'); monitor.Parse('quit')\""
        ));
        assert!(
            resc.contains("cpu AddHook 0x10000220 \"self.Log(LogLevel.Error, 'HIL FAIL (panic)')")
        );
        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 multi_machine_pass_does_not_quit_but_fail_does() {
        let resc = render_resc(
            &[vector_table_machine("a"), vector_table_machine("b")],
            "vcan0",
            None,
            10,
        );
        assert!(resc.contains("'HIL OK')\""));
        assert!(!resc.contains("'HIL OK'); monitor.Parse('quit')"));
        assert!(resc.contains("'HIL FAIL (panic)'); monitor.Parse('quit')"));
    }

    #[test]
    fn bridged_single_machine_pass_does_not_quit() {
        // Firmware may hit the pass marker at boot, then serve the bridged
        // UART; quitting on pass would cut the host off mid-conversation.
        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("'HIL OK')\""));
        assert!(!resc.contains("'HIL OK'); monitor.Parse('quit')"));
        assert!(resc.contains("'HIL FAIL (panic)'); monitor.Parse('quit')"));
    }

    #[test]
    fn console_uart_gets_an_analyzer() {
        let mut m = vector_table_machine("hil");
        assert!(!render_resc(std::slice::from_ref(&m), "vcan0", None, 10).contains("showAnalyzer"));
        m.uart = Some("sysbus.uart0");
        let resc = render_resc(&[m], "vcan0", None, 10);
        assert!(resc.contains("showAnalyzer sysbus.uart0"));
    }

    #[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 timeout_carries_into_hours_past_3600s() {
        // A naive "00:{mm}:{ss}" template silently truncates once minutes
        // exceed 59; hours must carry instead.
        assert_eq!(format_run_for(3600), "01:00:00");
        assert_eq!(format_run_for(3661), "01:01:01");
        assert_eq!(format_run_for(7325), "02:02:05");
    }

    #[test]
    fn json_str_field_extracts_and_unescapes() {
        let line = r#"{"executable":"/tmp/a \"weird\" path","name":"hil_controller"}"#;
        assert_eq!(
            json_str_field(line, "executable").as_deref(),
            Some(r#"/tmp/a "weird" path"#)
        );
        assert_eq!(
            json_str_field(line, "name").as_deref(),
            Some("hil_controller")
        );
        assert_eq!(json_str_field(line, "missing"), None);
    }

    #[test]
    fn find_executable_matches_target_name_and_ignores_others() {
        let stdout = concat!(
            r#"{"reason":"compiler-artifact","target":{"name":"other"},"executable":"/tmp/other"}"#,
            "\n",
            r#"{"reason":"build-script-executed","target":{"name":"hil_controller"}}"#,
            "\n",
            r#"{"reason":"compiler-artifact","target":{"name":"hil_controller"},"executable":"/tmp/thumbv7em-none-eabihf/release/hil_controller"}"#,
        );
        assert_eq!(
            find_executable(stdout, "hil_controller"),
            Some(PathBuf::from(
                "/tmp/thumbv7em-none-eabihf/release/hil_controller"
            ))
        );
        assert_eq!(find_executable(stdout, "nonexistent"), None);
    }

    #[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"));
    }
}