rldd 0.4.0

A program to print shared object dependencies
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
use std::io::Error;
use std::path::Path;
use std::{fmt, fs, str};

use object::elf::*;
use object::read::elf::*;
use object::read::StringTable;
use object::Endianness;

use crate::deptree::*;
mod platform;
use crate::pathutils;
use crate::search_path;

mod system_dirs;

#[cfg(target_os = "android")]
mod android;
#[cfg(target_os = "linux")]
mod interp;
#[cfg(target_os = "android")]
mod ld_config_txt;
#[cfg(target_os = "freebsd")]
mod ld_hints_freebsd;
#[cfg(target_os = "openbsd")]
mod ld_hints_openbsd;
#[cfg(target_os = "freebsd")]
mod ld_libmap_freebsd;
#[cfg(target_os = "linux")]
mod ld_preload;
#[cfg(target_os = "linux")]
mod ld_so_cache;
#[cfg(target_os = "netbsd")]
mod ld_so_conf_netbsd;
#[cfg(target_os = "linux")]
mod symbols;

#[cfg(target_os = "linux")]
type LoaderCache = ld_so_cache::LdCache;
#[cfg(target_os = "android")]
type LoaderCache = ld_config_txt::LdCache;
#[cfg(all(
    target_family = "unix",
    not(any(target_os = "linux", target_os = "android"))
))]
type LoaderCache = search_path::SearchPathVec;

type DepsVec = Vec<String>;

// A parsed ELF object with the relevant informations:
// - ei_class/ei_data/ei_osabi: ElfXX_Ehdr fields used in system library paths resolution,
// - soname: DT_SONAME, if present.
// - rpath: DT_RPATH search list paths, if present.
// - runpatch: DT_RUNPATH search list paths, if present.
// - nodeflibs: set if DF_1_NODEFLIB from DT_FLAGS_1 is set.
#[derive(Debug)]
struct ElfInfo {
    ei_class: FileClass,
    ei_data: DataEncoding,
    ei_osabi: OsAbi,
    #[allow(dead_code)]
    ei_abiver: u8,
    e_machine: Machine,
    #[allow(dead_code)]
    e_flags: FileFlags,

    interp: Option<String>,
    // Not used on OpenBSD, where the loader ignores DT_SONAME.
    #[cfg_attr(target_os = "openbsd", allow(dead_code))]
    soname: Option<String>,
    rpath: search_path::SearchPathVec,
    runpath: search_path::SearchPathVec,
    // Whether DT_RUNPATH is present.  It can not be derived from the runpath field,
    // since non existent directories are filtered out while the loader semantics
    // (ignoring DT_RPATH) only depend on the tag presence.
    has_runpath: bool,
    nodeflibs: bool,
    is_musl: bool,

    deps: DepsVec,
}

// ELF Parsing routines.

fn parse_object(
    data: &[u8],
    origin: &str,
    platform: Option<&String>,
) -> Result<ElfInfo, &'static str> {
    let kind = match object::FileKind::parse(data) {
        Ok(file) => file,
        Err(_err) => return Err("Failed to parse file"),
    };

    match kind {
        object::FileKind::Elf32 => parse_elf32(data, origin, platform),
        object::FileKind::Elf64 => parse_elf64(data, origin, platform),
        _ => Err("Invalid object"),
    }
}

fn parse_elf32(
    data: &[u8],
    origin: &str,
    platform: Option<&String>,
) -> Result<ElfInfo, &'static str> {
    if let Some(elf) = FileHeader32::<Endianness>::parse(data).handle_err() {
        return parse_elf(elf, data, origin, platform);
    }
    Err("Invalid ELF32 object")
}

fn parse_elf64(
    data: &[u8],
    origin: &str,
    platform: Option<&String>,
) -> Result<ElfInfo, &'static str> {
    if let Some(elf) = FileHeader64::<Endianness>::parse(data).handle_err() {
        return parse_elf(elf, data, origin, platform);
    }
    Err("Invalid ELF64 object")
}

fn parse_elf<Elf: FileHeader<Endian = Endianness>>(
    elf: &Elf,
    data: &[u8],
    origin: &str,
    platform: Option<&String>,
) -> Result<ElfInfo, &'static str> {
    let endian = match elf.endian() {
        Ok(val) => val,
        Err(_) => return Err("invalid endianess"),
    };

    match elf.e_type(endian) {
        ET_EXEC | ET_DYN => parse_header_elf(endian, elf, data, origin, platform),
        _ => Err("Invalid ELF file"),
    }
}

trait HandleErr<T> {
    fn handle_err(self) -> Option<T>;
}

impl<T, E: fmt::Display> HandleErr<T> for Result<T, E> {
    fn handle_err(self) -> Option<T> {
        self.ok()
    }
}

fn parse_header_elf<Elf: FileHeader<Endian = Endianness>>(
    endian: Elf::Endian,
    elf: &Elf,
    data: &[u8],
    origin: &str,
    platform: Option<&String>,
) -> Result<ElfInfo, &'static str> {
    match elf.program_headers(endian, data) {
        Ok(segments) => parse_elf_program_headers(endian, data, elf, segments, origin, platform),
        Err(_) => Err("invalid segment"),
    }
}

#[cfg(target_os = "linux")]
fn handle_loader(elc: &mut ElfInfo) {
    elc.is_musl = interp::is_musl(&elc.interp)
        || elc.deps.iter().any(|dep| dep.starts_with("libc.musl-"))
        || (elc.interp.is_none() && is_musl_system());
}

#[cfg(target_os = "linux")]
fn is_musl_system() -> bool {
    use std::sync::OnceLock;
    static MUSL_SYSTEM: OnceLock<bool> = OnceLock::new();
    *MUSL_SYSTEM
        .get_or_init(|| !Path::new("/etc/ld.so.cache").exists() && find_musl_loader().is_some())
}
#[cfg(all(target_family = "unix", not(target_os = "linux")))]
fn handle_loader(_elc: &mut ElfInfo) {}

fn parse_elf_program_headers<Elf: FileHeader>(
    endian: Elf::Endian,
    data: &[u8],
    elf: &Elf,
    headers: &[Elf::ProgramHeader],
    origin: &str,
    platform: Option<&String>,
) -> Result<ElfInfo, &'static str> {
    match parse_elf_dynamic_program_header(endian, data, elf, headers, origin, platform) {
        Ok(mut elc) => {
            elc.interp = parse_elf_interp::<Elf>(endian, data, headers);
            handle_loader(&mut elc);
            Ok(elc)
        }
        Err(e) => Err(e),
    }
}

fn parse_elf_interp<Elf: FileHeader>(
    endian: Elf::Endian,
    data: &[u8],
    headers: &[Elf::ProgramHeader],
) -> Option<String> {
    match headers.iter().find(|&hdr| hdr.p_type(endian) == PT_INTERP) {
        Some(hdr) => {
            let offset = hdr.p_offset(endian).into() as usize;
            let fsize = hdr.p_filesz(endian).into() as usize;
            data.get(offset..offset.checked_add(fsize)?)
                .and_then(|interp| str::from_utf8(interp).ok())
                .map(|s| s.trim_matches(char::from(0)).to_string())
        }
        None => None,
    }
}

