onelf 0.5.0

Packer CLI for creating onelf single-binary packages
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
//! ELF inspection and rewriting for bundled binaries: DT_NEEDED / PT_INTERP
//! parsing, libc-family detection, RUNPATH origin rewriting, loader-path and
//! Nix-store scrubbing, and bootstrap/interp injection.

use super::*;

pub(crate) fn parse_needed(path: &Path) -> io::Result<Vec<String>> {
    parse_needed_bytes(&fs::read(path)?)
}

/// DT_NEEDED sonames from already-read ELF bytes, so a caller that also
/// needs the raw bytes (e.g. the framework string scan) reads the file once.
pub(crate) fn parse_needed_bytes(data: &[u8]) -> io::Result<Vec<String>> {
    let elf = goblin::elf::Elf::parse(data)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
    // nixpkgs occasionally emits DT_NEEDED entries as absolute
    // `/nix/store/<hash>/lib/libfoo.so` paths rather than plain
    // sonames. Reduce those to their basename so our resolver can
    // find the lib on the host / search paths. `strip_absolute_needed`
    // rewrites the ELF's own DT_NEEDED string after bundling so the
    // runtime loader also picks up the bundled copy via RUNPATH.
    Ok(elf
        .libraries
        .iter()
        .map(|s| {
            if s.starts_with('/') {
                Path::new(s)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or(s)
                    .to_string()
            } else {
                s.to_string()
            }
        })
        .collect())
}

/// Directories named by absolute `DT_NEEDED` entries, mapped under `root`
/// when given. The walk searches by basename, so the directory such an
/// entry points at has to be on the search path for it to be found at
/// all; a toolchain linking a library by path with no soname writes one.
pub(crate) fn parse_needed_dirs_under(path: &Path, root: Option<&Path>) -> Vec<PathBuf> {
    let Ok(data) = fs::read(path) else {
        return Vec::new();
    };
    let Ok(elf) = goblin::elf::Elf::parse(&data) else {
        return Vec::new();
    };
    elf.libraries
        .iter()
        .filter(|s| s.starts_with('/'))
        .filter_map(|s| Path::new(s).parent().map(Path::to_path_buf))
        .map(|dir| match root {
            Some(root) => root.join(dir.strip_prefix("/").unwrap_or(&dir)),
            None => dir,
        })
        .collect()
}

/// Parse PT_INTERP from an ELF binary, returning the interpreter path.
///
/// goblin returns `p_filesz - 1` bytes verbatim, so a slot padded with
/// trailing NULs (common after our in-place PT_INTERP rewrite if the
/// phdr wasn't shrunk) would leak into callers as embedded NULs in
/// the returned string. Trim them so queue lookups and `file_name()`
/// behave correctly.
pub(crate) fn parse_interp(path: &Path) -> Option<String> {
    let data = fs::read(path).ok()?;
    let elf = goblin::elf::Elf::parse(&data).ok()?;
    elf.interpreter
        .map(|s| s.trim_end_matches('\0').to_string())
}

/// Whether `path` names itself with a `DT_SONAME`, as a shared library
/// does and an executable does not.
fn has_soname(path: &Path) -> bool {
    fs::read(path)
        .ok()
        .and_then(|data| {
            goblin::elf::Elf::parse(&data)
                .ok()
                .map(|elf| elf.soname.is_some())
        })
        .unwrap_or(true)
}

/// The loader an executable runs under: its `PT_INTERP`, or the one an
/// injected bootstrap carries.
///
/// The bootstrap injection turns `PT_INTERP` into the `PT_LOAD` holding
/// the bootstrap, so [`parse_interp`] finds nothing in a tree that was
/// bundled before. The executable is still one, and still bound to the
/// libc family of the loader the bootstrap names.
pub(crate) fn program_interp(path: &Path) -> Option<String> {
    let data = fs::read(path).ok()?;
    let elf = goblin::elf::Elf::parse(&data).ok()?;
    match elf.interpreter {
        Some(interp) => Some(interp.trim_end_matches('\0').to_string()),
        None => injected_interp(&data, &elf),
    }
}

/// The relative loader path an injected bootstrap carries, or `None` when
/// `elf` has no bootstrap.
///
/// [`inject_relative_interp`] points the entry at the start of a `PT_LOAD`
/// that ends with the path's `u16` length, the path, and a NUL. Reading
/// it from the end keeps the check independent of the bootstrap code,
/// which differs between onelf versions.
pub(crate) fn injected_interp(data: &[u8], elf: &goblin::elf::Elf) -> Option<String> {
    let seg = elf
        .program_headers
        .iter()
        .find(|p| p.p_type == goblin::elf::program_header::PT_LOAD && p.p_vaddr == elf.entry)?;
    let start = usize::try_from(seg.p_offset).ok()?;
    let end = start.checked_add(usize::try_from(seg.p_filesz).ok()?)?;
    let seg = data.get(start..end)?;
    let (&0, body) = seg.split_last()? else {
        return None;
    };
    (1..=body.len().saturating_sub(2).min(4096)).find_map(|len| {
        let at = body.len() - len;
        let recorded = u16::from_le_bytes([body[at - 2], body[at - 1]]);
        let path = &body[at..];
        if usize::from(recorded) != len || path.contains(&0) {
            return None;
        }
        let path = std::str::from_utf8(path).ok()?;
        is_dynamic_loader(Path::new(path).file_name()?.to_str()?).then(|| path.to_string())
    })
}

/// Map an ELF interpreter basename to the libc filename that serves it.
/// On musl, `ld-musl-<arch>.so.1` and `libc.musl-<arch>.so.1` are both
/// names for the same file. Returns None if no mapping is known.
pub(crate) fn libc_alias_for(interp_name: &str) -> Option<String> {
    interp_name
        .strip_prefix("ld-musl-")
        .map(|rest| format!("libc.musl-{rest}"))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LibcFamily {
    Musl,
    Glibc,
}

/// Detect a binary's libc family from its PT_INTERP basename.
pub(crate) fn libc_family_from_interp(interp: &str) -> Option<LibcFamily> {
    let name = Path::new(interp).file_name()?.to_str()?;
    if name.starts_with("ld-musl-") {
        Some(LibcFamily::Musl)
    } else if name.starts_with("ld-linux") {
        Some(LibcFamily::Glibc)
    } else {
        None
    }
}

/// The `DT_SONAME` of a shared object, the name its dependants use.
pub(crate) fn parse_soname(path: &Path) -> Option<String> {
    let data = fs::read(path).ok()?;
    let elf = goblin::elf::Elf::parse(&data).ok()?;
    elf.soname.map(String::from)
}

/// Map a soname to the libc family it belongs to, when known.
pub(crate) fn libc_family_of_soname(soname: &str) -> Option<LibcFamily> {
    if soname == "libc.so.6" || soname.starts_with("ld-linux") {
        Some(LibcFamily::Glibc)
    } else if soname.starts_with("libc.musl-")
        || soname.starts_with("ld-musl-")
        || soname == "libc.so"
    {
        // libc.so is musl's canonical libc filename; libc.musl-*/ld-musl-* are aliases.
        Some(LibcFamily::Musl)
    } else {
        None
    }
}

/// Parse RPATH and RUNPATH entries from an ELF binary.
/// Expand a single runpath entry, resolving `$ORIGIN` / `${ORIGIN}` to the
/// ELF's parent directory (the exact relative shape Nix and vendor binaries
/// emit). Non-`$ORIGIN` entries pass through unchanged.
pub(crate) fn expand_runpath_entry(entry: &str, origin: &Path) -> PathBuf {
    if let Some(rest) = entry.strip_prefix("${ORIGIN}") {
        origin.join(rest.trim_start_matches('/'))
    } else if let Some(rest) = entry.strip_prefix("$ORIGIN") {
        origin.join(rest.trim_start_matches('/'))
    } else {
        PathBuf::from(entry)
    }
}

/// Split colon-separated runpath strings into their component directories,
/// expand `$ORIGIN` relative to `origin`, and keep only those that exist.
#[cfg(test)]
pub(crate) fn resolve_runpath_dirs<'a>(
    raw: impl Iterator<Item = &'a str>,
    origin: &Path,
) -> Vec<PathBuf> {
    resolve_runpath_dirs_under(raw, origin, None)
}

/// As [`resolve_runpath_dirs`], with an absolute entry resolved as a path
/// inside `root` when one is given: a sysroot's binaries name the
/// sysroot's directories, which need not exist on the packer's machine.
pub(crate) fn resolve_runpath_dirs_under<'a>(
    raw: impl Iterator<Item = &'a str>,
    origin: &Path,
    root: Option<&Path>,
) -> Vec<PathBuf> {
    raw.flat_map(|s| s.split(':'))
        .filter(|s| !s.is_empty())
        .map(|entry| expand_runpath_entry(entry, origin))
        .filter_map(|dir| match root {
            Some(root) if dir.is_absolute() && !dir.starts_with(root) => {
                onelf_sysroot::path::in_root(root, &dir).ok()
            }
            _ => Some(dir),
        })
        .filter(|p| p.is_dir())
        .collect()
}

pub(crate) fn parse_rpaths(path: &Path) -> Vec<PathBuf> {
    parse_rpaths_under(path, None)
}

/// An ELF's run path entries as written, before `$ORIGIN` expansion or
/// any mapping. `DT_RUNPATH` when present, else `DT_RPATH`, matching what
/// the loader consults.
pub(crate) fn parse_rpaths_raw(path: &Path) -> Vec<String> {
    let Ok(data) = fs::read(path) else {
        return Vec::new();
    };
    let Ok(elf) = goblin::elf::Elf::parse(&data) else {
        return Vec::new();
    };
    let raw = if !elf.runpaths.is_empty() {
        &elf.runpaths
    } else {
        &elf.rpaths
    };
    raw.iter()
        .flat_map(|entry| entry.split(':'))
        .map(String::from)
        .collect()
}

