Skip to content

Commit a792b63

Browse files
d-e-s-odanielocfb
authored andcommitted
Use new Error type
This change replaces all call-sites using the previous enum based Error with the new version. For the most part it is a straight-forward conversion. Signed-off-by: Daniel Müller <[email protected]>
1 parent 7dca6fb commit a792b63

File tree

16 files changed

+112
-137
lines changed

16 files changed

+112
-137
lines changed

libbpf-cargo/src/gen/mod.rs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,7 @@ fn gen_skel_attach(skel: &mut String, object: &mut BpfObj, obj_name: &str) -> Re
609609
fn attach(&mut self) -> libbpf_rs::Result<()> {{
610610
let ret = unsafe {{ libbpf_sys::bpf_object__attach_skeleton(self.skel_config.get()) }};
611611
if ret != 0 {{
612-
return Err(libbpf_rs::Error::System(-ret));
612+
return Err(libbpf_rs::Error::from_raw_os_error(-ret));
613613
}}
614614
615615
self.links = {obj_name}Links {{
@@ -621,12 +621,8 @@ fn gen_skel_attach(skel: &mut String, object: &mut BpfObj, obj_name: &str) -> Re
621621

622622
write!(
623623
skel,
624-
r#"{prog_name}: (|| {{
625-
Ok(
626-
core::ptr::NonNull::new(self.skel_config.prog_link_ptr({idx})?)
627-
.map(|ptr| unsafe {{ libbpf_rs::Link::from_ptr(ptr) }})
628-
)
629-
}})()?,
624+
r#"{prog_name}: core::ptr::NonNull::new(self.skel_config.prog_link_ptr({idx})?)
625+
.map(|ptr| unsafe {{ libbpf_rs::Link::from_ptr(ptr) }}),
630626
"#
631627
)?;
632628
}
@@ -701,7 +697,7 @@ fn gen_skel_contents(_debug: bool, raw_obj_name: &str, obj_file_path: &Path) ->
701697
702698
let ret = unsafe {{ libbpf_sys::bpf_object__open_skeleton(skel_config.get(), open_opts) }};
703699
if ret != 0 {{
704-
return Err(libbpf_rs::Error::System(-ret));
700+
return Err(libbpf_rs::Error::from_raw_os_error(-ret));
705701
}}
706702
707703
let obj = unsafe {{ libbpf_rs::OpenObject::from_ptr(skel_config.object_ptr())? }};
@@ -717,7 +713,7 @@ fn gen_skel_contents(_debug: bool, raw_obj_name: &str, obj_file_path: &Path) ->
717713
718714
let ret = unsafe {{ libbpf_sys::bpf_object__open_skeleton(skel_config.get(), &open_opts) }};
719715
if ret != 0 {{
720-
return Err(libbpf_rs::Error::System(-ret));
716+
return Err(libbpf_rs::Error::from_raw_os_error(-ret));
721717
}}
722718
723719
let obj = unsafe {{ libbpf_rs::OpenObject::from_ptr(skel_config.object_ptr())? }};
@@ -758,7 +754,7 @@ fn gen_skel_contents(_debug: bool, raw_obj_name: &str, obj_file_path: &Path) ->
758754
fn load(mut self) -> libbpf_rs::Result<{name}Skel<'a>> {{
759755
let ret = unsafe {{ libbpf_sys::bpf_object__load_skeleton(self.skel_config.get()) }};
760756
if ret != 0 {{
761-
return Err(libbpf_rs::Error::System(-ret));
757+
return Err(libbpf_rs::Error::from_raw_os_error(-ret));
762758
}}
763759
764760
let obj = unsafe {{ libbpf_rs::Object::from_ptr(self.obj.take_ptr())? }};

libbpf-rs/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
Unreleased
22
----------
3+
- Reworked `Error` type:
4+
- Replaced `enum` with data variants with `struct` hiding internal structure
5+
- Added support for chaining of errors
6+
- Overhauled how errors are displayed
37
- Overhauled `query::ProgramInfo` and `query::ProgInfoIter` to make them more
48
readily usable
59
- Added `Btf::from_vmlinux` constructor and adjusted `Btf::from_path` to work

