profile-bee-aya 0.13.2

An eBPF library with a focus on developer experience and operability. Fork of aya for profile-bee.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! User space probes.
use std::{
    borrow::Cow,
    error::Error,
    ffi::{CStr, OsStr, OsString},
    fmt::{self, Write},
    fs,
    io::{self, BufRead as _, Cursor, Read as _},
    os::{
        fd::AsFd as _,
        unix::ffi::{OsStrExt as _, OsStringExt as _},
    },
    path::{Path, PathBuf},
    sync::LazyLock,
};

use aya_obj::generated::{bpf_link_type, bpf_prog_type::BPF_PROG_TYPE_KPROBE};
use object::{Object as _, ObjectSection as _, ObjectSymbol as _, Symbol};
use thiserror::Error;

use crate::{
    VerifierLogLevel,
    programs::{
        FdLink, LinkError, ProgramData, ProgramError, ProgramType, define_link_wrapper,
        impl_try_into_fdlink, load_program,
        perf_attach::{PerfLinkIdInner, PerfLinkInner},
        probe::{OsStringExt as _, Probe, ProbeKind, attach},
    },
    sys::bpf_link_get_info_by_fd,
    util::MMap,
};

const LD_SO_CACHE_FILE: &str = "/etc/ld.so.cache";

static LD_SO_CACHE: LazyLock<Result<LdSoCache, io::Error>> =
    LazyLock::new(|| LdSoCache::load(LD_SO_CACHE_FILE));
const LD_SO_CACHE_HEADER_OLD: &str = "ld.so-1.7.0\0";
const LD_SO_CACHE_HEADER_NEW: &str = "glibc-ld.so.cache1.1";

/// An user space probe.
///
/// User probes are eBPF programs that can be attached to any userspace
/// function. They can be of two kinds:
///
/// - `uprobe`: get attached to the *start* of the target functions
/// - `uretprobe`: get attached to the *return address* of the target functions
#[derive(Debug)]
#[doc(alias = "BPF_PROG_TYPE_KPROBE")]
pub struct UProbe {
    pub(crate) data: ProgramData<UProbeLink>,
    pub(crate) kind: ProbeKind,
}

/// The location in the target object file to which the uprobe is to be
/// attached.
pub enum UProbeAttachLocation<'a> {
    /// The location of the target function in the target object file.
    Symbol(&'a str),
    /// The location of the target function in the target object file, offset by
    /// the given number of bytes.
    SymbolOffset(&'a str, u64),
    /// The offset in the target object file, in bytes.
    AbsoluteOffset(u64),
}

impl<'a> From<&'a str> for UProbeAttachLocation<'a> {
    fn from(s: &'a str) -> Self {
        Self::Symbol(s)
    }
}

impl From<u64> for UProbeAttachLocation<'static> {
    fn from(offset: u64) -> Self {
        Self::AbsoluteOffset(offset)
    }
}

/// Describes a single attachment point along with its optional cookie.
pub struct UProbeAttachPoint<'a> {
    /// The actual target location.
    pub location: UProbeAttachLocation<'a>,
    /// Optional cookie available via `bpf_get_attach_cookie()`.
    pub cookie: Option<u64>,
}

impl<'a, L: Into<UProbeAttachLocation<'a>>> From<L> for UProbeAttachPoint<'a> {
    fn from(location: L) -> Self {
        Self {
            location: location.into(),
            cookie: None,
        }
    }
}

impl UProbe {
    /// The type of the program according to the kernel.
    pub const PROGRAM_TYPE: ProgramType = ProgramType::KProbe;

    /// Loads the program inside the kernel.
    pub fn load(&mut self) -> Result<(), ProgramError> {
        load_program(BPF_PROG_TYPE_KPROBE, &mut self.data)
    }

    /// Returns [`ProbeKind::Entry`] if the program is a `uprobe`, or
    /// [`ProbeKind::Return`] if the program is a `uretprobe`.
    pub const fn kind(&self) -> ProbeKind {
        self.kind
    }

    /// Attaches the program.
    ///
    /// Attaches the uprobe to the function `fn_name` defined in the `target`.
    /// If the attach point specifies an offset, it is added to the address of
    /// the target function. If `pid` is not `None`, the program executes only
    /// when the target function is executed by the given `pid`.
    ///
    /// The `target` argument can be an absolute path to a binary or library, or
    /// a library name (eg: `"libc"`).
    ///
    /// If the program is an `uprobe`, it is attached to the *start* address of
    /// the target function.  Instead if the program is a `uretprobe`, it is
    /// attached to the return address of the target function.
    ///
    /// The returned value can be used to detach, see [`UProbe::detach`].
    ///
    /// The cookie is supported since kernel 5.15, and it is made available to
    /// the eBPF program via the `bpf_get_attach_cookie()` helper. The `point`
    /// argument may be just a location (no cookie) or a [`UProbeAttachPoint`],
    /// only the latter sets the cookie explicitly.
    pub fn attach<'a, T: AsRef<Path>, Point: Into<UProbeAttachPoint<'a>>>(
        &mut self,
        point: Point,
        target: T,
        pid: Option<u32>,
    ) -> Result<UProbeLinkId, ProgramError> {
        let UProbeAttachPoint { location, cookie } = point.into();
        let proc_map = pid.map(ProcMap::new).transpose()?;
        let path = resolve_attach_path(target.as_ref(), proc_map.as_ref())?;
        let (symbol, offset) = match location {
            UProbeAttachLocation::Symbol(s) => (Some(s), 0),
            UProbeAttachLocation::SymbolOffset(s, offset) => (Some(s), offset),
            UProbeAttachLocation::AbsoluteOffset(offset) => (None, offset),
        };
        let offset = if let Some(symbol) = symbol {
            let symbol_offset =
                resolve_symbol(path, symbol).map_err(|error| UProbeError::SymbolError {
                    symbol: symbol.to_string(),
                    error: Box::new(error),
                })?;
            symbol_offset + offset
        } else {
            offset
        };

        let Self { data, kind } = self;
        let path = path.as_os_str();
        attach::<Self, _>(data, *kind, path, offset, pid, cookie)
    }