/// The directories an ELF's `DT_RUNPATH` (or failing that `DT_RPATH`)
/// names, absolute ones mapped under `root` when given.
pub(crate) fn parse_rpaths_under(path: &Path, root: Option<&Path>) -> Vec<PathBuf> {
    let Ok(data) = fs::read(path) else {
        return Vec::new();
    };
    let Ok(elf) = goblin::elf::Elf::parse(&data) else {
        return Vec::new();
    };
    // The ELF's own directory, for `$ORIGIN` expansion.
    let origin = path.parent().unwrap_or_else(|| Path::new("."));
    // The dynamic loader ignores DT_RPATH when DT_RUNPATH is present, so
    // match that precedence rather than chaining both (which could pull a
    // library from a dir the loader would never search).
    let raw = if !elf.runpaths.is_empty() {
        &elf.runpaths
    } else {
        &elf.rpaths
    };
    resolve_runpath_dirs_under(raw.iter().copied(), origin, root)
}

/// Rewrite RPATH/RUNPATH to `$ORIGIN/../lib` so the bundled ELF finds its
/// transitive libraries via its own on-disk location, never via
/// `LD_LIBRARY_PATH`. That matters because `LD_LIBRARY_PATH` is a
/// per-process env variable that gets inherited into host binaries the
/// app may spawn (for example, `postgres` uses `popen(3)` which execs
/// `/bin/sh` - a host binary linked against the host's glibc). If we
/// left our bundle dir on `LD_LIBRARY_PATH`, the host shell would load
/// our newer `libc.so.6` against its own older `ld-linux.so.2` and
/// crash with a null deref in the loader. Using `$ORIGIN/../lib` keeps
/// the bundle's library search scoped to the bundled ELF itself.
///
/// First tries in-place patching of an existing DT_RPATH/DT_RUNPATH
/// slot. If the binary has no slot or it's too small for our string
/// (e.g. Bun, Go, Zig outputs), falls back to `patchelf --set-rpath`
/// when available.
///
/// The outcome matters for re-exec safety: an executable that ends up
/// without a baked-in `$ORIGIN` RUNPATH can only find its bundled libs
/// via `LD_LIBRARY_PATH`, which is wiped when the app re-execs itself in
/// a sandbox (`clearenv()` + `execve`). The caller surfaces those so the
/// package isn't silently fragile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RunpathOutcome {
    /// `$ORIGIN` RUNPATH is baked into the ELF (in-place or via patchelf).
    Set,
    /// No RUNPATH needed: static binary, bare lib, or no DT_NEEDED.
    NotNeeded,
    /// RUNPATH could not be guaranteed: an executable with deps and no
    /// in-place slot, or a library whose own directory did not fit its
    /// slot, with patchelf missing or failing. Relies on
    /// `LD_LIBRARY_PATH`; not sandbox-re-exec-safe.
    Unguaranteed,
    /// Executable with a self-extract trailer: patchelf would clobber
    /// the trailer, so RUNPATH can't be added. Known limitation.
    SelfExtract,
    /// No usable in-place slot; the caller must invoke patchelf once its
    /// own edits to the image have been written back.
    NeedsPatchelf,
}

/// The `$ORIGIN` run path for a file `depth` directories below the tree
/// root, reaching the library directory `lib_rel`, itself relative to the
/// root: `bin/app` gets `$ORIGIN/../lib`, `opt/x/bin/app` gets
/// `$ORIGIN/../../../lib`, and a library in `lib/` gets `$ORIGIN/../lib`.
///
/// One exact entry per file, rather than one list for every depth. A list
/// carries entries that resolve outside the tree for every file but one,
/// and from a tree extracted two directories below `/` the deepest of them
/// is the host's `/lib`, which is precisely the directory a bundle must
/// never search.
pub(crate) fn origin_runpath(depth: usize, lib_rel: &Path) -> String {
    let mut s = String::from("$ORIGIN");
    for _ in 0..depth {
        s.push_str("/..");
    }
    s.push('/');
    s.push_str(&lib_rel.to_string_lossy());
    s
}

/// `$ORIGIN`-relative form of `target` seen from `from`, both inside the
/// same tree. `None` when either is not under it.
fn origin_relative(from: &Path, target: &Path, root: &Path) -> Option<String> {
    let (from, target) = (
        from.strip_prefix(root).ok()?,
        target.strip_prefix(root).ok()?,
    );
    let mut f = from.components();
    let mut t = target.components();
    let mut shared = 0usize;
    loop {
        match (f.clone().next(), t.clone().next()) {
            (Some(a), Some(b)) if a == b => {
                f.next();
                t.next();
                shared += 1;
            }
            _ => break,
        }
    }
    let _ = shared;
    let up = f.count();
    let mut out = String::from("$ORIGIN");
    for _ in 0..up {
        out.push_str("/..");
    }
    let rest: PathBuf = t.collect();
    if rest.as_os_str().is_empty() {
        return Some(out);
    }
    out.push('/');
    out.push_str(&rest.to_string_lossy());
    Some(out)
}

/// The run path an object in the tree at `root` needs: the entry that
/// reaches the library directory, plus every directory its original run
/// path named that the tree actually carries.
///
/// A tree assembled from a sysroot keeps the layout the distribution
/// used, so a library that keeps its plugins in a directory of its own
/// still needs to reach it, and the absolute path it was built with
/// names the host rather than the tree.
pub(crate) fn tree_runpath(root: &Path, object: &Path, lib_rel: &Path) -> String {
    let mut parts = vec![origin_runpath_for(root, object, lib_rel)];
    let Some(dir) = object.parent() else {
        return parts.join(":");
    };
    for target in run_path_dirs_in_tree(object, root) {
        if let Some(entry) = origin_relative(dir, &target, root)
            && !parts.iter().any(|p| p.split(':').any(|e| e == entry))
        {
            parts.push(entry);
        }
    }
    parts.join(":")
}

/// The `$ORIGIN` run path for `path` in the tree at `root`. A file in a
/// subdirectory of the library directory, a plugin or a charset module,
/// gets its own directory first, since such files name their helpers by
/// bare soname and expect them beside themselves.
pub(crate) fn origin_runpath_for(root: &Path, path: &Path, lib_rel: &Path) -> String {
    let dir = path
        .parent()
        .and_then(|dir| dir.strip_prefix(root).ok())
        .unwrap_or(Path::new(""));
    let to_lib = origin_runpath(dir.components().count(), lib_rel);
    if dir.starts_with(lib_rel) && dir != lib_rel {
        format!("$ORIGIN:{to_lib}")
    } else {
        to_lib
    }
}

/// File range of the dynamic string table.
///
/// From the `.dynstr` section header when there is one, else from
/// `DT_STRTAB` and `DT_STRSZ` mapped through the `PT_LOAD` holding them.
/// An object stripped of its section headers (`sstrip`, `llvm-strip
/// --strip-sections`, some vendor blobs) keeps its dynamic section, and
/// would otherwise keep its host RUNPATH too.
fn dynstr_range(elf: &goblin::elf::Elf) -> Option<(usize, usize)> {
    if let Some(sh) = elf
        .section_headers
        .iter()
        .find(|sh| elf.shdr_strtab.get_at(sh.sh_name) == Some(".dynstr"))
    {
        return Some((sh.sh_offset as usize, (sh.sh_offset + sh.sh_size) as usize));
    }
    let dynamic = elf.dynamic.as_ref()?;
    let strtab = dynamic.info.strtab as u64;
    let strsz = dynamic.info.strsz as u64;
    if strsz == 0 {
        return None;
    }
    let load = elf.program_headers.iter().find(|p| {
        p.p_type == goblin::elf::program_header::PT_LOAD
            && strtab >= p.p_vaddr
            && strtab < p.p_vaddr + p.p_filesz
    })?;
    let off = strtab - load.p_vaddr + load.p_offset;
    Some((off as usize, (off + strsz) as usize))
}

