Skip to main content

aya_friday/programs/
kprobe.rs

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