    /// Creates a program from a pinned entry on a bpffs.
    ///
    /// Existing links will not be populated. To work with existing links you should use [`crate::programs::links::PinnedLink`].
    ///
    /// On drop, any managed links are detached and the program is unloaded. This will not result in
    /// the program being unloaded from the kernel if it is still pinned.
    pub fn from_pin<P: AsRef<Path>>(path: P, kind: ProbeKind) -> Result<Self, ProgramError> {
        let data = ProgramData::from_pinned_path(path, VerifierLogLevel::default())?;
        Ok(Self { data, kind })
    }
}

impl Probe for UProbe {
    const PMU: &'static str = "uprobe";

    type Error = UProbeError;

    fn file_error(filename: PathBuf, io_error: io::Error) -> Self::Error {
        UProbeError::FileError { filename, io_error }
    }

    fn write_offset<W: Write>(w: &mut W, _: ProbeKind, offset: u64) -> fmt::Result {
        write!(w, ":{offset:#x}")
    }
}

fn resolve_attach_path<'a, 'b, 'c, T>(
    target: &'a Path,
    proc_map: Option<&'b ProcMap<T>>,
) -> Result<&'c Path, UProbeError>
where
    'a: 'c,
    'b: 'c,
    T: AsRef<[u8]>,
{
    proc_map
        .and_then(|proc_map| {
            proc_map
                .find_library_path_by_name(target)
                .map_err(|source| {
                    let ProcMap { pid, data: _ } = proc_map;
                    let pid = *pid;
                    UProbeError::ProcMap { pid, source }
                })
                .transpose()
        })
        .or_else(|| target.is_absolute().then(|| Ok(target)))
        .or_else(|| {
            LD_SO_CACHE
                .as_ref()
                .map_err(|io_error| UProbeError::InvalidLdSoCache { io_error })
                .map(|cache| cache.resolve(target))
                .transpose()
        })
        .unwrap_or_else(|| {
            Err(UProbeError::InvalidTarget {
                path: target.to_owned(),
            })
        })
}

define_link_wrapper!(
    UProbeLink,
    UProbeLinkId,
    PerfLinkInner,
    PerfLinkIdInner,
    UProbe,
);

impl_try_into_fdlink!(UProbeLink, PerfLinkInner);

impl TryFrom<FdLink> for UProbeLink {
    type Error = LinkError;

    fn try_from(fd_link: FdLink) -> Result<Self, Self::Error> {
        let info = bpf_link_get_info_by_fd(fd_link.fd.as_fd())?;
        if info.type_ == (bpf_link_type::BPF_LINK_TYPE_TRACING as u32) {
            return Ok(Self::new(PerfLinkInner::Fd(fd_link)));
        }
        Err(LinkError::InvalidLink)
    }
}

/// The type returned when attaching an [`UProbe`] fails.
#[derive(Debug, Error)]
pub enum UProbeError {
    /// There was an error parsing `/etc/ld.so.cache`.
    #[error("error reading `{}` file", LD_SO_CACHE_FILE)]
    InvalidLdSoCache {
        /// the original [`io::Error`].
        #[source]
        io_error: &'static io::Error,
    },

    /// The target program could not be found.
    #[error("could not resolve uprobe target `{path}`")]
    InvalidTarget {
        /// path to target.
        path: PathBuf,
    },

    /// There was an error resolving the target symbol.
    #[error("error resolving symbol")]
    SymbolError {
        /// symbol name.
        symbol: String,
        /// the original error.
        #[source]
        error: Box<dyn Error + Send + Sync>,
    },

    /// There was an error accessing `filename`.
    #[error("`{filename}`")]
    FileError {
        /// The file name
        filename: PathBuf,
        /// The [`io::Error`] returned from the file operation
        #[source]
        io_error: io::Error,
    },

    /// There was en error fetching the memory map for `pid`.
    #[error("error fetching libs for {pid}")]
    ProcMap {
        /// The pid.
        pid: u32,
        /// The [`ProcMapError`] that caused the error.
        #[source]
        source: ProcMapError,
    },
}