/// Rewrite RUNPATH within `data`, reporting what the caller still owes and
/// whether the image changed.
///
/// Returns [`RunpathOutcome::NeedsPatchelf`] when no in-place slot is big
/// enough, since patchelf has to run against the file rather than the image.
/// The image can change even then: every slot is scrubbed and retagged.
fn rewrite_origin_runpath_in(
    data: &mut [u8],
    path: &Path,
    runpath: &str,
    origin_only: &str,
) -> io::Result<(RunpathOutcome, bool)> {
    let new_bytes = runpath.as_bytes();
    let is_self_extract = has_embedded_payload(data);

    let elf = match goblin::elf::Elf::parse(data) {
        Ok(e) => e,
        Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidData, e.to_string())),
    };
    let has_needed = !elf.libraries.is_empty();
    let has_soname = elf.soname.is_some();
    let is_executable = !has_soname
        && elf
            .program_headers
            .iter()
            .any(|p| p.p_type == goblin::elf::program_header::PT_INTERP);
    let dynstr_range = dynstr_range(&elf);
    let dynamic_present = elf.dynamic.is_some();

    // File offset of the dynamic array, so a DT_RUNPATH tag can be rewritten
    // to DT_RPATH in place.
    let dyn_offset = elf
        .program_headers
        .iter()
        .find(|p| p.p_type == goblin::elf::program_header::PT_DYNAMIC)
        .map(|p| p.p_offset as usize);
    let dyn_entry_size = if elf.is_64 { 16 } else { 8 };

    let mut slots: Vec<usize> = Vec::new();
    let mut runpath_tags: Vec<usize> = Vec::new();
    if let (Some((dynstr_offset, _)), Some(dynamic)) = (dynstr_range, &elf.dynamic) {
        for (i, d) in dynamic.dyns.iter().enumerate() {
            if d.d_tag == goblin::elf::dynamic::DT_RPATH
                || d.d_tag == goblin::elf::dynamic::DT_RUNPATH
            {
                slots.push(dynstr_offset + d.d_val as usize);
                if d.d_tag == goblin::elf::dynamic::DT_RUNPATH
                    && let Some(base) = dyn_offset
                {
                    runpath_tags.push(base + i * dyn_entry_size);
                }
            }
        }
    }
    let is_64 = elf.is_64;
    let dynstr_end = dynstr_range.map(|(_, e)| e).unwrap_or(0);
    drop(elf);

    let mut rewritten = 0usize;
    let mut changed = false;
    let total = slots.len();
    let limit = dynstr_end.min(data.len());
    for file_pos in slots {
        if file_pos >= limit {
            continue;
        }
        let mut end = file_pos;
        while end < limit && data[end] != 0 {
            end += 1;
        }
        while end < limit && data[end] == 0 {
            end += 1;
        }
        let slot_size = end - file_pos;
        // The runpath when it fits, else `$ORIGIN` alone, else nothing.
        // The slot is always overwritten: leaving its old contents would
        // keep an absolute host path such as `/usr/lib`, which on a musl
        // host loads the host's own libraries into a glibc process. Any
        // of the three names no host path.
        let write = [runpath, origin_only, "$ORIGIN", ""]
            .into_iter()
            .find(|s| s.len() < slot_size)
            .unwrap_or("");
        data[file_pos..file_pos + write.len()].copy_from_slice(write.as_bytes());
        for b in &mut data[file_pos + write.len()..file_pos + slot_size] {
            *b = 0;
        }
        changed = true;
        if write.len() >= new_bytes.len() {
            rewritten += 1;
        }
    }
    // Retag every `DT_RUNPATH` as `DT_RPATH`, whether or not its string was
    // rewritten above.
    //
    // The loader does not consult `DT_RUNPATH` when resolving a dependency's
    // own dependencies, and an object carrying one is also barred from
    // inheriting its parent's path. So one `DT_RUNPATH` anywhere in the
    // bundle strands that object: on the packaging host the system copies
    // hide it, elsewhere the chain fails to load. `DT_RPATH` is inherited,
    // which lets a single entry on the executable serve the whole tree and
    // lets a library whose slot was too small fall back to it.
    for at in runpath_tags {
        let width = if is_64 { 8 } else { 4 };
        if at + width <= data.len() {
            let tag = goblin::elf::dynamic::DT_RPATH;
            if is_64 {
                data[at..at + 8].copy_from_slice(&tag.to_le_bytes());
            } else {
                data[at..at + 4].copy_from_slice(&(tag as u32).to_le_bytes());
            }
            changed = true;
        }
    }

    if total > 0 && rewritten == total {
        return Ok((RunpathOutcome::Set, changed));
    }
    // A slot too small for the full string was overwritten with the
    // longest safe `$ORIGIN` fallback instead, and retagged RPATH, so it
    // names no host path and the executable's inherited entry covers the
    // rest. Good enough for a library, unless the full string named a
    // directory of its own: that one is the only way its dependency is
    // reached, so the write has to happen even at the cost of patchelf.
    if total > 0 && !is_executable {
        let outcome = if runpath == origin_only {
            RunpathOutcome::Set
        } else {
            RunpathOutcome::NeedsPatchelf
        };
        return Ok((outcome, changed));
    }

    // Nothing to resolve: a static binary, or a bottom-of-stack library
    // like libc itself, which has no DT_NEEDED of its own.
    if !dynamic_present || !has_needed {
        return Ok((RunpathOutcome::NotNeeded, changed));
    }
    // A library with no slot of its own resolves through the executable's
    // `DT_RPATH`, which the loader inherits down the dependency chain. Only
    // executables are worth growing a file for.
    if !is_executable {
        return Ok((RunpathOutcome::NotNeeded, changed));
    }
    if is_self_extract {
        return Ok((RunpathOutcome::SelfExtract, changed));
    }
    let _ = path;
    Ok((RunpathOutcome::NeedsPatchelf, changed))
}

/// Run `patchelf --set-rpath` against `path`, reporting whether the RUNPATH
/// ended up guaranteed.
fn run_patchelf_rpath(path: &Path, runpath: &str, patchelf: Option<&Path>) -> RunpathOutcome {
    let Some(patchelf) = patchelf else {
        return RunpathOutcome::Unguaranteed;
    };
    match std::process::Command::new(patchelf)
        .arg("--force-rpath")
        .arg("--set-rpath")
        .arg(runpath)
        .arg(path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .output()
    {
        Ok(o) if o.status.success() => RunpathOutcome::Set,
        Ok(o) => {
            eprintln!(
                "  {} patchelf failed for {}: {}",
                color::bold_red("warning:"),
                path.display(),
                String::from_utf8_lossy(&o.stderr).trim()
            );
            RunpathOutcome::Unguaranteed
        }
        Err(e) => {
            eprintln!(
                "  {} could not run patchelf for {}: {e}",
                color::bold_red("warning:"),
                path.display(),
            );
            RunpathOutcome::Unguaranteed
        }
    }
}

/// Sonames a bundled object needs that the bundle does not provide where
/// the loader will look.
///
/// The packer writes every object an RPATH of `$ORIGIN/../lib`, and the
/// entrypoint's RPATH names `lib_dir`, so those two directories are the
/// whole search: a copy anywhere else in the tree, a vendor's `opt/`
/// install say, does not count. A soname listed here is resolved from
/// the host at runtime or not at all. On the packer's machine the host's
/// copy is the right one, so nothing else reports the omission.
///
/// The dynamic loader is excluded: it is named through PT_INTERP rather
/// than DT_NEEDED, and is handled separately.
/// The directories an object's absolute run path entries name, mapped
/// into the tree at `root`. A tree built from a sysroot keeps the run
/// paths the distribution wrote, and the conventional layout drops the
/// `usr/` prefix, so `/usr/lib/libproxy` is `lib/libproxy` here.
fn run_path_dirs_in_tree(object: &Path, root: &Path) -> Vec<PathBuf> {
    parse_rpaths_raw(object)
        .into_iter()
        .filter(|entry| entry.starts_with('/'))
        .flat_map(|entry| {
            let rel = entry.trim_start_matches('/').to_string();
            let flat = rel.strip_prefix("usr/").unwrap_or(&rel).to_string();
            [root.join(&rel), root.join(&flat)]
        })
        .filter(|d| d.is_dir())
        .collect()
}

pub(crate) fn audit_unbundled_needs(
    directory: &Path,
    lib_dir: &Path,
) -> Vec<(PathBuf, Vec<String>)> {
    use std::collections::{HashMap, HashSet};

    // A name counts only when it resolves: a soname link whose target was
    // pruned satisfies nothing the loader asks for.
    let names_in = |dir: &Path| -> HashSet<String> {
        fs::read_dir(dir)
            .into_iter()
            .flatten()
            .flatten()
            .filter(|e| e.path().exists())
            .filter_map(|e| e.file_name().to_str().map(String::from))
            .collect()
    };
    let lib_root = directory.join(lib_dir);
    let shared = names_in(&lib_root);
    let mut beside: HashMap<PathBuf, HashSet<String>> = HashMap::new();

    let mut findings: Vec<(PathBuf, Vec<String>)> = Vec::new();
    for path in find_elf_files(directory) {
        let Ok(needed) = parse_needed(&path) else {
            continue;
        };
        let dir = path.parent().unwrap_or_else(|| Path::new("."));
        let origin_lib = dir.join("../lib");
        let local = beside
            .entry(origin_lib.clone())
            .or_insert_with(|| names_in(&origin_lib));
        // Wherever the object's own run path points inside the tree. A
        // library that keeps its plugins in a directory of its own says
        // so there, and the plugin is no more missing than a sibling is.
        let mut on_run_path: HashSet<String> = HashSet::new();
        for entry in parse_rpaths(&path) {
            on_run_path.extend(names_in(&entry));
        }
        for entry in run_path_dirs_in_tree(&path, directory) {
            on_run_path.extend(names_in(&entry));
        }
        // A file in a subdirectory of the library directory has its own
        // directory on its run path too, for the helpers beside it.
        let siblings = if dir.starts_with(&lib_root) && dir != lib_root {
            names_in(dir)
        } else {
            HashSet::new()
        };
        let mut missing: Vec<String> = needed
            .into_iter()
            .filter(|soname| {
                let bare = Path::new(soname)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or(soname);
                !shared.contains(bare)
                    && !local.contains(bare)
                    && !siblings.contains(bare)
                    && !on_run_path.contains(bare)
                    && !is_dynamic_loader(bare)
            })
            .collect();
        if !missing.is_empty() {
            missing.sort();
            missing.dedup();
            findings.push((path, missing));
        }
    }
    findings
}

/// Finalize every ELF in `directory` for portability: rewrite RUNPATH to
/// `$ORIGIN/../lib`, scrub `/nix/store` paths, and strip absolute DT_NEEDED
/// entries, temporarily granting owner-write to read-only files. Returns
/// `(rewritten, scrubbed, unguaranteed, self_extract)`.
pub(crate) fn finalize_tree(
    directory: &Path,
    lib_rel: &Path,
) -> (usize, usize, Vec<PathBuf>, Vec<PathBuf>) {
    let mut rewritten = 0usize;
    let mut scrubbed = 0usize;
    let mut unguaranteed: Vec<PathBuf> = Vec::new();
    let mut self_extract: Vec<PathBuf> = Vec::new();
    // Resolved once: the lookup walks PATH, and running it per binary per
    // transformation is pure overhead on a tree with thousands of them.
    let patchelf = which_patchelf();

    for path in find_elf_files(directory) {
        // Every later edit, here and in the bootstrap injection, writes
        // the file in place.
        break_hardlink(&path);
        let perms = fs::metadata(&path)
            .map(|m| m.permissions().mode())
            .unwrap_or(0o755);
        let needs_chmod = perms & 0o200 == 0;
        if needs_chmod {
            let _ = fs::set_permissions(&path, PermissionsExt::from_mode(perms | 0o200));
        }

        let runpath = tree_runpath(directory, &path, lib_rel);
        let origin_only = origin_runpath_for(directory, &path, lib_rel);
        if let Ok((outcome, did_scrub)) =
            finalize_one(&path, &runpath, &origin_only, patchelf.as_deref())
        {
            match outcome {
                RunpathOutcome::Set => rewritten += 1,
                RunpathOutcome::Unguaranteed => unguaranteed.push(path.clone()),
                RunpathOutcome::SelfExtract => self_extract.push(path.clone()),
                // finalize_one resolves this before returning.
                RunpathOutcome::NotNeeded | RunpathOutcome::NeedsPatchelf => {}
            }
            if did_scrub {
                scrubbed += 1;
            }
        }

        // Re-pin the mtime: the writes above stamped "now", undoing the copy
        // step's normalization, and a second run would then differ.
        normalize_mtime(&path);
        if needs_chmod {
            let _ = fs::set_permissions(&path, PermissionsExt::from_mode(perms));
        }
    }
    (rewritten, scrubbed, unguaranteed, self_extract)
}

/// Give `path` an inode of its own before it is rewritten in place.
///
/// A hardlinked input shares its inode with the file it was linked from,
/// often the build's own output, and an in-place write would change that
/// too. The copy keeps the mode bits; a failure leaves the link as it was.
fn break_hardlink(path: &Path) {
    use std::os::unix::fs::MetadataExt;
    let Ok(meta) = fs::symlink_metadata(path) else {
        return;
    };
    if !meta.is_file() || meta.nlink() < 2 {
        return;
    }
    let mut tmp = path.as_os_str().to_os_string();
    tmp.push(".onelf-unlink.tmp");
    let tmp = PathBuf::from(tmp);
    if fs::copy(path, &tmp).is_err() || fs::rename(&tmp, path).is_err() {
        let _ = fs::remove_file(&tmp);
    }
}

/// Apply every in-place rewrite to one binary with a single read and a
/// single write.
///
/// The three transformations are all equal-length edits on the same image,
/// so running them as separate read-modify-write cycles read and wrote each
/// binary three times over. Returns the RUNPATH outcome and whether any
/// scrubbing changed the image.
fn finalize_one(
    path: &Path,
    runpath: &str,
    origin_only: &str,
    patchelf: Option<&Path>,
) -> io::Result<(RunpathOutcome, bool)> {
    let mut data = fs::read(path)?;

    let (outcome, rewritten) = rewrite_origin_runpath_in(&mut data, path, runpath, origin_only)?;
    let scrubbed = scrub_nix_store_paths_in(&mut data);
    let stripped = strip_absolute_needed_in(&mut data);

    if rewritten || scrubbed || stripped {
        fs::write(path, &data)?;
    }

    // patchelf owns the file itself, so it can only run after ours is
    // written back.
    if outcome == RunpathOutcome::NeedsPatchelf {
        return Ok((run_patchelf_rpath(path, runpath, patchelf), scrubbed));
    }
    Ok((outcome, scrubbed))
}

/// Warn that the listed executables could not get a baked-in `$ORIGIN`
/// RUNPATH and therefore won't survive a sandboxed re-exec. Printed once
/// per bundling pass; empty input prints nothing.
/// Report libraries that will be resolved from the host at runtime.
///
/// Worth a warning rather than an error: bundling GL, DRI, Vulkan and NSS
/// from the host is deliberate and common, so some entries here are
/// expected. The point is that the publisher gets to see the list on the
/// machine where it still resolves correctly, instead of a user finding
/// out through a mismatched libc.
pub(crate) fn report_unbundled_needs(findings: &[(PathBuf, Vec<String>)]) {
    if findings.is_empty() {
        return;
    }
    let mut sonames: Vec<&str> = findings
        .iter()
        .flat_map(|(_, libs)| libs.iter().map(|s| s.as_str()))
        .collect();
    sonames.sort();
    sonames.dedup();

    eprintln!(
        "{} {} librar(ies) are not in the bundle:",
        color::bold_red("warning:"),
        sonames.len()
    );
    for soname in &sonames {
        let by: Vec<String> = findings
            .iter()
            .filter(|(_, libs)| libs.iter().any(|l| l == soname))
            .filter_map(|(p, _)| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .map(|s| s.to_string())
            })
            .take(3)
            .collect();
        eprintln!("  - {soname} (needed by {})", by.join(", "));
    }
    eprintln!(
        "  These resolve to the host's copies, and load next to the bundled \
         libc, only for a package that keeps the host's library directories. \
         Otherwise loading them fails where they are first used. Add them \
         with --search-path, or leave them if they are meant to come from \
         the host (GL, DRI, Vulkan, NSS); `pack --host-libs` decides which \
         of the two happens."
    );
}