fn parse_elf_dynamic_program_header<Elf: FileHeader>(
    endian: Elf::Endian,
    data: &[u8],
    elf: &Elf,
    headers: &[Elf::ProgramHeader],
    origin: &str,
    platform: Option<&String>,
) -> Result<ElfInfo, &'static str> {
    match headers
        .iter()
        .find(|&&hdr| hdr.p_type(endian) == PT_DYNAMIC)
    {
        Some(hdr) => parse_elf_segment_dynamic(endian, data, elf, headers, hdr, origin, platform),
        None => Err("No dynamic segments found"),
    }
}

fn parse_elf_segment_dynamic<Elf: FileHeader>(
    endian: Elf::Endian,
    data: &[u8],
    elf: &Elf,
    segments: &[Elf::ProgramHeader],
    segment: &Elf::ProgramHeader,
    origin: &str,
    platform: Option<&String>,
) -> Result<ElfInfo, &'static str> {
    if let Ok(Some(dynamic)) = segment.dynamic(endian, data) {
        // The loader rejects an object whose dynamic section has no entries (for instance the
        // separated debug info files).
        if !dynamic.iter().any(|d| {
            let tag = d.d_tag(endian);
            tag != DT_NULL
        }) {
            return Err("Object file has no dynamic section");
        }
        let mut strtab = 0;
        let mut strsz = 0;

        // To obtain the DT_NEEDED name we first need to find the DT_STRTAB/DT_STRSZ.
        dynamic.iter().for_each(|d| {
            let tag = d.d_tag(endian);
            if tag == DT_STRTAB {
                strtab = d.d_val(endian).into();
            } else if tag == DT_STRSZ {
                strsz = d.d_val(endian).into();
            }
        });

        let dynstr = match parse_elf_stringtable::<Elf>(endian, data, segments, strtab, strsz) {
            Some(dynstr) => dynstr,
            None => return Err("Failure to parse the string table"),
        };

        let dt_flags_1 = DynamicFlags1(parse_elf_dyn_flags::<Elf>(endian, DT_FLAGS_1, dynamic));
        let nodeflibs = dt_flags_1.contains(DF_1_NODEFLIB);

        return match parse_elf_dtneeded::<Elf>(endian, dynamic, dynstr) {
            Ok(dtneeded) => Ok(ElfInfo {
                ei_class: elf.e_ident().class,
                ei_data: elf.e_ident().data,
                ei_osabi: elf.e_ident().os_abi,
                ei_abiver: elf.e_ident().abi_version,
                e_machine: elf.e_machine(endian),
                e_flags: elf.e_flags(endian),
                interp: None,
                soname: parse_elf_dyn_str::<Elf>(endian, DT_SONAME, dynamic, dynstr),
                rpath: parse_elf_dyn_searchpath(
                    endian, elf, DT_RPATH, dynamic, dynstr, origin, platform,
                ),
                runpath: parse_elf_dyn_searchpath(
                    endian, elf, DT_RUNPATH, dynamic, dynstr, origin, platform,
                ),
                has_runpath: parse_elf_dyn_str::<Elf>(endian, DT_RUNPATH, dynamic, dynstr)
                    .is_some(),
                nodeflibs,
                deps: dtneeded,
                is_musl: false,
            }),
            Err(e) => Err(e),
        };
    }
    Err("Failure to parse dynamic segment")
}

fn parse_elf_stringtable<'a, Elf: FileHeader>(
    endian: Elf::Endian,
    data: &'a [u8],
    segments: &'a [Elf::ProgramHeader],
    strtab: u64,
    strsz: u64,
) -> Option<StringTable<'a>> {
    for s in segments {
        if let Ok(Some(data)) = s.data_range(endian, data, strtab, strsz) {
            return Some(StringTable::new(data, 0, data.len() as u64));
        }
    }
    None
}

fn parse_elf_dyn_str<Elf: FileHeader>(
    endian: Elf::Endian,
    tag: DynamicTag,
    dynamic: &[Elf::Dyn],
    dynstr: StringTable,
) -> Option<String> {
    for d in dynamic {
        if d.d_tag(endian) == DT_NULL {
            break;
        }

        if d.tag32(endian).is_none() || d.d_tag(endian) != tag {
            continue;
        }

        if let Ok(s) = d.string(endian, dynstr) {
            if let Ok(s) = str::from_utf8(s) {
                return Some(s.to_string());
            }
        }
    }
    None
}

fn replace_dyn_str(dynstr: &str, token: &str, value: &str) -> String {
    let newdynstr = dynstr.replace(&format!("${token}"), value);
    // Also handle ${token}
    newdynstr.replace(&format!("${{{token}}}"), value)
}

#[cfg(target_os = "linux")]
fn parse_elf_dyn_searchpath_lib<Elf: FileHeader>(
    endian: Elf::Endian,
    elf: &Elf,
    dynstr: &mut String,
) {
    let libdir = system_dirs::get_slibdir(elf.e_machine(endian), elf.e_ident().class).unwrap();
    *dynstr = replace_dyn_str(dynstr, "LIB", libdir);
}

#[cfg(all(target_family = "unix", not(target_os = "linux")))]
fn parse_elf_dyn_searchpath_lib<Elf: FileHeader>(
    _endian: Elf::Endian,
    _elf: &Elf,
    _dynstr: &mut str,
) {
}

fn parse_elf_dyn_searchpath<Elf: FileHeader>(
    endian: Elf::Endian,
    elf: &Elf,
    tag: DynamicTag,
    dynamic: &[Elf::Dyn],
    dynstr: StringTable,
    origin: &str,
    platform: Option<&String>,
) -> search_path::SearchPathVec {
    if let Some(dynstr) = parse_elf_dyn_str::<Elf>(endian, tag, dynamic, dynstr) {
        // Expand $ORIGIN, $LIB, and $PLATFORM.
        let mut newdynstr = replace_dyn_str(&dynstr, "ORIGIN", origin);

        parse_elf_dyn_searchpath_lib(endian, elf, &mut newdynstr);

        let platform = match platform {
            Some(platform) => platform.to_string(),
            None => platform::get(elf.e_machine(endian), elf.e_ident().data),
        };
        let newdynstr = replace_dyn_str(&newdynstr, "PLATFORM", platform.as_str());

        return search_path::from_string(newdynstr, &[':']);
    }
    search_path::SearchPathVec::new()
}

fn parse_elf_dtneeded<Elf: FileHeader>(
    endian: Elf::Endian,
    dynamic: &[Elf::Dyn],
    dynstr: StringTable,
) -> Result<DepsVec, &'static str> {
    let mut dtneeded = DepsVec::new();
    for d in dynamic {
        if d.d_tag(endian) == DT_NULL {
            break;
        }

        if d.tag32(endian).is_none() || !d.is_string(endian) || d.d_tag(endian) != DT_NEEDED {
            continue;
        }

        match d.string(endian, dynstr) {
            Err(_) => continue,
            Ok(s) => {
                if let Ok(s) = str::from_utf8(s) {
                    dtneeded.push(s.to_string());
                }
            }
        }
    }
    Ok(dtneeded)
}

fn parse_elf_dyn_flags<Elf: FileHeader>(
    endian: Elf::Endian,
    tag: DynamicTag,
    dynamic: &[Elf::Dyn],
) -> u64 {
    for d in dynamic {
        if d.d_tag(endian) == DT_NULL {
            break;
        }

        if d.tag32(endian).is_none() || d.d_tag(endian) != tag {
            continue;
        }

        return d.d_val(endian).into();
    }
    0
}

