onelf 0.6.1

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
//! Descriptor plugin-group collection over the dependency walk.
//!
//! An activated rule's plugin group declares ordered source directories
//! against the libraries the walk has admitted. Discovery enumerates the
//! alternatives that exist and are admitted; collection walks every
//! directory a group's discovery found and hands each compatible plugin
//! to the walk as an object, written at the group's declared
//! destination with the source layout preserved.
//!
//! A group that lists its members collects only those, matched by their
//! path relative to the found directory. The rest of the directory is
//! passed over before any compatibility check.
//!
//! A member that is not an ELF object of the bundle's own class and
//! machine is refused with a reason and never shadows a compatible one,
//! so a multiarch plugin directory contributes only its matching half.
//! Collection is bounded: a directory past the member or depth cap is a
//! refused group, not an unbounded walk.

use std::collections::HashMap;
use std::fs;
use std::io;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};

use onelf_format::rules::{RelativePath, Requirement, ResourceGroup};

use super::elf::libc_family_of_soname;
use super::plan::TREE_WALK_LIMIT;
use super::{
    AdmittedLibrary, AdmittedUniverse, CandidateHit, GroupQuery, LibcFamily, counterpart_spelling,
    discover_group, is_nix_stub_ld, miss_text, parse_needed, read_elf_class, read_elf_machine,
    resolve_within,
};
use crate::bundle::sysroot::SysrootUniverse;

/// The most members one group's collection may yield. A directory past
/// this is a hostile or pathological source, not completeness.
const MAX_GROUP_MEMBERS: usize = 4096;

/// The deepest one found directory is walked for members, so a
/// hostile or pathological tree cannot recurse without end.
pub(crate) const MAX_GROUP_DEPTH: usize = 16;

/// The most unavailable locations one report names, so a wide
/// declaration cannot flood the build log.
const SHOWN_MISSES: usize = 8;

/// One compatible plugin a group collected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CollectedPlugin {
    /// The file name the plugin answers to, which the walk resolves and
    /// the loader asks for.
    pub soname: String,
    /// The destination relative to the AppDir, layout preserved.
    pub destination: PathBuf,
    /// Where the member was found, so the walk can search beside it
    /// when the plugin sits in a subdirectory of the group location.
    pub resolved: PathBuf,
}

/// What one activated plugin group's collection contributes to the walk.
#[derive(Debug, Default)]
pub(crate) struct GroupCollection {
    /// The rule that owns the group.
    pub rule: String,
    /// The group's identity within its rule.
    pub group: String,
    /// The directories discovery found, which the walk searches for the
    /// collected sonames.
    pub search_dirs: Vec<PathBuf>,
    /// The compatible plugins, in discovery order.
    pub plugins: Vec<CollectedPlugin>,
    /// Members examined and refused, each with its reason.
    pub skipped: Vec<(String, String)>,
    /// Why each declared location held nothing usable, bounded.
    pub misses: Vec<String>,
    /// Where the found directory lives under a host library directory,
    /// as the first hit's declared location spells it: the candidate's
    /// path for a library-directory base, the same path with its
    /// leading library directory taken off for an installation-prefix
    /// base. Empty when that first hit names no library directory, as
    /// a `share`-based group does not. Inference derives its own
    /// spelling from where the tree carries the directory, so its
    /// collections leave this empty.
    pub counterpart: String,
}

/// Collect one activated plugin group over the libraries the walk
/// admitted. A group whose declaration is required and that yields no
/// usable plugin is an error naming the rule, the group and the
/// reasons; an optional one is reported and the walk goes on.
pub(crate) fn collect_group(
    rule: &str,
    declared: &ResourceGroup,
    admitted: &[AdmittedLibrary],
    sysroot: Option<&SysrootUniverse>,
    target_class: Option<u8>,
    target_machine: Option<u16>,
) -> io::Result<GroupCollection> {
    let outcome = discover_group(
        &GroupQuery {
            rule,
            group: declared.id.as_str(),
            kind: declared.kind,
            destination: &declared.destination,
            candidates: &declared.candidates,
        },
        &AdmittedUniverse {
            libraries: admitted,
            sysroot,
        },
    )?;

    let mut collection = collect_found(
        rule,
        declared.id.as_str(),
        &declared.members,
        &outcome.found,
        sysroot,
        target_class,
        target_machine,
    )?;
    collection.misses = outcome
        .misses
        .iter()
        .take(SHOWN_MISSES)
        .map(|m| format!("{}: {}", m.root.display(), miss_text(&m.reason)))
        .collect();

    if collection.plugins.is_empty() && declared.requirement == Requirement::Required {
        let mut text = format!(
            "rule {rule} group {} is required but no usable plugin was found",
            declared.id.as_str()
        );
        for reason in collection.misses.iter().take(3) {
            text.push_str("; ");
            text.push_str(reason);
        }
        for (name, reason) in collection.skipped.iter().take(3) {
            text.push_str(&format!("; {name}: {reason}"));
        }
        return Err(io::Error::new(io::ErrorKind::NotFound, text));
    }
    Ok(collection)
}

