varve-core 0.46.0

Layer manifests, resolution, the core store, and verification wiring for varve
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
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
//! Tree-shaped payload export and relocation (REQ-SDK-001).
//!
//! A `sdk` payload is a TREE — a Yocto SDK is thousands of files — and it is
//! the first payload varve cannot simply hand over verbatim. Yocto's installer
//! runs `relocate_sdk.py`, which opens each file `"r+b"` and byte-patches in
//! place: the `PT_INTERP` dynamic-loader path, the loader's own SYSDIRS string
//! table and its parallel length array, and the `ld.so.cache` path. The wrapper
//! `toolchain-shar-relocate.sh` additionally `sed -i`s every text file and
//! re-points every symlink. After installation the bytes no longer hash to the
//! signed digest.
//!
//! # Why the store keeps the archive and the tree lives in the export
//!
//! Relocation is bounded, and the bound is read from the script rather than
//! assumed:
//!
//! ```text
//! if (len(new_dl_path) >= p_filesz):
//!     print("ERROR: could not relocate %s, interp size = %i and %i is needed.")
//!     return False
//! ```
//!
//! The new interpreter path must FIT the old one's field, so an SDK can only
//! ever move to a path NO LONGER than the one it was built with. varve's store
//! path is ~90 characters before any content
//! (`…/realms/<16hex>/core/sha256-<64hex>/…`), so relocating INTO the store
//! would frequently be impossible. That is one of two reasons the design is
//! pristine-store-plus-relocated-export rather than in-place; the other is
//! clause 2 — `verify` and `archive` hash ONE file against ONE signed digest,
//! so the store must keep exactly the bytes the producer signed. varve
//! therefore verifies only what was signed, never what relocation produced,
//! and nothing here ever writes back into the store.
//!
//! # What this module owes the caller
//!
//! The tree is materialised HERE, from an archive whose member names come out
//! of a signed blob. Signed means attributable, not benign: a tree has far more
//! path components than a single payload name, and a symlink inside one can
//! escape the export even when every component looks safe (the Cargo
//! CVE-2026-5223 class — link out, then write through it). So every
//! destination is resolved and validated BEFORE a byte is written, exactly as
//! `Store::lay_down_payloads` does, and a tree that cannot be laid out whole is
//! not laid out at all.

use std::borrow::Cow;
use std::collections::BTreeSet;
use std::io::Read;
use std::path::Path;

/// The signed annotation naming the absolute path an SDK was BUILT for.
///
/// It is the producer's declaration, carried in the layer manifest and covered
/// by the DSSE signature, because the relocation budget is derived from it: a
/// destination longer than this prefix cannot be patched into the interpreter
/// fields, and a consumer must not be able to talk varve into trying.
pub const ANN_SDK_PREFIX: &str = "eu.pulseengine.varve.sdk.prefix";

/// What one archive member is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemberBody {
    Dir,
    File { mode: u32, bytes: Vec<u8> },
    Symlink { target: String },
}

/// One validated member of a tree payload, with its path relative to the export
/// root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Member {
    pub path: String,
    pub body: MemberBody,
}

/// What an export actually did — reported rather than assumed, because
/// "relocated 0 fields" and "relocated 40 000 fields" look identical on disk.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SdkExportReport {
    pub dirs: usize,
    pub files: usize,
    pub symlinks: usize,
    /// NUL-padded path fields patched in place in binaries (the `relocate_sdk.py`
    /// half — total file length preserved).
    pub patched_fields: usize,
    /// Path occurrences substituted in text files (the `sed -i` half).
    pub substitutions: usize,
    /// Symlinks whose absolute target was re-pointed into the export.
    pub relocated_symlinks: usize,
}

/// Why a tree payload could not be exported or relocated.
#[derive(Debug, thiserror::Error)]
pub enum SdkExportError {
    #[error("io error at {path}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("the sdk payload is not a readable tar archive: {0}")]
    Archive(String),
    #[error(
        "the sdk declares no build-time prefix ({ANN_SDK_PREFIX}) — without it there is no \
         relocation budget and no path to patch; re-deposit the sdk with the prefix it was \
         built for"
    )]
    NoBuiltPrefix,
    #[error(
        "the export destination must be an absolute path, got {0:?} — the destination is \
         PATCHED INTO the SDK's binaries, and a relative path there would resolve against \
         whatever directory the compiler happens to run in"
    )]
    DestinationNotAbsolute(String),
    #[error(
        "cannot relocate this sdk to {dest}: the destination is {dest_len} characters and the \
         sdk was built for {built_prefix} ({budget}). An SDK's interpreter path is patched IN \
         PLACE into a fixed-size field, so it can only ever move to a path NO LONGER than the \
         one it was built with. Choose a destination of at most {budget} characters."
    )]
    DestinationTooLong {
        dest: String,
        dest_len: usize,
        built_prefix: String,
        budget: usize,
    },
    #[error(
        "{member}: the path field at offset {offset} needs {needed} bytes but the field holds \
         {capacity} — this is `relocate_sdk.py`'s own limit (len(new) >= field size), reached \
         after the destination-length check passed, so the sdk's fields are tighter than its \
         build prefix implies"
    )]
    FieldTooSmall {
        member: String,
        offset: usize,
        needed: usize,
        capacity: usize,
    },
    #[error(
        "{member}: the loader's SYSDIRS table (.sysdirs) names the sdk's build prefix but its \
         length array (.sysdirslen) was not found, so moving to a path of a different length \
         would leave ld.so stepping through the table by the old lengths — refusing rather than \
         produce a loader that opens empty file names"
    )]
    SysdirsWithoutLengths { member: String },
    #[error(
        "{member}: .sysdirs holds {paths} path(s) but .sysdirslen has room for {slots} length(s) \
         — the two tables disagree, so neither can be rewritten safely"
    )]
    SysdirsLengthsDisagree {
        member: String,
        paths: usize,
        slots: usize,
    },
    #[error("sdk member {member:?} is not a usable path ({why}) — refusing to lay the tree down")]
    UnsafeMember { member: String, why: String },
    #[error(
        "two members of this sdk both land on {path} — one would overwrite the other, and the \
         survivor would carry the wrong bytes under the right name"
    )]
    Collision { path: String },
    #[error(
        "sdk member {member:?} would be written THROUGH the symlink {link:?} — a link out of \
         the export followed by a write through it places bytes anywhere on the filesystem"
    )]
    WriteThroughSymlink { member: String, link: String },
    #[error(
        "sdk symlink {member:?} points at {target:?}, which is outside both the sdk and the \
         export — a relocated SDK is self-contained, and a link to the host is neither \
         verified nor reproducible"
    )]
    SymlinkEscapes { member: String, target: String },
    #[error("this platform cannot create the symlink {member:?} an sdk tree requires")]
    SymlinksUnsupported { member: String },
}

/// Trim a trailing `/` so `/opt/poky` and `/opt/poky/` mean one prefix and
/// budget the same number of characters.
fn normalise_prefix(p: &str) -> &str {
    let t = p.trim_end_matches('/');
    if t.is_empty() { p } else { t }
}

/// The relocation fit check (clause 4), as a pure function so it can be run
/// EARLY — before the archive is even opened, let alone thousands of files
/// written.
///
/// Every patched field holds `<prefix><suffix>`; relocation replaces only the
/// prefix, so the new string fits every field it came from exactly when the new
/// prefix is no longer than the built one. That single comparison is therefore
/// complete for the whole tree — which is what makes the early refusal possible
/// rather than a guess that has to be re-checked file by file.
pub fn check_destination_fits(built_prefix: &str, dest: &str) -> Result<(), SdkExportError> {
    let built = normalise_prefix(built_prefix);
    if built.is_empty() {
        return Err(SdkExportError::NoBuiltPrefix);
    }
    if !dest.starts_with('/') {
        return Err(SdkExportError::DestinationNotAbsolute(dest.to_string()));
    }
    let dest_n = normalise_prefix(dest);
    if dest_n.len() > built.len() {
        return Err(SdkExportError::DestinationTooLong {
            dest: dest_n.to_string(),
            dest_len: dest_n.len(),
            built_prefix: built.to_string(),
            budget: built.len(),
        });
    }
    Ok(())
}

/// First occurrence of `needle` in `haystack`, by bytes.
fn find_sub(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
    if needle.is_empty() || haystack.len() < needle.len() {
        return None;
    }
    (from..=haystack.len() - needle.len()).find(|&i| &haystack[i..i + needle.len()] == needle)
}

/// Every occurrence of `from` in `hay` replaced by `to`, and how many there
/// were. ONE copy, used by the text path, the per-string binary path and the
/// SYSDIRS table.
///
/// Written without index arithmetic on purpose. The three loops this replaced
/// advanced with `i = hit + from.len()`, and cargo-mutants' `+` → `*` turned
/// that into a loop that never advances when the hit is at 0 — while
/// appending on every pass. It did not just hang: it grew a buffer until the
/// CI runner ran out of memory and was shut down, twice, taking the whole
/// mutation shard with it. Slicing with `get` leaves no operator for that
/// mutant, and the loop below cannot run without consuming input.
fn replace_all(hay: &[u8], from: &[u8], to: &[u8]) -> (Vec<u8>, usize) {
    let mut out = Vec::with_capacity(hay.len());
    let mut rest = hay;
    let mut count = 0;
    // Every pass must CONSUME input or stop. Advancing only past a match
    // that lies wholly inside `rest` makes termination independent of what
    // `find_sub` answers: a mutant `find_sub` that always says `Some(0)`
    // once spun this loop forever on an empty `rest`, appending each time,
    // until the CI runner ran out of memory — the failure it was written to
    // end, reached by a different mutant (2026-10-16).
    while let Some(at) = find_sub(rest, from, 0) {
        let Some(tail) = rest.get(at..).and_then(|t| t.get(from.len()..)) else {
            break;
        };
        out.extend_from_slice(&rest[..at]);
        out.extend_from_slice(to);
        rest = tail;
        count += 1;
    }
    out.extend_from_slice(rest);
    (out, count)
}

/// What relocating one member's bytes produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Relocation {
    pub bytes: Vec<u8>,
    /// In-place NUL-padded fields patched (binary, length preserved).
    pub fields: usize,
    /// Text occurrences substituted (length may change).
    pub substitutions: usize,
}

/// Does this payload look like a binary? The same test
/// `toolchain-shar-relocate.sh` makes with `grep -qIl`: a NUL byte anywhere.
/// A binary is patched IN PLACE inside its fixed-size fields; a text file is
/// rewritten freely, which is what lets `environment-setup-*` grow or shrink.
fn is_binary(bytes: &[u8]) -> bool {
    bytes.contains(&0)
}