fn open_elf_file<P: AsRef<Path>>(
    filename: &P,
    melc: Option<&ElfInfo>,
    dtneeded: Option<&String>,
    platform: Option<&String>,
    preload: bool,
) -> Result<ElfInfo, std::io::Error> {
    let file = match fs::File::open(filename) {
        Ok(file) => file,
        Err(_) => return Err(Error::other("Failed to open file")),
    };

    let mmap = match unsafe { memmap2::Mmap::map(&file) } {
        Ok(mmap) => mmap,
        Err(_) => return Err(Error::other("Failed to map file")),
    };

    let parent = filename
        .as_ref()
        .parent()
        .and_then(Path::to_str)
        .unwrap_or("");

    match parse_object(&mmap, parent, platform) {
        Ok(elc) => {
            if let Some(melc) = melc {
                // Skip DT_NEEDED and SONAME checks for preload objects.
                if !preload && !match_elf_name(melc, dtneeded, &elc) {
                    return Err(Error::other("Error parsing ELF object"));
                }
            }
            Ok(elc)
        }
        Err(e) => Err(Error::other(e)),
    }
}

fn match_elf_name(melc: &ElfInfo, dtneeded: Option<&String>, elc: &ElfInfo) -> bool {
    if !check_elf_header(elc) || !match_elf_header(melc, elc) {
        return false;
    }

    // If DT_SONAME is defined compare against it.
    if let Some(dtneeded) = dtneeded {
        return match_elf_soname(dtneeded, elc);
    };

    true
}

#[cfg(any(target_os = "linux", target_os = "android"))]
fn check_elf_header(elc: &ElfInfo) -> bool {
    let maxver = match elc.e_machine {
        EM_MIPS | EM_MIPS_RS3_LE => 6,
        EM_PPC | EM_PPC64 | EM_SPARC | EM_X86_64 | EM_RISCV => 5,
        _ => 4,
    };

    let check_elf_osabi = match elc.e_machine {
        EM_ARM => |osabi: OsAbi| {
            osabi == ELFOSABI_SYSV || osabi == ELFOSABI_GNU || osabi == ELFOSABI_ARM_AEABI
        },
        _ => |osabi: OsAbi| osabi == ELFOSABI_SYSV || osabi == ELFOSABI_GNU,
    };

    let check_elf_abiversion = match elc.e_machine {
        EM_MIPS => |osabi: OsAbi, ver: u8, maxver: u8| {
            ver == 0
                || (osabi == ELFOSABI_SYSV && ver < 6)
                || (osabi == ELFOSABI_GNU && ver < maxver)
        },
        _ => {
            |osabi: OsAbi, ver: u8, maxver: u8| ver == 0 || (osabi == ELFOSABI_GNU && ver < maxver)
        }
    };

    check_elf_osabi(elc.ei_osabi) && check_elf_abiversion(elc.ei_osabi, elc.ei_abiver, maxver)
}
#[cfg(target_os = "freebsd")]
fn check_elf_header(elc: &ElfInfo) -> bool {
    elc.ei_osabi == ELFOSABI_FREEBSD
}
#[cfg(target_os = "openbsd")]
fn check_elf_header(elc: &ElfInfo) -> bool {
    elc.ei_osabi == ELFOSABI_SYSV || elc.ei_osabi == ELFOSABI_OPENBSD
}
#[cfg(target_os = "netbsd")]
fn check_elf_header(elc: &ElfInfo) -> bool {
    elc.ei_osabi == ELFOSABI_SYSV || elc.ei_osabi == ELFOSABI_NETBSD
}
#[cfg(any(target_os = "illumos", target_os = "solaris"))]
fn check_elf_header(elc: &ElfInfo) -> bool {
    elc.ei_osabi == ELFOSABI_SYSV || elc.ei_osabi == ELFOSABI_SOLARIS
}

fn match_elf_header(a1: &ElfInfo, a2: &ElfInfo) -> bool {
    a1.ei_class == a2.ei_class && a1.ei_data == a2.ei_data && a1.e_machine == a2.e_machine
}

#[cfg(not(target_os = "openbsd"))]
fn match_elf_soname(dtneeded: &String, elc: &ElfInfo) -> bool {
    let soname = &elc.soname;
    if let Some(soname) = soname {
        return dtneeded == soname;
    }
    true
}
// The OpenBSD loader does not take DT_SONAME in consideration, the resolution
// is done by file name with major/minor version matching (so a DT_NEEDED with
// an older minor is satisfied by a newer minor with a different DT_SONAME).
#[cfg(target_os = "openbsd")]
fn match_elf_soname(_dtneeded: &String, _elc: &ElfInfo) -> bool {
    true
}

// Global configuration used on program dynamic resolution:
// - ld_preload: Search path parser from ld.so.preload
// - ld_library_path: Search path parsed from --ld-library-path.
// - ld_so_conf: paths parsed from the ld.so.conf in the system.
// - system_dirs: system defaults deirectories based on binary architecture.
struct Config<'a> {
    ld_preload: &'a search_path::SearchPathVec,
    ld_library_path: &'a search_path::SearchPathVec,
    ld_cache: &'a Option<LoaderCache>,
    system_dirs: search_path::SearchPathVec,
    platform: Option<&'a String>,
    all: bool,
    #[cfg(target_os = "freebsd")]
    libmap: Option<ld_libmap_freebsd::LibMap>,
}

// Remap the dependency name using the libmap.conf mappings for the referencing
// object path (FreeBSD only).
#[cfg(target_os = "freebsd")]
fn libmap_dependency(config: &Config, refpath: &str, dependency: &String) -> String {
    match &config.libmap {
        Some(libmap) => libmap
            .lookup(refpath, dependency)
            .map(|target| target.to_string())
            .unwrap_or_else(|| dependency.to_string()),
        None => dependency.to_string(),
    }
}
#[cfg(all(target_family = "unix", not(target_os = "freebsd")))]
fn libmap_dependency(_config: &Config, _refpath: &str, dependency: &String) -> String {
    dependency.to_string()
}

#[cfg(target_os = "linux")]
fn format_ld_cache(ld_cache: &Option<LoaderCache>) -> String {
    match ld_cache {
        Some(ld_cache) => format!("{} entries", ld_cache.len()),
        None => "(none)".to_string(),
    }
}
#[cfg(target_os = "android")]
fn format_ld_cache(ld_cache: &Option<LoaderCache>) -> String {
    match ld_cache {
        Some(ld_cache) => format!("{} namespaces", ld_cache.namespaces_count()),
        None => "(none)".to_string(),
    }
}
#[cfg(all(
    target_family = "unix",
    not(any(target_os = "linux", target_os = "android"))
))]
fn format_ld_cache(ld_cache: &Option<LoaderCache>) -> String {
    match ld_cache {
        Some(ld_cache) => search_path::format_list(ld_cache),
        None => "(none)".to_string(),
    }
}

fn push_searched(r: &mut Vec<String>, name: &str, searchpaths: &search_path::SearchPathVec) {
    if !searchpaths.is_empty() {
        r.push(format!("{name}: {}", search_path::format_list(searchpaths)));
    }
}

// Describe the locations searched while failing to resolve a dependency, shown
// on the not found diagnostics in verbose mode.
fn searched_locations(config: &Config, elc: &ElfInfo, dependency: &str) -> Vec<String> {
    let mut r = Vec::new();
    if Path::new(dependency).is_absolute() {
        r.push(dependency.to_string());
        return r;
    }
    if !elc.has_runpath {
        push_searched(&mut r, "rpath", &elc.rpath);
    }
    push_searched(&mut r, "library path", config.ld_library_path);
    push_searched(&mut r, "runpath", &elc.runpath);
    if !elc.nodeflibs {
        if config.ld_cache.is_some() {
            r.push(format!("cache {}", DepMode::LdCache));
        }
        push_searched(&mut r, "default paths", &config.system_dirs);
    }
    r
}