/// Collect the compatible plugins below directories already found, each
/// at its hit's destination with the layout preserved. A non-empty
/// `members_allowed` collects only the listed members. Members refused
/// for their kind, class or machine, and second members for one
/// destination, are recorded as skipped with the reason.
pub(crate) fn collect_found(
    rule: &str,
    group: &str,
    members_allowed: &[RelativePath],
    found: &[CandidateHit],
    sysroot: Option<&SysrootUniverse>,
    target_class: Option<u8>,
    target_machine: Option<u16>,
) -> io::Result<GroupCollection> {
    let mut collection = GroupCollection {
        rule: rule.to_string(),
        group: group.to_string(),
        search_dirs: Vec::new(),
        plugins: Vec::new(),
        skipped: Vec::new(),
        misses: Vec::new(),
        counterpart: found
            .first()
            .and_then(|hit| {
                let declared = hit.source.strip_prefix(&hit.root).ok()?;
                counterpart_spelling(hit.base, declared)
            })
            .unwrap_or_default(),
    };
    // Members are keyed by where they land: a nested layout keeps
    // same-named members apart (babl's `x86-64-v2/` and `x86-64-v3/`
    // variants), and only a second member for one destination is
    // refused, with the member that took it named.
    let mut taken: HashMap<PathBuf, PathBuf> = HashMap::new();
    let target = (target_class, target_machine);
    for hit in found {
        collection.search_dirs.push(hit.resolved.clone());
        for (rel, path) in members(hit, sysroot)? {
            let named_so = rel
                .file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.ends_with(".so"));
            if !named_so {
                continue;
            }
            let shown = rel.to_string_lossy();
            if !members_allowed.is_empty() && !members_allowed.iter().any(|m| m.as_str() == shown) {
                continue;
            }
            take_member(&mut collection, &mut taken, hit, &rel, &path, target)?;
        }
    }
    Ok(collection)
}

/// Collect every ELF object among `members`, already read from `hit`,
/// whatever its name: a versioned library, a backend named `*.so.N` or
/// a helper program beside the modules. A member that is not an ELF
/// object is left to the caller, which carries it as data.
pub(crate) fn collect_objects(
    rule: &str,
    group: &str,
    hit: &CandidateHit,
    members: &[(PathBuf, PathBuf)],
    (target_class, target_machine, target_libc): (Option<u8>, Option<u16>, Option<LibcFamily>),
) -> io::Result<GroupCollection> {
    let mut collection = GroupCollection {
        rule: rule.to_string(),
        group: group.to_string(),
        search_dirs: vec![hit.resolved.clone()],
        ..GroupCollection::default()
    };
    let mut taken: HashMap<PathBuf, PathBuf> = HashMap::new();
    for (rel, path) in members {
        if read_elf_class(path).is_some() {
            // An object linking another libc than the bundle runs would
            // pull that libc into the process: it stays out, named.
            if let Some(want) = target_libc
                && let Some(have) = parse_needed(path)
                    .unwrap_or_default()
                    .iter()
                    .find_map(|d| libc_family_of_soname(d))
                && have != want
            {
                collection.skipped.push((
                    rel.to_string_lossy().into_owned(),
                    format!("links {have:?} libc, the bundle runs {want:?}"),
                ));
                continue;
            }
            take_member(
                &mut collection,
                &mut taken,
                hit,
                rel,
                path,
                (target_class, target_machine),
            )?;
        }
    }
    Ok(collection)
}