/// Rewrite every occurrence of the SDK's build-time prefix in one member.
///
/// Binaries are patched the way `relocate_sdk.py` does: the C string containing
/// the occurrence is rewritten IN PLACE and re-padded with NULs to its original
/// field width, so the file's length and every offset in it are preserved. A
/// string that would no longer fit is refused rather than truncated — a
/// truncated interpreter path is a binary that fails to exec with no
/// explanation.
pub fn relocate_bytes(
    member: &str,
    bytes: &[u8],
    built_prefix: &str,
    dest_prefix: &str,
) -> Result<Relocation, SdkExportError> {
    let built = normalise_prefix(built_prefix).as_bytes();
    let dest = normalise_prefix(dest_prefix).as_bytes();

    if !is_binary(bytes) {
        // The `sed -i` half: no field to overflow, so the text may change length.
        let (out, substitutions) = replace_all(bytes, built, dest);
        return Ok(Relocation {
            bytes: out,
            fields: 0,
            substitutions,
        });
    }

    let mut out = bytes.to_vec();
    // The loader's SYSDIRS table first: its paths are packed back to back and
    // indexed by a parallel length array, so they are rewritten as a TABLE,
    // and the generic per-string patching below must not touch that range.
    let sysdirs = relocate_sysdirs(member, &mut out, built, dest)?;
    let mut fields = sysdirs.as_ref().map_or(0, |(_, n)| *n);
    let mut cursor = 0;
    while let Some(hit) = find_sub(&out, built, cursor) {
        // A hit behind the cursor is a search that did not advance; stop
        // rather than re-patch the same field forever (a mutant `find_sub`
        // returning a fixed position hung here until the test timed out).
        if hit < cursor {
            break;
        }
        if let Some((range, _)) = &sysdirs
            && range.contains(&hit)
        {
            cursor = range.end;
            continue;
        }
        // The C string the occurrence belongs to: from just past the previous
        // NUL to the next one. `LD_LIBRARY_PATH=/opt/poky/…` is one string, and
        // patching from the occurrence rather than the string start would leave
        // the padding computation wrong.
        let start = out[..hit]
            .iter()
            .rposition(|b| *b == 0)
            .map(|p| p + 1)
            .unwrap_or(0);
        let Some(end) = out[hit..].iter().position(|b| *b == 0).map(|p| hit + p) else {
            // No terminator between here and the end of the file — so there is
            // none for any LATER occurrence either, since every later one
            // searches a suffix of this same range. Nothing after this point
            // can be a padded field, so stop rather than advance a cursor.
            //
            // This was `cursor = hit + built.len(); continue;`, which scanned
            // on to find nothing. Mutation testing left `hit * built.len()`
            // alive here and it was right to: any advance past `hit` reaches
            // the same conclusion, so the arithmetic could not be observed.
            // The arithmetic was the thing that did not need to exist.
            break;
        };
        // Capacity is the string PLUS its NUL padding: exactly the `p_filesz`
        // the script compares against.
        // Counted, not accumulated: `pad_end += 1` neutralised by a mutation
        // never grows, and the loop then runs forever — a hang rather than a
        // wrong answer. `take_while` has no counter to neutralise, so the same
        // mutation now produces an observable number instead of an infinite
        // loop, and the capacity test can see it.
        let pad_end = end + out[end..].iter().take_while(|b| **b == 0).count();
        let capacity = pad_end - start;

        // Replace every occurrence of the prefix WITHIN this one string.
        let (new, _) = replace_all(&out[start..end], built, dest);

        // `if len(new_dl_path) >= p_filesz: ERROR` — transcribed, not
        // paraphrased. The destination check has already made this
        // unreachable for a well-formed SDK; it stays because the field is
        // where truncation would actually happen, and a silent truncation here
        // produces a binary that cannot exec with nothing to point at.
        if new.len() >= capacity {
            return Err(SdkExportError::FieldTooSmall {
                member: member.to_string(),
                offset: start,
                needed: new.len() + 1,
                capacity,
            });
        }
        out[start..start + new.len()].copy_from_slice(&new);
        for b in &mut out[start + new.len()..pad_end] {
            *b = 0;
        }
        fields += 1;
        cursor = pad_end;
    }
    Ok(Relocation {
        bytes: out,
        fields,
        substitutions: 0,
    })
}

/// One ELF section's file range, by name, with the file's class and byte
/// order. `None` for anything that is not a well-formed ELF with a readable
/// section-header table — such a file has no SYSDIRS table to rewrite, and the
/// generic patching handles it as before. Every read is bounds-checked.
fn elf_section(bytes: &[u8], name: &[u8]) -> Option<(usize, usize, bool, bool)> {
    if bytes.get(..4)? != b"\x7fELF" {
        return None;
    }
    let class64 = match *bytes.get(4)? {
        1 => false,
        2 => true,
        _ => return None,
    };
    let little = match *bytes.get(5)? {
        1 => true,
        2 => false,
        _ => return None,
    };
    // An unsigned integer of `n` bytes at `at`, in the file's byte order.
    let rd = |at: usize, n: usize| -> Option<usize> {
        let field = bytes.get(at..at.checked_add(n)?)?;
        let mut buf = [0u8; 8];
        let v = if little {
            buf[..n].copy_from_slice(field);
            u64::from_le_bytes(buf)
        } else {
            buf[8 - n..].copy_from_slice(field);
            u64::from_be_bytes(buf)
        };
        usize::try_from(v).ok()
    };
    let word = if class64 { 8 } else { 4 };
    let (shoff, shentsize, shnum, shstrndx) = if class64 {
        (rd(0x28, 8)?, rd(0x3A, 2)?, rd(0x3C, 2)?, rd(0x3E, 2)?)
    } else {
        (rd(0x20, 4)?, rd(0x2E, 2)?, rd(0x30, 2)?, rd(0x32, 2)?)
    };
    // (name, offset, size) of section header `i`. The offset and size fields
    // sit after sh_name/sh_type and sh_flags/sh_addr, each `word` wide.
    let header = |i: usize| -> Option<(usize, usize, usize)> {
        let base = shoff.checked_add(i.checked_mul(shentsize)?)?;
        let off_at = base.checked_add(8 + 2 * word)?;
        Some((
            rd(base, 4)?,
            rd(off_at, word)?,
            rd(off_at.checked_add(word)?, word)?,
        ))
    };
    let (_, str_off, str_size) = header(shstrndx)?;
    let strtab = bytes.get(str_off..str_off.checked_add(str_size)?)?;
    (0..shnum).find_map(|i| {
        let (name_at, off, size) = header(i)?;
        let tail = strtab.get(name_at..)?;
        let this = tail.split(|b| *b == 0).next()?;
        (this == name && bytes.get(off..off.checked_add(size)?).is_some())
            .then_some((off, size, class64, little))
    })
}

/// Rewrite a glibc loader's SYSDIRS table the way `relocate_sdk.py`'s
/// `change_dl_sysdirs` does, transcribed: split `.sysdirs` on NUL and stop at
/// the first empty entry, substitute the prefix in each path, pack them back
/// to back NUL-terminated, zero-pad to the section size, and write each new
/// length into `.sysdirslen` (u32 for ELFCLASS32, u64 for ELFCLASS64).
///
/// Returns the `.sysdirs` range (so the caller leaves it alone) and how many
/// paths were rewritten, or `None` when there is no table naming the prefix.
fn relocate_sysdirs(
    member: &str,
    out: &mut [u8],
    built: &[u8],
    dest: &[u8],
) -> Result<Option<(std::ops::Range<usize>, usize)>, SdkExportError> {
    let Some((off, size, class64, little)) = elf_section(out, b".sysdirs") else {
        return Ok(None);
    };
    let table = &out[off..off + size];
    if find_sub(table, built, 0).is_none() {
        return Ok(None);
    }
    let Some((len_off, len_size, _, _)) = elf_section(out, b".sysdirslen") else {
        if built.len() == dest.len() {
            // Every length is unchanged, so the generic in-place patching is
            // exactly right — the one case that always worked.
            return Ok(None);
        }
        return Err(SdkExportError::SysdirsWithoutLengths {
            member: member.to_string(),
        });
    };
    let paths: Vec<Vec<u8>> = table
        .split(|b| *b == 0)
        .take_while(|p| !p.is_empty())
        .map(|p| replace_all(p, built, dest).0)
        .collect();
    let width = if class64 { 8 } else { 4 };
    let slots = len_size / width;
    if paths.len() != slots {
        return Err(SdkExportError::SysdirsLengthsDisagree {
            member: member.to_string(),
            paths: paths.len(),
            slots,
        });
    }
    let mut packed = Vec::with_capacity(size);
    for p in &paths {
        packed.extend_from_slice(p);
        packed.push(0);
    }
    if packed.len() > size {
        return Err(SdkExportError::FieldTooSmall {
            member: member.to_string(),
            offset: off,
            needed: packed.len(),
            capacity: size,
        });
    }
    packed.resize(size, 0);
    out[off..off + size].copy_from_slice(&packed);
    let slots_bytes = &mut out[len_off..len_off + slots * width];
    for (slot, p) in slots_bytes.chunks_exact_mut(width).zip(&paths) {
        let len = p.len() as u64;
        match (class64, little) {
            (true, true) => slot.copy_from_slice(&len.to_le_bytes()),
            (true, false) => slot.copy_from_slice(&len.to_be_bytes()),
            (false, true) => slot.copy_from_slice(&(len as u32).to_le_bytes()),
            (false, false) => slot.copy_from_slice(&(len as u32).to_be_bytes()),
        }
    }
    Ok(Some((off..off + size, paths.len())))
}

/// Refuse a path component that is not a single, safe name — the same rule
/// `Store::lay_down_payloads` applies to a payload name, applied to EVERY
/// component of every member of the tree, because a tree has thousands of them
/// and one is enough to escape.
fn component_fault(value: &str) -> Option<String> {
    if value.is_empty() {
        return Some("an empty path component".into());
    }
    if value == "." || value == ".." {
        return Some("a relative path element".into());
    }
    if let Some(c) = value
        .chars()
        .find(|c| matches!(c, '/' | '\\' | '\0') || c.is_control())
    {
        return Some(format!("contains {c:?}"));
    }
    None
}