libbpf-rs/src/btf/mod.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use std::ffi::CString;
1919
use std::fmt;
2020
use std::fmt::Debug;
2121
use std::fmt::Display;
22+
use std::io;
2223
use std::marker::PhantomData;
2324
use std::mem::size_of;
2425
use std::num::NonZeroUsize;
@@ -137,7 +138,7 @@ impl Btf<'static> {
137138
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
138139
fn inner(path: &Path) -> Result<Btf<'static>> {
139140
let path = CString::new(path.as_os_str().as_bytes()).map_err(|_| {
140-
Error::InvalidInput(format!("invalid path {path:?}, has null bytes"))
141+
Error::with_invalid_data(format!("invalid path {path:?}, has null bytes"))
141142
})?;
142143
let ptr = create_bpf_entity_checked(|| unsafe {
143144
libbpf_sys::btf__parse(path.as_ptr(), std::ptr::null_mut())
@@ -192,8 +193,9 @@ impl Btf<'static> {
192193

193194
impl<'btf> Btf<'btf> {
194195
pub(crate) fn from_bpf_object(obj: &'btf libbpf_sys::bpf_object) -> Result<Self> {
195-
Self::from_bpf_object_raw(obj)
196-
.and_then(|opt| opt.ok_or_else(|| Error::Internal("btf not found".into())))
196+
Self::from_bpf_object_raw(obj).and_then(|opt| {
197+
opt.ok_or_else(|| Error::with_io_error(io::ErrorKind::NotFound, "btf not found"))
198+
})
197199
}
198200

199201
fn from_bpf_object_raw(obj: *const libbpf_sys::bpf_object) -> Result<Option<Self>> {
@@ -213,7 +215,7 @@ impl<'btf> Btf<'btf> {
213215
/// From raw bytes coming from an object file.
214216
pub fn from_raw(name: &'btf str, object_file: &'btf [u8]) -> Result<Option<Self>> {
215217
let cname = CString::new(name)
216-
.map_err(|_| Error::InvalidInput(format!("invalid path {name:?}, has null bytes")))
218+
.map_err(|_| Error::with_invalid_data(format!("invalid path {name:?}, has null bytes")))
217219
.unwrap();
218220

219221
let obj_opts = libbpf_sys::bpf_object_open_opts {
@@ -284,8 +286,9 @@ impl<'btf> Btf<'btf> {
284286
/// The btf pointer size.
285287
pub fn ptr_size(&self) -> Result<NonZeroUsize> {
286288
let sz = unsafe { libbpf_sys::btf__pointer_size(self.ptr.as_ptr()) as usize };
287-
NonZeroUsize::new(sz)
288-
.ok_or_else(|| Error::Internal("could not determine pointer size".into()))
289+
NonZeroUsize::new(sz).ok_or_else(|| {
290+
Error::with_io_error(io::ErrorKind::Other, "could not determine pointer size")
291+
})
289292
}
290293

291294
/// Find a btf type by name
@@ -297,7 +300,7 @@ impl<'btf> Btf<'btf> {
297300
K: TryFrom<BtfType<'s>>,
298301
{
299302
let c_string = CString::new(name)
300-
.map_err(|_| Error::InvalidInput(format!("{name:?} contains null bytes")))
303+
.map_err(|_| Error::with_invalid_data(format!("{name:?} contains null bytes")))
301304
.unwrap();
302305
let ty = unsafe {
303306
// SAFETY: the btf pointer is valid and the c_string pointer was created from safe code
@@ -609,7 +612,7 @@ impl<'btf> BtfType<'btf> {
609612
// SAFETY: We checked the type.
610613
NonZeroUsize::new(skipped.size_unchecked() as usize)
611614
}
612-
.ok_or_else(|| Error::Internal("DataSec with size of 0".into())),
615+
.ok_or_else(|| Error::with_invalid_data("DataSec with size of 0")),
613616
BtfKind::Void
614617
| BtfKind::Volatile
615618
| BtfKind::Const
@@ -619,7 +622,7 @@ impl<'btf> BtfType<'btf> {
619622
| BtfKind::Fwd
620623
| BtfKind::Func
621624
| BtfKind::DeclTag
622-
| BtfKind::TypeTag => Err(Error::InvalidInput(format!(
625+
| BtfKind::TypeTag => Err(Error::with_invalid_data(format!(
623626
"Cannot get alignment of type with kind {:?}. TypeId is {}",
624627
skipped.kind(),
625628
skipped.type_id(),

libbpf-rs/src/iter.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,17 @@ impl Iter {
2828
let link_fd = link.as_fd().as_raw_fd();
2929
let fd = unsafe { libbpf_sys::bpf_iter_create(link_fd) };
3030
if fd < 0 {
31-
return Err(Error::System(errno::errno()));
31+
return Err(Error::from_raw_os_error(errno::errno()));
3232
}
3333
Ok(Self { fd })
3434
}
3535
}
3636

3737
impl io::Read for Iter {
38-
fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> {
38+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3939
let bytes_read = unsafe { libc::read(self.fd, buf.as_mut_ptr() as *mut _, buf.len()) };
4040
if bytes_read < 0 {
41-
return Err(std::io::Error::last_os_error());
41+
return Err(io::Error::last_os_error());
4242
}
4343
Ok(bytes_read as usize)
4444
}

libbpf-rs/src/lib.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,10 @@ pub use libbpf_sys;
9999
pub use crate::btf::Btf;
100100
pub use crate::btf::HasSize;
101101
pub use crate::btf::ReferencesType;
102-
pub use crate::error::Error;
103-
pub use crate::error::Result;
102+
pub use crate::error2::Error;
103+
pub use crate::error2::ErrorExt;
104+
pub use crate::error2::ErrorKind;
105+
pub use crate::error2::Result;
104106
pub use crate::iter::Iter;
105107
pub use crate::link::Link;
106108
pub use crate::linker::Linker;

libbpf-rs/src/linker.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use crate::util;
66
use crate::util::path_to_cstring;
77
use crate::AsRawLibbpf;
88
use crate::Error;
9+
use crate::ErrorExt as _;
910
use crate::Result;
1011

1112
/// A type used for linking multiple BPF object files into a single one.
@@ -45,7 +46,7 @@ impl Linker {
4546
let err =
4647
unsafe { libbpf_sys::bpf_linker__add_file(self.linker.as_ptr(), file.as_ptr(), opts) };
4748
if err != 0 {
48-
Err(Error::System(err))
49+
Err(Error::from_raw_os_error(err)).context("bpf_linker__add_file failed")
4950
} else {
5051
Ok(())
5152
}
@@ -57,7 +58,7 @@ impl Linker {
5758
// SAFETY: `linker` is a valid pointer.
5859
let err = unsafe { libbpf_sys::bpf_linker__finalize(self.linker.as_ptr()) };
5960
if err != 0 {
60-
return Err(Error::System(err));
61+
return Err(Error::from_raw_os_error(err)).context("bpf_linker__finalize failed");
6162
}
6263
Ok(())
6364
}

0 commit comments

Comments
 (0)