fn print_search_path_information<P: AsRef<Path>>(filename: &P, config: &Config, elc: &ElfInfo) {
    println!(
        "{}: search path information\n\
        \x20 rpath: {}\n\
        \x20 preload: {}\n\
        \x20 library path: {}\n\
        \x20 runpath: {}\n\
        \x20 cache ({}): {}\n\
        \x20 default paths: {}",
        filename.as_ref().display(),
        search_path::format_list(&elc.rpath),
        search_path::format_list(config.ld_preload),
        search_path::format_list(config.ld_library_path),
        search_path::format_list(&elc.runpath),
        DepMode::LdCache,
        format_ld_cache(config.ld_cache),
        search_path::format_list(&config.system_dirs),
    );
}

// Function that mimic the dynamic loader resolution.
#[cfg(target_os = "linux")]
fn resolve_binary_arch(
    elc: &ElfInfo,
    deptree: &mut DepTree,
    depp: usize,
) -> Result<(), std::io::Error> {
    // musl loader and libc is on the same shared object, so adds a synthetic dependendy for
    // the binary so it is also shown and to be returned in case a objects has libc.so
    // as needed.
    if !elc.is_musl {
        return Ok(());
    }

    let interp = match &elc.interp {
        Some(interp) => Some(interp.clone()),
        None => find_musl_loader(),
    };
    if let Some(interp) = interp {
        let path = Path::new(&interp);
        deptree.addnode(
            DepNode {
                path: pathutils::get_path(&path),
                name: pathutils::get_name(&path),
                mode: DepMode::SystemDirs,
                found: false,
                attrs: Vec::new(),
                version: None,
                searched: Vec::new(),
            },
            depp,
        );
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn find_musl_loader() -> Option<String> {
    for entry in fs::read_dir("/lib").ok()?.flatten() {
        if let Some(name) = entry.file_name().to_str() {
            if name.starts_with("ld-musl-") && name.ends_with(".so.1") {
                return Some(format!("/lib/{name}"));
            }
        }
    }
    None
}
#[cfg(all(target_family = "unix", not(target_os = "linux")))]
fn resolve_binary_arch(
    _elc: &ElfInfo,
    _deptree: &mut DepTree,
    _depp: usize,
) -> Result<(), std::io::Error> {
    Ok(())
}

// The loader search cache is lazy loaded if the binary has a loader that actually
// supports it.
pub fn create_context() -> Option<LoaderCache> {
    None
}

pub fn resolve_binary(
    ld_cache: &mut Option<LoaderCache>,
    ld_preload: &search_path::SearchPathVec,
    ld_library_path: &search_path::SearchPathVec,
    platform: &Option<String>,
    all: bool,
    verbose: bool,
    arg: &str,
) -> Result<DepTree, std::io::Error> {
    // On glibc/Linux the RTLD_DI_ORIGIN for the executable itself (used for $ORIGIN
    // expansion) is obtained by first following the '/proc/self/exe' symlink and if
    // it is not available the loader also checks the 'LD_ORIGIN_PATH' environment
    // variable.
    // The '/proc/self/exec' is an absolute path and to mimic loader behavior we first
    // try to canocalize the input filename to remove any symlinks.  There is not much
    // sense in trying LD_ORIGIN_PATH, since it is only checked by the loader if
    // the binary can not dereference the procfs entry.
    let filename = Path::new(arg).canonicalize()?;

    let elc = open_elf_file(&filename, None, None, platform.as_ref(), false)?;

    // The OpenBSD loader matches a library by name and major version, picking the best
    // minor available on the directory (even for the dlopen argument). Mimic it for
    // shared library inputs (executables are executed directly, with no redirection).
    #[cfg(target_os = "openbsd")]
    let (filename, elc) = redirect_to_best_minor(filename, elc, platform.as_ref());

    let mut elc = elc;

    // DT_RPATH is ignored if the object also defines DT_RUNPATH (the latter only
    // applies to the object own dependencies, so it is not propagated).
    if elc.has_runpath {
        elc.rpath.clear();
    }

    // The cache/hints/config file is usually an optional file and failing to open it
    // does not incur on a resolution failure.
    load_so_cache(ld_cache, &filename, &elc);

    // Same for glibc ld.so.preload file.
    let mut preload = ld_preload.to_vec();
    // glibc first parses LD_PRELOAD and then ld.so.preload.
    // We need a new vector for the case of binaries with different interpreters.
    preload.extend(load_ld_so_preload(&elc.interp));

    // android loader only uses the default system search patch if the ld.so.config file can not
    // be loader or if an error was found parsing it (for instance if the executable does not
    // has an entry associated in the section).
    #[cfg(target_os = "android")]
    fn load_system_dirs(ld_cache: &Option<LoaderCache>) -> bool {
        ld_cache.is_none()
    }
    #[cfg(not(target_os = "android"))]
    fn load_system_dirs(_ld_cache: &Option<LoaderCache>) -> bool {
        true
    }

    let system_dirs = if load_system_dirs(&*ld_cache) {
        system_dirs::get_system_dirs(&elc.interp, elc.is_musl, elc.e_machine, elc.ei_class)?
    } else {
        search_path::SearchPathVec::new()
    };

    let config = Config {
        ld_preload: &preload,
        ld_library_path,
        ld_cache,
        system_dirs,
        platform: platform.as_ref(),
        all,
        #[cfg(target_os = "freebsd")]
        libmap: ld_libmap_freebsd::parse_libmap(&Path::new("/etc/libmap.conf")),
    };

    if verbose {
        print_search_path_information(&filename, &config, &elc);
    }

    let mut deptree = DepTree::new();

    let depp = deptree.addroot(DepNode {
        path: pathutils::get_path(&filename),
        name: pathutils::get_name(&filename),
        mode: DepMode::Executable,
        found: false,
        attrs: Vec::new(),
        version: None,
        searched: Vec::new(),
    });

    resolve_binary_arch(&elc, &mut deptree, depp)?;

    let refpath = filename.to_string_lossy().into_owned();
    resolve_dependencies(&config, elc, refpath, &mut deptree, depp);

    Ok(deptree)
}

#[cfg(target_os = "openbsd")]
fn redirect_to_best_minor(
    filename: std::path::PathBuf,
    elc: ElfInfo,
    platform: Option<&String>,
) -> (std::path::PathBuf, ElfInfo) {
    if elc.interp.is_some() {
        return (filename, elc);
    }
    let (Some(dir), Some(name)) = (
        filename.parent().and_then(|p| p.to_str()),
        filename.file_name().and_then(|n| n.to_str()),
    ) else {
        return (filename, elc);
    };
    let candidate = dependency_path(dir, name);
    if candidate != filename {
        if let Ok(nelc) = open_elf_file(&candidate, None, None, platform, false) {
            return (candidate, nelc);
        }
    }
    (filename, elc)
}

#[cfg(target_os = "linux")]
fn load_so_cache<P: AsRef<Path>>(ld_cache: &mut Option<LoaderCache>, _binary: &P, elc: &ElfInfo) {
    if interp::is_glibc(&elc.interp) {
        // glibc's ld.so.cache is shared between all executables, so there is no need
        // to reload for multiple entries.
        if ld_cache.is_none() {
            *ld_cache = ld_so_cache::parse_ld_so_cache(
                &Path::new("/etc/ld.so.cache"),
                elc.ei_class,
                elc.e_machine,
                elc.e_flags,
            )
            .ok();
        }
    };
}
#[cfg(target_os = "android")]
fn load_so_cache<P: AsRef<Path>>(ld_cache: &mut Option<LoaderCache>, binary: &P, elc: &ElfInfo) {
    if let Some(ld_config_path) =
        ld_config_txt::get_ld_config_path(binary, elc.e_machine, elc.ei_class)
    {
        // On Android 10 and forward each executable might have a associated ld.config.txt
        // file in different paths, so we need to reload for each argument.
        *ld_cache = ld_config_txt::parse_ld_config_txt(
            &Path::new(&ld_config_path),
            binary,
            elc.interp.as_ref().unwrap(),
            elc.e_machine,
            elc.ei_class,
        )
        .ok();
    }
}
#[cfg(target_os = "freebsd")]
fn load_so_cache<P: AsRef<Path>>(ld_cache: &mut Option<LoaderCache>, _binary: &P, elc: &ElfInfo) {
    // The 32-bit compat objects use a separate hints file (the rtld
    // COMPAT_libcompat suffix), so the cache is reloaded for each binary.
    let hints = if cfg!(target_pointer_width = "64") && elc.ei_class == ELFCLASS32 {
        "/var/run/ld-elf32.so.hints"
    } else {
        "/var/run/ld-elf.so.hints"
    };
    *ld_cache = ld_hints_freebsd::parse_ld_so_hints(&Path::new(hints)).ok();
}
#[cfg(target_os = "openbsd")]
fn load_so_cache<P: AsRef<Path>>(ld_cache: &mut Option<LoaderCache>, _binary: &P, _ecl: &ElfInfo) {
    if ld_cache.is_none() {
        *ld_cache = ld_hints_openbsd::parse_ld_so_hints(&Path::new("/var/run/ld.so.hints")).ok()
    }
}
#[cfg(target_os = "netbsd")]
fn load_so_cache<P: AsRef<Path>>(ld_cache: &mut Option<LoaderCache>, _binary: &P, _ecl: &ElfInfo) {
    if ld_cache.is_none() {
        *ld_cache = ld_so_conf_netbsd::parse_ld_so_conf(&Path::new("/etc/ld.so.conf")).ok()
    }
}
#[cfg(any(target_os = "illumos", target_os = "solaris"))]
fn load_so_cache<P: AsRef<Path>>(_ld_cache: &mut Option<LoaderCache>, _binary: &P, _ecl: &ElfInfo) {
}

#[cfg(target_os = "linux")]
fn load_ld_so_preload(interp: &Option<String>) -> search_path::SearchPathVec {
    if interp::is_glibc(interp) {
        return ld_preload::parse_ld_so_preload(&Path::new("/etc/ld.so.preload"));
    }
    search_path::SearchPathVec::new()
}
#[cfg(all(target_family = "unix", not(target_os = "linux")))]
fn load_ld_so_preload(_interp: &Option<String>) -> search_path::SearchPathVec {
    search_path::SearchPathVec::new()
}

// Return the path candidate for a dependency on a search directory.  OpenBSD
// shared objects do not have a DT_SONAME and the DT_NEEDED entries carry the
// full libname.so.major.minor name, with the loader matching the major version
// and picking the best minor available on the directory.
#[cfg(target_os = "openbsd")]
fn dependency_path(dir: &str, dtneeded: &str) -> std::path::PathBuf {
    fn parse_version(name: &str) -> Option<(&str, u64)> {
        let idx = name.find(".so.")?;
        let stem = &name[..idx + 3];
        // The version might be either major.minor or only the major.
        let major = match name[idx + 4..].split_once('.') {
            Some((major, minor)) => {
                minor.parse::<u64>().ok()?;
                major
            }
            None => &name[idx + 4..],
        };
        Some((stem, major.parse().ok()?))
    }

    if let Some((stem, major)) = parse_version(dtneeded) {
        let prefix = format!("{stem}.{major}.");
        let mut best: Option<(u64, std::path::PathBuf)> = None;
        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries.flatten() {
                if let Some(minor) = entry
                    .file_name()
                    .to_str()
                    .and_then(|filename| filename.strip_prefix(&prefix))
                    .and_then(|minor| minor.parse::<u64>().ok())
                {
                    if best.as_ref().is_none_or(|(m, _)| minor > *m) {
                        best = Some((minor, entry.path()));
                    }
                }
            }
        }
        if let Some((_, path)) = best {
            return path;
        }
    }
    Path::new(dir).join(dtneeded)
}
#[cfg(all(target_family = "unix", not(target_os = "openbsd")))]
fn dependency_path(dir: &str, dtneeded: &str) -> std::path::PathBuf {
    Path::new(dir).join(dtneeded)
}

#[cfg(target_os = "linux")]
fn rpath_search(elc: &ElfInfo) -> bool {
    !elc.has_runpath
}
#[cfg(all(target_family = "unix", not(target_os = "linux")))]
fn rpath_search(_elc: &ElfInfo) -> bool {
    true
}

// Returned from resolve_dependency_1 with resolved information.
#[derive(Debug)]
struct ResolvedDependency<'a> {
    elc: ElfInfo,
    path: &'a String,
    // The resolved file name, which might differ from the DT_NEEDED entry
    // (for instance on OpenBSD minor version matching).
    filename: String,
    mode: DepMode,
}