/// Does this member name the archive ROOT itself — `./`, `.`, `././`?
///
/// `tar -C dir .` writes the root as its first member, and a Yocto SDK
/// installer's payload is made exactly that way. As a DIRECTORY it names the
/// export directory, which already exists, so the loops skip it. A file or a
/// symlink with this name is not skipped and meets `safe_member_path`'s
/// refusal like any other member.
pub(crate) fn names_archive_root(raw: &str) -> bool {
    let mut p = raw.trim_end_matches('/');
    while let Some(rest) = p.strip_prefix("./") {
        p = rest.trim_start_matches('/');
    }
    p == "."
}

/// Validate a member path and return it normalised (no trailing slash).
///
/// `pub(crate)` so the docs exporter uses THIS rule rather than a second copy
/// of it. A tree of documentation is written to disk by the same kind of loop
/// as an SDK, and two implementations of "may this member escape the export
/// directory" would drift — with a defect in either masked by the other.
pub(crate) fn safe_member_path(raw: &str) -> Result<String, SdkExportError> {
    let unsafe_member = |why: &str| SdkExportError::UnsafeMember {
        member: raw.to_string(),
        why: why.to_string(),
    };
    if raw.starts_with('/') {
        return Err(unsafe_member(
            "absolute — it would place bytes outside the export",
        ));
    }
    let trimmed = raw.trim_end_matches('/');
    // `./x` is how GNU tar writes a member when the archive was created from
    // `.` — varve's own traceability bundle is entirely `./index.html`,
    // `./_assets/…`. It denotes the archive root, not a traversal, and
    // refusing it means neither `export-docs` nor `export-sdk` can open such
    // an archive at all. Stripped in a loop so `././x` normalises too; a `.`
    // or `..` anywhere ELSE still falls through to the component check below,
    // which is the rule that actually prevents an escape. `./../x` therefore
    // becomes `../x` and is still refused.
    let mut trimmed = trimmed;
    while let Some(rest) = trimmed.strip_prefix("./") {
        trimmed = rest;
    }
    if trimmed.is_empty() {
        return Err(unsafe_member("empty"));
    }
    for component in trimmed.split('/') {
        if let Some(why) = component_fault(component) {
            return Err(unsafe_member(&why));
        }
    }
    Ok(trimmed.to_string())
}

/// Decompress a gzip or xz archive, or pass a plain tar through.
///
/// Decided by MAGIC, not by a file name — and deliberately the opposite of the
/// producer, which chooses an unpacker from the asset name. The two are at
/// different points in the same pipeline: the producer is picking a tool to
/// run on bytes nobody has verified yet, so a name that disagrees with the
/// content is a reason to stop; here the bytes have already been checked
/// against the signed digest, so what they ARE is the only question left.
///
/// xz matters because it is not an edge case: every wasmtime archive and all
/// 140 Zephyr SDK toolchains are .tar.xz. Decoding it with a pure-Rust
/// implementation keeps a C build dependency out of the crate every consumer
/// links (REQ-SDKDEPOSIT-001).
fn decompress(archive: &[u8]) -> Result<Cow<'_, [u8]>, SdkExportError> {
    if archive.starts_with(&[0x1f, 0x8b]) {
        let mut out = Vec::new();
        flate2::read::GzDecoder::new(archive)
            .read_to_end(&mut out)
            .map_err(|e| SdkExportError::Archive(e.to_string()))?;
        return Ok(Cow::Owned(out));
    }
    // xz: FD 37 7A 58 5A 00
    if archive.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]) {
        let mut out = Vec::new();
        let mut input = std::io::BufReader::new(archive);
        lzma_rs::xz_decompress(&mut input, &mut out)
            .map_err(|e| SdkExportError::Archive(format!("xz: {e}")))?;
        return Ok(Cow::Owned(out));
    }
    // bzip2: "BZh". Named rather than left to fail as a tar parse error,
    // because "not a readable tar archive" sends a reader looking for a
    // corrupt download when the real answer is that varve cannot open this
    // compression at all. A payload varve cannot decode must say so.
    if archive.starts_with(b"BZh") {
        return Err(SdkExportError::Archive(
            "this payload is bzip2-compressed, which varve cannot decode. It was \
             deposited and its bytes verify; what is missing is a decoder. \
             Re-deposit the sdk as .tar.gz or .tar.xz, or file for bzip2 support."
                .into(),
        ));
    }
    Ok(Cow::Borrowed(archive))
}

/// Read every member of a tree payload out of its archive.
///
/// Paths are carried through VERBATIM and judged in `export_members`, which is
/// the only thing that writes. Validating in both places would look safer and
/// be worse: two copies of one rule drift, and a defect in either is masked by
/// the other, so neither can be shown to matter.
pub fn read_members(archive: &[u8]) -> Result<Vec<Member>, SdkExportError> {
    let raw = decompress(archive)?;
    let mut tar = tar::Archive::new(raw.as_ref());
    let entries = tar
        .entries()
        .map_err(|e| SdkExportError::Archive(e.to_string()))?;
    let mut members = Vec::new();
    for entry in entries {
        let mut entry = entry.map_err(|e| SdkExportError::Archive(e.to_string()))?;
        let raw_path = entry
            .path()
            .map_err(|e| SdkExportError::Archive(e.to_string()))?
            .to_string_lossy()
            .into_owned();
        let header = entry.header().clone();
        let body = match header.entry_type() {
            tar::EntryType::Directory => MemberBody::Dir,
            // A hard link is treated as a symlink: varve is materialising a
            // fresh tree, and a link that must stay inside the export is the
            // same question either way.
            tar::EntryType::Symlink | tar::EntryType::Link => {
                let target = entry
                    .link_name()
                    .map_err(|e| SdkExportError::Archive(e.to_string()))?
                    .map(|t| t.to_string_lossy().into_owned())
                    .unwrap_or_default();
                MemberBody::Symlink { target }
            }
            _ => {
                let mut bytes = Vec::new();
                entry
                    .read_to_end(&mut bytes)
                    .map_err(|e| SdkExportError::Archive(e.to_string()))?;
                let mode = header.mode().unwrap_or(0o644);
                MemberBody::File { mode, bytes }
            }
        };
        members.push(Member {
            path: raw_path,
            body,
        });
    }
    Ok(members)
}

/// Where a symlink target lands, and whether it stays inside the export.
///
/// Three cases, and each has to be decided rather than defaulted:
///   * absolute and under the SDK's build prefix — an SDK's own internal
///     absolute link, re-pointed into the export;
///   * absolute and anywhere else — a link to the HOST, refused: a relocated
///     SDK is self-contained, and a link varve did not verify is not part of
///     what the trust root anchored;
///   * relative — resolved lexically against the link's own directory and
///     refused if it climbs out of the export root.
fn resolve_link_target(
    member: &str,
    target: &str,
    built_prefix: &str,
    dest_prefix: &str,
) -> Result<(String, bool), SdkExportError> {
    let escapes = || SdkExportError::SymlinkEscapes {
        member: member.to_string(),
        target: target.to_string(),
    };
    if target.is_empty() {
        return Err(escapes());
    }
    if target.starts_with('/') {
        let built = normalise_prefix(built_prefix);
        let dest = normalise_prefix(dest_prefix);
        if target == built {
            return Ok((dest.to_string(), true));
        }
        if let Some(rest) = target.strip_prefix(&format!("{built}/")) {
            // Being under the build prefix is not the same as staying under
            // it. `<built>/../../../tmp/x` starts with the prefix and lands
            // outside the export, so the remainder is walked exactly as the
            // relative branch below walks its target — that branch always did,
            // this one did not, and the asymmetry WAS the hole: the escape was
            // accepted and counted as a re-pointed symlink, exit 0.
            let mut depth: isize = 0;
            for component in rest.split('/') {
                match component {
                    "" | "." => {}
                    ".." => {
                        depth -= 1;
                        // Climbing above the export root, not merely within it.
                        if depth < 0 {
                            return Err(escapes());
                        }
                    }
                    _ => depth += 1,
                }
            }
            return Ok((format!("{dest}/{rest}"), true));
        }
        return Err(escapes());
    }
    // Relative: walk it against the link's own directory, lexically. `..` past
    // the export root is the escape; `..` within it is ordinary and common.
    let mut stack: Vec<&str> = member.split('/').collect();
    stack.pop(); // the link itself
    for component in target.split('/') {
        match component {
            "" | "." => {}
            ".." => {
                if stack.pop().is_none() {
                    return Err(escapes());
                }
            }
            other => stack.push(other),
        }
    }
    Ok((target.to_string(), false))
}

/// Lay a verified tree payload out under `out`, relocated from its build-time
/// prefix to `out` (clause 3).
///
/// `out` must be ABSOLUTE: the destination is patched into the SDK's binaries,
/// so a relative one would resolve against whatever directory a compiler
/// happens to run in. Every destination is validated and resolved before any
/// byte is written, so a tree that cannot be laid out whole is not laid out at
/// all.
///
/// This never touches the store. The signed archive stays exactly as the
/// producer signed it, which is what `verify` and `archive` re-hash; the
/// relocated tree is a DERIVED artifact, deliberately outside the trust path
/// (clause 2).
pub fn export_sdk(
    archive: &[u8],
    built_prefix: &str,
    out: &Path,
) -> Result<SdkExportReport, SdkExportError> {
    let dest = out.to_string_lossy().into_owned();
    // FIRST, and before the archive is even decompressed: an SDK that cannot
    // reach this destination must be refused now, not after thousands of files
    // have been written and patched (clause 4).
    check_destination_fits(built_prefix, &dest)?;
    let members = read_members(archive)?;
    export_members(&members, built_prefix, out)
}