pub(crate) fn report_unguaranteed_runpath(unguaranteed: &[PathBuf], self_extract: &[PathBuf]) {
    if !unguaranteed.is_empty() {
        eprintln!(
            "{} {} file(s) have no baked-in $ORIGIN RUNPATH and rely \
             on LD_LIBRARY_PATH:",
            color::bold_red("warning:"),
            unguaranteed.len()
        );
        for p in unguaranteed {
            eprintln!("  - {}", p.display());
        }
        eprintln!(
            "  These break if the app re-execs itself in a sandbox \
             (clearenv). Install `patchelf` (or set ONELF_PATCHELF) and \
             repack to make them re-exec-safe."
        );
    }
    if !self_extract.is_empty() {
        eprintln!(
            "{} {} self-extracting executable(s) can't take a baked-in \
             RUNPATH (would clobber the embedded payload):",
            color::bold_red("warning:"),
            self_extract.len()
        );
        for p in self_extract {
            eprintln!("  - {}", p.display());
        }
        eprintln!(
            "  These rely on the runtime's LD_LIBRARY_PATH and are not \
             sandbox-re-exec-safe."
        );
    }
}

/// Detect binaries that embed a self-extracting payload at the end of
/// the file. Bootstrap injection appends to the file, which would clobber
/// such payloads and prevent runtime detection.
///
/// Currently detects: pre-1.3.12 Bun (`bun build --compile`) binaries
/// which end with `\n---- Bun! ----\n` followed by an 8-byte length.
/// Bun >=1.3.12 dropped the trailer for a `.bun` section; that case is
/// covered by [`has_bun_section`].
pub(crate) fn has_self_extract_trailer(data: &[u8]) -> bool {
    // Bun's trailer is 16 bytes; pre-1.3.12 also has an 8-byte length
    // word after it (so check at offsets -16 and -24).
    const BUN_TRAILER: &[u8] = b"\n---- Bun! ----\n";
    if data.len() >= BUN_TRAILER.len() && data.ends_with(BUN_TRAILER) {
        return true;
    }
    if data.len() >= BUN_TRAILER.len() + 8
        && &data[data.len() - BUN_TRAILER.len() - 8..data.len() - 8] == BUN_TRAILER
    {
        return true;
    }
    false
}

/// Detect Bun >=1.3.12 `bun build --compile` binaries, which embed the module
/// graph in a `.bun` ELF section (commit 66f7c41, released in 1.3.12) and
/// locate it at runtime by parsing their own program headers. Any structural
/// rewrite (a second patchelf pass, a bootstrap PT_LOAD) reshuffles that
/// layout and makes the lookup dereference unmapped memory, so these are left
/// untouched like self-extract binaries.
pub(crate) fn has_bun_section(data: &[u8]) -> bool {
    let Ok(elf) = goblin::elf::Elf::parse(data) else {
        return false;
    };
    elf.section_headers
        .iter()
        .any(|sh| elf.shdr_strtab.get_at(sh.sh_name) == Some(".bun"))
}

/// True for binaries whose embedded payload would break if the ELF layout were
/// rewritten: pre-1.3.12 Bun (EOF trailer) and >=1.3.12 Bun (`.bun` section).
/// Such binaries skip the RUNPATH / DT_NEEDED / bootstrap edits and rely on
/// runtime-set env (`LD_LIBRARY_PATH`) instead.
pub(crate) fn has_embedded_payload(data: &[u8]) -> bool {
    has_self_extract_trailer(data) || has_bun_section(data)
}

/// Locate patchelf in PATH (or ONELF_PATCHELF override).
pub(crate) fn which_patchelf() -> Option<PathBuf> {
    if let Ok(p) = std::env::var("ONELF_PATCHELF") {
        let p = PathBuf::from(p);
        if p.is_file() {
            return Some(p);
        }
    }
    let path = std::env::var("PATH").ok()?;
    for dir in path.split(':') {
        if dir.is_empty() {
            continue;
        }
        let p = PathBuf::from(dir).join("patchelf");
        if p.is_file() {
            return Some(p);
        }
    }
    None
}

/// Rewrite any absolute-path DT_NEEDED entry to just its basename. The
/// pack host's nixpkgs stack sometimes emits a full
/// `/nix/store/<hash>-name/lib/libfoo.so` as the DT_NEEDED string. The
/// dynamic loader treats those literally and ignores `RUNPATH` /
/// `LD_LIBRARY_PATH`, so a binary built with them will try to `open`
/// that exact path on the user's machine and fail. Stripping to the
/// basename puts the lookup back on the standard search path and
/// picks up our bundled copy via `$ORIGIN/../lib`.
///
/// Operates in place: writes the new basename over the old string and
/// NUL-pads the rest of the slot. The old slot is always longer than
/// the new basename, so this never needs to grow the string table.
/// [`strip_absolute_needed`] against an in-memory image. Returns whether
/// anything changed, so a caller batching several rewrites can decide once
/// whether the file needs writing back.
pub(crate) fn strip_absolute_needed_in(modified: &mut [u8]) -> bool {
    let Ok(elf) = goblin::elf::Elf::parse(modified) else {
        return false;
    };
    let dynstr_offset = dynstr_range(&elf).map(|(off, _)| off);
    let (Some(dynstr_offset), Some(dynamic)) = (dynstr_offset, &elf.dynamic) else {
        return false;
    };

    let mut edits: Vec<(usize, usize, usize)> = Vec::new();
    for dyn_entry in &dynamic.dyns {
        if dyn_entry.d_tag != goblin::elf::dynamic::DT_NEEDED {
            continue;
        }
        let file_pos = dynstr_offset + dyn_entry.d_val as usize;
        if file_pos >= modified.len() || modified[file_pos] != b'/' {
            continue;
        }
        let mut end = file_pos;
        while end < modified.len() && modified[end] != 0 {
            end += 1;
        }
        let slot_size = end - file_pos;
        let original = &modified[file_pos..end];
        let basename_start = match original.iter().rposition(|&b| b == b'/') {
            Some(p) => p + 1,
            None => 0,
        };
        let basename_len = original.len() - basename_start;
        if basename_len == 0 || basename_len >= slot_size {
            continue;
        }
        edits.push((file_pos, basename_start, slot_size));
    }
    drop(elf);

    let changed = !edits.is_empty();
    for (file_pos, basename_start, slot_size) in edits {
        let basename: Vec<u8> = modified[file_pos + basename_start..file_pos + slot_size].to_vec();
        let basename: Vec<u8> = basename.into_iter().take_while(|&b| b != 0).collect();
        let len = basename.len();
        modified[file_pos..file_pos + len].copy_from_slice(&basename);
        for b in &mut modified[file_pos + len..file_pos + slot_size] {
            *b = 0;
        }
    }
    changed
}