/// Error reading from /proc/pid/maps.
#[derive(Debug, Error)]
pub enum ProcMapError {
    /// Unable to read /proc/pid/maps.
    #[error(transparent)]
    ReadFile(#[from] io::Error),

    /// Error parsing a line of /proc/pid/maps.
    #[error("could not parse {}", line.display())]
    ParseLine {
        /// The line that could not be parsed.
        line: OsString,
    },
}

/// A entry that has been parsed from /proc/`pid`/maps.
///
/// This contains information about a mapped portion of memory
/// for the process, ranging from address to `address_end`.
#[cfg_attr(test, derive(Debug, PartialEq))]
struct ProcMapEntry<'a> {
    #[cfg_attr(not(test), expect(dead_code, reason = "parsed but not exposed"))]
    address: u64,
    #[cfg_attr(not(test), expect(dead_code, reason = "parsed but not exposed"))]
    address_end: u64,
    #[cfg_attr(not(test), expect(dead_code, reason = "parsed but not exposed"))]
    perms: &'a OsStr,
    #[cfg_attr(not(test), expect(dead_code, reason = "parsed but not exposed"))]
    offset: u64,
    #[cfg_attr(not(test), expect(dead_code, reason = "parsed but not exposed"))]
    dev: &'a OsStr,
    #[cfg_attr(not(test), expect(dead_code, reason = "parsed but not exposed"))]
    inode: u32,
    path: Option<&'a OsStr>,
}

/// Split a byte slice on ASCII whitespace up to `n` times.
///
/// The last item yielded contains the remainder of the slice and may itself
/// contain whitespace.
fn split_ascii_whitespace_n(s: &[u8], mut n: usize) -> impl Iterator<Item = &[u8]> {
    let mut s = s.trim_ascii_end();

    std::iter::from_fn(move || {
        if n == 0 {
            None
        } else {
            s = s.trim_ascii_start();

            n -= 1;
            Some(if n == 0 {
                s
            } else if let Some(i) = s.iter().position(u8::is_ascii_whitespace) {
                let (next, rest) = s.split_at(i);
                s = rest;
                next
            } else {
                n = 0;
                s
            })
        }
    })
}

impl<'a> ProcMapEntry<'a> {
    fn parse(line: &'a [u8]) -> Result<Self, ProcMapError> {
        use std::os::unix::ffi::OsStrExt as _;

        let err = || ProcMapError::ParseLine {
            line: OsString::from_vec(line.to_vec()),
        };

        let mut parts =
            // address, perms, offset, dev, inode, path = 6.
            split_ascii_whitespace_n(line, 6)
            .filter(|part| !part.is_empty());

        let mut next = || parts.next().ok_or_else(err);

        let (start, end) = {
            let addr = next()?;
            let mut addr_parts = addr.split(|b| *b == b'-');
            let mut next = || {
                addr_parts
                    .next()
                    .ok_or(())
                    .and_then(|part| {
                        let s =
                            std::str::from_utf8(part).map_err(|std::str::Utf8Error { .. }| ())?;
                        let n = u64::from_str_radix(s, 16)
                            .map_err(|std::num::ParseIntError { .. }| ())?;
                        Ok(n)
                    })
                    .map_err(|()| err())
            };
            let start = next()?;
            let end = next()?;
            if let Some(_part) = addr_parts.next() {
                return Err(err());
            }
            (start, end)
        };

        let perms = next()?;
        let perms = OsStr::from_bytes(perms);
        let offset = next()?;
        let offset = std::str::from_utf8(offset).map_err(|std::str::Utf8Error { .. }| err())?;
        let offset =
            u64::from_str_radix(offset, 16).map_err(|std::num::ParseIntError { .. }| err())?;
        let dev = next()?;
        let dev = OsStr::from_bytes(dev);
        let inode = next()?;
        let inode = std::str::from_utf8(inode).map_err(|std::str::Utf8Error { .. }| err())?;
        let inode = inode
            .parse()
            .map_err(|std::num::ParseIntError { .. }| err())?;

        let path = parts.next().map(OsStr::from_bytes);

        if let Some(_part) = parts.next() {
            return Err(err());
        }

        Ok(Self {
            address: start,
            address_end: end,
            perms,
            offset,
            dev,
            inode,
            path,
        })
    }
}

/// The memory maps of a process.
///
/// This is read from /proc/`pid`/maps.
///
/// The information here may be used to resolve addresses to paths.
struct ProcMap<T> {
    pid: u32,
    data: T,
}

impl ProcMap<Vec<u8>> {
    fn new(pid: u32) -> Result<Self, UProbeError> {
        let filename = PathBuf::from(format!("/proc/{pid}/maps"));
        let data = fs::read(&filename)
            .map_err(|io_error| UProbeError::FileError { filename, io_error })?;
        Ok(Self { pid, data })
    }
}

impl<T: AsRef<[u8]>> ProcMap<T> {
    fn libs(&self) -> impl Iterator<Item = Result<ProcMapEntry<'_>, ProcMapError>> {
        let Self { pid: _, data } = self;

