Skip to content

Commit

Permalink
bpf: Add bpf_strncmp helper
Browse files Browse the repository at this point in the history
The `bpf_strncmp` helper allows for better string comparison in eBPF
programs.

Added in torvalds/linux@c5fb19937455095573a19.
  • Loading branch information
vadorovsky authored and tamird committed Nov 20, 2024
1 parent a63b02c commit 0c4a0fb
Show file tree
Hide file tree
Showing 7 changed files with 145 additions and 1 deletion.
30 changes: 29 additions & 1 deletion ebpf/aya-ebpf/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@
//! helpers, but also expose bindings to the underlying helpers as a fall-back
//! in case of a missing implementation.
use core::mem::{self, MaybeUninit};
use core::{
cmp::Ordering,
ffi::CStr,
mem::{self, MaybeUninit},
};

pub use aya_ebpf_bindings::helpers as gen;
#[doc(hidden)]
Expand Down Expand Up @@ -838,3 +842,27 @@ pub unsafe fn bpf_printk_impl<const FMT_LEN: usize, const NUM_ARGS: usize>(
_ => gen::bpf_trace_vprintk(fmt_ptr, fmt_size, args.as_ptr() as _, (NUM_ARGS * 8) as _),
}
}

/// Compares the given byte `s1` with a [`&CStr`](core::ffi::CStr) `s2`.
///
/// # Examples
///
/// ```no_run
/// # use aya_ebpf::helpers::bpf_strncmp;
/// # let data = b"something";
/// assert_ne!(bpf_strncmp(data, c"foo"), core::cmp::Ordering::Equal);
/// ```
#[inline]
pub fn bpf_strncmp(s1: &[u8], s2: &CStr) -> Ordering {
// NB: s1 does not need to be null-terminated.
//
// See https://github.com/torvalds/linux/blob/adc2186/include/uapi/linux/bpf.h#L5391-L5393.
unsafe {
gen::bpf_strncmp(
s1.as_ptr() as *const _,
s1.len() as u32,
s2.as_ptr() as *const _,
)
}
.cmp(&0)
}
4 changes: 4 additions & 0 deletions test/integration-ebpf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ path = "src/ring_buf.rs"
name = "simple_prog"
path = "src/simple_prog.rs"

[[bin]]
name = "strncmp"
path = "src/strncmp.rs"

[[bin]]
name = "tcx"
path = "src/tcx.rs"
Expand Down
40 changes: 40 additions & 0 deletions test/integration-ebpf/src/strncmp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#![no_std]
#![no_main]

use core::cmp::Ordering;

use aya_ebpf::{
cty::c_long,
helpers::{bpf_probe_read_user_str_bytes, bpf_strncmp},
macros::{map, uprobe},
maps::Array,
programs::ProbeContext,
};

#[repr(C)]
struct TestResult(Ordering);

#[map]
static RESULT: Array<TestResult> = Array::with_max_entries(1, 0);

#[uprobe]
pub fn test_bpf_strncmp(ctx: ProbeContext) -> Result<(), c_long> {
let str_bytes: *const u8 = ctx.arg(0).ok_or(-1)?;
let mut buf = [0u8; 16];
let str_bytes = unsafe { bpf_probe_read_user_str_bytes(str_bytes, &mut buf)? };

let ptr = RESULT.get_ptr_mut(0).ok_or(-1)?;
let dst = unsafe { ptr.as_mut() };
let TestResult(dst_res) = dst.ok_or(-1)?;

let cmp_res = bpf_strncmp(str_bytes, c"fff");
*dst_res = cmp_res;

Ok(())
}

