Skip to content

Commit 3dec5cd

Browse files
mendessdanielocfb
authored andcommitted
check for nullability of the object_ptr to fail fast before causing UB
1 parent 989e55b commit 3dec5cd

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

libbpf-rs/src/object.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -187,8 +187,8 @@ impl OpenObject {
187187
/// - points to a loaded `bpf_object`
188188
///
189189
/// It is not safe to manipulate `ptr` after this operation.
190-
pub unsafe fn from_ptr(ptr: *mut libbpf_sys::bpf_object) -> Result<Self> {
191-
unsafe { Self::new(NonNull::new_unchecked(ptr)) }
190+
pub unsafe fn from_ptr(ptr: NonNull<libbpf_sys::bpf_object>) -> Result<Self> {
191+
unsafe { Self::new(ptr) }
192192
}
193193

194194
/// Takes underlying `libbpf_sys::bpf_object` pointer.

libbpf-rs/src/skeleton.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::boxed::Box;
44
use std::ffi::CString;
55
use std::mem::size_of;
66
use std::os::raw::{c_char, c_ulong};
7-
use std::ptr;
7+
use std::ptr::{self, NonNull};
88

99
use libbpf_sys::{
1010
bpf_link, bpf_map, bpf_map_skeleton, bpf_object, bpf_object_skeleton, bpf_prog_skeleton,
@@ -227,8 +227,18 @@ impl<'a> ObjectSkeletonConfig<'a> {
227227
}
228228

229229
/// Warning: the returned pointer is only valid while the `ObjectSkeletonConfig` is alive.
230-
pub fn object_ptr(&mut self) -> *mut bpf_object {
231-
unsafe { *self.inner.obj }
230+
///
231+
/// # Panic
232+
/// This method panics if the inner [`bpf_object_skeleton`] has not be initialized.
233+
///
234+
/// To initialize it, first call [`Self::get`] and initialize the skeleton.
235+
pub fn object_ptr(&mut self) -> NonNull<bpf_object> {
236+
NonNull::new(unsafe { *self.inner.obj }).expect(
237+
r#"
238+
The generated code failed to initialize bpf_object_skeleton.obj pointer through the use
239+
of `bpf_object__open_skeleton(skel_config.get(), &open_opts)`
240+
"#,
241+
)
232242
}
233243

234244
/// Returns the `mmaped` pointer for a map at the specified `index`.

0 commit comments

Comments
 (0)