onelf 0.3.3

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

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

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

/// 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.
pub(crate) fn resolve_runpath_dirs<'a>(
    raw: impl Iterator<Item = &'a str>,
    origin: &Path,
) -> Vec<PathBuf> {
    raw.flat_map(|s| s.split(':'))
        .filter(|s| !s.is_empty())
        .map(|entry| expand_runpath_entry(entry, origin))
        .filter(|p| p.is_dir())
        .collect()
}

pub(crate) fn parse_rpaths(path: &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(raw.iter().copied(), origin)
}

/// 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,
    /// Executable with deps but RUNPATH could not be guaranteed (no
    /// in-place slot and patchelf missing or failed). 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,
}

/// RUNPATH string written into every bundled binary.
///
/// Covers a binary sitting at the package root (`blender`), and at depth 1
/// (`bin/foo`), 2 (`libexec/podman/x`), and 3 (`share/pkg/helpers/y`).
/// Entries that do not exist are ignored by the loader, so one list serves
/// every depth.
///
/// The root case matters: an application whose executable is the top-level
/// file, which is how Blender and similar redistributables ship, resolves
/// `$ORIGIN/../lib` to a directory above the package and finds nothing.
const ORIGIN_RUNPATH: &str = "$ORIGIN/lib:$ORIGIN/../lib:$ORIGIN/../../lib:$ORIGIN/../../../lib";

/// Rewrite RUNPATH within `data`, reporting what the caller still owes.
///
/// Returns [`RunpathOutcome::NeedsPatchelf`] when no in-place slot is big
/// enough, since patchelf has to run against the file rather than the image.
fn rewrite_origin_runpath_in(data: &mut [u8], path: &Path) -> io::Result<RunpathOutcome> {
    let new_bytes = ORIGIN_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 = elf
        .section_headers
        .iter()
        .find(|sh| elf.shdr_strtab.get_at(sh.sh_name) == Some(".dynstr"))
        .map(|sh| (sh.sh_offset as usize, (sh.sh_offset + sh.sh_size) as usize));
    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 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;
        if new_bytes.len() + 1 > slot_size {
            continue;
        }
        data[file_pos..file_pos + new_bytes.len()].copy_from_slice(new_bytes);
        for b in &mut data[file_pos + new_bytes.len()..file_pos + slot_size] {
            *b = 0;
        }
        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());
            }
        }
    }

    if total > 0 && rewritten == total {
        return Ok(RunpathOutcome::Set);
    }
    // A slot too small to hold the new string keeps its old contents, but is
    // now an RPATH, so the executable's entry still covers it.
    if total > 0 && !is_executable {
        return Ok(RunpathOutcome::Set);
    }

    // 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);
    }
    // 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);
    }
    if is_self_extract {
        return Ok(RunpathOutcome::SelfExtract);
    }
    let _ = path;
    Ok(RunpathOutcome::NeedsPatchelf)
}

/// Run `patchelf --set-rpath` against `path`, reporting whether the RUNPATH
/// ended up guaranteed.
fn run_patchelf_rpath(path: &Path, 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(ORIGIN_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
        }
    }
}