/// Take one member into `collection` at its place below the hit's
/// destination, or record it skipped with the reason: an object the
/// bundle cannot load, or a second member for a destination already
/// `taken`.
fn take_member(
    collection: &mut GroupCollection,
    taken: &mut HashMap<PathBuf, PathBuf>,
    hit: &CandidateHit,
    rel: &Path,
    path: &Path,
    (target_class, target_machine): (Option<u8>, Option<u16>),
) -> io::Result<()> {
    let Some(name) = rel.file_name().and_then(|n| n.to_str()) else {
        return Ok(());
    };
    let shown = rel.to_string_lossy().into_owned();
    if let Err(reason) = compatible_object(path, target_class, target_machine) {
        collection.skipped.push((shown, reason));
        return Ok(());
    }
    let destination = hit.destination.join(rel);
    if let Some(first) = taken.get(&destination) {
        collection.skipped.push((
            shown,
            format!(
                "{} is already collected from {}",
                destination.display(),
                first.display()
            ),
        ));
        return Ok(());
    }
    if collection.plugins.len() >= MAX_GROUP_MEMBERS {
        return Err(bounded(
            &collection.rule,
            &collection.group,
            MAX_GROUP_MEMBERS,
        ));
    }
    taken.insert(destination.clone(), path.to_path_buf());
    collection.plugins.push(CollectedPlugin {
        soname: name.to_string(),
        destination,
        resolved: path.to_path_buf(),
    });
    Ok(())
}

/// The bounded-collection error: which group stopped, and at what.
fn bounded(rule: &str, group: &str, cap: usize) -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidData,
        format!(
            "rule {rule} group {group}: more than {cap} members in one plugin \
             group; refusing unbounded collection"
        ),
    )
}

/// The files one found directory holds, as pairs of the path relative
/// to the directory and the absolute path, in sorted order. A sysroot
/// build takes its members from the build's own admitted files, so a
/// pruned member is never walked; a host scan walks the directory.
pub(crate) fn members(
    hit: &CandidateHit,
    sysroot: Option<&SysrootUniverse>,
) -> io::Result<Vec<(PathBuf, PathBuf)>> {
    let mut out = Vec::new();
    visit_members(hit, sysroot, &mut |rel, path| {
        out.push((rel, path));
        ControlFlow::Continue(())
    })?;
    Ok(out)
}

/// Visit the files [`members`] lists, in the same order, until `visit`
/// breaks, so a question one member answers stops the walk there.
pub(crate) fn visit_members(
    hit: &CandidateHit,
    sysroot: Option<&SysrootUniverse>,
    visit: &mut dyn FnMut(PathBuf, PathBuf) -> ControlFlow<()>,
) -> io::Result<()> {
    if let Some(universe) = sysroot {
        let dir_rel = hit
            .resolved
            .strip_prefix(universe.root())
            .map_err(|_| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "{}: outside the sysroot it was found in",
                        hit.resolved.display()
                    ),
                )
            })?
            .to_string_lossy()
            .into_owned();
        // Each admitted member, a link among them, resolves inside the
        // sysroot, never through an absolute link onto the packer's
        // machine.
        for f in universe.admitted_under(&dir_rel) {
            let rel = PathBuf::from(&f)
                .strip_prefix(&dir_rel)
                .unwrap_or(Path::new(&f))
                .to_path_buf();
            let Ok(path) = onelf_sysroot::path::in_root(universe.root(), Path::new(&f)) else {
                continue;
            };
            if visit(rel, path).is_break() {
                break;
            }
        }
        return Ok(());
    }
    let mut visited = 0usize;
    walk_members(
        &hit.root,
        &hit.resolved,
        Path::new(""),
        0,
        &mut visited,
        visit,
    )
    .map(|_| ())
}