pub(crate) fn is_excluded(soname: &str, excludes: &[&str]) -> bool {
    excludes.iter().any(|pat| soname.starts_with(pat))
}

/// True for sonames that denote the dynamic linker itself.
pub(crate) fn is_dynamic_loader(soname: &str) -> bool {
    soname.starts_with("ld-linux") || soname.starts_with("ld-musl-") || soname == "ld.so"
}

/// Byte patterns a loader bakes in that name the packer's filesystem, and
/// their equal-length replacements. Each replacement is a path that does
/// not exist on any sane system, so the loader's lookup fails cleanly
/// instead of reading a host file.
///
/// glibc's `ld-linux` hardcodes its build-time `/etc/ld.so.cache`,
/// `/etc/ld-nix.so.preload`, `/nix/store/<hash>-glibc-X/lib/`, and its
/// fallback library directories, and nothing else under those prefixes.
///
/// musl's loader is libc itself, so `/etc/passwd`, `/etc/resolv.conf`,
/// and `/usr/share/zoneinfo/` sit in the same file and must survive: they
/// are what `getpwnam`, `getaddrinfo`, and `localtime` read at runtime.
/// Only its default library search path names the host.
fn loader_scrub_list(family: LibcFamily) -> &'static [(&'static [u8], &'static [u8])] {
    match family {
        LibcFamily::Glibc => &[
            (b"/etc/", b"/XXX/"),
            (b"/usr/", b"/XXX/"),
            (b"/nix/", b"/XXX/"),
            // /lib/ and /lib64/ appear as glibc's hardcoded fallback
            // library search paths. Our bundled libs live in `lib/` (no
            // leading slash), so scrubbing absolute /lib doesn't hurt.
            (b"/lib/", b"/XXX/"),
            (b"/lib64/", b"/XXX///"),
        ],
        LibcFamily::Musl => &[(
            b"/lib:/usr/local/lib:/usr/lib",
            b"/XXX:/XXX/local/lib:/XXX/lib",
        )],
    }
}

/// Rewrite absolute-path byte sequences baked into the dynamic loader.
///
/// The paths exist on the packer's machine but not on the user's; worse,
/// if any do exist, they'll point at a libc that disagrees with the one
/// we bundled. The fix is to replace each with a path that is guaranteed
/// not to resolve (starts with `/XXX`), keeping byte length identical so
/// ELF offsets stay valid. What gets replaced depends on the libc family,
/// see [`loader_scrub_list`].
///
/// This is the same idea as sharun's `sed` pass, done in pure Rust
/// with a more targeted prefix list.
pub(crate) fn scrub_loader_paths(path: &Path, family: LibcFamily) -> io::Result<()> {
    let mut data = fs::read(path)?;
    let mut changed = false;
    let replacements = loader_scrub_list(family);

    for (needle, replace) in replacements {
        debug_assert_eq!(needle.len(), replace.len());
        let len = needle.len();
        let mut i = 0;
        while i + len <= data.len() {
            if &data[i..i + len] == *needle {
                data[i..i + len].copy_from_slice(replace);
                changed = true;
                i += len;
            } else {
                i += 1;
            }
        }
    }

    if changed {
        fs::write(path, &data)?;
    }
    Ok(())
}

/// Rewrite specific `/nix/store/<hash>-<name>-<version>/...` strings
/// baked into a bundled ELF with sensible host equivalents. Called for
/// every bundled non-loader ELF, not just the loader.
///
/// nixpkgs typically compiles postgres with `--with-system-tzdata=<store>`
/// and embeds the full path to the `locale` binary it will shell out
/// to. Both paths exist only on the packer's machine. On the user's
/// machine postgres prints a parade of warnings about the missing
/// directory, then falls back to internal UTC-only behavior and
/// still-functional locale defaults. The bundle still works, but the
/// noise is confusing.
///
/// Replacements are equal-length to avoid any ELF structure shifts,
/// with the replacement null-padded to the original slot size. We
/// target the suffix (e.g. `/share/zoneinfo`, `/bin/locale`) and walk
/// back to the nearest NUL to find the start of the whole path
/// string.
/// [`scrub_nix_store_paths`] against an in-memory image.
pub(crate) fn scrub_nix_store_paths_in(data: &mut [u8]) -> bool {
    let mut changed = false;
    let rewrites: &[(&[u8], &[u8])] = &[
        (b"/share/zoneinfo", b"/usr/share/zoneinfo"),
        (b"/bin/locale", b"/usr/bin/locale"),
    ];
    for (suffix, replacement) in rewrites {
        let mut i = 0;
        while i + suffix.len() <= data.len() {
            if &data[i..i + suffix.len()] != *suffix {
                i += 1;
                continue;
            }
            let mut start = i;
            while start > 0 && data[start - 1] != 0 {
                start -= 1;
            }
            if start + 11 > data.len() || &data[start..start + 11] != b"/nix/store/" {
                i += suffix.len();
                continue;
            }
            let mut end = i + suffix.len();
            while end < data.len() && data[end] != 0 {
                end += 1;
            }
            if replacement.len() + 1 > end - start {
                i = end;
                continue;
            }
            data[start..start + replacement.len()].copy_from_slice(replacement);
            for b in &mut data[start + replacement.len()..end] {
                *b = 0;
            }
            changed = true;
            i = end;
        }
    }
    changed
}

/// Inject the AT_EXECFN bootstrap into a single ELF binary.
///
/// Repurposes PT_INTERP as PT_LOAD containing the bootstrap payload +
/// metadata. At runtime the bootstrap reads AT_EXECFN from the aux
/// vector, computes the interpreter path relative to the binary's own
/// location (not CWD), mmaps the interpreter, and jumps to its entry.
///
/// Page alignment for the injected bootstrap `PT_LOAD` segment. aarch64
/// kernels may use a 4K, 16K, or 64K page size and the target host can
/// differ from the build host, so `0x10000` is used there (valid under every
/// aarch64 page size); x86-64 keeps 4K.
pub(crate) fn bootstrap_page_align(is_aarch64: bool) -> u64 {
    if is_aarch64 { 0x10000 } else { 0x1000 }
}