        // /proc/<pid>/maps ends with '\n', so split() yields a trailing empty slice without this.
        data.as_ref()
            .trim_ascii()
            .split(|&b| b == b'\n')
            .map(ProcMapEntry::parse)
    }

    // Find the full path of a library by its name.
    //
    // This isn't part of the public API since it's really only useful for
    // attaching uprobes.
    fn find_library_path_by_name(&self, lib: &Path) -> Result<Option<&Path>, ProcMapError> {
        let lib = lib.as_os_str();
        let lib = lib.strip_suffix(OsStr::new(".so")).unwrap_or(lib);

        for entry in self.libs() {
            let ProcMapEntry {
                address: _,
                address_end: _,
                perms: _,
                offset: _,
                dev: _,
                inode: _,
                path,
            } = entry?;
            if let Some(path) = path {
                let path = Path::new(path);
                if let Some(filename) = path.file_name() {
                    if let Some(suffix) = filename.strip_prefix(lib) {
                        if suffix.is_empty()
                            || suffix.starts_with(OsStr::new(".so"))
                            || suffix.starts_with(OsStr::new("-"))
                        {
                            return Ok(Some(path));
                        }
                    }
                }
            }
        }
        Ok(None)
    }
}

#[derive(Debug)]
pub(crate) struct CacheEntry {
    key: OsString,
    value: OsString,
    _flags: i32,
}

#[derive(Debug)]
pub(crate) struct LdSoCache {
    entries: Vec<CacheEntry>,
}

impl LdSoCache {
    fn load<T: AsRef<Path>>(path: T) -> Result<Self, io::Error> {
        let data = fs::read(path)?;
        Self::parse(&data)
    }

    fn parse(data: &[u8]) -> Result<Self, io::Error> {
        let mut cursor = Cursor::new(data);

        let read_u32 = |cursor: &mut Cursor<_>| -> Result<u32, io::Error> {
            let mut buf = [0u8; size_of::<u32>()];
            cursor.read_exact(&mut buf)?;

            Ok(u32::from_ne_bytes(buf))
        };

        let read_i32 = |cursor: &mut Cursor<_>| -> Result<i32, io::Error> {
            let mut buf = [0u8; size_of::<i32>()];
            cursor.read_exact(&mut buf)?;

            Ok(i32::from_ne_bytes(buf))
        };

        // Check for new format
        let mut buf = [0u8; LD_SO_CACHE_HEADER_NEW.len()];
        cursor.read_exact(&mut buf)?;
        let header = std::str::from_utf8(&buf).map_err(|std::str::Utf8Error { .. }| {
            io::Error::new(io::ErrorKind::InvalidData, "invalid ld.so.cache header")
        })?;

        let new_format = header == LD_SO_CACHE_HEADER_NEW;

        // Check for old format
        if !new_format {
            cursor.set_position(0);
            let mut buf = [0u8; LD_SO_CACHE_HEADER_OLD.len()];
            cursor.read_exact(&mut buf)?;
            let header = std::str::from_utf8(&buf).map_err(|std::str::Utf8Error { .. }| {
                io::Error::new(io::ErrorKind::InvalidData, "invalid ld.so.cache header")
            })?;

            if header != LD_SO_CACHE_HEADER_OLD {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "invalid ld.so.cache header",
                ));
            }
        }

        let num_entries = read_u32(&mut cursor)?;

        if new_format {
            cursor.consume(6 * size_of::<u32>());
        }

        let offset = if new_format {
            0
        } else {
            cursor.position() as usize + num_entries as usize * 12
        };

        let entries = std::iter::repeat_with(|| {
            let flags = read_i32(&mut cursor)?;
            let k_pos = read_u32(&mut cursor)? as usize;
            let v_pos = read_u32(&mut cursor)? as usize;

            if new_format {
                cursor.consume(12);
            }

            let read_str = |pos| {
                use std::os::unix::ffi::OsStrExt as _;
                OsStr::from_bytes(
                    unsafe { CStr::from_ptr(cursor.get_ref()[offset + pos..].as_ptr().cast()) }
                        .to_bytes(),
                )
                .to_owned()
            };

            let key = read_str(k_pos);
            let value = read_str(v_pos);

            Ok::<_, io::Error>(CacheEntry {
                key,
                value,
                _flags: flags,
            })
        })
        .take(num_entries as usize)
        .collect::<Result<_, _>>()?;

        Ok(Self { entries })
    }

    fn resolve(&self, lib: &Path) -> Option<&Path> {
        let Self { entries } = self;

        let lib = lib.as_os_str();
        let lib = lib.strip_suffix(OsStr::new(".so")).unwrap_or(lib);

        entries
            .iter()
            .find_map(|CacheEntry { key, value, _flags }| {
                let suffix = key.strip_prefix(lib)?;
                suffix
                    .starts_with(OsStr::new(".so"))
                    .then_some(Path::new(value.as_os_str()))
            })
    }
}

