From abe91fa1900398cc2139711d66dd7a58708166fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix=20Cantournet?= Date: Fri, 5 Nov 2021 17:55:03 +0100 Subject: [PATCH] xdp: Add XdpContext method to access data as &[u8] This is a port of data_buffer and data_pointer from redbpf https://sourcegraph.com/github.com/rebpf/rebpf@50e235721228c1ece2c685f9357a954bd4a322d3/-/blob/rebpf/src/libbpf.rs?L547:12#tab=def --- bpf/aya-bpf/src/programs/xdp.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/bpf/aya-bpf/src/programs/xdp.rs b/bpf/aya-bpf/src/programs/xdp.rs index cc5157c7..14185525 100644 --- a/bpf/aya-bpf/src/programs/xdp.rs +++ b/bpf/aya-bpf/src/programs/xdp.rs @@ -7,17 +7,43 @@ pub struct XdpContext { } impl XdpContext { + + #[inline(always)] pub fn new(ctx: *mut xdp_md) -> XdpContext { XdpContext { ctx } } + #[inline(always)] pub fn data(&self) -> usize { unsafe { (*self.ctx).data as usize } } + #[inline(always)] pub fn data_end(&self) -> usize { unsafe { (*self.ctx).data_end as usize } } + + #[inline(always)] + pub fn data_buffer(&self) -> Option<&[u8]> { + unsafe { + let data_buffer: *const u8 = (*self.ctx).data as usize as *const u8; + if (*self.ctx).data_end <= (*self.ctx).data { + return None; + } + let data_buffer_size = ((*self.ctx).data_end - (*self.ctx).data) as usize; + Some(core::slice::from_raw_parts(data_buffer, data_buffer_size)) + } + } + + #[inline(always)] + pub fn data_pointer(&self) -> (*const u8, *const u8) { + unsafe { + ( + (*self.ctx).data as usize as *const u8, + (*self.ctx).data_end as usize as *const u8, + ) + } + } } impl BpfContext for XdpContext {