// A pending dependency to resolve: the DT_NEEDED name along the index of the
// loading object information (on the parents vector) and the dependency tree
// node to attach the resolution result.
struct WorkItem {
    dependency: String,
    parent: usize,
    depp: usize,
    preload: bool,
}

// Resolve the dependencies in breadth-first order, mimicking the loader: each
// object DT_NEEDED list is fully processed before the dependencies own
// dependencies, so a shared dependency is attributed to the first object that
// requests it in load order (which defines the search path used).
fn resolve_dependencies(
    config: &Config,
    root_elc: ElfInfo,
    root_refpath: String,
    deptree: &mut DepTree,
    root_depp: usize,
) {
    use std::collections::VecDeque;

    // The already loaded objects information, used to resolve their own
    // dependencies (rpath chain and libmap reference path).
    let mut parents: Vec<(ElfInfo, String)> = Vec::new();

    let mut queue = VecDeque::new();
    for searchpath in config.ld_preload {
        queue.push_back(WorkItem {
            dependency: searchpath.path.clone(),
            parent: 0,
            depp: root_depp,
            preload: true,
        });
    }
    for dep in &root_elc.deps {
        queue.push_back(WorkItem {
            dependency: dep.clone(),
            parent: 0,
            depp: root_depp,
            preload: false,
        });
    }
    parents.push((root_elc, root_refpath));

    while let Some(item) = queue.pop_front() {
        let (elc, refpath) = &parents[item.parent];

        // FreeBSD libmap.conf may remap the dependency name based on the
        // referencing object path.
        let dependency = &libmap_dependency(config, refpath, &item.dependency);

        if elc.is_musl && dependency == "libc.so" {
            continue;
        }

        // If DF_1_NODEFLIB is set ignore the search cache in the case a
        // dependency could resolve the library.
        if !elc.nodeflibs {
            if let Some(entry) = deptree.get(dependency) {
                if config.all {
                    deptree.addnode(
                        DepNode {
                            path: entry.path,
                            name: pathutils::get_name(&Path::new(dependency)),
                            mode: entry.mode,
                            found: true,
                            attrs: Vec::new(),
                            version: None,
                            searched: Vec::new(),
                        },
                        item.depp,
                    );
                }
                continue;
            }
        }

        if let Some(mut dep) = resolve_dependency_1(dependency, config, elc, item.preload) {
            let r = if dep.mode == DepMode::Direct {
                // Decompose the direct object path in path and filename so when
                // print the dependencies only the file name is showed in
                // default mode.
                let p = Path::new(dependency);
                (pathutils::get_path(&p), pathutils::get_name(&p))
            } else {
                (Some(dep.path.to_string()), dep.filename.clone())
            };
            // The resolved path of this dependency, used as the reference path
            // for its own dependencies resolution.
            let depref = match &r.0 {
                Some(path) => format!("{}{}{}", path, std::path::MAIN_SEPARATOR, r.1),
                None => r.1.clone(),
            };
            let c = deptree.addnode(
                DepNode {
                    path: r.0,
                    name: r.1,
                    mode: dep.mode,
                    found: false,
                    attrs: Vec::new(),
                    version: None,
                    searched: Vec::new(),
                },
                item.depp,
            );

            // The DT_RPATH scope used for the indirect dependencies is system
            // specific: the glibc loader searches the object own DT_RPATH and
            // then walks up the chain of loading objects (up to the
            // executable), the FreeBSD and OpenBSD loaders search the object
            // own DT_RPATH and then the main object one, while the NetBSD
            // loader only searches the requesting object DT_RPATH.  In all
            // cases an object DT_RPATH is ignored if the object also defines
            // DT_RUNPATH, without affecting the inherited part.
            if dep.elc.has_runpath {
                dep.elc.rpath.clear();
            }
            #[cfg(target_os = "linux")]
            dep.elc.rpath.extend(elc.rpath.clone());
            #[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
            dep.elc.rpath.extend(parents[0].0.rpath.clone());

            let parent = parents.len();
            for sdep in &dep.elc.deps {
                queue.push_back(WorkItem {
                    dependency: sdep.clone(),
                    parent,
                    depp: c,
                    preload: item.preload,
                });
            }
            parents.push((dep.elc, depref));
        } else {
            let path = Path::new(dependency);
            let searched = searched_locations(config, elc, dependency);
            deptree.addnode(
                DepNode {
                    path: pathutils::get_path(&path),
                    name: pathutils::get_name(&path),
                    mode: DepMode::NotFound,
                    found: false,
                    attrs: Vec::new(),
                    version: None,
                    searched,
                },
                item.depp,
            );
        }
    }

    add_loader_dependency(config, &parents[0].0, deptree, root_depp);
}

