strncmp.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. use std::{
  2. cmp::Ordering,
  3. ffi::{c_char, CStr},
  4. };
  5. use aya::{
  6. maps::{Array, MapData},
  7. programs::UProbe,
  8. Ebpf,
  9. };
  10. use integration_common::strncmp::TestResult;
  11. #[test]
  12. fn bpf_strncmp() {
  13. let mut bpf = Ebpf::load(crate::STRNCMP).unwrap();
  14. {
  15. let prog: &mut UProbe = bpf
  16. .program_mut("test_bpf_strncmp")
  17. .unwrap()
  18. .try_into()
  19. .unwrap();
  20. prog.load().unwrap();
  21. prog.attach("trigger_bpf_strncmp", "/proc/self/exe", None, None)
  22. .unwrap();
  23. }
  24. let array = Array::<_, TestResult>::try_from(bpf.map("RESULT").unwrap()).unwrap();
  25. assert_eq!(do_bpf_strncmp(&array, c"ff"), Ordering::Equal);
  26. // This is truncated in BPF; the buffer size is 3 including the null terminator.
  27. assert_eq!(do_bpf_strncmp(&array, c"fff"), Ordering::Equal);
  28. assert_eq!(do_bpf_strncmp(&array, c"aa"), Ordering::Less);
  29. assert_eq!(do_bpf_strncmp(&array, c"zz"), Ordering::Greater);
  30. }
  31. fn do_bpf_strncmp(array: &Array<&MapData, TestResult>, s1: &CStr) -> Ordering {
  32. trigger_bpf_strncmp(s1.as_ptr());
  33. let TestResult(ord) = array.get(&0, 0).unwrap();
  34. ord
  35. }
  36. #[no_mangle]
  37. #[inline(never)]
  38. pub extern "C" fn trigger_bpf_strncmp(s1: *const c_char) {
  39. core::hint::black_box(s1);
  40. }