#[derive(Error, Debug)]
enum ResolveSymbolError {
    #[error(transparent)]
    Io(#[from] io::Error),

    #[error("error parsing ELF")]
    Object(#[from] object::Error),

    #[error("unknown symbol `{0}`")]
    Unknown(String),

    #[error("symbol `{0}` does not appear in section")]
    NotInSection(String),

    #[error("symbol `{0}` in section `{1:?}` which has no offset")]
    SectionFileRangeNone(String, Result<String, object::Error>),

    #[error("failed to access debuglink file `{0}`: `{1}`")]
    DebuglinkAccessError(PathBuf, io::Error),

    #[error("symbol `{0}` not found, mismatched build IDs in main and debug files")]
    BuildIdMismatch(String),
}

fn construct_debuglink_path<'a>(filename: &'a [u8], main_path: &Path) -> Cow<'a, Path> {
    let filename_str = OsStr::from_bytes(filename);
    let debuglink_path = Path::new(filename_str);

    if debuglink_path.is_relative() {
        // If the debug path is relative, resolve it against the parent of the main path
        main_path.parent().map_or_else(
            || debuglink_path.into(), // Use original if no parent
            |parent| parent.join(debuglink_path).into(),
        )
    } else {
        // If the path is not relative, just use original
        debuglink_path.into()
    }
}