pub(crate) fn set_origin_runpath(path: &Path) -> io::Result<RunpathOutcome> {
    let new_bytes = ORIGIN_RUNPATH.as_bytes();
    let data = fs::read(path)?;

    // Binaries with an embedded payload (pre-1.3.12 Bun via an EOF trailer,
    // >=1.3.12 Bun via a `.bun` section) must not be structurally rewritten:
    // patchelf grows the file and reshuffles the program headers, clobbering
    // the trailer or perturbing the layout the runtime payload lookup depends
    // on. The in-place rewrite is safe (same file size), so we still attempt
    // that, but we skip the patchelf fallback for these binaries.
    let is_self_extract = has_embedded_payload(&data);

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

    // Only meaningful for binaries with dynamic dependencies. A bottom-
    // of-stack lib like libc.so.6 or the dynamic loader has no DT_NEEDED
    // entries and doesn't need DT_RUNPATH itself.
    let has_needed = !elf.libraries.is_empty();
    // PT_INTERP marks an executable; pure shared libraries lack it. We
    // only warn / fall back to patchelf for executables, since libs
    // typically resolve their deps via the executable's DT_RUNPATH.
    // glibc's libc.so.6 (and ld.so) carry PT_INTERP but are libraries,
    // distinguished by a DT_SONAME; exclude anything with a SONAME so
    // they aren't mis-flagged as un-RUNPATH'd app executables.
    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);

    // Find the .dynstr section's file range. The end matters: the slot scan
    // below counts trailing NULs, and without a bound it runs off the end of
    // the string table into whatever section follows.
    let dynstr_range = elf
        .section_headers
        .iter()
        .find(|sh| elf.shdr_strtab.get_at(sh.sh_name) == Some(".dynstr"))
        .map(|sh| (sh.sh_offset as usize, (sh.sh_offset + sh.sh_size) as usize));

    let dynamic_present = elf.dynamic.is_some();
    // Track per-slot outcome: the in-place rewrite is trustworthy only when
    // *every* present DT_RPATH/DT_RUNPATH slot was rewritten. Rewriting some
    // and skipping a too-small one would leave a stale runpath behind, so in
    // that case we fall through to patchelf, which resets the runpath whole.
    let mut slots_total = 0usize;
    let mut slots_rewritten = 0usize;

    if let (Some((dynstr_offset, dynstr_end)), Some(dynamic)) = (dynstr_range, &elf.dynamic) {
        let mut modified = data.clone();
        let limit = dynstr_end.min(modified.len());
        for dyn_entry in &dynamic.dyns {
            if dyn_entry.d_tag == goblin::elf::dynamic::DT_RPATH
                || dyn_entry.d_tag == goblin::elf::dynamic::DT_RUNPATH
            {
                slots_total += 1;
                let file_pos = dynstr_offset + dyn_entry.d_val as usize;
                if file_pos >= limit {
                    continue;
                }
                let mut end = file_pos;
                while end < limit && modified[end] != 0 {
                    end += 1;
                }
                while end < limit && modified[end] == 0 {
                    end += 1;
                }
                let slot_size = end - file_pos;
                if new_bytes.len() + 1 > slot_size {
                    // Slot too small; will fall back to patchelf below.
                    continue;
                }
                modified[file_pos..file_pos + new_bytes.len()].copy_from_slice(new_bytes);
                for i in new_bytes.len()..slot_size {
                    modified[file_pos + i] = 0;
                }
                slots_rewritten += 1;
            }
        }
        if slots_total > 0 && slots_rewritten == slots_total {
            fs::write(path, &modified)?;
            return Ok(RunpathOutcome::Set);
        }
    }

    drop(elf);

    if !dynamic_present || !has_needed {
        // Nothing depends on libs (static binary, libc.so itself, the
        // dynamic loader, etc.). DT_RUNPATH wouldn't help here.
        return Ok(RunpathOutcome::NotNeeded);
    }

    if !is_executable {
        // Shared libraries usually resolve their deps via the
        // executable's DT_RUNPATH (transitive search). Skip patchelf
        // and the noisy warning for bare libs.
        return Ok(RunpathOutcome::NotNeeded);
    }

    if is_self_extract {
        // Don't risk patchelf growing the file and clobbering the
        // self-extract trailer. The runtime still sets LD_LIBRARY_PATH
        // as a fallback for these binaries.
        return Ok(RunpathOutcome::SelfExtract);
    }

    // No usable in-place slot. Fall back to patchelf, which can
    // either resize an existing slot or add a fresh DT_RUNPATH by
    // growing the file's string table.
    if let Some(patchelf) = which_patchelf() {
        let status = std::process::Command::new(&patchelf)
            .arg("--force-rpath")
            .arg("--set-rpath")
            .arg(ORIGIN_RUNPATH)
            .arg(path)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::piped())
            .output();
        match status {
            Ok(o) if o.status.success() => return Ok(RunpathOutcome::Set),
            Ok(o) => {
                let stderr = String::from_utf8_lossy(&o.stderr);
                eprintln!(
                    "  {} patchelf failed for {}: {}",
                    color::bold_red("warning:"),
                    path.display(),
                    stderr.trim()
                );
            }
            Err(e) => {
                eprintln!(
                    "  {} could not run patchelf for {}: {e}",
                    color::bold_red("warning:"),
                    path.display(),
                );
            }
        }
    }
    // No patchelf available and no in-place slot. The runtime still sets
    // LD_LIBRARY_PATH as a fallback for the initial launch, but it won't
    // survive a sandboxed re-exec. The caller reports this.
    Ok(RunpathOutcome::Unguaranteed)
}