/// Returns Ok(true) if injected, Ok(false) if the binary has no
/// PT_INTERP (static, shared lib, or already injected).
pub(crate) fn inject_relative_interp(path: &Path, rel_interp: &str) -> io::Result<bool> {
    use crate::payload;
    use goblin::elf::program_header::PT_INTERP;

    let data = fs::read(path)?;

    // Skip binaries with an embedded payload. Pre-1.3.12 Bun stores metadata
    // at the file end, so appending a bootstrap PT_LOAD would clobber the
    // trailer; >=1.3.12 Bun locates a `.bun` section by parsing its own
    // program headers, so rewriting them makes the lookup fault. For these the
    // runtime sets LD_LIBRARY_PATH and the kernel resolves PT_INTERP normally.
    if has_embedded_payload(&data) {
        eprintln!(
            "  note: {} appears to be a Bun-compiled or self-extracting \
             binary; skipping bootstrap injection",
            path.display(),
        );
        return Ok(false);
    }

    let elf = goblin::elf::Elf::parse(&data)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;

    if elf.header.e_ident[5] != 1 {
        return Ok(false); // little-endian only
    }
    let is64 = match elf.header.e_ident[4] {
        1 => false,
        2 => true,
        _ => return Ok(false),
    };
    let is_x86_64 = elf.header.e_machine == goblin::elf::header::EM_X86_64;
    let is_aarch64 = elf.header.e_machine == goblin::elf::header::EM_AARCH64;
    let is_i686 = elf.header.e_machine == goblin::elf::header::EM_386;
    if !is_x86_64 && !is_aarch64 && !is_i686 {
        return Ok(false);
    }
    // The bootstrap layout is width-specific; require the ELF class to match the
    // machine (i686 => 32-bit; x86_64 / aarch64 => 64-bit).
    if is_i686 == is64 {
        return Ok(false);
    }

    let phdr_idx = match elf
        .program_headers
        .iter()
        .position(|p| p.p_type == PT_INTERP)
    {
        Some(i) => i,
        None => return Ok(false),
    };

    let highest_vend: u64 = elf
        .program_headers
        .iter()
        .filter(|p| p.p_type == goblin::elf::program_header::PT_LOAD)
        .map(|p| p.p_vaddr + p.p_memsz)
        .max()
        .unwrap_or(0);

    // The same value drives new_vaddr, the file-offset padding, and p_align,
    // so the kernel's `p_offset % p_align == p_vaddr % p_align` rule holds.
    let page_size: u64 = bootstrap_page_align(is_aarch64);
    let new_vaddr = (highest_vend + page_size - 1) & !(page_size - 1);
    let orig_entry = elf.header.e_entry;
    let e_phoff = elf.header.e_phoff as usize;
    let e_phentsize = elf.header.e_phentsize as usize;
    let e_machine = elf.header.e_machine;
    drop(elf);

    let Some(code) = payload::bootstrap_blob(e_machine) else {
        eprintln!(
            "  {} onelf was built without the bootstrap payload for this target's \
             architecture; skipping relative-interp injection for {}",
            color::bold_red("warning:"),
            path.display()
        );
        return Ok(false);
    };
    let rel_bytes = rel_interp.as_bytes();

    // Build: [code] [padding to 8-byte align] [entry_delta] [path_len u16] [path NUL].
    // entry_delta is pointer-width (i64 on 64-bit ELF, i32 on 32-bit).
    let mut blob = Vec::with_capacity(code.len() + 64);
    blob.extend_from_slice(code);
    while blob.len() % 8 != 0 {
        blob.push(0);
    }
    let metadata_offset = blob.len();
    let entry_delta = (orig_entry as i64) - (new_vaddr as i64);
    if is64 {
        blob.extend_from_slice(&entry_delta.to_le_bytes());
    } else {
        blob.extend_from_slice(&(entry_delta as i32).to_le_bytes());
    }
    blob.extend_from_slice(&(rel_bytes.len() as u16).to_le_bytes());
    blob.extend_from_slice(rel_bytes);
    blob.push(0);

    // Patch the trampoline's metadata-pointer instruction.
    if is_x86_64 {
        let disp = (metadata_offset as i32) - (payload::X86_64_METADATA_LEA_RIP as i32);
        blob[payload::X86_64_METADATA_LEA_DISP_OFFSET
            ..payload::X86_64_METADATA_LEA_DISP_OFFSET + 4]
            .copy_from_slice(&disp.to_le_bytes());
    } else if is_aarch64 {
        payload::patch_aarch64_adr(&mut blob, metadata_offset);
    } else {
        // i686: `add ecx, imm32` reaches the metadata from the popped PC.
        let disp = (metadata_offset as i32) - (payload::I686_METADATA_ADD_PC as i32);
        blob[payload::I686_METADATA_ADD_DISP_OFFSET..payload::I686_METADATA_ADD_DISP_OFFSET + 4]
            .copy_from_slice(&disp.to_le_bytes());
    }

    let mut modified = data;
    // Pad to page alignment so p_offset % p_align == p_vaddr % p_align.
    // The kernel rejects PT_LOAD segments where this doesn't hold.
    let page = page_size as usize;
    while modified.len() % page != 0 {
        modified.push(0);
    }
    let file_offset = modified.len() as u64;
    let blob_len = blob.len() as u64;
    modified.extend_from_slice(&blob);

    // Overwrite PT_INTERP phdr -> PT_LOAD, then swap it to the end of
    // the phdr table. The bootstrap has the highest vaddr and the kernel
    // uses the FIRST PT_LOAD to compute the ASLR base. If our high-vaddr
    // segment is first, the base is too high and original segments at
    // lower vaddrs fall outside the reserved region.
    let phdr_off = e_phoff + phdr_idx * e_phentsize;
    if is64 {
        // Elf64_Phdr: type, flags, offset, vaddr, paddr, filesz, memsz, align.
        modified[phdr_off..phdr_off + 4].copy_from_slice(&1u32.to_le_bytes()); // PT_LOAD
        modified[phdr_off + 4..phdr_off + 8].copy_from_slice(&5u32.to_le_bytes()); // PF_R|PF_X
        modified[phdr_off + 8..phdr_off + 16].copy_from_slice(&file_offset.to_le_bytes());
        modified[phdr_off + 16..phdr_off + 24].copy_from_slice(&new_vaddr.to_le_bytes());
        modified[phdr_off + 24..phdr_off + 32].copy_from_slice(&new_vaddr.to_le_bytes());
        modified[phdr_off + 32..phdr_off + 40].copy_from_slice(&blob_len.to_le_bytes());
        modified[phdr_off + 40..phdr_off + 48].copy_from_slice(&blob_len.to_le_bytes());
        modified[phdr_off + 48..phdr_off + 56].copy_from_slice(&page_size.to_le_bytes());
    } else {
        // Elf32_Phdr: type, offset, vaddr, paddr, filesz, memsz, flags, align
        // (p_flags sits after p_memsz, unlike Elf64_Phdr).
        modified[phdr_off..phdr_off + 4].copy_from_slice(&1u32.to_le_bytes()); // PT_LOAD
        modified[phdr_off + 4..phdr_off + 8].copy_from_slice(&(file_offset as u32).to_le_bytes());
        modified[phdr_off + 8..phdr_off + 12].copy_from_slice(&(new_vaddr as u32).to_le_bytes());
        modified[phdr_off + 12..phdr_off + 16].copy_from_slice(&(new_vaddr as u32).to_le_bytes());
        modified[phdr_off + 16..phdr_off + 20].copy_from_slice(&(blob_len as u32).to_le_bytes());
        modified[phdr_off + 20..phdr_off + 24].copy_from_slice(&(blob_len as u32).to_le_bytes());
        modified[phdr_off + 24..phdr_off + 28].copy_from_slice(&5u32.to_le_bytes()); // PF_R|PF_X
        modified[phdr_off + 28..phdr_off + 32].copy_from_slice(&(page_size as u32).to_le_bytes());
    }

    // Swap our phdr entry with the last one so original PT_LOADs come first.
    // e_phnum lives at file offset 56 (Elf64) / 44 (Elf32).
    let e_phnum_off = if is64 { 56 } else { 44 };
    let e_phnum =
        u16::from_le_bytes(modified[e_phnum_off..e_phnum_off + 2].try_into().unwrap()) as usize;
    let last_phdr_off = e_phoff + (e_phnum - 1) * e_phentsize;
    if phdr_off != last_phdr_off {
        let mut tmp = vec![0u8; e_phentsize];
        tmp.copy_from_slice(&modified[phdr_off..phdr_off + e_phentsize]);
        modified.copy_within(last_phdr_off..last_phdr_off + e_phentsize, phdr_off);
        modified[last_phdr_off..last_phdr_off + e_phentsize].copy_from_slice(&tmp);
    }

    // Rewrite e_entry (8 bytes at 24 on Elf64, 4 bytes at 24 on Elf32).
    if is64 {
        modified[24..32].copy_from_slice(&new_vaddr.to_le_bytes());
    } else {
        modified[24..28].copy_from_slice(&(new_vaddr as u32).to_le_bytes());
    }

    fs::write(path, &modified)?;
    Ok(true)
}

/// Outcome of trying to make an entrypoint load the onelf-env
/// constructor (re-exec-safe `.onelf/env` / `.onelf/preload`).
pub(crate) enum EnvNeededOutcome {
    /// The onelf-env constructor is now a DT_NEEDED of the binary.
    Added,
    /// Already a DT_NEEDED (idempotent repack).
    AlreadyPresent,
    /// No onelf-env blob built for this arch; runtime-only env.
    NoBlobForArch,
    /// patchelf unavailable, so DT_NEEDED couldn't be added; the binary
    /// falls back to runtime-set env (not sandbox-re-exec-safe).
    NoPatchelf,
    /// Self-extract trailer or unsupported ELF: left untouched.
    Skipped,
}