#[cfg(not(test))]
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
loop {}
}
1 change: 1 addition & 0 deletions test/integration-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub const REDIRECT: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/re
pub const RELOCATIONS: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/relocations"));
pub const RING_BUF: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/ring_buf"));
pub const SIMPLE_PROG: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/simple_prog"));
pub const STRNCMP: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/strncmp"));
pub const TCX: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/tcx"));
pub const TEST: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/test"));
pub const TWO_PROGS: &[u8] = include_bytes_aligned!(concat!(env!("OUT_DIR"), "/two_progs"));
Expand Down
1 change: 1 addition & 0 deletions test/integration-test/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ mod rbpf;
mod relocations;
mod ring_buf;
mod smoke;
mod strncmp;
mod tcx;
mod xdp;
69 changes: 69 additions & 0 deletions test/integration-test/src/tests/strncmp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use std::cmp::Ordering;

use aya::{maps::Array, programs::UProbe, Ebpf};

#[derive(Copy, Clone)]
#[repr(C)]
struct TestResult(Ordering);

unsafe impl aya::Pod for TestResult {}

#[test]
fn bpf_strncmp_equal() {
let bpf = load_and_attach_uprobe();
trigger_bpf_strncmp(b"fff".as_ptr());
let res = fetch_result(&bpf);
assert_eq!(res, Ordering::Equal);
}

#[test]
fn bpf_strncmp_equal_longer() {
let bpf = load_and_attach_uprobe();
trigger_bpf_strncmp(b"ffffff".as_ptr());
let res = fetch_result(&bpf);
assert_eq!(res, Ordering::Equal);
}

#[test]
fn bpf_strncmp_less() {
let bpf = load_and_attach_uprobe();
trigger_bpf_strncmp(b"aaa".as_ptr());
let res = fetch_result(&bpf);
assert_eq!(res, Ordering::Less);
}

#[test]
fn bpf_strncmp_greater() {
let bpf = load_and_attach_uprobe();
trigger_bpf_strncmp(b"zzz".as_ptr());
let res = fetch_result(&bpf);
assert_eq!(res, Ordering::Greater);
}

fn load_and_attach_uprobe() -> Ebpf {
let mut bpf = Ebpf::load(crate::STRNCMP).unwrap();

let prog: &mut UProbe = bpf
.program_mut("test_bpf_strncmp")
.unwrap()
.try_into()
.unwrap();
prog.load().unwrap();

prog.attach(Some("trigger_bpf_strncmp"), 0, "/proc/self/exe", None)
.unwrap();

bpf
}

fn fetch_result(bpf: &Ebpf) -> Ordering {
let array = Array::<_, TestResult>::try_from(bpf.map("RESULT").unwrap()).unwrap();
let TestResult(res) = array.get(&0, 0).unwrap();
res
}

#[no_mangle]
#[inline(never)]
pub extern "C" fn trigger_bpf_strncmp(string: *const u8) {
core::hint::black_box(string);
}
1 change: 1 addition & 0 deletions xtask/public-api/aya-ebpf.txt
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ pub unsafe fn aya_ebpf::helpers::bpf_probe_read_user_buf(src: *const u8, dst: &m
pub unsafe fn aya_ebpf::helpers::bpf_probe_read_user_str(src: *const u8, dest: &mut [u8]) -> core::result::Result<usize, aya_ebpf_cty::od::c_long>
pub unsafe fn aya_ebpf::helpers::bpf_probe_read_user_str_bytes(src: *const u8, dest: &mut [u8]) -> core::result::Result<&[u8], aya_ebpf_cty::od::c_long>
pub unsafe fn aya_ebpf::helpers::bpf_probe_write_user<T>(dst: *mut T, src: *const T) -> core::result::Result<(), aya_ebpf_cty::od::c_long>
pub fn aya_ebpf::helpers::bpf_strncmp(s1: &[u8], s2: &core::ffi::c_str::CStr) -> core::cmp::Ordering
pub mod aya_ebpf::maps
pub mod aya_ebpf::maps::array
#[repr(transparent)] pub struct aya_ebpf::maps::array::Array<T>
Expand Down

0 comments on commit 0c4a0fb

Please sign in to comment.