// The dynamic loader is always loaded, and ldd always shows it.  The libc.so is
// explicitly lists it as a dependency, but an object might not depend on libc at
// all.  Objects without any dependency are skipped, since the loader is not
// involved.
#[cfg(target_os = "linux")]
fn add_loader_dependency(config: &Config, elc: &ElfInfo, deptree: &mut DepTree, root_depp: usize) {
    if !interp::is_glibc(&elc.interp) || deptree.arena[root_depp].children.is_empty() {
        return;
    }
    if deptree
        .arena
        .iter()
        .any(|n| interp::is_glibc_name(&n.val.name))
    {
        return;
    }

    // For an executable the PT_INTERP segment has the loader path.
    if let Some(interp) = &elc.interp {
        let path = Path::new(interp);
        if path.exists() {
            deptree.addnode(
                DepNode {
                    path: pathutils::get_path(&path),
                    name: pathutils::get_name(&path),
                    mode: DepMode::Direct,
                    found: false,
                    attrs: Vec::new(),
                    version: None,
                    searched: Vec::new(),
                },
                root_depp,
            );
            return;
        }
    }

    // Otherwise resolve the loader soname through the loader cache and the
    // system directories (only the soname matching the object architecture
    // resolves).  The object search paths do not apply, since the loader is
    // not subject to the dependency search.
    for name in interp::glibc_names() {
        let dtneeded = name.to_string();
        let mut dep = None;
        if let Some(ld_cache) = config.ld_cache {
            dep = resolve_dependency_ld_cache(&dtneeded, ld_cache, config.platform, elc);
        }
        if dep.is_none() {
            for searchpath in &config.system_dirs {
                let path = dependency_path(&searchpath.path, &dtneeded);
                if let Ok(elc) =
                    open_elf_file(&path, Some(elc), Some(&dtneeded), config.platform, false)
                {
                    dep = Some(ResolvedDependency {
                        elc,
                        path: &searchpath.path,
                        filename: pathutils::get_name(&path),
                        mode: DepMode::SystemDirs,
                    });
                    break;
                }
            }
        }
        if let Some(dep) = dep {
            deptree.addnode(
                DepNode {
                    path: Some(dep.path.to_string()),
                    name: dep.filename.clone(),
                    mode: dep.mode,
                    found: false,
                    attrs: Vec::new(),
                    version: None,
                    searched: Vec::new(),
                },
                root_depp,
            );
            return;
        }
    }
}
// The OpenBSD ldd lists the loader (/usr/libexec/ld.so) for executables (the
// dlopen trace used for shared libraries does not show it).
#[cfg(target_os = "openbsd")]
fn add_loader_dependency(_config: &Config, elc: &ElfInfo, deptree: &mut DepTree, root_depp: usize) {
    if let Some(interp) = &elc.interp {
        let path = Path::new(interp);
        if path.exists() {
            deptree.addnode(
                DepNode {
                    path: pathutils::get_path(&path),
                    name: pathutils::get_name(&path),
                    mode: DepMode::Direct,
                    found: false,
                    attrs: Vec::new(),
                    version: None,
                    searched: Vec::new(),
                },
                root_depp,
            );
        }
    }
}
#[cfg(all(
    target_family = "unix",
    not(target_os = "linux"),
    not(target_os = "openbsd")
))]
fn add_loader_dependency(
    _config: &Config,
    _elc: &ElfInfo,
    _deptree: &mut DepTree,
    _root_depp: usize,
) {
}