/// Stage the arch-appropriate onelf-env constructor into `lib_dest` and add
/// it as a `DT_NEEDED` of `path`. Run on the pristine binary *before*
/// bootstrap injection so patchelf operates on a normal ELF (the
/// bootstrap later only repurposes PT_INTERP and appends at EOF, which
/// doesn't disturb the added DT_NEEDED).
pub(crate) fn add_onelf_env_needed(path: &Path, lib_dest: &Path) -> io::Result<EnvNeededOutcome> {
    let data = fs::read(path)?;
    if data.len() < 20 || &data[0..4] != b"\x7fELF" || (data[4] != 1 && data[4] != 2) {
        return Ok(EnvNeededOutcome::Skipped); // not a 32- or 64-bit ELF
    }
    // Binaries with an embedded payload (Bun-compiled: EOF trailer pre-1.3.12,
    // `.bun` section >=1.3.12) break if patchelf rewrites them. Leave them
    // untouched; env is applied at runtime instead.
    if has_embedded_payload(&data) {
        return Ok(EnvNeededOutcome::Skipped);
    }
    let e_machine = u16::from_le_bytes([data[18], data[19]]);
    let Some(blob) = crate::payload::onelf_env_blob(e_machine) else {
        return Ok(EnvNeededOutcome::NoBlobForArch);
    };
    let soname = crate::payload::onelf_env_soname(e_machine);

    // Skip if this binary already lists the constructor (idempotent).
    if let Ok(elf) = goblin::elf::Elf::parse(&data)
        && elf.libraries.contains(&soname)
    {
        return Ok(EnvNeededOutcome::AlreadyPresent);
    }

    // Stage the blob into lib/ (write once; idempotent across binaries).
    let dest = lib_dest.join(soname);
    let need_write = match fs::read(&dest) {
        Ok(existing) => existing != blob,
        Err(_) => true,
    };
    if need_write {
        fs::create_dir_all(lib_dest)?;
        fs::write(&dest, blob)?;
        let _ = fs::set_permissions(&dest, std::os::unix::fs::PermissionsExt::from_mode(0o755));
        normalize_mtime(&dest);
    }

    let Some(patchelf) = which_patchelf() else {
        return Ok(EnvNeededOutcome::NoPatchelf);
    };
    let out = std::process::Command::new(&patchelf)
        .arg("--add-needed")
        .arg(soname)
        .arg(path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .output();
    match out {
        Ok(o) if o.status.success() => Ok(EnvNeededOutcome::Added),
        Ok(o) => Err(io::Error::other(
            String::from_utf8_lossy(&o.stderr).trim().to_string(),
        )),
        Err(e) => Err(e),
    }
}

/// Walk every ELF under `app_dir` and inject the AT_EXECFN bootstrap
/// so the bundled interpreter is found relative to each binary's own
/// location. CWD-independent. Returns the count of injected files.
pub(crate) fn inject_bootstraps(app_dir: &Path, lib_dest: &Path) -> io::Result<usize> {
    let rel_lib = lib_dest
        .strip_prefix(app_dir)
        .unwrap_or(lib_dest)
        .to_path_buf();

    let mut injected = 0usize;
    let mut env_added = 0usize;
    let mut env_no_patchelf: Vec<PathBuf> = Vec::new();
    let mut env_no_blob = false;
    for path in find_elf_files(app_dir) {
        let Some(interp) = parse_interp(&path) else {
            continue;
        };
        let Some(basename) = Path::new(&interp).file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        let bundled = lib_dest.join(basename);
        if !bundled.exists() {
            continue;
        }
        // Shared objects in lib/ (the libraries, libc, which has a
        // PT_INTERP of its own) are left alone. An executable there, a
        // helper a toolkit keeps beside its libraries such as
        // QtWebEngineProcess or WebKit's processes, is an application
        // binary like any other: it needs the bundled loader, and the
        // onelf-env hooks for whatever it spawns.
        if path.starts_with(lib_dest) && has_soname(&path) {
            continue;
        }

        // Compute relative path from binary's dir to the bundled loader.
        let rel_bin = match path.strip_prefix(app_dir) {
            Ok(r) => r,
            Err(_) => continue,
        };
        let depth = rel_bin
            .parent()
            .map(|p| p.components().count())
            .unwrap_or(0);
        let mut rel = PathBuf::new();
        for _ in 0..depth {
            rel.push("..");
        }
        rel.push(&rel_lib);
        rel.push(basename);
        let rel_interp = rel.to_string_lossy().into_owned();

        let perms = fs::metadata(&path)
            .map(|m| m.permissions().mode())
            .unwrap_or(0o755);
        let needs_chmod = perms & 0o200 == 0;
        if needs_chmod {
            let _ = fs::set_permissions(
                &path,
                std::os::unix::fs::PermissionsExt::from_mode(perms | 0o200),
            );
        }
        // Make .onelf/env + .onelf/preload re-exec-safe by injecting the
        // onelf-env constructor as a DT_NEEDED (resolved via the
        // $ORIGIN RUNPATH set earlier). Done before bootstrap injection
        // so patchelf sees a normal ELF.
        match add_onelf_env_needed(&path, lib_dest) {
            Ok(EnvNeededOutcome::Added) => env_added += 1,
            Ok(EnvNeededOutcome::AlreadyPresent) => {}
            Ok(EnvNeededOutcome::NoBlobForArch) => env_no_blob = true,
            Ok(EnvNeededOutcome::NoPatchelf) => env_no_patchelf.push(path.clone()),
            Ok(EnvNeededOutcome::Skipped) => {}
            Err(e) => {
                eprintln!(
                    "  {} could not add onelf-env to {}: {e}",
                    color::bold_red("warning:"),
                    path.display()
                );
            }
        }

        match inject_relative_interp(&path, &rel_interp) {
            Ok(true) => injected += 1,
            Ok(false) => {}
            Err(e) => {
                eprintln!(
                    "  {} could not inject bootstrap into {}: {e}",
                    color::bold_red("warning:"),
                    path.display()
                );
            }
        }
        // Re-pin the mtime: the env-needed and interp injections above run
        // after finalize_tree normalized it, so without this the target
        // executable carries a wall-clock mtime and breaks reproducibility.
        normalize_mtime(&path);
        if needs_chmod {
            let _ = fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(perms));
        }
    }

    if env_added > 0 {
        eprintln!(
            "{} onelf-env (re-exec-safe .onelf/env) into {} binaries",
            color::bold("Injected"),
            env_added
        );
    }
    if !env_no_patchelf.is_empty() {
        eprintln!(
            "{} patchelf unavailable; {} executable(s) won't re-apply \
             .onelf/env after a sandboxed re-exec:",
            color::bold_red("warning:"),
            env_no_patchelf.len()
        );
        for p in &env_no_patchelf {
            eprintln!("  - {}", p.display());
        }
        eprintln!(
            "  Install `patchelf` (or set ONELF_PATCHELF) and repack for \
             re-exec-safe env."
        );
    }
    if env_no_blob {
        eprintln!(
            "{} no onelf-env blob built for this target arch; \
             .onelf/env is runtime-only (not sandbox-re-exec-safe). \
             Build it via crates/onelf/src/payload/Makefile.",
            color::bold_red("warning:"),
        );
    }
    Ok(injected)
}

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

    /// Minimal 64-bit ELF whose only named section is `.bun`, mimicking a
    /// Bun >=1.3.12 `--compile` binary for detection purposes.
    fn elf_with_bun_section() -> Vec<u8> {
        let shstrtab = b"\0.bun\0.shstrtab\0";
        let mut f = vec![0u8; 64 + shstrtab.len()];
        f[0..4].copy_from_slice(b"\x7fELF");
        f[4] = 2; // ELFCLASS64
        f[5] = 1; // ELFDATA2LSB
        f[6] = 1; // EV_CURRENT
        f[16..18].copy_from_slice(&2u16.to_le_bytes()); // ET_EXEC
        f[18..20].copy_from_slice(&0x3eu16.to_le_bytes()); // EM_X86_64
        f[20..24].copy_from_slice(&1u32.to_le_bytes()); // e_version
        f[52..54].copy_from_slice(&64u16.to_le_bytes()); // e_ehsize
        f[58..60].copy_from_slice(&64u16.to_le_bytes()); // e_shentsize
        f[62..64].copy_from_slice(&2u16.to_le_bytes()); // e_shstrndx

        let shstr_off = 64u64;
        f[64..64 + shstrtab.len()].copy_from_slice(shstrtab);
        while !f.len().is_multiple_of(8) {
            f.push(0);
        }
        let sh_off = f.len() as u64;
        f[40..48].copy_from_slice(&sh_off.to_le_bytes()); // e_shoff
        f[60..62].copy_from_slice(&3u16.to_le_bytes()); // e_shnum

        let mut sh = |name: u32, typ: u32, off: u64, size: u64| {
            let mut e = vec![0u8; 64];
            e[0..4].copy_from_slice(&name.to_le_bytes());
            e[4..8].copy_from_slice(&typ.to_le_bytes());
            e[24..32].copy_from_slice(&off.to_le_bytes());
            e[32..40].copy_from_slice(&size.to_le_bytes());
            f.extend_from_slice(&e);
        };
        sh(0, 0, 0, 0); // SHT_NULL
        sh(1, 1, 0, 0); // .bun -> SHT_PROGBITS
        sh(6, 3, shstr_off, shstrtab.len() as u64); // .shstrtab -> SHT_STRTAB
        f
    }

    #[test]
    fn detects_bun_section_binary() {
        let f = elf_with_bun_section();
        assert!(has_bun_section(&f));
        assert!(!has_self_extract_trailer(&f));
        assert!(has_embedded_payload(&f));
    }

    #[test]
    fn detects_pre_1_3_12_trailer() {
        let mut f = vec![0u8; 64];
        f.extend_from_slice(b"\n---- Bun! ----\n");
        assert!(has_self_extract_trailer(&f));
        assert!(has_embedded_payload(&f));
    }

    #[test]
    fn plain_elf_is_not_embedded_payload() {
        let mut f = vec![0u8; 64];
        f[0..4].copy_from_slice(b"\x7fELF");
        f[4] = 2;
        f[5] = 1;
        assert!(!has_bun_section(&f));
        assert!(!has_self_extract_trailer(&f));
        assert!(!has_embedded_payload(&f));
    }
}

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

    /// Only meaningful in a build that embeds the i686 constructor, as
    /// `ONELF_PAYLOAD_ALL=1` builds do.
    #[test]
    fn each_elf_class_gets_its_own_env_constructor() {
        let Some(blob32) = crate::payload::onelf_env_blob(goblin::elf::header::EM_386) else {
            return;
        };
        let dir = std::env::temp_dir().join(format!("onelf-envclass-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("lib");
        fs::create_dir_all(dir.join("bin")).unwrap();
        fs::copy(std::env::current_exe().unwrap(), dir.join("bin/app64")).unwrap();
        // Any 32-bit object stands in for an i686 executable here.
        fs::write(dir.join("bin/app32"), blob32).unwrap();
        for bin in ["bin/app64", "bin/app32"] {
            let _ = add_onelf_env_needed(&dir.join(bin), &lib);
        }
        let class = |name: &str| fs::read(lib.join(name)).ok().map(|b| b[4]);
        let (class64, class32) = (class("libonelf-env.so"), class("libonelf-env32.so"));
        let _ = fs::remove_dir_all(&dir);
        assert_eq!(class64, Some(2));
        assert_eq!(class32, Some(1));
    }
}

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

    /// Byte the guard region after `.dynstr` is filled with. A real binary
    /// keeps a section there (`.gnu.version`, in the case that surfaced
    /// this), so anything the rewrite writes past the string table lands
    /// on data the loader still reads.
    const GUARD: u8 = 0xAA;
    const GUARD_LEN: usize = 32;

    /// Minimal 64-bit ELF with a PT_DYNAMIC segment carrying one DT_RUNPATH
    /// slot. `runpath` is the only string in `.dynstr`, so its NUL is the
    /// section's last byte and the guard region begins immediately after.
    /// Returns the file bytes and the guard's offset.
    fn elf_with_runpath(runpath: &[u8]) -> (Vec<u8>, usize) {
        elf_with_runpath_and(runpath, true)
    }

    /// [`elf_with_runpath`], optionally without section headers, in which
    /// case a `PT_LOAD` covering the file and `DT_STRTAB`/`DT_STRSZ` are
    /// the only way to the string table, as after `sstrip`.
    fn elf_with_runpath_and(runpath: &[u8], section_headers: bool) -> (Vec<u8>, usize) {
        const SHSTRTAB: &[u8] = b"\0.dynstr\0.shstrtab\0";
        let mut dynstr = vec![0u8];
        dynstr.extend_from_slice(runpath);
        dynstr.push(0);

        let mut f = vec![0u8; 64];
        f[0..4].copy_from_slice(b"\x7fELF");
        f[4] = 2; // ELFCLASS64
        f[5] = 1; // ELFDATA2LSB
        f[6] = 1; // EV_CURRENT
        f[16..18].copy_from_slice(&2u16.to_le_bytes()); // ET_EXEC
        f[18..20].copy_from_slice(&0x3eu16.to_le_bytes()); // EM_X86_64
        f[20..24].copy_from_slice(&1u32.to_le_bytes()); // e_version
        f[32..40].copy_from_slice(&64u64.to_le_bytes()); // e_phoff
        f[52..54].copy_from_slice(&64u16.to_le_bytes()); // e_ehsize
        f[54..56].copy_from_slice(&56u16.to_le_bytes()); // e_phentsize
        f[56..58].copy_from_slice(&2u16.to_le_bytes()); // e_phnum
        f[58..60].copy_from_slice(&64u16.to_le_bytes()); // e_shentsize
        if section_headers {
            f[60..62].copy_from_slice(&3u16.to_le_bytes()); // e_shnum
            f[62..64].copy_from_slice(&2u16.to_le_bytes()); // e_shstrndx
        }

        // PT_LOAD first, mapping the whole file at vaddr 0, then PT_DYNAMIC.
        let load_off = f.len();
        f.extend_from_slice(&[0u8; 56]);
        let ph_off = f.len();
        f.extend_from_slice(&[0u8; 56]);

        let dynstr_off = f.len() as u64;
        f.extend_from_slice(&dynstr);
        let guard_off = f.len();
        f.extend_from_slice(&[GUARD; GUARD_LEN]);

        while !f.len().is_multiple_of(8) {
            f.push(0);
        }
        let dyn_off = f.len() as u64;
        for (tag, val) in [
            (goblin::elf::dynamic::DT_RUNPATH, 1u64),
            (goblin::elf::dynamic::DT_STRTAB, dynstr_off),
            (goblin::elf::dynamic::DT_STRSZ, dynstr.len() as u64),
            (0, 0),
        ] {
            f.extend_from_slice(&tag.to_le_bytes());
            f.extend_from_slice(&val.to_le_bytes());
        }
        let dyn_size = f.len() as u64 - dyn_off;
        f[ph_off..ph_off + 4].copy_from_slice(&2u32.to_le_bytes()); // PT_DYNAMIC
        f[ph_off + 8..ph_off + 16].copy_from_slice(&dyn_off.to_le_bytes());
        f[ph_off + 16..ph_off + 24].copy_from_slice(&dyn_off.to_le_bytes());
        f[ph_off + 32..ph_off + 40].copy_from_slice(&dyn_size.to_le_bytes());
        f[ph_off + 40..ph_off + 48].copy_from_slice(&dyn_size.to_le_bytes());

        let file_len = f.len() as u64;
        f[load_off..load_off + 4].copy_from_slice(&1u32.to_le_bytes()); // PT_LOAD
        f[load_off + 4..load_off + 8].copy_from_slice(&5u32.to_le_bytes()); // PF_R|PF_X
        f[load_off + 32..load_off + 40].copy_from_slice(&file_len.to_le_bytes());
        f[load_off + 40..load_off + 48].copy_from_slice(&file_len.to_le_bytes());
        f[load_off + 48..load_off + 56].copy_from_slice(&0x1000u64.to_le_bytes());
        if !section_headers {
            return (f, guard_off);
        }

        let shstr_off = f.len() as u64;
        f.extend_from_slice(SHSTRTAB);
        while !f.len().is_multiple_of(8) {
            f.push(0);
        }
        let sh_off = f.len() as u64;
        f[40..48].copy_from_slice(&sh_off.to_le_bytes());

        let mut sh = |name: u32, typ: u32, off: u64, size: u64| {
            let mut e = vec![0u8; 64];
            e[0..4].copy_from_slice(&name.to_le_bytes());
            e[4..8].copy_from_slice(&typ.to_le_bytes());
            e[24..32].copy_from_slice(&off.to_le_bytes());
            e[32..40].copy_from_slice(&size.to_le_bytes());
            f.extend_from_slice(&e);
        };
        sh(0, 0, 0, 0); // SHT_NULL
        sh(1, 3, dynstr_off, dynstr.len() as u64); // .dynstr -> SHT_STRTAB
        sh(9, 3, shstr_off, SHSTRTAB.len() as u64); // .shstrtab -> SHT_STRTAB

        (f, guard_off)
    }

    /// Write `bytes` to a fresh file, finalize it the way `bundle-libs`
    /// does (with no patchelf to fall back to), and return what was left
    /// on disk.
    fn rewrite(tag: &str, bytes: &[u8]) -> Vec<u8> {
        let dir = std::env::temp_dir().join(format!("onelf-runpath-{tag}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("lib.so");
        fs::write(&path, bytes).unwrap();
        finalize_one(&path, "$ORIGIN/../lib", "$ORIGIN/../lib", None).unwrap();
        let out = fs::read(&path).unwrap();
        let _ = fs::remove_dir_all(&dir);
        out
    }

    #[test]
    fn short_slot_is_scrubbed_without_touching_the_next_section() {
        let old = b"/usr/lib/tinysparql-3.0";
        let (bytes, guard_off) = elf_with_runpath(old);
        let out = rewrite("short", &bytes);
        assert_eq!(out.len(), bytes.len());
        assert!(
            out[guard_off..guard_off + GUARD_LEN]
                .iter()
                .all(|&b| b == GUARD)
        );
        // The slot holds an `$ORIGIN` fallback or nothing, never the host
        // path it came with, and its NUL terminator stays inside it.
        let slot = &out[guard_off - old.len() - 1..guard_off];
        let written = &slot[..slot.iter().position(|&b| b == 0).unwrap()];
        assert!(written.is_empty() || written.starts_with(b"$ORIGIN"));
        assert!(!out.windows(old.len()).any(|w| w == old));
    }

    #[test]
    fn a_section_stripped_object_is_still_rewritten() {
        let old = b"/usr/lib/tinysparql-3.0";
        let (bytes, guard_off) = elf_with_runpath_and(old, false);
        let out = rewrite("stripped", &bytes);
        assert_eq!(out.len(), bytes.len());
        assert!(
            out[guard_off..guard_off + GUARD_LEN]
                .iter()
                .all(|&b| b == GUARD)
        );
        assert!(!out.windows(old.len()).any(|w| w == old));
    }

    #[test]
    fn a_slot_left_for_patchelf_is_still_scrubbed() {
        let old = b"/usr/lib/tinysparql-3.0";
        let (bytes, _) = elf_with_runpath(old);
        let dir = std::env::temp_dir().join(format!("onelf-runpath-owed-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("lib.so");
        fs::write(&path, &bytes).unwrap();
        // The full run path names a directory of the library's own and
        // does not fit, so patchelf is owed, and there is none.
        let (outcome, _) = finalize_one(
            &path,
            "$ORIGIN/../lib:$ORIGIN/../lib/tinysparql-3.0",
            "$ORIGIN/../lib",
            None,
        )
        .unwrap();
        assert_eq!(outcome, RunpathOutcome::Unguaranteed);
        let out = fs::read(&path).unwrap();
        let _ = fs::remove_dir_all(&dir);
        assert!(!out.windows(old.len()).any(|w| w == old));
        let elf = goblin::elf::Elf::parse(&out).unwrap();
        let tags: Vec<u64> = elf.dynamic.unwrap().dyns.iter().map(|d| d.d_tag).collect();
        assert!(tags.contains(&goblin::elf::dynamic::DT_RPATH));
        assert!(!tags.contains(&goblin::elf::dynamic::DT_RUNPATH));
    }

    #[test]
    fn the_runpath_reaches_lib_from_every_depth() {
        let lib = Path::new("lib");
        assert_eq!(origin_runpath(0, lib), "$ORIGIN/lib");
        assert_eq!(origin_runpath(1, lib), "$ORIGIN/../lib");
        assert_eq!(origin_runpath(3, lib), "$ORIGIN/../../../lib");
        let root = Path::new("/tree");
        assert_eq!(
            origin_runpath_for(root, Path::new("/tree/opt/x/bin/app"), lib),
            "$ORIGIN/../../../lib"
        );
        assert_eq!(
            origin_runpath_for(root, Path::new("/tree/lib/libfoo.so"), lib),
            "$ORIGIN/../lib"
        );
        assert_eq!(
            origin_runpath_for(root, Path::new("/tree/app"), Path::new("usr/lib")),
            "$ORIGIN/usr/lib"
        );
        assert_eq!(
            origin_runpath_for(root, Path::new("/tree/lib/gconv/EUC-CN.so"), lib),
            "$ORIGIN:$ORIGIN/../../lib"
        );
    }

    #[test]
    fn large_enough_slot_is_rewritten_in_place() {
        let (bytes, guard_off) = elf_with_runpath(&[b'x'; 80]);
        let out = rewrite("large", &bytes);
        assert_eq!(out.len(), bytes.len());
        assert!(
            out[guard_off..guard_off + GUARD_LEN]
                .iter()
                .all(|&b| b == GUARD)
        );
        let written = &out[guard_off - 81..guard_off - 81 + "$ORIGIN/../lib".len()];
        assert_eq!(written, b"$ORIGIN/../lib");
    }
}

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

    const MUSL_LIBC: &[u8] =
        b"\0/etc/passwd\0/etc/resolv.conf\0/usr/share/zoneinfo/\0/lib:/usr/local/lib:/usr/lib\0";
    const GLIBC_LDSO: &[u8] = b"\0/etc/ld.so.cache\0/etc/ld.so.preload\0/usr/lib64/\0/lib64/\0";

    fn scrub(tag: &str, bytes: &[u8], family: LibcFamily) -> Vec<u8> {
        let dir = std::env::temp_dir().join(format!("onelf-scrub-{tag}-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("loader");
        fs::write(&path, bytes).unwrap();
        scrub_loader_paths(&path, family).unwrap();
        let out = fs::read(&path).unwrap();
        fs::remove_dir_all(&dir).unwrap();
        out
    }

    #[test]
    fn musl_keeps_the_paths_libc_reads_at_runtime() {
        let out = scrub("musl", MUSL_LIBC, LibcFamily::Musl);
        assert_eq!(out.len(), MUSL_LIBC.len());
        assert_eq!(
            out,
            b"\0/etc/passwd\0/etc/resolv.conf\0/usr/share/zoneinfo/\0/XXX:/XXX/local/lib:/XXX/lib\0"
        );
    }

    #[test]
    fn glibc_loses_every_host_prefix() {
        let out = scrub("glibc", GLIBC_LDSO, LibcFamily::Glibc);
        assert_eq!(out.len(), GLIBC_LDSO.len());
        assert_eq!(
            out,
            b"\0/XXX/ld.so.cache\0/XXX/ld.so.preload\0/XXX/XXX///\0/XXX///\0"
        );
    }
}

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

    #[test]
    fn a_dangling_soname_link_satisfies_no_need() {
        let tree = std::env::temp_dir().join(format!("onelf-audit-{}", std::process::id()));
        let _ = fs::remove_dir_all(&tree);
        fs::create_dir_all(tree.join("bin")).unwrap();
        fs::create_dir_all(tree.join("lib")).unwrap();
        // The test binary needs libc.so.6, which is all this needs.
        fs::copy(std::env::current_exe().unwrap(), tree.join("bin/app")).unwrap();
        std::os::unix::fs::symlink("libc.so.6.pruned", tree.join("lib/libc.so.6")).unwrap();

        let findings = audit_unbundled_needs(&tree, Path::new("lib"));
        let _ = fs::remove_dir_all(&tree);
        assert!(
            findings
                .iter()
                .any(|(_, libs)| libs.iter().any(|l| l == "libc.so.6")),
            "a link to nothing is reported missing: {findings:?}"
        );
    }
}