Skip to content

Commit

Permalink
programs: ProgramFd is owned
Browse files Browse the repository at this point in the history
This avoids the overlapping borrow problem in the prior commit.
  • Loading branch information
tamird committed Aug 11, 2023
1 parent 5b872db commit 35d85e5
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 99 deletions.
14 changes: 2 additions & 12 deletions aya/src/programs/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,12 @@ pub enum ExtensionError {
/// use aya::{BpfLoader, programs::{Xdp, XdpFlags, Extension}};
///
/// let mut bpf = BpfLoader::new().extension("extension").load_file("app.o")?;
/// let mut prog = None;
/// let mut ext = None;
/// for (name, program) in bpf.programs_mut() {
/// match name {
/// "main" => prog = Some(program),
/// "extension" => ext = Some(program),
/// _ => {},
/// }
/// }
///
/// let prog: &mut Xdp = prog.unwrap().try_into()?;
/// let prog: &mut Xdp = bpf.program_mut("main").unwrap().try_into()?;
/// prog.load()?;
/// prog.attach("eth0", XdpFlags::default())?;
///
/// let prog_fd = prog.fd().unwrap();
/// let ext: &mut Extension = ext.unwrap().try_into()?;
/// let ext: &mut Extension = bpf.program_mut("extension").unwrap().try_into()?;
/// ext.load(prog_fd, "function_to_replace")?;
/// ext.attach()?;
/// Ok::<(), aya::BpfError>(())
Expand Down
17 changes: 10 additions & 7 deletions aya/src/programs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,13 +211,12 @@ pub enum ProgramError {
}

/// A [`Program`] file descriptor.
#[derive(Copy, Clone)]
pub struct ProgramFd<'program>(BorrowedFd<'program>);
pub struct ProgramFd(OwnedFd);

impl AsFd for ProgramFd<'_> {
impl AsFd for ProgramFd {
fn as_fd(&self) -> BorrowedFd<'_> {
let Self(fd) = self;
*fd
fd.as_fd()
}
}

Expand Down Expand Up @@ -370,7 +369,7 @@ impl Program {
///
/// Can be used to add a program to a [`crate::maps::ProgramArray`] or attach an [`Extension`] program.
/// Can be converted to [`RawFd`] using [`AsRawFd`].
pub fn fd(&self) -> Option<ProgramFd> {
pub fn fd(&self) -> Result<ProgramFd, ProgramError> {
match self {
Program::KProbe(p) => p.fd(),
Program::UProbe(p) => p.fd(),
Expand Down Expand Up @@ -721,8 +720,12 @@ macro_rules! impl_fd {
$(
impl $struct_name {
/// Returns the file descriptor of this Program.
pub fn fd(&self) -> Option<ProgramFd> {
self.data.fd.as_ref().map(|fd| ProgramFd(fd.as_fd()))
pub fn fd(&self) -> Result<ProgramFd, ProgramError> {
self.data.fd
.as_ref()
.ok_or(ProgramError::NotLoaded)
.and_then(|fd| fd.try_clone().map_err(Into::into))
.map(ProgramFd)
}
}
)+
Expand Down
Loading

0 comments on commit 35d85e5

Please sign in to comment.