fn resolve_dependency_1<'a>(
    dtneeded: &'a String,
    config: &'a Config,
    elc: &'a ElfInfo,
    preload: bool,
) -> Option<ResolvedDependency<'a>> {
    let path = Path::new(&dtneeded);

    // If the path is absolute skip the other modes.
    if path.is_absolute() {
        if let Ok(elc) = open_elf_file(&path, Some(elc), Some(dtneeded), config.platform, preload) {
            return Some(ResolvedDependency {
                elc,
                path: dtneeded,
                filename: pathutils::get_name(&path),
                mode: if preload {
                    DepMode::Preload
                } else {
                    DepMode::Direct
                },
            });
        }
        return None;
    }

    // The rpath field holds the object own DT_RPATH along with any inherited
    // part.  The glibc loader skips the whole search (including the inherited
    // chain) if the object issuing the load has a DT_RUNPATH, while the BSD
    // loaders still search the main object DT_RPATH (the object own rpath is
    // already cleared on DT_RUNPATH presence).
    if rpath_search(elc) {
        for searchpath in &elc.rpath {
            let path = dependency_path(&searchpath.path, dtneeded);
            if let Ok(elc) = open_elf_file(&path, Some(elc), Some(dtneeded), config.platform, false)
            {
                return Some(ResolvedDependency {
                    elc,
                    path: &searchpath.path,
                    filename: pathutils::get_name(&path),
                    mode: DepMode::DtRpath,
                });
            }
        }
    }

    // Check LD_LIBRARY_PATH paths.
    for searchpath in config.ld_library_path {
        let path = dependency_path(&searchpath.path, dtneeded);
        if let Ok(elc) = open_elf_file(&path, Some(elc), Some(dtneeded), config.platform, false) {
            return Some(ResolvedDependency {
                elc,
                path: &searchpath.path,
                filename: pathutils::get_name(&path),
                mode: DepMode::LdLibraryPath,
            });
        }
    }

    // Check DT_RUNPATH.
    for searchpath in &elc.runpath {
        let path = dependency_path(&searchpath.path, dtneeded);
        if let Ok(elc) = open_elf_file(&path, Some(elc), Some(dtneeded), config.platform, false) {
            return Some(ResolvedDependency {
                elc,
                path: &searchpath.path,
                filename: pathutils::get_name(&path),
                mode: DepMode::DtRunpath,
            });
        }
    }

    // Skip system paths if DF_1_NODEFLIB is set.
    if elc.nodeflibs {
        return None;
    }

    // Check the loader cache.
    if let Some(ld_cache) = config.ld_cache {
        if let Some(dep) = resolve_dependency_ld_cache(dtneeded, ld_cache, config.platform, elc) {
            return Some(dep);
        }
    }

    // Finally the system directories.
    for searchpath in &config.system_dirs {
        let path = dependency_path(&searchpath.path, dtneeded);
        if let Ok(elc) = open_elf_file(&path, Some(elc), Some(dtneeded), config.platform, false) {
            return Some(ResolvedDependency {
                elc,
                path: &searchpath.path,
                filename: pathutils::get_name(&path),
                mode: DepMode::SystemDirs,
            });
        }
    }

    None
}

#[cfg(target_os = "linux")]
fn resolve_dependency_ld_cache<'a>(
    dtneeded: &'a String,
    ld_cache: &'a LoaderCache,
    platform: Option<&String>,
    elc: &'a ElfInfo,
) -> Option<ResolvedDependency<'a>> {
    use std::path::PathBuf;
    if let Some(path) = ld_cache.get(dtneeded) {
        let mut pathbuf = PathBuf::new();
        pathbuf.push(path);
        pathbuf.push(dtneeded);
        if let Ok(elc) = open_elf_file(&pathbuf, Some(elc), Some(dtneeded), platform, false) {
            return Some(ResolvedDependency {
                elc,
                path,
                filename: pathutils::get_name(&pathbuf),
                mode: DepMode::LdCache,
            });
        }
    }
    None
}

#[cfg(target_os = "android")]
fn resolve_dependency_ld_cache<'a>(
    dtneeded: &'a String,
    ld_cache: &'a LoaderCache,
    platform: Option<&String>,
    elc: &'a ElfInfo,
) -> Option<ResolvedDependency<'a>> {
    // The constraint function is used to instruct the compiler with a higher-ranked trait
    // bounds (for <...>) that the closure must return a reference of the same lifetime as
    // the argument.  Otherwise it complains that the closure arguments has a different
    // lifetime than result.
    fn constraint<F>(f: F) -> F
    where
        F: for<'a> Fn(&'a ld_config_txt::NamespaceConfig) -> Option<ResolvedDependency<'a>>,
    {
        f
    }

    let search_namespace = constraint(|namespace: &ld_config_txt::NamespaceConfig| {
        for searchpath in &namespace.search_paths {
            let path = Path::new(&searchpath.path).join(dtneeded);
            if let Ok(elc) = open_elf_file(&path, Some(elc), Some(dtneeded), platform, false) {
                return Some(ResolvedDependency {
                    elc,
                    path: &searchpath.path,
                    filename: pathutils::get_name(&path),
                    mode: DepMode::LdCache,
                });
            }
        }
        None
    });

    // First check the default namespace and then the linked namespaces for the default one.
    // For latter, do not follow further linked namespaces.
    if let Some(default_ns) = ld_cache.get_default_namespace() {
        if let Some(resolved) = search_namespace(default_ns) {
            return Some(resolved);
        }

        for linked_ns in &default_ns.namespaces {
            if let Some(namespace) = ld_cache.get_namespace(linked_ns) {
                if !namespace.is_accessible(dtneeded) {
                    continue;
                }

                if let Some(resolved) = search_namespace(namespace) {
                    return Some(resolved);
                }
            }
        }
    }

    None
}

#[cfg(all(
    target_family = "unix",
    not(any(target_os = "linux", target_os = "android"))
))]
fn resolve_dependency_ld_cache<'a>(
    dtneeded: &'a String,
    ld_cache: &'a LoaderCache,
    platform: Option<&String>,
    elc: &'a ElfInfo,
) -> Option<ResolvedDependency<'a>> {
    for searchpath in ld_cache {
        let path = dependency_path(&searchpath.path, dtneeded);
        if let Ok(elc) = open_elf_file(&path, Some(elc), Some(dtneeded), platform, false) {
            return Some(ResolvedDependency {
                elc,
                path: &searchpath.path,
                filename: pathutils::get_name(&path),
                mode: DepMode::LdCache,
            });
        }
    }
    None
}

// Symbol resolution mimicking, used to implement the ldd like --data-relocs,
// --function-relocs, and --unused options.  The checks mimic the glibc loader
// and are only enabled on Linux; on Android the linker provides the loader
// symbols with mangled names, while the BSD run-time linkers were not verified.

// An unresolved symbol reference found while processing the dynamic relocations.
#[cfg(target_os = "linux")]
pub struct UndefinedSymbol {
    pub name: String,
    // The required symbol version, if any.
    pub version: Option<String>,
    // Full path of the object with the undefined reference.
    pub object: String,
}

// A version definition required by some object that the dependency providing
// it does not define (the loader version check).
#[cfg(target_os = "linux")]
pub struct VersionError {
    // Full path of the object that should provide the version.
    pub object: String,
    pub version: String,
    // Full path of the object requiring the version.
    pub required_by: String,
}

#[cfg(target_os = "linux")]
#[derive(Default)]
pub struct RelocCheckResult {
    pub version_errors: Vec<VersionError>,
    pub undefined: Vec<UndefinedSymbol>,
    pub unused: Vec<String>,
}

#[cfg(target_os = "linux")]
fn deptree_node_path(node: &DepNode) -> Option<String> {
    node.path.as_ref().map(|path| {
        Path::new(path)
            .join(&node.name)
            .to_string_lossy()
            .into_owned()
    })
}

// Build the loader global search scope: the resolved objects from the dependency
// tree in breadth-first order (the order the loader uses for symbol resolution),
// with each object dynamic symbol table and relocation references parsed.
#[cfg(target_os = "linux")]
fn build_symbol_scope(deptree: &DepTree) -> Vec<(String, symbols::ObjectSymbols)> {
    use std::collections::{HashSet, VecDeque};

    let mut scope = Vec::new();
    let mut seen = HashSet::new();

    let mut queue = VecDeque::from([0usize]);
    while let Some(idx) = queue.pop_front() {
        let node = &deptree.arena[idx];
        queue.extend(node.children.iter());

        // Skip unresolved dependencies and the duplicated entries printed by the
        // --all option.
        if node.val.mode == DepMode::NotFound || node.val.found {
            continue;
        }
        let path = match deptree_node_path(&node.val) {
            Some(path) => path,
            None => continue,
        };
        if !seen.insert(path.clone()) {
            continue;
        }
        if let Some(obj) = symbols::parse(&path) {
            scope.push((path, obj));
        }
    }
    scope
}