fn verify_build_ids<'a>(
    main_obj: &'a object::File<'a>,
    debug_obj: &'a object::File<'a>,
    symbol_name: &str,
) -> Result<(), ResolveSymbolError> {
    let main_build_id = main_obj.build_id().ok().flatten();
    let debug_build_id = debug_obj.build_id().ok().flatten();

    match (debug_build_id, main_build_id) {
        (Some(debug_build_id), Some(main_build_id)) => {
            // Only perform a comparison if both build IDs are present
            if debug_build_id != main_build_id {
                return Err(ResolveSymbolError::BuildIdMismatch(symbol_name.to_owned()));
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

fn find_debug_path_in_object<'a>(
    obj: &object::File<'a>,
    main_path: &Path,
    symbol: &str,
) -> Result<Cow<'a, Path>, ResolveSymbolError> {
    match obj.gnu_debuglink() {
        Ok(Some((filename, _))) => Ok(construct_debuglink_path(filename, main_path)),
        Ok(None) => Err(ResolveSymbolError::Unknown(symbol.to_string())),
        Err(err) => Err(ResolveSymbolError::Object(err)),
    }
}

fn find_symbol_in_object<'a>(obj: &'a object::File<'a>, symbol: &str) -> Option<Symbol<'a, 'a>> {
    obj.dynamic_symbols()
        .chain(obj.symbols())
        .find(|sym| sym.name().is_ok_and(|name| name == symbol))
}

fn resolve_symbol(path: &Path, symbol: &str) -> Result<u64, ResolveSymbolError> {
    let data = MMap::map_copy_read_only(path)?;
    let obj = object::read::File::parse(data.as_ref())?;

    if let Some(sym) = find_symbol_in_object(&obj, symbol) {
        symbol_translated_address(&obj, sym, symbol)
    } else {
        // Only search in the debug object if the symbol was not found in the main object
        let debug_path = find_debug_path_in_object(&obj, path, symbol)?;
        let debug_data = MMap::map_copy_read_only(&debug_path)
            .map_err(|e| ResolveSymbolError::DebuglinkAccessError(debug_path.into_owned(), e))?;
        let debug_obj = object::read::File::parse(debug_data.as_ref())?;

        verify_build_ids(&obj, &debug_obj, symbol)?;

        let sym = find_symbol_in_object(&debug_obj, symbol)
            .ok_or_else(|| ResolveSymbolError::Unknown(symbol.to_string()))?;

        symbol_translated_address(&debug_obj, sym, symbol)
    }
}

fn symbol_translated_address(
    obj: &object::File<'_>,
    sym: Symbol<'_, '_>,
    symbol_name: &str,
) -> Result<u64, ResolveSymbolError> {
    let needs_addr_translation = matches!(
        obj.kind(),
        object::ObjectKind::Dynamic | object::ObjectKind::Executable
    );
    if needs_addr_translation {
        let index = sym
            .section_index()
            .ok_or_else(|| ResolveSymbolError::NotInSection(symbol_name.to_string()))?;
        let section = obj.section_by_index(index)?;
        let (offset, _size) = section.file_range().ok_or_else(|| {
            ResolveSymbolError::SectionFileRangeNone(
                symbol_name.to_string(),
                section.name().map(str::to_owned),
            )
        })?;
        Ok(sym.address() - section.address() + offset)
    } else {
        Ok(sym.address())
    }
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use object::{Architecture, BinaryFormat, Endianness, write::SectionKind};
    use test_case::test_case;

    use super::*;

    // Only run this test on with libc dynamically linked so that it can
    // exercise resolving the path to libc via the current process's memory map.
    #[test]
    #[cfg_attr(
        any(miri, not(target_os = "linux"), target_feature = "crt-static"),
        ignore = "requires dynamic linkage of libc"
    )]
    fn test_resolve_attach_path() {
        // Look up the current process's pid.
        let pid = std::process::id();
        let proc_map = ProcMap::new(pid).expect("failed to get proc map");

        // Now let's resolve the path to libc. It should exist in the current process's memory map and
        // then in the ld.so.cache.
        assert_matches!(
            resolve_attach_path("libc".as_ref(), Some(&proc_map)),
            Ok(path) => {
                // Make sure we got a path that contains libc.
                assert_matches!(
                    path.to_str(),
                    Some(path) if path.contains("libc"), "path: {}", path.display()
                );
            }
        );

        // If we pass an absolute path that doesn't match anything in /proc/<pid>/maps, we should fall
        // back to the provided path instead of erroring out. Using a synthetic absolute path keeps the
        // test hermetic.
        let synthetic_absolute = Path::new("/tmp/.aya-test-resolve-attach-absolute");
        assert_matches!(
            resolve_attach_path(synthetic_absolute, Some(&proc_map)),
            Ok(path) => {
                assert_eq!(path, synthetic_absolute, "path: {}", path.display());
            }
        );
    }

    #[test]
    fn test_relative_path_with_parent() {
        let filename = b"debug_info";
        let main_path = Path::new("/usr/lib/main_binary");
        let expected = Path::new("/usr/lib/debug_info");

        let result = construct_debuglink_path(filename, main_path);
        assert_eq!(
            result, expected,
            "The debug path should resolve relative to the main path's parent"
        );
    }

    #[test]
    fn test_relative_path_without_parent() {
        let filename = b"debug_info";
        let main_path = Path::new("main_binary");
        let expected = Path::new("debug_info");

        let result = construct_debuglink_path(filename, main_path);
        assert_eq!(
            result, expected,
            "The debug path should be the original path as there is no parent"
        );
    }

    #[test]
    fn test_absolute_path() {
        let filename = b"/absolute/path/to/debug_info";
        let main_path = Path::new("/usr/lib/main_binary");
        let expected = Path::new("/absolute/path/to/debug_info");

        let result = construct_debuglink_path(filename, main_path);
        assert_eq!(
            result, expected,
            "The debug path should be the same as the input absolute path"
        );
    }

    #[expect(
        clippy::little_endian_bytes,
        reason = "ELF debuglink fields are encoded as little-endian"
    )]
    fn create_elf_with_debuglink(
        debug_filename: &[u8],
        crc: u32,
    ) -> Result<Vec<u8>, object::write::Error> {
        let mut obj =
            object::write::Object::new(BinaryFormat::Elf, Architecture::X86_64, Endianness::Little);

        let section_name = b".gnu_debuglink";

        let section_id = obj.add_section(vec![], section_name.to_vec(), SectionKind::Note);

        let mut debuglink_data = Vec::new();

        debuglink_data.extend_from_slice(debug_filename);
        debuglink_data.push(0); // Null terminator

        while debuglink_data.len() % 4 != 0 {
            debuglink_data.push(0);
        }

        debuglink_data.extend(&crc.to_le_bytes());

        obj.append_section_data(section_id, &debuglink_data, 4 /* align */);

        obj.write()
    }

    #[expect(
        clippy::little_endian_bytes,
        reason = "ELF note headers are encoded as little-endian"
    )]
    fn create_elf_with_build_id(build_id: &[u8]) -> Result<Vec<u8>, object::write::Error> {
        let mut obj =
            object::write::Object::new(BinaryFormat::Elf, Architecture::X86_64, Endianness::Little);

        let section_name = b".note.gnu.build-id";

        let section_id = obj.add_section(vec![], section_name.to_vec(), SectionKind::Note);

        let mut note_data = Vec::new();
        let build_id_name = b"GNU";

        note_data.extend(&(build_id_name.len() as u32 + 1).to_le_bytes());
        note_data.extend(&(build_id.len() as u32).to_le_bytes());
        note_data.extend(&3u32.to_le_bytes());

        note_data.extend_from_slice(build_id_name);
        note_data.push(0); // Null terminator
        note_data.extend_from_slice(build_id);

        obj.append_section_data(section_id, &note_data, 4 /* align */);

        obj.write()
    }

    fn aligned_slice(vec: &mut Vec<u8>) -> &mut [u8] {
        let alignment = 8;

        let original_size = vec.len();
        let total_size = original_size + alignment - 1;

        if vec.capacity() < total_size {
            vec.reserve(total_size - vec.capacity());
        }

        if vec.len() < total_size {
            vec.resize(total_size, 0);
        }

        let ptr = vec.as_ptr() as usize;

        let aligned_ptr = ptr.next_multiple_of(alignment);

        let offset = aligned_ptr - ptr;

        if offset > 0 {
            let tmp = vec.len();
            vec.copy_within(0..tmp - offset, offset);
        }

        &mut vec[offset..offset + original_size]
    }

    #[test]
    fn test_find_debug_path_success() {
        let debug_filepath = b"main.debug";
        let mut main_bytes = create_elf_with_debuglink(debug_filepath, 0x123 /* fake CRC */)
            .expect("got main_bytes");
        let align_bytes = aligned_slice(&mut main_bytes);
        let main_obj = object::File::parse(&*align_bytes).expect("got main obj");

        let main_path = Path::new("/path/to/main");

        assert_matches!(
            find_debug_path_in_object(&main_obj, main_path, "symbol"),
            Ok(path) => {
                assert_eq!(&*path, "/path/to/main.debug", "path: {}", path.display());
            }
        );
    }

    #[test]
    fn test_verify_build_ids_same() {
        let build_id = b"test_build_id";
        let mut main_bytes = create_elf_with_build_id(build_id).expect("got main_bytes");
        let align_bytes = aligned_slice(&mut main_bytes);
        let main_obj = object::File::parse(&*align_bytes).expect("got main obj");
        let debug_build_id = b"test_build_id";
        let mut debug_bytes = create_elf_with_build_id(debug_build_id).expect("got debug bytes");
        let align_bytes = aligned_slice(&mut debug_bytes);
        let debug_obj = object::File::parse(&*align_bytes).expect("got debug obj");

        assert_matches!(
            verify_build_ids(&main_obj, &debug_obj, "symbol_name"),
            Ok(())
        );
    }

    #[test]
    fn test_verify_build_ids_different() {
        let build_id = b"main_build_id";
        let mut main_bytes = create_elf_with_build_id(build_id).expect("got main_bytes");
        let align_bytes = aligned_slice(&mut main_bytes);
        let main_obj = object::File::parse(&*align_bytes).expect("got main obj");
        let debug_build_id = b"debug_build_id";
        let mut debug_bytes = create_elf_with_build_id(debug_build_id).expect("got debug bytes");
        let align_bytes = aligned_slice(&mut debug_bytes);
        let debug_obj = object::File::parse(&*align_bytes).expect("got debug obj");

        assert_matches!(
            verify_build_ids(&main_obj, &debug_obj, "symbol_name"),
            Err(ResolveSymbolError::BuildIdMismatch(symbol_name)) if symbol_name == "symbol_name"
        );
    }

    #[derive(Debug, Clone, Copy)]
    struct ExpectedProcMapEntry {
        address: u64,
        address_end: u64,
        perms: &'static str,
        offset: u64,
        dev: &'static str,
        inode: u32,
        path: Option<&'static str>,
    }

    #[test_case(
        b"7ffd6fbea000-7ffd6fbec000  r-xp  00000000  00:00  0  [vdso]",
        ExpectedProcMapEntry {
            address: 0x7ffd6fbea000,
            address_end: 0x7ffd6fbec000,
            perms: "r-xp",
            offset: 0,
            dev: "00:00",
            inode: 0,
            path: Some("[vdso]"),
        };
        "bracketed_name"
    )]
    #[test_case(
        b"7f1bca83a000-7f1bca83c000  rw-p  00036000  fd:01  2895508  /usr/lib64/ld-linux-x86-64.so.2",
        ExpectedProcMapEntry {
            address: 0x7f1bca83a000,
            address_end: 0x7f1bca83c000,
            perms: "rw-p",
            offset: 0x00036000,
            dev: "fd:01",
            inode: 2895508,
            path: Some("/usr/lib64/ld-linux-x86-64.so.2"),
        };
        "absolute_path"
    )]
    #[test_case(
        b"7f1bca5f9000-7f1bca601000  rw-p  00000000  00:00  0",
        ExpectedProcMapEntry {
            address: 0x7f1bca5f9000,
            address_end: 0x7f1bca601000,
            perms: "rw-p",
            offset: 0,
            dev: "00:00",
            inode: 0,
            path: None,
        };
        "no_path"
    )]
    #[test_case(
        b"7f1bca5f9000-7f1bca601000  rw-p  00000000  00:00  0  deadbeef",
        ExpectedProcMapEntry {
            address: 0x7f1bca5f9000,
            address_end: 0x7f1bca601000,
            perms: "rw-p",
            offset: 0,
            dev: "00:00",
            inode: 0,
            path: Some("deadbeef"),
        };
        "relative_path_token"
    )]
    #[test_case(
        b"7f1bca83a000-7f1bca83c000  rw-p  00036000  fd:01  2895508  /usr/lib/libc.so.6 (deleted)",
        ExpectedProcMapEntry {
            address: 0x7f1bca83a000,
            address_end: 0x7f1bca83c000,
            perms: "rw-p",
            offset: 0x00036000,
            dev: "fd:01",
            inode: 2895508,
            path: Some("/usr/lib/libc.so.6 (deleted)"),
        };
        "deleted_suffix_in_path"
    )]
    // The path field is the remainder of the line. It may contain whitespace and arbitrary tokens.
    #[test_case(
        b"71064dc000-71064df000 ---p 00000000 00:00 0  [page size compat] extra",
        ExpectedProcMapEntry {
            address: 0x71064dc000,
            address_end: 0x71064df000,
            perms: "---p",
            offset: 0,
            dev: "00:00",
            inode: 0,
            path: Some("[page size compat] extra"),
        };
        "path_remainder_with_spaces"
    )]
    #[test_case(
        b"724a0000-72aab000 rw-p 00000000 00:00 0 [anon:dalvik-zygote space] (deleted) extra",
        ExpectedProcMapEntry {
            address: 0x724a0000,
            address_end: 0x72aab000,
            perms: "rw-p",
            offset: 0,
            dev: "00:00",
            inode: 0,
            path: Some("[anon:dalvik-zygote space] (deleted) extra"),
        };
        "bracketed_name_with_spaces"
    )]
    #[test_case(
        b"5ba3b000-5da3b000 r--s 00000000 00:01 1033 /memfd:jit-zygote-cache (deleted)",
        ExpectedProcMapEntry {
            address: 0x5ba3b000,
            address_end: 0x5da3b000,
            perms: "r--s",
            offset: 0,
            dev: "00:01",
            inode: 1033,
            path: Some("/memfd:jit-zygote-cache (deleted)"),
        };
        "memfd_deleted"
    )]
    #[test_case(
        b"6cd539c000-6cd559c000 rw-s 00000000 00:01 7215 /dev/ashmem/CursorWindow: /data/user/0/package/databases/kitefly.db (deleted)",
        ExpectedProcMapEntry {
            address: 0x6cd539c000,
            address_end: 0x6cd559c000,
            perms: "rw-s",
            offset: 0,
            dev: "00:01",
            inode: 7215,
            path: Some("/dev/ashmem/CursorWindow: /data/user/0/package/databases/kitefly.db (deleted)"),
        };
        "ashmem_with_spaces"
    )]
    fn test_parse_proc_map_entry_ok(line: &'static [u8], expected: ExpectedProcMapEntry) {
        use std::ffi::OsStr;

        let ExpectedProcMapEntry {
            address,
            address_end,
            perms,
            offset,
            dev,
            inode,
            path,
        } = expected;

        assert_matches!(ProcMapEntry::parse(line), Ok(entry) if entry == ProcMapEntry {
            address,
            address_end,
            perms: OsStr::new(perms),
            offset,
            dev: OsStr::new(dev),
            inode,
            path: path.map(OsStr::new),
        });
    }

    #[test_case(b"zzzz-7ffd6fbea000  r-xp  00000000  00:00  0  [vdso]"; "bad_address")]
    #[test_case(b"7f1bca5f9000-7f1bca601000  r-xp  zzzz  00:00  0  [vdso]"; "bad_offset")]
    #[test_case(b"7f1bca5f9000-7f1bca601000  r-xp  00000000  00:00  zzzz  [vdso]"; "bad_inode")]
    #[test_case(b"7f1bca5f90007ffd6fbea000  r-xp  00000000  00:00  0  [vdso]"; "bad_address_range")]
    #[test_case(b"7f1bca5f9000-7f1bca601000  r-xp  00000000"; "missing_fields")]
    #[test_case(b"7f1bca5f9000-7f1bca601000-deadbeef  rw-p  00000000  00:00  0"; "bad_address_delimiter")]
    fn test_parse_proc_map_entry_err(line: &'static [u8]) {
        assert_matches!(
            ProcMapEntry::parse(line),
            Err(ProcMapError::ParseLine { line: _ })
        );
    }

    #[test]
    fn test_proc_map_find_lib_by_name() {
        let proc_map_libs = ProcMap {
            pid: 0xdead,
            data: b"
7fc4a9800000-7fc4a98ad000	r--p	00000000	00:24	18147308	/usr/lib64/libcrypto.so.3.0.9
",
        };

        assert_matches!(
            proc_map_libs.find_library_path_by_name(Path::new("libcrypto.so.3.0.9")),
            Ok(Some(path)) => {
                assert_eq!(path, "/usr/lib64/libcrypto.so.3.0.9", "path: {}", path.display());
            }
        );
    }

    #[test]
    fn test_proc_map_find_lib_by_partial_name() {
        let proc_map_libs = ProcMap {
            pid: 0xdead,
            data: b"
7fc4a9800000-7fc4a98ad000	r--p	00000000	00:24	18147308	/usr/lib64/libcrypto.so.3.0.9
",
        };

        assert_matches!(
            proc_map_libs.find_library_path_by_name(Path::new("libcrypto")),
            Ok(Some(path)) => {
                assert_eq!(path, "/usr/lib64/libcrypto.so.3.0.9", "path: {}", path.display());
            }
        );
    }

    #[test]
    fn test_proc_map_with_multiple_lib_entries() {
        let proc_map_libs = ProcMap {
            pid: 0xdead,
            data: b"
7f372868000-7f3722869000	r--p	00000000	00:24	18097875	/usr/lib64/ld-linux-x86-64.so.2
7f3722869000-7f372288f000	r-xp	00001000	00:24	18097875	/usr/lib64/ld-linux-x86-64.so.2
7f372288f000-7f3722899000	r--p	00027000	00:24	18097875	/usr/lib64/ld-linux-x86-64.so.2
7f3722899000-7f372289b000	r--p	00030000	00:24	18097875	/usr/lib64/ld-linux-x86-64.so.2
7f372289b000-7f372289d000	rw-p	00032000	00:24	18097875	/usr/lib64/ld-linux-x86-64.so.2
",
        };

        assert_matches!(
            proc_map_libs.find_library_path_by_name(Path::new("ld-linux-x86-64.so.2")),
            Ok(Some(path)) => {
                assert_eq!(path, "/usr/lib64/ld-linux-x86-64.so.2", "path: {}", path.display());
            }
        );
    }
}