Skip to main content

libbpf_rs/
iter.rs

1use std::io;
2use std::os::fd::AsFd;
3use std::os::fd::AsRawFd;
4use std::os::fd::FromRawFd;
5use std::os::fd::OwnedFd;
6
7use crate::Error;
8use crate::Link;
9use crate::Result;
10
11/// Represents a bpf iterator for reading kernel data structures. This requires
12/// Linux 5.8.
13///
14/// This implements [`std::io::Read`] for reading bytes from the iterator.
15/// Methods require working with raw bytes. You may find libraries such as
16/// [`plain`](https://crates.io/crates/plain) helpful.
17#[derive(Debug)]
18#[doc(alias = "bpf_iter_create")]
19pub struct Iter {
20    fd: OwnedFd,
21}
22
23impl Iter {
24    /// Create a new `Iter` wrapping the provided `Link`.
25    pub fn new(link: &Link) -> Result<Self> {
26        let link_fd = link.as_fd().as_raw_fd();
27        let fd = unsafe { libbpf_sys::bpf_iter_create(link_fd) };
28        if fd < 0 {
29            return Err(Error::from(io::Error::last_os_error()));
30        }
31        Ok(Self {
32            fd: unsafe { OwnedFd::from_raw_fd(fd) },
33        })
34    }
35}
36
37impl io::Read for Iter {
38    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
39        let bytes_read =
40            unsafe { libc::read(self.fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) };
41        if bytes_read < 0 {
42            return Err(io::Error::last_os_error());
43        }
44        Ok(bytes_read as usize)
45    }
46}