/// The write half, split out so a tree can be laid down from members obtained
/// any way — and so the plan-then-write discipline is testable without a tar.
pub fn export_members(
    members: &[Member],
    built_prefix: &str,
    out: &Path,
) -> Result<SdkExportReport, SdkExportError> {
    let dest = out.to_string_lossy().into_owned();
    check_destination_fits(built_prefix, &dest)?;

    // ---- plan: resolve and validate EVERY destination before writing ----
    let mut placed: BTreeSet<String> = BTreeSet::new();
    let mut links: BTreeSet<String> = BTreeSet::new();
    let mut planned: Vec<(String, &Member)> = Vec::with_capacity(members.len());
    for m in members {
        if matches!(m.body, MemberBody::Dir) && names_archive_root(&m.path) {
            continue;
        }
        let path = safe_member_path(&m.path)?;
        if !placed.insert(path.clone()) {
            return Err(SdkExportError::Collision { path });
        }
        if let MemberBody::Symlink { .. } = m.body {
            links.insert(path.clone());
        }
        planned.push((path, m));
    }
    // A symlink out of the tree followed by a write THROUGH it places bytes
    // anywhere on the filesystem, and every component of the offending member
    // still looks perfectly safe on its own. Refuse the pair, not the shape.
    for (path, _) in &planned {
        let mut prefix = String::new();
        for component in path.split('/') {
            if !prefix.is_empty() {
                prefix.push('/');
            }
            prefix.push_str(component);
            if prefix.len() < path.len() && links.contains(&prefix) {
                return Err(SdkExportError::WriteThroughSymlink {
                    member: path.clone(),
                    link: prefix,
                });
            }
        }
    }
    // Link targets, resolved and refused before anything exists on disk.
    let mut resolved_links: Vec<(&str, String, bool)> = Vec::new();
    for (path, m) in &planned {
        if let MemberBody::Symlink { target } = &m.body {
            let (t, relocated) = resolve_link_target(path, target, built_prefix, &dest)?;
            resolved_links.push((path, t, relocated));
        }
    }
    // Relocate every file's bytes before creating the export directory: a
    // field that will not fit must leave the destination untouched.
    let mut relocated_files: Vec<(&str, Relocation, u32)> = Vec::new();
    for (path, m) in &planned {
        if let MemberBody::File { mode, bytes } = &m.body {
            let r = relocate_bytes(path, bytes, built_prefix, &dest)?;
            relocated_files.push((path, r, *mode));
        }
    }

    // ---- write ----
    let io = |path: &Path, source: std::io::Error| SdkExportError::Io {
        path: path.display().to_string(),
        source,
    };
    let mut report = SdkExportReport::default();
    std::fs::create_dir_all(out).map_err(|e| io(out, e))?;
    for (rel, m) in &planned {
        if matches!(m.body, MemberBody::Dir) {
            let path = out.join(rel);
            std::fs::create_dir_all(&path).map_err(|e| io(&path, e))?;
            report.dirs += 1;
        }
    }
    for (rel, relocation, mode) in &relocated_files {
        let path = out.join(rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
        }
        std::fs::write(&path, &relocation.bytes).map_err(|e| io(&path, e))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode & 0o7777))
                .map_err(|e| io(&path, e))?;
        }
        #[cfg(not(unix))]
        let _ = mode;
        report.files += 1;
        report.patched_fields += relocation.fields;
        report.substitutions += relocation.substitutions;
    }
    for (rel, target, relocated) in &resolved_links {
        let path = out.join(rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
        }
        #[cfg(unix)]
        std::os::unix::fs::symlink(target, &path).map_err(|e| io(&path, e))?;
        #[cfg(not(unix))]
        {
            let _ = target;
            return Err(SdkExportError::SymlinksUnsupported {
                member: (*rel).to_string(),
            });
        }
        report.symlinks += 1;
        if *relocated {
            report.relocated_symlinks += 1;
        }
    }
    Ok(report)
}