/// Sonames a bundled object needs that no bundled file provides.
///
/// Anything listed here is resolved from the host at runtime, and not by
/// accident: the runtime appends the host's library directories to the
/// search path so GPU drivers stay reachable (`drivers::host_driver_paths`).
/// Those directories hold the whole system's libraries, not just drivers,
/// so a soname missing from the bundle is quietly satisfied by the host's
/// copy and loaded next to the bundled libc. A glibc that disagrees with
/// the bundled one is exactly the mismatch that crashes, and nothing
/// reports it, because on the packer's machine the host copy is the right
/// one.
///
/// The loader's own fallbacks are already closed: `scrub_loader_paths`
/// blanks its compiled-in directories and its `ld.so.cache` path. This is
/// the one remaining route, and it is one the runtime opens deliberately.
///
/// The dynamic loader is excluded: it is named through PT_INTERP rather
/// than DT_NEEDED, and is handled separately.
pub(crate) fn audit_unbundled_needs(directory: &Path) -> Vec<(PathBuf, Vec<String>)> {
    let mut provided: std::collections::HashSet<String> = std::collections::HashSet::new();
    for entry in jwalk::WalkDir::new(directory).sort(true) {
        let Ok(entry) = entry else { continue };
        if let Some(name) = entry.file_name().to_str() {
            provided.insert(name.to_string());
        }
    }

    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 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);
                !provided.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) -> (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) {
        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));
        }

        if let Ok((outcome, did_scrub)) = finalize_one(&path, 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)
}

/// 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, patchelf: Option<&Path>) -> io::Result<(RunpathOutcome, bool)> {
    let mut data = fs::read(path)?;

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

    if outcome == RunpathOutcome::Set || 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, 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!(
            "{} {} executable(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 = elf
        .section_headers
        .iter()
        .find(|sh| elf.shdr_strtab.get_at(sh.sh_name) == Some(".dynstr"))
        .map(|sh| sh.sh_offset as usize);
    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"
}

/// Rewrite absolute-path byte sequences baked into the dynamic loader.
///
/// glibc's `ld-linux` hardcodes its build-time `/etc/ld.so.cache`,
/// `/etc/ld-nix.so.preload`, `/nix/store/<hash>-glibc-X/lib/`, and a
/// few other absolute paths. Those 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 prefix with a path that is guaranteed not to resolve (starts
/// with `/XXX`), keeping byte length identical so ELF offsets stay
/// valid.
///
/// 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) -> io::Result<()> {
    let mut data = fs::read(path)?;
    let mut changed = false;
    // Each pattern and replacement are equal length to avoid any ELF
    // structure shifts. Replacements are paths that simply don't exist
    // on any sane system.
    let replacements: &[(&[u8], &[u8])] = &[
        (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///"),
    ];

    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 {
    /// `libonelf-env.so` 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 `libonelf-env.so` 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);
    };

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

    // Stage the blob into lib/ (write once; idempotent across binaries).
    let dest = lib_dest.join(crate::payload::ONELF_ENV_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(crate::payload::ONELF_ENV_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;
        }
        // Skip everything in lib/ (shared libs, the ld, libc, etc).
        // Only inject into application binaries outside the lib dir.
        if path.starts_with(lib_dest) {
            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 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) {
        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(&1u16.to_le_bytes()); // e_phnum
        f[58..60].copy_from_slice(&64u16.to_le_bytes()); // e_shentsize
        f[60..62].copy_from_slice(&3u16.to_le_bytes()); // e_shnum
        f[62..64].copy_from_slice(&2u16.to_le_bytes()); // e_shstrndx

        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), (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 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, run `set_origin_runpath` on it, and
    /// return what the function 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();
        set_origin_runpath(&path).unwrap();
        let out = fs::read(&path).unwrap();
        let _ = fs::remove_dir_all(&dir);
        out
    }

    #[test]
    fn short_slot_leaves_the_next_section_alone() {
        let (bytes, guard_off) = elf_with_runpath(b"/usr/lib/tinysparql-3.0");
        let out = rewrite("short", &bytes);
        assert_eq!(out.len(), bytes.len());
        assert!(
            out[guard_off..guard_off + GUARD_LEN]
                .iter()
                .all(|&b| b == GUARD)
        );
        assert_eq!(&out[..guard_off], &bytes[..guard_off]);
    }

    #[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_RUNPATH.len()];
        assert_eq!(written, ORIGIN_RUNPATH.as_bytes());
    }
}