uprobe_cookie.rs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. use aya::{maps::ring_buf::RingBuf, programs::UProbe, EbpfLoader};
  2. use test_log::test;
  3. #[test]
  4. fn test_uprobe_cookie() {
  5. const RING_BUF_BYTE_SIZE: u32 = 512; // arbitrary, but big enough
  6. let mut bpf = EbpfLoader::new()
  7. .set_max_entries("RING_BUF", RING_BUF_BYTE_SIZE)
  8. .load(crate::UPROBE_COOKIE)
  9. .unwrap();
  10. let ring_buf = bpf.take_map("RING_BUF").unwrap();
  11. let mut ring_buf = RingBuf::try_from(ring_buf).unwrap();
  12. let prog: &mut UProbe = bpf
  13. .program_mut("uprobe_cookie")
  14. .unwrap()
  15. .try_into()
  16. .unwrap();
  17. prog.load().unwrap();
  18. const PROG_A: &str = "uprobe_cookie_trigger_ebpf_program_a";
  19. const PROG_B: &str = "uprobe_cookie_trigger_ebpf_program_b";
  20. let attach = |prog: &mut UProbe, fn_name, cookie| {
  21. prog.attach(fn_name, "/proc/self/exe", None, Some(cookie))
  22. .unwrap()
  23. };
  24. // Note that the arguments we pass to the functions are meaningless, but we
  25. // pass the value we expect to see in the ring buffer from the cookie for
  26. // readability.
  27. let a = attach(prog, PROG_A, 1);
  28. let _b = attach(prog, PROG_B, 2);
  29. uprobe_cookie_trigger_ebpf_program_a(1);
  30. uprobe_cookie_trigger_ebpf_program_b(2);
  31. uprobe_cookie_trigger_ebpf_program_a(1);
  32. prog.detach(a).unwrap();
  33. let _a = attach(prog, PROG_A, 3);
  34. uprobe_cookie_trigger_ebpf_program_a(3);
  35. const EXP: &[u64] = &[1, 2, 1, 3];
  36. let mut seen = Vec::new();
  37. while let Some(read) = ring_buf.next() {
  38. let read = read.as_ref();
  39. match read.try_into() {
  40. Ok(read) => seen.push(u64::from_le_bytes(read)),
  41. Err(std::array::TryFromSliceError { .. }) => {
  42. panic!("invalid ring buffer data: {read:x?}")
  43. }
  44. }
  45. }
  46. assert_eq!(seen, EXP);
  47. }
  48. #[no_mangle]
  49. #[inline(never)]
  50. pub extern "C" fn uprobe_cookie_trigger_ebpf_program_a(arg: u64) {
  51. std::hint::black_box(arg);
  52. }
  53. #[no_mangle]
  54. #[inline(never)]
  55. pub extern "C" fn uprobe_cookie_trigger_ebpf_program_b(arg: u32) {
  56. std::hint::black_box(arg);
  57. }