// Reparse the root object, used to obtain the PT_INTERP and DT_NEEDED values.
#[cfg(target_os = "linux")]
fn open_root_elf(deptree: &DepTree) -> Option<ElfInfo> {
    let root = deptree.arena.first()?;
    let path = deptree_node_path(&root.val)?;
    open_elf_file(&path, None, None, None, false).ok()
}

// The dynamic loader is part of the global scope (libc binds to symbols the
// loader provides, like _rtld_global), however it might not be present in the
// dependency tree if no object lists it as an explicit dependency.
#[cfg(target_os = "linux")]
fn append_interp_to_scope(scope: &mut Vec<(String, symbols::ObjectSymbols)>, elc: &ElfInfo) {
    if let Some(interp) = &elc.interp {
        let name = pathutils::get_name(&Path::new(interp));
        if scope
            .iter()
            .any(|(path, _)| pathutils::get_name(&Path::new(path)) == name)
        {
            return;
        }
        if let Some(obj) = symbols::parse(interp) {
            scope.push((interp.to_string(), obj));
        }
    }
}

// Mimic the musl loader relocation processing, which the musl ldd always
// performs: musl has no lazy binding, so all the relocations (data and
// DT_JMPREL) are processed eagerly, and the symbol versioning is ignored on
// the load time resolution.  The unresolved references are reported as
// 'Error relocating OBJECT: SYMBOL: symbol not found' and the loader exits
// with status 127.  Returns None when the object is not a musl one.
#[cfg(target_os = "linux")]
pub fn check_musl_relocations(deptree: &DepTree) -> Option<Vec<UndefinedSymbol>> {
    let root_elc = open_root_elf(deptree)?;
    if !root_elc.is_musl {
        return None;
    }

    let mut scope = build_symbol_scope(deptree);
    append_interp_to_scope(&mut scope, &root_elc);

    let mut undefined = Vec::new();
    for (idx, (path, obj)) in scope.iter().enumerate().rev() {
        for sref in &obj.references {
            if sref.weak {
                continue;
            }
            if !scope
                .iter()
                .enumerate()
                .any(|(i, (_, o))| (!sref.copy || i != idx) && o.defined.contains(&sref.name))
            {
                undefined.push(UndefinedSymbol {
                    name: sref.name.clone(),
                    version: None,
                    object: path.clone(),
                });
            }
        }
    }
    Some(undefined)
}

// Mimic the loader relocation processing and version checking, used to
// implement the ldd like --data-relocs, --function-relocs, and --unused
// options:
// - version_errors: version definitions required by some object that the
//   dependency providing them does not define (always computed).
// - undefined: non weak undefined symbol references that no object in the
//   global scope satisfies.  If PROCESS_PLT is false the DT_JMPREL function
//   relocations are only processed for bind-now objects, as the loader does
//   in LD_WARN mode.
// - unused: the executable DT_NEEDED entries that provide no symbol used by
//   the executable own relocations (computed iff CHECK_UNUSED is set).
#[cfg(target_os = "linux")]
pub fn check_relocations(
    deptree: &DepTree,
    process_plt: bool,
    check_unused: bool,
) -> RelocCheckResult {
    use std::collections::{HashMap, HashSet};

    let mut r = RelocCheckResult::default();

    let root_elc = open_root_elf(deptree);

    let mut scope = build_symbol_scope(deptree);
    if let Some(root_elc) = &root_elc {
        append_interp_to_scope(&mut scope, root_elc);
    }

    // Whether the OBJ object provides a definition satisfying the REF
    // reference, following the loader lookup rules: a versioned reference is
    // satisfied by a matching version definition or by any definition from an
    // object without version information.
    fn satisfies(obj: &symbols::ObjectSymbols, sref: &symbols::SymbolRef) -> bool {
        match &sref.version {
            Some(version) => {
                obj.defined_versioned
                    .contains(&(sref.name.clone(), version.clone()))
                    || (!obj.has_verdef && obj.defined.contains(&sref.name))
            }
            None => obj.defined.contains(&sref.name),
        }
    }

    // The loader version check (mimicking _dl_check_all_versions): for each
    // required version, check whether the object providing it (matched by file
    // name) actually defines it.
    for (opath, obj) in &scope {
        for need in &obj.verneeded {
            if need.weak {
                continue;
            }
            if let Some((dpath, dobj)) = scope
                .iter()
                .find(|(path, _)| pathutils::get_name(&Path::new(path)) == need.file)
            {
                if !dobj.verdef_names.contains(&need.version) {
                    r.version_errors.push(VersionError {
                        object: dpath.clone(),
                        version: need.version.clone(),
                        required_by: opath.clone(),
                    });
                }
            }
        }
    }

    // The loader relocates the objects in the inverse scope order, with the
    // executable itself being the last one.
    for (idx, (path, obj)) in scope.iter().enumerate().rev() {
        for sref in &obj.references {
            if sref.weak || (sref.plt && !process_plt && !obj.bind_now) {
                continue;
            }
            // A COPY relocation lookup skips the referencing object own definition).
            if !scope
                .iter()
                .enumerate()
                .any(|(i, (_, o))| (!sref.copy || i != idx) && satisfies(o, sref))
            {
                r.undefined.push(UndefinedSymbol {
                    name: sref.name.clone(),
                    version: sref.version.clone(),
                    object: path.clone(),
                });
            }
        }
    }

    if !check_unused {
        return r;
    }
    let Some(root_elc) = root_elc else {
        return r;
    };

    // Only the executable own references mark the dependencies as used (the
    // loader with LD_DEBUG=unused only relocates the main executable), with
    // the first object satisfying the reference in the scope order being the
    // one marked.
    let mut used = vec![false; scope.len()];
    if let Some((_, robj)) = scope.first() {
        for sref in &robj.references {
            // A COPY relocation lookup skips the referencing object own definition).
            let skip = if sref.copy { 1 } else { 0 };
            if let Some(p) = scope
                .iter()
                .skip(skip)
                .position(|(_, o)| satisfies(o, sref))
            {
                used[p + skip] = true;
            }
        }
    }

    let scope_index: HashMap<&str, usize> = scope
        .iter()
        .enumerate()
        .map(|(i, (path, _))| (path.as_str(), i))
        .collect();

    let mut reported = HashSet::new();
    for dtneeded in &root_elc.deps {
        // The loader map is always marked as used by the loader itself, so
        // ldd never reports an explicit loader dependency.
        if interp::is_glibc_name(dtneeded) {
            continue;
        }
        let node = match deptree.get(dtneeded) {
            Some(node) => node,
            None => continue,
        };
        if node.mode == DepMode::NotFound {
            // The loader creates a faked entry for a missing dependency, which
            // can never have a symbol bound to it.
            if reported.insert(dtneeded.clone()) {
                r.unused.push(dtneeded.clone());
            }
            continue;
        }
        let path = match node.path {
            Some(ref path) => Path::new(path)
                .join(&node.name)
                .to_string_lossy()
                .into_owned(),
            None => continue,
        };
        if let Some(&i) = scope_index.get(path.as_str()) {
            if !used[i] && reported.insert(path.clone()) {
                r.unused.push(path);
            }
        }
    }
    r
}