/// Visit the regular-file members under `dir` as pairs of the path
/// relative to the group directory and the file to read, until `visit`
/// breaks. A symlinked member, an ALSA module alias say, is followed
/// with every landing confined to `root`, the admitted root the group
/// was found under, so the alias is collected under its own name and a
/// link leaving the root is not. The walk admits no more entries than
/// the tree walk limit, counting directories and links with files, and
/// stops with the bound named before reading past it.
fn walk_members(
    root: &Path,
    dir: &Path,
    rel: &Path,
    depth: usize,
    visited: &mut usize,
    visit: &mut dyn FnMut(PathBuf, PathBuf) -> ControlFlow<()>,
) -> io::Result<ControlFlow<()>> {
    if depth > MAX_GROUP_DEPTH {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "{}: deeper than the {MAX_GROUP_DEPTH} level group walk limit",
                dir.display()
            ),
        ));
    }
    let mut entries: Vec<fs::DirEntry> = Vec::new();
    for entry in fs::read_dir(dir)? {
        *visited += 1;
        if *visited > TREE_WALK_LIMIT {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "{}: more than {TREE_WALK_LIMIT} entries, past the walk limit",
                    dir.display()
                ),
            ));
        }
        entries.push(entry?);
    }
    entries.sort_by_key(|e| e.file_name());
    for entry in entries {
        let child_rel = rel.join(entry.file_name());
        let child = dir.join(entry.file_name());
        let kind = entry.file_type()?;
        let flow = if kind.is_dir() {
            walk_members(root, &child, &child_rel, depth + 1, visited, visit)?
        } else if kind.is_file() {
            visit(child_rel, child)
        } else if kind.is_symlink()
            && let Ok(inside) = child.strip_prefix(root)
            && let Ok(target) = resolve_within(root, inside)
            && target.is_file()
        {
            visit(child_rel, target)
        } else {
            ControlFlow::Continue(())
        };
        if flow.is_break() {
            return Ok(flow);
        }
    }
    Ok(ControlFlow::Continue(()))
}

