Skip to main content

profile_bee_aya/programs/
kprobe.rs

1//! Kernel space probes.
2use std::{
3    ffi::OsStr,
4    fmt::{self, Write},
5    io,
6    os::fd::AsFd as _,
7    path::{Path, PathBuf},
8};
9
10use aya_obj::generated::{bpf_link_type, bpf_prog_type::BPF_PROG_TYPE_KPROBE};
11use thiserror::Error;
12
13use crate::{
14    VerifierLogLevel,
15    programs::{
16        FdLink, LinkError, ProgramData, ProgramError, ProgramType, define_link_wrapper,
17        impl_try_into_fdlink, load_program,
18        perf_attach::{PerfLinkIdInner, PerfLinkInner},
19        probe::{Probe, ProbeKind, attach},
20    },
21    sys::bpf_link_get_info_by_fd,
22};
23
24/// A kernel probe.
25///
26/// Kernel probes are eBPF programs that can be attached to almost any function inside
27/// the kernel. They can be of two kinds:
28///
29/// - `kprobe`: get attached to the *start* of the target functions
30/// - `kretprobe`: get attached to the *return address* of the target functions
31///
32/// # Minimum kernel version
33///
34/// The minimum kernel version required to use this feature is 4.1.
35///
36/// # Examples
37///
38/// ```no_run
39/// # let mut bpf = Ebpf::load_file("ebpf_programs.o")?;
40/// use aya::{Ebpf, programs::KProbe};
41///
42/// let program: &mut KProbe = bpf.program_mut("intercept_wakeups").unwrap().try_into()?;
43/// program.load()?;
44/// program.attach("try_to_wake_up", 0)?;
45/// # Ok::<(), aya::EbpfError>(())
46/// ```
47#[derive(Debug)]
48#[doc(alias = "BPF_PROG_TYPE_KPROBE")]
49pub struct KProbe {
50    pub(crate) data: ProgramData<KProbeLink>,
51    pub(crate) kind: ProbeKind,
52}
53
54impl KProbe {
55    /// The type of the program according to the kernel.
56    pub const PROGRAM_TYPE: ProgramType = ProgramType::KProbe;
57
58    /// Loads the program inside the kernel.
59    pub fn load(&mut self) -> Result<(), ProgramError> {
60        load_program(BPF_PROG_TYPE_KPROBE, &mut self.data)
61    }
62
63    /// Returns [`ProbeKind::Entry`] if the program is a `kprobe`, or
64    /// [`ProbeKind::Return`] if the program is a `kretprobe`.
65    pub const fn kind(&self) -> ProbeKind {
66        self.kind
67    }
68
69    /// Attaches the program.
70    ///
71    /// Attaches the probe to the given function name inside the kernel. If
72    /// `offset` is non-zero, it is added to the address of the target
73    /// function.
74    ///
75    /// If the program is a `kprobe`, it is attached to the *start* address of the target function.
76    /// Conversely if the program is a `kretprobe`, it is attached to the return address of the
77    /// target function.
78    ///
79    /// The returned value can be used to detach from the given function, see [`KProbe::detach`].
80    pub fn attach<T: AsRef<OsStr>>(
81        &mut self,
82        fn_name: T,
83        offset: u64,
84    ) -> Result<KProbeLinkId, ProgramError> {
85        let Self { data, kind } = self;
86        attach::<Self, _>(
87            data,
88            *kind,
89            fn_name.as_ref(),
90            offset,
91            None, // pid
92            None, // cookie
93        )
94    }
95
96    /// Creates a program from a pinned entry on a bpffs.
97    ///
98    /// Existing links will not be populated. To work with existing links you should use [`crate::programs::links::PinnedLink`].
99    ///
100    /// On drop, any managed links are detached and the program is unloaded. This will not result in
101    /// the program being unloaded from the kernel if it is still pinned.
102    pub fn from_pin<P: AsRef<Path>>(path: P, kind: ProbeKind) -> Result<Self, ProgramError> {
103        let data = ProgramData::from_pinned_path(path, VerifierLogLevel::default())?;
104        Ok(Self { data, kind })
105    }
106}
107
108impl Probe for KProbe {
109    const PMU: &'static str = "kprobe";
110
111    type Error = KProbeError;
112
113    fn file_error(filename: PathBuf, io_error: io::Error) -> Self::Error {
114        KProbeError::FileError { filename, io_error }
115    }
116
117    fn write_offset<W: Write>(w: &mut W, kind: ProbeKind, offset: u64) -> fmt::Result {
118        match kind {
119            ProbeKind::Entry => write!(w, "+{offset}"),
120            ProbeKind::Return => Ok(()),
121        }
122    }
123}
124
125define_link_wrapper!(
126    KProbeLink,
127    KProbeLinkId,
128    PerfLinkInner,
129    PerfLinkIdInner,
130    KProbe,
131);
132
133/// The type returned when attaching a [`KProbe`] fails.
134#[derive(Debug, Error)]
135pub enum KProbeError {
136    /// Error detaching from debugfs
137    #[error("`{filename}`")]
138    FileError {
139        /// The file name
140        filename: PathBuf,
141        /// The [`io::Error`] returned from the file operation
142        #[source]
143        io_error: io::Error,
144    },
145}
146
147impl_try_into_fdlink!(KProbeLink, PerfLinkInner);
148
149impl TryFrom<FdLink> for KProbeLink {
150    type Error = LinkError;
151
152    fn try_from(fd_link: FdLink) -> Result<Self, Self::Error> {
153        let info = bpf_link_get_info_by_fd(fd_link.fd.as_fd())?;
154        if info.type_ == (bpf_link_type::BPF_LINK_TYPE_KPROBE_MULTI as u32) {
155            return Ok(Self::new(PerfLinkInner::Fd(fd_link)));
156        }
157        Err(LinkError::InvalidLink)
158    }
159}