#[cfg(test)]
mod safe_path_probe {
    /// `./x` is the ordinary GNU tar prefix — `tar czf a.tgz ./file` writes it,
    /// and varve's OWN traceability bundle is full of it. Refusing it as a
    /// "relative path element" means neither `export-docs` nor `export-sdk`
    /// can open such an archive at all.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_leading_dot_slash_is_tar_convention_not_traversal() {
        assert_eq!(
            super::safe_member_path("./index.html").expect("the tar root prefix is not an escape"),
            "index.html"
        );
        assert_eq!(
            super::safe_member_path("./a/b.html").expect("nested under the tar root"),
            "a/b.html"
        );
    }

    /// …but only as the LEADING component. A `.` or `..` anywhere else is the
    /// thing the rule exists for, and one member is enough to escape.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn an_interior_relative_element_is_still_refused() {
        for bad in ["a/./b", "a/../b", "../escape", "a/..", "./../x"] {
            assert!(
                super::safe_member_path(bad).is_err(),
                "{bad:?} must still be refused"
            );
        }
    }
}

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

    /// The absolute path this synthetic SDK was BUILT for.
    ///
    /// Deliberately long, and that is not cosmetic: a real Yocto SDK is built
    /// for a long default installation directory PRECISELY so it can be
    /// relocated afterwards, since relocation can only ever shorten a path. The
    /// tests' own temporary directory has to fit inside that budget, which is
    /// the same arithmetic a real user does.
    const BUILT: &str = "/opt/poky/4.0.15/x86_64-pokysdk-linux/default-installation-directory-padded-so-a-temporary-directory-fits-inside-the-relocation-budget-which-can-only-ever-shrink-a-path-never-grow-it";

    /// The slack a real `PT_INTERP` field carries past its terminator.
    const SLACK: usize = 8;

    /// A NUL-padded path field, the way an ELF `PT_INTERP` segment holds one:
    /// the string, its terminator, and slack up to the field width.
    fn nul_field(s: &str, width: usize) -> Vec<u8> {
        let mut v = s.as_bytes().to_vec();
        v.resize(width, 0);
        v
    }

    /// A path field sized as an SDK's own build produced it.
    fn field(s: &str) -> Vec<u8> {
        nul_field(s, s.len() + SLACK)
    }

    fn interp() -> String {
        format!("{BUILT}/sysroots/x86_64/lib/ld-linux.so.2")
    }

    fn fake_binary() -> Vec<u8> {
        let mut v = b"\x7fELF".to_vec();
        v.extend_from_slice(&field(&interp()));
        v.extend_from_slice(&field(&format!("{BUILT}/sysroots/x86_64/usr/lib")));
        v.extend_from_slice(b"\0\0trailer\0");
        v
    }

    fn env_setup() -> Vec<u8> {
        format!(
            "export SDKTARGETSYSROOT={BUILT}/sysroots/aarch64\n\
             export PATH={BUILT}/sysroots/x86_64/usr/bin:$PATH\n\
             export CC=\"aarch64-poky-linux-gcc --sysroot={BUILT}/sysroots/aarch64\"\n"
        )
        .into_bytes()
    }

    fn synthetic_sdk() -> Vec<Member> {
        vec![
            Member {
                path: "sysroots".into(),
                body: MemberBody::Dir,
            },
            Member {
                path: "sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc".into(),
                body: MemberBody::File {
                    mode: 0o755,
                    bytes: fake_binary(),
                },
            },
            Member {
                path: "environment-setup-aarch64-poky-linux".into(),
                body: MemberBody::File {
                    mode: 0o644,
                    bytes: env_setup(),
                },
            },
            Member {
                path: "sysroots/x86_64/usr/bin/cc".into(),
                body: MemberBody::Symlink {
                    target: format!("{BUILT}/sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc"),
                },
            },
        ]
    }

    /// A Yocto SDK installer packs its payload with `tar -C dir .`, so the
    /// archive's FIRST member is the bare root directory `./`. Found by
    /// exporting the real Zephyr SDK host tools: the whole export was refused
    /// with "a relative path element". The root entry names the export
    /// directory itself, which already exists; it is skipped, not written.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn the_archive_root_directory_entry_is_not_a_refusal() {
        let tmp = tempfile::tempdir().unwrap();
        let out = out_of_len(tmp.path(), BUILT.len());
        let mut members = vec![
            Member {
                path: "./".into(),
                body: MemberBody::Dir,
            },
            Member {
                path: ".".into(),
                body: MemberBody::Dir,
            },
        ];
        members.extend(synthetic_sdk());
        let report =
            export_members(&members, BUILT, &out).expect("a `tar -C dir .` archive exports");
        assert!(out.join("sysroots").is_dir());
        assert_eq!(
            report.dirs,
            synthetic_sdk()
                .iter()
                .filter(|m| matches!(m.body, MemberBody::Dir))
                .count()
        );
    }

    /// Only a DIRECTORY may name the root. A file or link claiming to BE the
    /// export root is still the refusal it always was.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn only_a_directory_may_name_the_archive_root() {
        let tmp = tempfile::tempdir().unwrap();
        let out = out_of_len(tmp.path(), BUILT.len());
        for body in [
            MemberBody::File {
                mode: 0o644,
                bytes: b"x".to_vec(),
            },
            MemberBody::Symlink {
                target: "/etc".into(),
            },
        ] {
            let members = vec![Member {
                path: "./".into(),
                body,
            }];
            let err = export_members(&members, BUILT, &out).unwrap_err();
            assert!(matches!(err, SdkExportError::UnsafeMember { .. }), "{err}");
        }
        // And a traversal dressed as the root is still a traversal.
        let members = vec![Member {
            path: "./../".into(),
            body: MemberBody::Dir,
        }];
        assert!(export_members(&members, BUILT, &out).is_err());
    }

    /// An export root of a chosen length, so the fit check is exercised against
    /// a REAL path rather than a string that only looks like one.
    fn out_of_len(base: &Path, len: usize) -> PathBuf {
        let base_s = base.to_string_lossy().into_owned();
        assert!(base_s.len() < len, "tempdir already longer than {len}");
        let pad = len - base_s.len() - 1;
        base.join("d".repeat(pad))
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_destination_longer_than_the_build_prefix_is_refused_before_anything_is_written() {
        // Clause 4, and the constraint the whole design turns on:
        //   if (len(new_dl_path) >= p_filesz): ERROR
        // The interpreter path is patched IN PLACE into a fixed-size field, so
        // an SDK can only ever move to a path no longer than the one it was
        // built with. Refusing here — before the archive is even opened — is
        // the difference between a one-line error and thousands of files
        // written and then abandoned.
        let tmp = tempfile::tempdir().unwrap();
        let too_long = out_of_len(tmp.path(), BUILT.len() + 1);
        let err = export_members(&synthetic_sdk(), BUILT, &too_long).unwrap_err();
        match &err {
            SdkExportError::DestinationTooLong {
                dest_len, budget, ..
            } => {
                assert_eq!(*dest_len, BUILT.len() + 1);
                assert_eq!(*budget, BUILT.len());
            }
            other => panic!("expected DestinationTooLong, got {other}"),
        }
        // Refused BY NAME: the message must carry the destination, the budget,
        // and why — an operator whose export directory is one character too
        // long has to be able to fix it without reading relocate_sdk.py.
        let msg = err.to_string();
        assert!(msg.contains(&too_long.display().to_string()), "{msg}");
        assert!(
            msg.contains(BUILT),
            "names the prefix it was built for: {msg}"
        );
        assert!(msg.contains("NO LONGER"), "states the rule: {msg}");
        // And nothing was written: not one file, not the directory itself.
        assert!(!too_long.exists(), "a refused export must write nothing");

        // Exactly at the budget is allowed — the constraint is `no longer`, and
        // an off-by-one here would refuse a legitimate destination.
        let exact = out_of_len(tmp.path(), BUILT.len());
        assert!(check_destination_fits(BUILT, &exact.to_string_lossy()).is_ok());
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_relative_or_prefixless_destination_is_refused() {
        // The destination is PATCHED INTO the binaries. A relative one would
        // resolve against whatever directory the compiler happens to run in.
        assert!(matches!(
            check_destination_fits(BUILT, "toolchains/poky"),
            Err(SdkExportError::DestinationNotAbsolute(_))
        ));
        // …and an SDK with no declared build prefix has no budget at all,
        // which is a different fault with a different fix.
        assert!(matches!(
            check_destination_fits("", "/opt/x"),
            Err(SdkExportError::NoBuiltPrefix)
        ));
        assert!(matches!(
            check_destination_fits("/", "/opt/x"),
            Err(SdkExportError::DestinationTooLong { .. })
        ));
        // A trailing slash is the same prefix, not a longer one.
        assert!(check_destination_fits("/opt/poky", "/opt/abcd/").is_ok());
    }

    /// `matches!(c, '/' | '\\' | '\0') || c.is_control()` — the OR is what makes
    /// this catch two different families. Narrowed to AND, only a character
    /// that is BOTH a separator AND a control character is refused, which is
    /// almost none of them: a component containing `/` sails through, and so
    /// does a newline.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_component_is_refused_for_a_separator_or_for_a_control_character() {
        // A separator, which is not a control character.
        assert!(
            super::component_fault("a/b").is_some(),
            "a component containing a separator must be refused"
        );
        assert!(super::component_fault("a\\b").is_some());
        // A control character, which is not a separator.
        assert!(
            super::component_fault("a\nb").is_some(),
            "a control character must be refused even though it is not a separator"
        );
        assert!(super::component_fault("a\tb").is_some());
        // And an ordinary name is still fine, or the check would refuse the world.
        assert!(super::component_fault("libc.so.6").is_none());
    }

    /// `""` and `"."` contribute NO depth. Delete that arm and they count as
    /// real components, so an escape that leans on them stops being detected —
    /// `./..` climbs out of the export root while looking like it went nowhere.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn empty_and_dot_components_add_no_depth_to_the_escape_check() {
        let r = super::resolve_link_target("m", "./..", "/opt/poky", "/opt/sdk");
        assert!(
            r.is_err(),
            "`./..` climbs above the export root and must be refused, got {r:?}"
        );
        // `.//..` is still one step above the root — the empty and dot
        // components must contribute nothing. (`a//./..` is NOT an escape: it
        // resolves to `a/..`, which lands back at the root, and asserting
        // otherwise was my error, caught by this test failing.)
        let r = super::resolve_link_target("m", ".//..", "/opt/poky", "/opt/sdk");
        assert!(r.is_err(), "empty and dot components must not fund a climb");
    }

    /// The ABSOLUTE branch walks its remainder too, and the two mutants that
    /// survived my first attempt were there — I tested the relative branch and
    /// assumed it covered both. Being under the build prefix is not the same as
    /// staying under it: `<built>/../../tmp/x` starts with the prefix and lands
    /// outside the export, which is the hole this walk was added to close.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn an_absolute_target_under_the_prefix_is_walked_not_merely_prefix_matched() {
        let built = "/opt/poky";
        // Empty and dot components contribute NO depth, so a climb that leans
        // on them is still a climb.
        for target in ["/opt/poky/./..", "/opt/poky/.//..", "/opt/poky/../.."] {
            assert!(
                super::resolve_link_target("m", target, built, "/opt/sdk").is_err(),
                "{target} climbs out of the export root and must be refused"
            );
        }
        // …and stepping down and back up is NOT an escape, so the test is
        // `depth < 0` rather than `<= 0`. A real SDK is full of these.
        let (t, _) = super::resolve_link_target("m", "/opt/poky/lib/..", built, "/opt/sdk")
            .expect("returning to the root stays inside it");
        assert_eq!(t, "/opt/sdk/lib/..");
        super::resolve_link_target("m", "/opt/poky/usr/../lib/libc.so", built, "/opt/sdk")
            .expect("an ordinary absolute SDK symlink must not be refused");
    }

    /// The escape test is `depth < 0`, not `<= 0`. Relaxed, a link that steps
    /// down and back up to the root — `lib/../lib` and its kin, which are
    /// everywhere in a real SDK — is refused as an escape and the export fails
    /// on a correct tree.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn returning_to_the_root_is_not_an_escape() {
        let (target, _) = super::resolve_link_target("m", "a/..", "/opt/poky", "/opt/sdk")
            .expect("stepping down and back up stays inside the root");
        assert_eq!(target, "a/..");
        super::resolve_link_target("m", "lib/../lib/libc.so", "/opt/poky", "/opt/sdk")
            .expect("a normal SDK symlink must not be refused");
        // One step further out IS an escape.
        assert!(super::resolve_link_target("m", "a/../..", "/opt/poky", "/opt/sdk").is_err());
    }

    /// The neighbouring string must survive byte-for-byte.
    ///
    /// Every arithmetic mutant in `relocate_bytes` — the `== 0` that finds the
    /// previous NUL, the `p + 1` that steps past it, the `hit + p` that finds
    /// the terminator, the `pad_end - start` that measures capacity — preserves
    /// the file's LENGTH while moving where the patch lands. Asserting on
    /// length and on counts cannot see any of them; only the bytes can. The
    /// mutation gate found seven survivors here, and this is what they had in
    /// common.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn patching_one_string_leaves_the_string_before_it_untouched() {
        // Two NUL-terminated strings. The prefix appears mid-way through the
        // SECOND, so `start` has to be found by walking back to the previous
        // NUL — not by starting at the occurrence, and not by running into the
        // first string.
        let mut buf = b"KEEP-ME-EXACTLY".to_vec();
        let head = buf.len();
        let field = format!("LD_LIBRARY_PATH={BUILT}/sysroots/lib");
        buf.extend_from_slice(&nul_field(&field, field.len() + 1 + SLACK));

        let r = relocate_bytes("libc.so", &buf, BUILT, "/opt/sdk").unwrap();

        assert_eq!(r.bytes.len(), buf.len(), "in-place patch preserves length");
        assert_eq!(
            &r.bytes[..head],
            b"KEEP-ME-EXACTLY\0",
            "the preceding string was corrupted — `start` walked past its own \
             string boundary"
        );
        let patched = &r.bytes[head..];
        let text = &patched[..patched.iter().position(|b| *b == 0).unwrap()];
        assert_eq!(
            text,
            b"LD_LIBRARY_PATH=/opt/sdk/sysroots/lib",
            "the patched field is wrong: {}",
            String::from_utf8_lossy(text)
        );
        assert!(
            patched[text.len()..].iter().all(|b| *b == 0),
            "everything past the terminator must be NUL padding"
        );
        assert_eq!(r.fields, 1);
    }

    /// A prefix occurrence with NO terminator after it is not a field that can
    /// be padded, so relocation steps over it. The cursor advance in that
    /// branch had no test at all: leave it un-advanced and the same occurrence
    /// is found forever.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn an_unterminated_occurrence_is_stepped_over_rather_than_scanned_forever() {
        // NUL first so the member is treated as a binary, then the prefix
        // running to the end of the buffer with nothing to terminate it.
        let mut buf = vec![0u8];
        buf.extend_from_slice(BUILT.as_bytes());

        let r = relocate_bytes("weird.bin", &buf, BUILT, "/opt/sdk").unwrap();
        assert_eq!(
            r.fields, 0,
            "an unterminated occurrence is not a padded field and must not be patched"
        );
        assert_eq!(r.bytes, buf, "and nothing about it may be rewritten");
    }

    /// Capacity is `pad_end - start`, and it decides whether a destination
    /// FITS. Getting it wrong does not corrupt anything visibly — it accepts a
    /// path that does not fit, or refuses one that does, and the SDK breaks
    /// later on someone else's machine.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn capacity_is_measured_from_the_string_start_not_from_the_occurrence() {
        // A field whose string begins BEFORE the prefix occurrence. If capacity
        // were measured from the occurrence rather than the string start, this
        // would appear to have more room than it has.
        let field = format!("PATH={BUILT}");
        // A PRECEDING string, so `start` is non-zero. With start == 0,
        // `pad_end - start` and `pad_end + start` are the same number and the
        // capacity arithmetic cannot be observed at all — which is why the
        // first version of this test left that mutant alive.
        let head = b"PRECEDING\0";
        let mut buf = head.to_vec();
        // Exactly enough room for the string, its NUL, and nothing else.
        buf.extend_from_slice(&nul_field(&field, field.len() + 1));

        // A destination the same length as the built prefix always fits.
        let same = "/x".repeat(BUILT.len() / 2);
        let r = relocate_bytes("x", &buf, BUILT, &same).unwrap();
        assert_eq!(r.bytes.len(), buf.len());

        // One byte longer than the built prefix does NOT fit in a field with
        // no slack, and must be refused rather than truncated.
        let longer = format!("{same}Z");
        let err = relocate_bytes("x", &buf, BUILT, &longer).unwrap_err();
        let msg = err.to_string();
        // The refusal names both numbers, which is what makes it actionable —
        // and what pins the capacity arithmetic: a wrongly-measured field
        // would report a different pair.
        assert!(
            msg.contains(&format!("needs {} bytes", field.len() + 2)),
            "must say how much the destination needs: {msg}"
        );
        assert!(
            msg.contains(&format!("the field holds {}", buf.len() - head.len())),
            "the field is measured from the STRING START, not from the buffer \
             start — a capacity that included the preceding string would accept \
             a destination that does not fit and overrun the field: {msg}"
        );
        assert!(
            msg.contains(&format!("at offset {}", head.len())),
            "and the offset reported is the string start: {msg}"
        );
    }

    /// `find_sub` guards with `haystack.len() < needle.len()`. Relaxed to
    /// `<=`, a needle that is exactly the whole haystack stops being found —
    /// and a prefix that fills its field entirely is the realistic case, since
    /// the built prefix is padded to be as long as the field allows.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_needle_exactly_as_long_as_the_haystack_is_still_found() {
        assert_eq!(super::find_sub(b"abc", b"abc", 0), Some(0));
        assert_eq!(super::find_sub(b"abc", b"abcd", 0), None);
        assert_eq!(super::find_sub(b"xabc", b"abc", 0), Some(1));
        // And the `from` cursor is respected rather than ignored.
        assert_eq!(super::find_sub(b"abcabc", b"abc", 1), Some(3));
        assert_eq!(super::find_sub(b"abc", b"", 0), None);
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_nul_padded_field_is_patched_in_place_and_the_file_length_is_preserved() {
        // The heart of relocate_sdk.py: the field is opened "r+b" and written
        // over, so every offset in the binary stays valid. A rewrite that
        // changed the length would relocate the SDK and corrupt the ELF.
        let original = fake_binary();
        let r = relocate_bytes("gcc", &original, BUILT, "/opt/sdk").unwrap();
        assert_eq!(
            r.bytes.len(),
            original.len(),
            "an in-place patch must not change the file's length"
        );
        assert_eq!(r.fields, 2, "both path fields patched");
        assert_eq!(r.substitutions, 0, "a binary is patched, never sed'ed");

        // The new path is there, NUL-terminated, and the old one is gone.
        let text = String::from_utf8_lossy(&r.bytes).into_owned();
        assert!(text.contains("/opt/sdk/sysroots/x86_64/lib/ld-linux.so.2"));
        assert!(
            !text.contains(BUILT),
            "the build-time prefix must not survive relocation: {text:?}"
        );
        // The slack really is NUL, not leftover bytes of the old path — a
        // truncating rewrite leaves the tail of the old path behind and execs
        // something that does not exist.
        let width = interp().len() + SLACK;
        let patched = &r.bytes[4..4 + width];
        let end = patched.iter().position(|b| *b == 0).unwrap();
        assert_eq!(
            &patched[..end],
            b"/opt/sdk/sysroots/x86_64/lib/ld-linux.so.2"
        );
        assert!(
            patched[end..].iter().all(|b| *b == 0),
            "the field must be re-padded with NUL"
        );
        // The trailer past the fields is untouched.
        assert!(r.bytes.ends_with(b"trailer\0"));
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_field_too_small_for_the_new_path_is_refused_rather_than_truncated() {
        // The script's own guard, transcribed: `len(new) >= p_filesz` fails.
        // A truncated interpreter path is a binary that cannot exec with
        // nothing at all to point at, so this must never silently succeed.
        // Field width 20 holds "/opt/a/ld.so" plus padding; "/opt/aaaaaaaaaa"
        // is longer than the prefix but the destination check is bypassed here
        // to reach the field guard directly.
        let bytes = nul_field("/opt/a/ld.so", 14);
        // 13 characters of path + terminator == 14: the last width that fits.
        let ok = relocate_bytes("x", &bytes, "/opt/a", "/opt/ab").unwrap();
        assert_eq!(ok.fields, 1);
        assert_eq!(ok.bytes.len(), bytes.len());
        // One more character and it does not.
        let err = relocate_bytes("libc.so", &bytes, "/opt/a", "/opt/abc").unwrap_err();
        match err {
            SdkExportError::FieldTooSmall {
                member,
                needed,
                capacity,
                ..
            } => {
                assert_eq!(member, "libc.so", "the refusal must name the FILE");
                assert_eq!(capacity, 14);
                assert_eq!(needed, 15);
            }
            other => panic!("expected FieldTooSmall, got {other}"),
        }
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_text_file_is_substituted_and_may_change_length() {
        // `toolchain-shar-relocate.sh` seds every text file, and
        // `environment-setup-*` is the one that matters: it is SOURCED, and a
        // stale SYSROOT in it silently builds against the wrong headers.
        let original = env_setup();
        let r = relocate_bytes("environment-setup", &original, BUILT, "/opt/sdk").unwrap();
        assert_eq!(r.fields, 0, "a text file has no fixed-size field");
        assert_eq!(r.substitutions, 3, "every occurrence, not just the first");
        let text = String::from_utf8(r.bytes).unwrap();
        assert!(text.contains("export SDKTARGETSYSROOT=/opt/sdk/sysroots/aarch64"));
        assert!(text.contains("--sysroot=/opt/sdk/sysroots/aarch64"));
        assert!(!text.contains(BUILT));
        assert!(
            text.len() < original.len(),
            "a text rewrite is free to change length"
        );
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn the_whole_synthetic_tree_lands_relocated_and_the_source_bytes_are_untouched() {
        // Clause 3 end to end, and clause 2 alongside it: what the producer
        // signed is not what the export contains, and varve never records a
        // post-relocation digest — the relocator stays outside the trust path.
        let tmp = tempfile::tempdir().unwrap();
        let out = tmp.path().join("sdk");
        let members = synthetic_sdk();
        let signed_binary = fake_binary();

        let report = export_members(&members, BUILT, &out).unwrap();
        // `dirs` was the one field this assertion block never checked, so
        // `report.dirs += 1` survived mutation as `*= 1` — the counter stuck at
        // zero while every directory was still created. A report is evidence:
        // "created 0 directories" and "created 40 000" look identical on disk,
        // which is what the struct's own doc comment says.
        let expected_dirs = members
            .iter()
            .filter(|m| matches!(m.body, MemberBody::Dir))
            .count();
        assert!(
            expected_dirs > 0,
            "the fixture must contain directories or this asserts nothing"
        );
        assert_eq!(
            report.dirs, expected_dirs,
            "every directory in the tree is created AND counted"
        );
        assert_eq!(report.files, 2);
        assert_eq!(report.symlinks, 1);
        assert_eq!(report.relocated_symlinks, 1);
        assert_eq!(report.patched_fields, 2);
        assert_eq!(report.substitutions, 3);

        let gcc = out.join("sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc");
        let on_disk = std::fs::read(&gcc).unwrap();
        assert_eq!(on_disk.len(), signed_binary.len(), "in-place patch");
        assert_ne!(
            on_disk, signed_binary,
            "the relocated bytes are NOT the signed bytes — which is exactly why \
             the store keeps the archive and verify never hashes the export"
        );
        assert!(!String::from_utf8_lossy(&on_disk).contains(BUILT));

        // The internal absolute symlink now points inside the export.
        #[cfg(unix)]
        {
            let link = out.join("sysroots/x86_64/usr/bin/cc");
            let target = std::fs::read_link(&link).unwrap();
            assert_eq!(target, gcc, "an SDK-internal link follows the SDK");
        }
        // The directory member is a directory.
        assert!(out.join("sysroots").is_dir());
        // And the members handed in are untouched: nothing wrote back.
        assert_eq!(members, synthetic_sdk());
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_member_whose_path_escapes_the_export_is_refused_and_nothing_is_written() {
        // Every component of every member gets the treatment a single payload
        // name gets in the store. A tree has thousands, and one is enough.
        let tmp = tempfile::tempdir().unwrap();
        let out = tmp.path().join("sdk");
        for bad in [
            "../../evil",
            "/etc/passwd",
            "a/../../evil",
            "a//b",
            "a/./b",
            "",
            "..",
        ] {
            let members = vec![
                Member {
                    path: "good".into(),
                    body: MemberBody::File {
                        mode: 0o644,
                        bytes: b"good".to_vec(),
                    },
                },
                Member {
                    path: bad.into(),
                    body: MemberBody::File {
                        mode: 0o644,
                        bytes: b"evil".to_vec(),
                    },
                },
            ];
            let err = export_members(&members, BUILT, &out).unwrap_err();
            assert!(
                matches!(err, SdkExportError::UnsafeMember { .. }),
                "member {bad:?} must be refused, got {err}"
            );
            // A partially written tree must not be possible: the good member
            // did not land either.
            assert!(
                !out.join("good").exists(),
                "member {bad:?}: the tree must be refused whole"
            );
        }
        // …and safe paths that merely look unusual still work.
        assert!(safe_member_path("a/b/c").is_ok());
        assert!(safe_member_path("a/b/").is_ok());
        assert_eq!(safe_member_path("a/b/").unwrap(), "a/b");
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_symlink_that_leaves_the_export_is_refused_even_though_every_component_is_safe() {
        // The escape a per-component check cannot see. `link` is a fine name
        // and `link/pwned` is a fine path; the escape is the LINK's target.
        let tmp = tempfile::tempdir().unwrap();
        let out = tmp.path().join("sdk");
        let outside = tmp.path().join("OUTSIDE");
        std::fs::create_dir_all(&outside).unwrap();

        // 1. an absolute link to the host, under no prefix varve relocates.
        let err = export_members(
            &[Member {
                path: "bin/link".into(),
                body: MemberBody::Symlink {
                    target: outside.to_string_lossy().into_owned(),
                },
            }],
            BUILT,
            &out,
        )
        .unwrap_err();
        assert!(
            matches!(err, SdkExportError::SymlinkEscapes { .. }),
            "got {err}"
        );

        // 2. a relative link that climbs out of the export root.
        let err = export_members(
            &[Member {
                path: "bin/link".into(),
                body: MemberBody::Symlink {
                    target: "../../OUTSIDE".into(),
                },
            }],
            BUILT,
            &out,
        )
        .unwrap_err();
        assert!(
            matches!(err, SdkExportError::SymlinkEscapes { .. }),
            "got {err}"
        );

        // 2b. absolute, UNDER the build prefix, climbing out with `..`.
        //     The branch that re-points an SDK's own internal absolute links
        //     stripped the prefix and re-pointed the remainder WITHOUT walking
        //     it, so this shape was accepted and reported as "1 symlink(s)
        //     re-pointed" — exit 0. Found by clean-room review, reproduced
        //     end to end through the release binary. The relative branch below
        //     had always walked its target; only this one did not.
        let err = export_members(
            &[Member {
                path: "bin/link".into(),
                body: MemberBody::Symlink {
                    target: format!("{BUILT}/../../../../../../../../tmp/varve-pwned"),
                },
            }],
            BUILT,
            &out,
        )
        .unwrap_err();
        assert!(
            matches!(err, SdkExportError::SymlinkEscapes { .. }),
            "got {err}"
        );

        // …while `..` that stays INSIDE the export is ordinary and must still
        // work, or the fix would just be a ban on `..`.
        let ok = export_members(
            &[
                Member {
                    path: "lib/sub/link".into(),
                    body: MemberBody::Symlink {
                        target: format!("{BUILT}/lib/sub/../real"),
                    },
                },
                Member {
                    path: "lib/real".into(),
                    body: MemberBody::File {
                        bytes: b"x".to_vec(),
                        mode: 0o644,
                    },
                },
            ],
            BUILT,
            &out,
        )
        .expect("`..` inside the export is legal");
        assert_eq!(ok.relocated_symlinks, 1);

        // 3. …and the pair that is the actual CVE class: a link out, then a
        //    write THROUGH it. Refused as a pair — neither member is unsafe on
        //    its own, and the tar order does not decide it.
        let err = export_members(
            &[
                Member {
                    path: "bin/link".into(),
                    body: MemberBody::Symlink {
                        target: "../lib".into(),
                    },
                },
                Member {
                    path: "bin/link/pwned".into(),
                    body: MemberBody::File {
                        mode: 0o644,
                        bytes: b"PWNED".to_vec(),
                    },
                },
            ],
            BUILT,
            &out,
        )
        .unwrap_err();
        assert!(
            matches!(err, SdkExportError::WriteThroughSymlink { .. }),
            "got {err}"
        );

        assert!(
            std::fs::read_dir(&outside).unwrap().next().is_none(),
            "nothing may be written outside the export"
        );
        assert!(!out.join("bin/link").exists(), "nothing written at all");

        // A relative link INSIDE the tree is ordinary and must still work.
        let ok = export_members(
            &[
                Member {
                    path: "lib/libc.so.6".into(),
                    body: MemberBody::File {
                        mode: 0o644,
                        bytes: b"libc".to_vec(),
                    },
                },
                Member {
                    path: "bin/libc".into(),
                    body: MemberBody::Symlink {
                        target: "../lib/libc.so.6".into(),
                    },
                },
            ],
            BUILT,
            &out,
        )
        .unwrap();
        assert_eq!(ok.symlinks, 1);
        assert_eq!(
            ok.relocated_symlinks, 0,
            "a relative link needs no patching"
        );
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn two_members_claiming_one_path_are_refused_before_anything_is_written() {
        // The same invariant `Store::lay_down_payloads` holds, for a tree: the
        // survivor of a silent overwrite carries the wrong bytes under the
        // right name, and nothing downstream can tell.
        let tmp = tempfile::tempdir().unwrap();
        let out = tmp.path().join("sdk");
        let err = export_members(
            &[
                Member {
                    path: "bin/gcc".into(),
                    body: MemberBody::File {
                        mode: 0o755,
                        bytes: b"first".to_vec(),
                    },
                },
                Member {
                    path: "bin/gcc".into(),
                    body: MemberBody::File {
                        mode: 0o755,
                        bytes: b"second".to_vec(),
                    },
                },
            ],
            BUILT,
            &out,
        )
        .unwrap_err();
        assert!(matches!(err, SdkExportError::Collision { .. }), "got {err}");
        assert!(!out.join("bin/gcc").exists());
    }

    /// The synthetic SDK as a gzip tar, the shape a producer actually signs.
    fn synthetic_tarball() -> Vec<u8> {
        use std::io::Write;
        let mut tar_bytes = Vec::new();
        {
            let mut b = tar::Builder::new(&mut tar_bytes);
            let mut dir = tar::Header::new_gnu();
            dir.set_entry_type(tar::EntryType::Directory);
            dir.set_size(0);
            dir.set_mode(0o755);
            b.append_data(&mut dir, "sysroots/", std::io::empty())
                .unwrap();

            let bin = fake_binary();
            let mut f = tar::Header::new_gnu();
            f.set_size(bin.len() as u64);
            f.set_mode(0o755);
            b.append_data(
                &mut f,
                "sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc",
                bin.as_slice(),
            )
            .unwrap();

            let env = env_setup();
            let mut t = tar::Header::new_gnu();
            t.set_size(env.len() as u64);
            t.set_mode(0o644);
            b.append_data(
                &mut t,
                "environment-setup-aarch64-poky-linux",
                env.as_slice(),
            )
            .unwrap();

            let mut link = tar::Header::new_gnu();
            link.set_entry_type(tar::EntryType::Symlink);
            link.set_size(0);
            link.set_mode(0o777);
            b.append_link(
                &mut link,
                "sysroots/x86_64/usr/bin/cc",
                format!("{BUILT}/sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc"),
            )
            .unwrap();
            b.finish().unwrap();
        }
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        gz.write_all(&tar_bytes).unwrap();
        gz.finish().unwrap()
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_signed_archive_unpacks_and_relocates_and_the_archive_is_never_modified() {
        // Clause 1 and 2 together, on the bytes a producer signs: the store
        // holds ONE blob with ONE digest — which is what makes an sdk payload
        // hold like any other, and what lets `verify` and `archive` keep
        // hashing a single file — and the tree exists only in the export.
        let tmp = tempfile::tempdir().unwrap();
        let out = tmp.path().join("sdk");
        let archive = synthetic_tarball();
        let before = archive.clone();

        let report = export_sdk(&archive, BUILT, &out).unwrap();
        assert_eq!(report.files, 2);
        assert_eq!(report.symlinks, 1);
        assert_eq!(report.patched_fields, 2);
        assert_eq!(report.substitutions, 3);
        assert_eq!(archive, before, "the signed archive is read-only, always");

        let gcc = out.join("sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc");
        assert!(!String::from_utf8_lossy(&std::fs::read(&gcc).unwrap()).contains(BUILT));
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(
                std::fs::metadata(&gcc).unwrap().permissions().mode() & 0o777,
                0o755,
                "a compiler must survive the export executable"
            );
        }
        // A plain (uncompressed) tar is equally acceptable — an SDK ships as
        // either, and guessing from the file name is one more thing to get
        // wrong.
        let mut plain = Vec::new();
        flate2::read::GzDecoder::new(archive.as_slice())
            .read_to_end(&mut plain)
            .unwrap();
        let out2 = tmp.path().join("sdk2");
        assert_eq!(export_sdk(&plain, BUILT, &out2).unwrap(), report);
    }

    // rivet: verifies REQ-SDK-001
    #[test]
    fn an_archive_member_that_escapes_is_refused_before_the_tree_is_written() {
        // The tar crate's own `unpack` sanitises; this path does not use it,
        // so the refusal has to be ours and has to be tested as ours.
        use std::io::Write;
        let mut tar_bytes = Vec::new();
        {
            let mut b = tar::Builder::new(&mut tar_bytes);
            let mut f = tar::Header::new_gnu();
            let payload = b"PWNED";
            f.set_size(payload.len() as u64);
            f.set_mode(0o644);
            // The name is written into the header DIRECTLY: `set_path` refuses
            // `..` itself, and an archive built by other software is under no
            // obligation to have used it. The refusal has to be varve's.
            {
                let gnu = f.as_gnu_mut().unwrap();
                let name = b"../../escape";
                gnu.name[..name.len()].copy_from_slice(name);
            }
            f.set_cksum();
            b.append(&f, &payload[..]).unwrap();
            b.finish().unwrap();
        }
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        gz.write_all(&tar_bytes).unwrap();
        let evil = gz.finish().unwrap();

        let tmp = tempfile::tempdir().unwrap();
        let err = export_sdk(&evil, BUILT, &tmp.path().join("sdk")).unwrap_err();
        assert!(
            matches!(err, SdkExportError::UnsafeMember { .. }),
            "got {err}"
        );
        assert!(!tmp.path().join("escape").exists());
        // Bytes that are not an archive at all are a distinct, named failure —
        // not a silent empty export.
        assert!(matches!(
            export_sdk(b"\x1f\x8bnot really gzip", BUILT, &tmp.path().join("s2")),
            Err(SdkExportError::Archive(_))
        ));
    }
}

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

    /// Build a real xz stream with the system `xz`, so this is not a fixture
    /// that agrees with my own encoder.
    fn xz(bytes: &[u8]) -> Option<Vec<u8>> {
        use std::io::Write;
        let mut c = std::process::Command::new("xz")
            .args(["-c", "-0"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .spawn()
            .ok()?;
        c.stdin.as_mut()?.write_all(bytes).ok()?;
        let out = c.wait_with_output().ok()?;
        out.status.success().then_some(out.stdout)
    }

    /// Every wasmtime archive and all 140 Zephyr SDK toolchains are .tar.xz.
    /// Before this, `decompress` passed them through as though they were plain
    /// tar and the caller reported "not a readable tar archive" — a message
    /// that sends a reader looking for a corrupt download.
    // rivet: verifies REQ-SDKDEPOSIT-001
    #[test]
    fn an_xz_payload_is_decoded() {
        let plain = b"the tar bytes, near enough for a decoder test".repeat(40);
        let Some(compressed) = xz(&plain) else {
            eprintln!("system xz unavailable; skipping");
            return;
        };
        assert!(compressed.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]));
        assert_ne!(compressed, plain, "the fixture is not actually compressed");
        let out = decompress(&compressed).expect("xz must decode");
        assert_eq!(out.as_ref(), plain.as_slice());
    }

    // rivet: verifies REQ-SDKDEPOSIT-001
    #[test]
    fn gzip_and_plain_tar_still_work() {
        use std::io::Write;
        let plain = b"still a tar".repeat(30);
        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        enc.write_all(&plain).unwrap();
        let gz = enc.finish().unwrap();
        assert_eq!(decompress(&gz).unwrap().as_ref(), plain.as_slice());
        assert_eq!(decompress(&plain).unwrap().as_ref(), plain.as_slice());
    }

    /// A compression varve cannot decode must SAY so. Left to fall through, a
    /// bzip2 payload reaches the tar parser and reports "not a readable tar
    /// archive", which is true and useless: the download is fine and the
    /// decoder is missing.
    // rivet: verifies REQ-SDKDEPOSIT-001
    #[test]
    fn a_compression_varve_cannot_decode_names_itself() {
        let mut bz = b"BZh9".to_vec();
        bz.extend_from_slice(&[0x31, 0x41, 0x59, 0x26, 0x53, 0x59]);
        let e = decompress(&bz).expect_err("must refuse");
        let msg = e.to_string();
        assert!(msg.contains("bzip2"), "{msg}");
        assert!(msg.contains("what is missing is a decoder"), "{msg}");
    }

    /// Truncated xz must fail, not yield a short tree. The bytes are
    /// digest-verified before they reach here, so this is a decoder-integrity
    /// check rather than a trust one — but a decoder that returns partial
    /// output on truncation would hand `export_members` an SDK missing files.
    // rivet: verifies REQ-SDKDEPOSIT-001
    #[test]
    fn a_truncated_xz_stream_is_an_error_not_a_short_tree() {
        let plain = b"a payload long enough to span blocks".repeat(200);
        let Some(compressed) = xz(&plain) else { return };
        let cut = &compressed[..compressed.len() / 2];
        assert!(
            decompress(cut).is_err(),
            "a truncated stream decoded anyway"
        );
    }

    /// A minimal ELF file with real section headers holding a glibc loader's
    /// `.sysdirs` (paths packed back to back) and `.sysdirslen` (each path's
    /// length) — the layout measured in the Yocto-built
    /// `ld-linux-x86-64.so.2` of the Zephyr SDK 1.0.1 host tools — in either
    /// class and either byte order.
    fn loader(
        dirs: &[&str],
        sysdirs_size: usize,
        class64: bool,
        little: bool,
    ) -> (Vec<u8>, usize, usize) {
        let word = if class64 { 8 } else { 4 };
        let put = |v: &mut Vec<u8>, at: usize, n: usize, x: u64| {
            let b = if little {
                x.to_le_bytes()
            } else {
                x.to_be_bytes()
            };
            let b = if little { &b[..n] } else { &b[8 - n..] };
            v[at..at + n].copy_from_slice(b);
        };
        let shstrtab = b"\0.shstrtab\0.sysdirslen\0.sysdirs\0".to_vec();
        let mut packed = Vec::new();
        for d in dirs {
            packed.extend_from_slice(d.as_bytes());
            packed.push(0);
        }
        packed.resize(sysdirs_size, 0);
        let mut lens = vec![0u8; dirs.len() * word];
        for (i, d) in dirs.iter().enumerate() {
            put(&mut lens, i * word, word, d.len() as u64);
        }

        let mut v = vec![0u8; 64];
        v[..4].copy_from_slice(b"\x7fELF");
        v[4] = if class64 { 2 } else { 1 };
        v[5] = if little { 1 } else { 2 };
        v[6] = 1;
        let shstr_off = v.len();
        v.extend_from_slice(&shstrtab);
        let lens_off = v.len();
        v.extend_from_slice(&lens);
        let sys_off = v.len();
        v.extend_from_slice(&packed);
        let shoff = v.len();
        let entsize = if class64 { 64 } else { 40 };
        for (name, off, size) in [
            (0u64, 0usize, 0usize),
            (1, shstr_off, shstrtab.len()),
            (11, lens_off, lens.len()),
            (23, sys_off, packed.len()),
        ] {
            let mut h = vec![0u8; entsize];
            put(&mut h, 0, 4, name);
            put(&mut h, 8 + 2 * word, word, off as u64);
            put(&mut h, 8 + 3 * word, word, size as u64);
            v.extend_from_slice(&h);
        }
        let (shoff_at, ent_at) = if class64 { (0x28, 0x3A) } else { (0x20, 0x2E) };
        put(&mut v, shoff_at, word, shoff as u64);
        put(&mut v, ent_at, 2, entsize as u64);
        put(&mut v, ent_at + 2, 2, 4);
        put(&mut v, ent_at + 4, 2, 1);
        (v, lens_off, sys_off)
    }

    fn loader_with_sysdirs(dirs: &[&str], sysdirs_size: usize) -> (Vec<u8>, usize, usize) {
        loader(dirs, sysdirs_size, true, true)
    }

    fn read_len(b: &[u8], at: usize, width: usize, little: bool) -> u64 {
        let mut buf = [0u8; 8];
        if little {
            buf[..width].copy_from_slice(&b[at..at + width]);
            u64::from_le_bytes(buf)
        } else {
            buf[8 - width..].copy_from_slice(&b[at..at + width]);
            u64::from_be_bytes(buf)
        }
    }

    const ZBUILT: &str = "/usr/local/oe-sdk-hardcoded-buildpath";
    const ZDIRS: [&str; 2] = [
        "/usr/local/oe-sdk-hardcoded-buildpath/sysroots/x86_64-pokysdk-linux/lib/",
        "/usr/local/oe-sdk-hardcoded-buildpath/sysroots/x86_64-pokysdk-linux/usr/lib/",
    ];

    /// Every class and byte order a loader can have gets the same rewrite,
    /// with lengths in its own word size and byte order.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn sysdirs_are_rewritten_for_every_class_and_byte_order() {
        for (class64, little) in [(true, true), (true, false), (false, true), (false, false)] {
            let (elf, lens_off, sys_off) = loader(&ZDIRS, 512, class64, little);
            let r = relocate_bytes("ld.so", &elf, ZBUILT, "/opt/s").unwrap();
            let width = if class64 { 8 } else { 4 };
            let want = [
                "/opt/s/sysroots/x86_64-pokysdk-linux/lib/",
                "/opt/s/sysroots/x86_64-pokysdk-linux/usr/lib/",
            ];
            assert_eq!(
                (
                    read_len(&r.bytes, lens_off, width, little),
                    read_len(&r.bytes, lens_off + width, width, little)
                ),
                (want[0].len() as u64, want[1].len() as u64),
                "class64={class64} little={little}"
            );
            let got = &r.bytes[sys_off..sys_off + want[0].len()];
            assert_eq!(got, want[0].as_bytes(), "class64={class64} little={little}");
            assert_eq!(r.fields, 2, "two table entries, nothing else in this file");
        }
    }

    /// The table is rewritten as a table and EVERYTHING ELSE in the file still
    /// gets the per-string patch — a real loader also carries its own
    /// interpreter path, which must move with the SDK.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_prefix_outside_the_table_is_still_patched() {
        let (mut elf, _, sys_off) = loader(&ZDIRS, 512, true, true);
        let tail = elf.len();
        elf.extend_from_slice(b"/usr/local/oe-sdk-hardcoded-buildpath/lib/ld.so\0\0\0\0");
        let r = relocate_bytes("ld.so", &elf, ZBUILT, "/opt/s").unwrap();
        assert_eq!(r.fields, 3, "two table entries and the trailing path");
        assert_eq!(&r.bytes[tail..tail + 17], b"/opt/s/lib/ld.so\0");
        assert!(sys_off < tail);
    }

    /// A table that exactly fills its section is not too big; one byte more is.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_table_that_exactly_fills_its_section_fits_and_one_byte_more_does_not() {
        let dest = "/opt/s";
        let exact: usize = ZDIRS
            .iter()
            .map(|d| d.len() - ZBUILT.len() + dest.len() + 1)
            .sum();
        // The ORIGINAL table must fit too, so size the section for it and
        // relocate to a destination that grows the table to exactly `size`.
        let size = ZDIRS.iter().map(|d| d.len() + 1).sum::<usize>();
        let grow = (size - exact) / 2 + dest.len();
        let longer = format!("/{}", "x".repeat(grow - 1));
        let (elf, _, _) = loader(&ZDIRS, size, true, true);
        let fits = relocate_bytes("ld.so", &elf, ZBUILT, &longer).expect("exactly fills");
        assert_eq!(fits.fields, 2);
        let over = format!("{longer}y");
        let err = relocate_bytes("ld.so", &elf, ZBUILT, &over).unwrap_err();
        assert!(matches!(err, SdkExportError::FieldTooSmall { .. }), "{err}");
    }

    /// Something that merely starts like an ELF, or is shorter than a header,
    /// is patched as a plain binary rather than read past its end.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_truncated_elf_is_not_read_past_its_end() {
        let mut short = b"\x7fELF\x02\x01".to_vec();
        short.extend_from_slice(b"/usr/local/oe-sdk-hardcoded-buildpath/lib\0\0\0");
        let r = relocate_bytes("x", &short, ZBUILT, "/opt/s").unwrap();
        assert_eq!(r.fields, 1);
        let tiny = b"\x7fE\0".to_vec();
        assert!(relocate_bytes("x", &tiny, ZBUILT, "/opt/s").is_ok());
    }

    /// Reported against varve 0.39: an SDK exported to a path SHORTER than the
    /// one it was built under could not start its tools (`dtc`: "cannot read
    /// file data: Error 21"). varve shortened each SYSDIRS path in place and
    /// NUL-padded it, but left `.sysdirslen` alone, so ld.so stepped through
    /// the table by the OLD lengths, landed in the padding and opened a file
    /// with an empty name in the library directory. `relocate_sdk.py` repacks
    /// the paths and rewrites the lengths; so must varve.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn a_shorter_destination_repacks_sysdirs_and_rewrites_their_lengths() {
        let built = "/usr/local/oe-sdk-hardcoded-buildpath";
        let dirs = [
            "/usr/local/oe-sdk-hardcoded-buildpath/sysroots/x86_64-pokysdk-linux/lib/",
            "/usr/local/oe-sdk-hardcoded-buildpath/sysroots/x86_64-pokysdk-linux/usr/lib/",
        ];
        let (elf, lens_off, sys_off) = loader_with_sysdirs(&dirs, 4096);
        let r = relocate_bytes("lib/ld-linux-x86-64.so.2", &elf, built, "/opt/short").unwrap();
        assert_eq!(r.bytes.len(), elf.len());
        let want_a = "/opt/short/sysroots/x86_64-pokysdk-linux/lib/";
        let want_b = "/opt/short/sysroots/x86_64-pokysdk-linux/usr/lib/";
        let mut packed = format!("{want_a}\0{want_b}\0").into_bytes();
        packed.resize(4096, 0);
        assert_eq!(
            &r.bytes[sys_off..sys_off + 4096],
            &packed[..],
            "paths packed back to back"
        );
        let len = |i: usize| {
            u64::from_le_bytes(
                r.bytes[lens_off + 8 * i..lens_off + 8 * i + 8]
                    .try_into()
                    .unwrap(),
            )
        };
        assert_eq!((len(0), len(1)), (want_a.len() as u64, want_b.len() as u64));
    }

    /// The same length is the one case that always worked; it must still.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn an_equal_length_destination_leaves_the_lengths_equal() {
        let built = "/tmp/zephyr-sdk-1.0.1";
        let dirs = [
            "/tmp/zephyr-sdk-1.0.1/lib/",
            "/tmp/zephyr-sdk-1.0.1/usr/lib/",
        ];
        let (elf, lens_off, _) = loader_with_sysdirs(&dirs, 256);
        let r = relocate_bytes("ld.so", &elf, built, "/opt/zephyr-sdk-1.0.1").unwrap();
        let len0 = u64::from_le_bytes(r.bytes[lens_off..lens_off + 8].try_into().unwrap());
        assert_eq!(len0, dirs[0].len() as u64);
    }

    /// A `.sysdirs` without its `.sysdirslen` cannot be relocated correctly —
    /// the lengths live somewhere varve cannot see — so it refuses rather than
    /// produce a loader that opens empty file names.
    // rivet: verifies REQ-SDK-001
    #[test]
    fn sysdirs_without_their_lengths_refuse_a_change_of_length() {
        let built = "/tmp/zephyr-sdk-1.0.1";
        let dirs = ["/tmp/zephyr-sdk-1.0.1/lib/"];
        let (mut elf, _, _) = loader_with_sysdirs(&dirs, 128);
        // Rename `.sysdirslen` so it is no longer found.
        let at = elf.windows(11).position(|w| w == b".sysdirslen").unwrap();
        elf[at + 1] = b'X';
        let err = relocate_bytes("ld.so", &elf, built, "/opt/z").unwrap_err();
        assert!(err.to_string().contains(".sysdirslen"), "{err}");
    }
}