From 04f269b13cd75ffc642f61095de0b7fe7ceeee2e Mon Sep 17 00:00:00 2001 From: Ayrton Sparling Date: Mon, 26 Dec 2022 09:52:46 -0800 Subject: [PATCH] Fix some leaked file descriptors in programs Also added some todos for the switch to OwnedFd Signed-off-by: Ayrton Sparling --- aya/src/programs/mod.rs | 25 +++++++++++++++++++++---- aya/src/sys/bpf.rs | 1 + 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/aya/src/programs/mod.rs b/aya/src/programs/mod.rs index a2a45969..8a361195 100644 --- a/aya/src/programs/mod.rs +++ b/aya/src/programs/mod.rs @@ -407,6 +407,7 @@ impl Drop for Program { pub(crate) struct ProgramData { pub(crate) name: Option, pub(crate) obj: obj::Program, + // TODO: replace with OwnedFd, then we don't need to manually impl Drop for ProgramData pub(crate) fd: Option, pub(crate) links: LinkMap, pub(crate) expected_attach_type: Option, @@ -449,6 +450,12 @@ impl ProgramData { } } +impl Drop for ProgramData { + fn drop(&mut self) { + self.fd.map(|fd| unsafe { libc::close(fd) }); + } +} + fn unload_program(data: &mut ProgramData) -> Result<(), ProgramError> { data.links.remove_all()?; let fd = data.fd.take().ok_or(ProgramError::NotLoaded)?; @@ -830,6 +837,7 @@ impl ProgramInfo { } /// Loads a program from a pinned path in bpffs. + // TODO: Switch RawFd to OwnedFd pub fn from_pin>(path: P) -> Result { let path_string = CString::new(path.as_ref().to_str().unwrap()).unwrap(); let fd = @@ -838,14 +846,23 @@ impl ProgramInfo { io_error, })? as RawFd; - let info = bpf_prog_get_info_by_fd(fd).map_err(|io_error| ProgramError::SyscallError { - call: "bpf_prog_get_info_by_fd".to_owned(), - io_error, - })?; + let info = Self::from_fd(&fd); + + // Ensure RawFd is closed independent of the result of Self::from_fd unsafe { libc::close(fd); } + info + } + + /// Create ProgramInfo from the file descriptor of a program. + pub fn from_fd(fd: &RawFd) -> Result { + let info = bpf_prog_get_info_by_fd(*fd).map_err(|io_error| ProgramError::SyscallError { + call: "bpf_prog_get_info_by_fd".to_owned(), + io_error, + })?; + Ok(ProgramInfo(info)) } } diff --git a/aya/src/sys/bpf.rs b/aya/src/sys/bpf.rs index 43d08fbd..b75140a4 100644 --- a/aya/src/sys/bpf.rs +++ b/aya/src/sys/bpf.rs @@ -425,6 +425,7 @@ pub(crate) fn bpf_prog_query( ret } +// TODO: Replace RawFd with OwnedFd pub(crate) fn bpf_prog_get_fd_by_id(prog_id: u32) -> Result { let mut attr = unsafe { mem::zeroed::() };