/// Whether a member is an ELF object the bundle can load: the same
/// checks the library walk applies to every candidate it resolves. A
/// non-object, a wrong class and another machine are all refusals, so
/// an incompatible candidate is recorded instead of shadowing a valid
/// one.
fn compatible_object(
    path: &Path,
    target_class: Option<u8>,
    target_machine: Option<u16>,
) -> Result<(), String> {
    if is_nix_stub_ld(path) {
        return Err("a stub loader that loads nothing".to_string());
    }
    let Some(class) = read_elf_class(path) else {
        return Err("not an ELF object".to_string());
    };
    if let Some(want) = target_class
        && class != want
    {
        return Err(format!(
            "ELF class {class}, the bundle builds for class {want}"
        ));
    }
    match (target_machine, read_elf_machine(path)) {
        (Some(want), Some(machine)) if machine != want => Err(format!(
            "machine {machine}, the bundle builds for machine {want}"
        )),
        (Some(_), None) => Err("not an ELF object".to_string()),
        _ => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bundle::sysroot::fixture;
    use onelf_format::catalog;
    use onelf_format::rules::{ResourceKind, SourceBase};

    /// Minimal ELF-shaped bytes: magic + EI_CLASS + e_machine, enough
    /// for the compatibility checks to classify.
    fn fake_elf(class: u8, machine: u16) -> Vec<u8> {
        let mut v = vec![0u8; 64];
        v[0..4].copy_from_slice(b"\x7fELF");
        v[4] = class;
        v[18..20].copy_from_slice(&machine.to_le_bytes());
        v
    }

    fn write(path: &Path, bytes: &[u8]) {
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, bytes).unwrap();
    }

    fn admitted_lib(path: &Path) -> AdmittedLibrary {
        AdmittedLibrary::new(path.file_name().unwrap().to_str().unwrap(), path)
    }

    fn builtin_group(rule: &str) -> ResourceGroup {
        catalog::builtins()
            .iter()
            .find(|d| d.id.as_str() == rule)
            .unwrap()
            .resources
            .plugins
            .first()
            .unwrap()
            .clone()
    }

    fn collected<'a>(collection: &'a GroupCollection, soname: &str) -> &'a CollectedPlugin {
        collection
            .plugins
            .iter()
            .find(|p| p.soname == soname)
            .unwrap()
    }

    #[test]
    fn an_activated_group_collects_every_compatible_member() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");
        write(&lib.join("libgstreamer-1.0.so.0"), &fake_elf(2, 62));
        write(&lib.join("gstreamer-1.0/pulse.so"), &fake_elf(2, 62));
        write(&lib.join("gstreamer-1.0/loop.so"), &fake_elf(2, 62));
        write(&lib.join("gstreamer-1.0/README"), b"notes");
        let libs = [admitted_lib(&lib.join("libgstreamer-1.0.so.0"))];

        let collection = collect_group(
            "gstreamer",
            &builtin_group("gstreamer"),
            &libs,
            None,
            Some(2),
            Some(62),
        )
        .unwrap();

        assert_eq!(collection.search_dirs, vec![lib.join("gstreamer-1.0")]);
        assert_eq!(collection.plugins.len(), 2, "{:?}", collection.plugins);
        assert_eq!(
            collected(&collection, "pulse.so").destination,
            PathBuf::from("lib/gstreamer-1.0/pulse.so")
        );
        assert!(collection.skipped.is_empty(), "{:?}", collection.skipped);
        let _ = fs::remove_dir_all(&dir);
    }

    /// Same-named members in different subdirectories of one group are
    /// different plugins: each lands at its own destination, copied
    /// from where it was found, and none is dropped as a duplicate.
    #[test]
    fn same_named_members_in_nested_layouts_are_all_collected() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");
        write(&lib.join("libgstreamer-1.0.so.0"), &fake_elf(2, 62));
        write(
            &lib.join("gstreamer-1.0/x86-64-v2/cmyk.so"),
            &fake_elf(2, 62),
        );
        write(
            &lib.join("gstreamer-1.0/x86-64-v3/cmyk.so"),
            &fake_elf(2, 62),
        );
        write(&lib.join("gstreamer-1.0/cmyk.so"), &fake_elf(2, 62));
        let libs = [admitted_lib(&lib.join("libgstreamer-1.0.so.0"))];

        let collection = collect_group(
            "gstreamer",
            &builtin_group("gstreamer"),
            &libs,
            None,
            Some(2),
            Some(62),
        )
        .unwrap();
        let mut found: Vec<(PathBuf, PathBuf)> = collection
            .plugins
            .iter()
            .map(|p| (p.destination.clone(), p.resolved.clone()))
            .collect();
        found.sort();
        assert_eq!(
            found,
            vec![
                (
                    PathBuf::from("lib/gstreamer-1.0/cmyk.so"),
                    lib.join("gstreamer-1.0/cmyk.so")
                ),
                (
                    PathBuf::from("lib/gstreamer-1.0/x86-64-v2/cmyk.so"),
                    lib.join("gstreamer-1.0/x86-64-v2/cmyk.so")
                ),
                (
                    PathBuf::from("lib/gstreamer-1.0/x86-64-v3/cmyk.so"),
                    lib.join("gstreamer-1.0/x86-64-v3/cmyk.so")
                ),
            ]
        );
        assert!(collection.skipped.is_empty(), "{:?}", collection.skipped);
        let _ = fs::remove_dir_all(&dir);
    }

    /// A symlinked member, an ALSA module alias, is collected under its
    /// own name from the file it names inside the admitted root, and a
    /// link that leaves the root is not followed.
    #[test]
    fn a_symlinked_member_is_followed_inside_its_root() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");
        let outside = dir.join("outside/libasound_module_pcm_far.so");
        write(&lib.join("libasound.so.2"), &fake_elf(2, 62));
        write(
            &lib.join("gstreamer-1.0/libasound_module_pcm_pulse.so"),
            &fake_elf(2, 62),
        );
        write(&outside, &fake_elf(2, 62));
        std::os::unix::fs::symlink(
            "libasound_module_pcm_pulse.so",
            lib.join("gstreamer-1.0/libasound_module_pcm_alias.so"),
        )
        .unwrap();
        std::os::unix::fs::symlink(
            &outside,
            lib.join("gstreamer-1.0/libasound_module_pcm_far.so"),
        )
        .unwrap();
        let libs = [admitted_lib(&lib.join("libasound.so.2"))];

        let collection = collect_group(
            "gstreamer",
            &builtin_group("gstreamer"),
            &libs,
            None,
            Some(2),
            Some(62),
        )
        .unwrap();
        let alias = collected(&collection, "libasound_module_pcm_alias.so");
        assert_eq!(
            alias.destination,
            PathBuf::from("lib/gstreamer-1.0/libasound_module_pcm_alias.so")
        );
        assert_eq!(
            alias.resolved,
            lib.join("gstreamer-1.0/libasound_module_pcm_pulse.so")
        );
        assert!(
            !collection
                .plugins
                .iter()
                .any(|p| p.soname == "libasound_module_pcm_far.so"),
            "{:?}",
            collection.plugins
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn nested_layout_is_preserved_into_the_destination() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib/x86_64-linux-gnu");
        write(&lib.join("gstreamer-1.0.so.1"), &fake_elf(2, 62));
        write(&lib.join("gstreamer-1.0/plugins/x264.so"), &fake_elf(2, 62));
        write(&lib.join("gstreamer-1.0/deep/a/avif.so"), &fake_elf(2, 62));
        let libs = [admitted_lib(&lib.join("gstreamer-1.0.so.1"))];

        let collection = collect_group(
            "gstreamer",
            &builtin_group("gstreamer"),
            &libs,
            None,
            Some(2),
            Some(62),
        )
        .unwrap();

        assert_eq!(
            collected(&collection, "x264.so").destination,
            PathBuf::from("lib/gstreamer-1.0/plugins/x264.so"),
            "the nested layout a distribution ships is kept"
        );
        assert_eq!(
            collected(&collection, "avif.so").destination,
            PathBuf::from("lib/gstreamer-1.0/deep/a/avif.so")
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_incompatible_member_is_refused_without_shadowing() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");
        write(&lib.join("libgstreamer-1.0.so.0"), &fake_elf(2, 62));
        write(&lib.join("gstreamer-1.0/arm.so"), &fake_elf(2, 183));
        write(&lib.join("gstreamer-1.0/text.so"), b"not elf");
        write(&lib.join("gstreamer-1.0/thin.so"), &fake_elf(1, 62));
        write(&lib.join("gstreamer-1.0/core.so"), &fake_elf(2, 62));
        write(&lib.join("gstreamer-1.0/helper"), b"not a candidate");
        let libs = [admitted_lib(&lib.join("libgstreamer-1.0.so.0"))];

        let collection = collect_group(
            "gstreamer",
            &builtin_group("gstreamer"),
            &libs,
            None,
            Some(2),
            Some(62),
        )
        .unwrap();

        assert_eq!(collection.plugins.len(), 1);
        assert_eq!(collection.plugins[0].soname, "core.so");
        let refused: Vec<(&str, &str)> = collection
            .skipped
            .iter()
            .map(|(n, r)| (n.as_str(), r.as_str()))
            .collect();
        assert_eq!(
            refused,
            [
                ("arm.so", "machine 183, the bundle builds for machine 62"),
                ("text.so", "not an ELF object"),
                ("thin.so", "ELF class 1, the bundle builds for class 2"),
            ],
            "every refusal names its reason, in walk order"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_sysroot_group_walks_only_admitted_members() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let root = dir.join("sys");
        write(&root.join("usr/bin/app"), &fake_elf(2, 62));
        write(&root.join("usr/lib/libgio-2.0.so.0"), &fake_elf(2, 62));
        write(
            &root.join("usr/lib/gio/modules/gnutls.so"),
            &fake_elf(2, 62),
        );
        write(&root.join("usr/lib/gio/modules/other.so"), &fake_elf(2, 62));
        let mut app = fixture::package("app", &["usr/bin/app", "usr/lib/libgio-2.0.so.0"]);
        app.depends = vec!["gio".into()];
        let mut gio = fixture::package(
            "gio",
            &["usr/lib/libgio-2.0.so.0", "usr/lib/gio/modules/gnutls.so"],
        );
        gio.provides = vec!["gio".into()];
        let extra = fixture::package("extra-modules", &["usr/lib/gio/modules/other.so"]);
        let universe =
            fixture::populate_universe(&root, &[app, gio, extra], "app", &[], None, None);
        let libs = [admitted_lib(&root.join("usr/lib/libgio-2.0.so.0"))];

        let collection = collect_group(
            "gio",
            &builtin_group("gio"),
            &libs,
            Some(&universe),
            Some(2),
            Some(62),
        )
        .unwrap();

        assert_eq!(collection.plugins.len(), 1, "{:?}", collection.plugins);
        assert_eq!(collection.plugins[0].soname, "gnutls.so");
        assert_eq!(
            collection.plugins[0].destination,
            PathBuf::from("lib/gio/modules/gnutls.so"),
            "the unselected package's member never becomes a candidate"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_required_group_with_nothing_usable_is_an_error() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");
        write(&lib.join("libasound.so.2"), &fake_elf(2, 62));
        write(&lib.join("gstreamer-1.0/arm.so"), &fake_elf(2, 183));
        let libs = [admitted_lib(&lib.join("libasound.so.2"))];
        let mut required = builtin_group("gstreamer");
        required.requirement = Requirement::Required;

        let err = collect_group("gstreamer", &required, &libs, None, Some(2), Some(62))
            .expect_err("a required group with only an incompatible member fails");
        assert!(
            err.to_string()
                .contains("rule gstreamer group plugins is required but no usable plugin"),
            "{err}"
        );
        assert!(
            err.to_string().contains("arm.so"),
            "the refusal names the incompatible member: {err}"
        );

        fs::remove_dir_all(lib.join("gstreamer-1.0")).unwrap();
        let err = collect_group("gstreamer", &required, &libs, None, Some(2), Some(62))
            .expect_err("a required group with no directory fails");
        assert!(
            err.to_string().contains("absent"),
            "the refusal names the absent location: {err}"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_optional_group_with_nothing_usable_is_reported_not_failed() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");
        write(&lib.join("libgstreamer-1.0.so.0"), &fake_elf(2, 62));
        let libs = [admitted_lib(&lib.join("libgstreamer-1.0.so.0"))];

        let collection = collect_group(
            "gstreamer",
            &builtin_group("gstreamer"),
            &libs,
            None,
            Some(2),
            Some(62),
        )
        .unwrap();

        assert!(collection.plugins.is_empty());
        assert_eq!(collection.misses.len(), 1, "{:?}", collection.misses);
        assert!(collection.misses[0].contains("absent"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn the_same_member_in_two_roots_is_collected_once() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let one = dir.join("one/usr/lib");
        let two = dir.join("two/usr/lib");
        write(&one.join("libgio-2.0.so.0"), &fake_elf(2, 62));
        write(&two.join("libgio-2.0.so.0"), &fake_elf(2, 62));
        write(&one.join("gio/modules/shared.so"), &fake_elf(2, 62));
        write(&two.join("gio/modules/shared.so"), &fake_elf(2, 62));
        write(&two.join("gio/modules/other.so"), &fake_elf(2, 62));
        let libs = [
            admitted_lib(&one.join("libgio-2.0.so.0")),
            admitted_lib(&two.join("libgio-2.0.so.0")),
        ];

        let collection =
            collect_group("gio", &builtin_group("gio"), &libs, None, Some(2), Some(62)).unwrap();

        assert_eq!(collection.search_dirs.len(), 2);
        assert_eq!(collection.plugins.len(), 2, "{:?}", collection.plugins);
        assert_eq!(
            collected(&collection, "shared.so").destination,
            PathBuf::from("lib/gio/modules/shared.so"),
            "the first root in admission order decides the soname"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    /// A group listing its members collects those alone, a nested one by
    /// its relative path, and a non-member is neither collected nor
    /// recorded as refused.
    #[test]
    fn a_member_allowlist_collects_only_the_listed_members() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");
        write(&lib.join("libspa-0.2.so.0"), &fake_elf(2, 62));
        write(
            &lib.join("spa-0.2/support/libspa-support.so"),
            &fake_elf(2, 62),
        );
        write(
            &lib.join("spa-0.2/bluez5/libspa-bluez5.so"),
            &fake_elf(2, 62),
        );
        write(&lib.join("spa-0.2/libspa-support.so"), &fake_elf(2, 62));
        write(
            &lib.join("spa-0.2/audioconvert/libspa-arm.so"),
            &fake_elf(2, 183),
        );
        let libs = [admitted_lib(&lib.join("libspa-0.2.so.0"))];
        let mut listed = builtin_group("spa");
        listed.members = ["support/libspa-support.so", "audioconvert/libspa-arm.so"]
            .into_iter()
            .map(|m| onelf_format::rules::RelativePath::new(m).unwrap())
            .collect();

        let collection = collect_group("spa", &listed, &libs, None, Some(2), Some(62)).unwrap();
        let found: Vec<&Path> = collection
            .plugins
            .iter()
            .map(|p| p.destination.as_path())
            .collect();
        assert_eq!(found, [Path::new("lib/spa-0.2/support/libspa-support.so")]);
        assert_eq!(
            collection
                .skipped
                .iter()
                .map(|(n, _)| n.as_str())
                .collect::<Vec<_>>(),
            ["audioconvert/libspa-arm.so"],
            "a listed incompatible member is still refused with its reason"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn collection_is_bounded() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");
        write(&lib.join("libgstreamer-1.0.so.0"), &fake_elf(2, 62));
        for i in 0..MAX_GROUP_MEMBERS + 1 {
            write(
                &lib.join(format!("gstreamer-1.0/m{i}.so")),
                &fake_elf(2, 62),
            );
        }
        let libs = [admitted_lib(&lib.join("libgstreamer-1.0.so.0"))];

        let err = collect_group(
            "gstreamer",
            &builtin_group("gstreamer"),
            &libs,
            None,
            Some(2),
            Some(62),
        )
        .expect_err("a group past the member cap is refused");
        assert!(
            err.to_string()
                .contains("more than 4096 members in one plugin group"),
            "{err}"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    /// A hit of one base at one declared path, with the group directory
    /// laid out and a compatible member placed inside it.
    fn found(
        base: SourceBase,
        root: &Path,
        path: &str,
        member: &str,
        destination: &str,
    ) -> CandidateHit {
        write(&root.join(path).join(member), &fake_elf(2, 62));
        CandidateHit {
            candidate: 0,
            base,
            kind: ResourceKind::Directory,
            source: root.join(path),
            resolved: root.join(path),
            root: root.to_path_buf(),
            destination: PathBuf::from(destination),
        }
    }

    /// The record's host library path comes from the found candidate: a
    /// library-directory base spells the declared path itself.
    #[test]
    fn a_library_dir_base_spells_the_declared_path() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let lib = dir.join("usr/lib");

        let collection = collect_found(
            "alsa",
            "plugins",
            &[],
            &[found(
                SourceBase::LibraryDir,
                &lib,
                "alsa-lib",
                "pulse.so",
                "lib/alsa-lib",
            )],
            None,
            Some(2),
            Some(62),
        )
        .unwrap();

        assert_eq!(collection.counterpart, "alsa-lib");
        let _ = fs::remove_dir_all(&dir);
    }

    /// An installation-prefix base spells the declared path with its
    /// leading library directory, multiarch level included, taken off.
    #[test]
    fn a_prefix_base_spells_below_its_library_directory() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let prefix = dir.join("usr");

        let collection = collect_found(
            "gstreamer",
            "plugins",
            &[],
            &[found(
                SourceBase::InstallationPrefix,
                &prefix,
                "lib/x86_64-linux-gnu/gstreamer-1.0",
                "coreelements.so",
                "lib/gstreamer-1.0",
            )],
            None,
            Some(2),
            Some(62),
        )
        .unwrap();

        assert_eq!(collection.counterpart, "gstreamer-1.0");
        let _ = fs::remove_dir_all(&dir);
    }

    /// A prefix path outside every library directory, as a `share`
    /// location is, spells no host counterpart at all.
    #[test]
    fn a_prefix_base_outside_the_library_directories_spells_nothing() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let prefix = dir.join("usr");

        let collection = collect_found(
            "examplefw",
            "data",
            &[],
            &[found(
                SourceBase::InstallationPrefix,
                &prefix,
                "share/examplefw",
                "keep.so",
                "share/examplefw",
            )],
            None,
            Some(2),
            Some(62),
        )
        .unwrap();

        assert_eq!(collection.counterpart, "");
        let _ = fs::remove_dir_all(&dir);
    }

    /// Two installations providing one group leave the first hit's
    /// spelling as the single host library path the record may name.
    #[test]
    fn the_first_hit_spells_the_counterpart() {
        let dir =
            std::env::temp_dir().join(format!("onelf-gather-{}-{}", std::process::id(), line!()));
        let _ = fs::remove_dir_all(&dir);
        let first = dir.join("opt/example");
        let second = dir.join("usr/lib");

        let collection = collect_found(
            "alsa",
            "plugins",
            &[],
            &[
                found(
                    SourceBase::InstallationPrefix,
                    &first,
                    "lib/alsa-lib/deep",
                    "pulse.so",
                    "lib/alsa-lib",
                ),
                found(
                    SourceBase::LibraryDir,
                    &second,
                    "alsa-lib",
                    "pulse.so",
                    "lib/alsa-lib",
                ),
            ],
            None,
            Some(2),
            Some(62),
        )
        .unwrap();

        assert_eq!(collection.counterpart, "alsa-lib/deep");
        let _ = fs::remove_dir_all(&dir);
    }
}