tp_btf.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. use core::ffi::c_void;
  2. use crate::{args::FromBtfArgument, BpfContext};
  3. pub struct BtfTracePointContext {
  4. ctx: *mut c_void,
  5. }
  6. impl BtfTracePointContext {
  7. pub fn new(ctx: *mut c_void) -> BtfTracePointContext {
  8. BtfTracePointContext { ctx }
  9. }
  10. /// Returns the `n`th argument of the BTF tracepoint, starting from 0.
  11. ///
  12. /// You can use the tplist tool provided by bcc to get a list of tracepoints and their
  13. /// arguments. TODO: document this better, possibly add a tplist alternative to aya.
  14. ///
  15. /// SAFETY: This function is deeply unsafe, as we are reading raw pointers into kernel memory.
  16. /// In particular, the value of `n` must not exceed the number of function arguments.
  17. /// Luckily, the BPF verifier will catch this for us.
  18. ///
  19. /// # Examples
  20. ///
  21. /// ```no_run
  22. /// # #![allow(dead_code)]
  23. /// # use aya_ebpf::{programs::BtfTracePointContext, cty::{c_int, c_ulong, c_char}};
  24. /// unsafe fn try_tp_btf_sched_process_fork(ctx: BtfTracePointContext) -> Result<u32, u32> {
  25. /// // Grab arguments
  26. /// let parent_comm: *const c_char = ctx.arg(0);
  27. /// let parent_pid: c_int = ctx.arg(1);
  28. /// let child_comm: *const c_char = ctx.arg(2);
  29. /// let child_pid: c_int = ctx.arg(3);
  30. ///
  31. /// // You can then do stuff with parent_pidm parent_comm, child_pid, and
  32. /// // child_comm down here.
  33. ///
  34. /// Ok(0)
  35. /// }
  36. /// ```
  37. ///
  38. /// [1]: https://elixir.bootlin.com/linux/latest/source/include/linux/lsm_hook_defs.h
  39. pub unsafe fn arg<T: FromBtfArgument>(&self, n: usize) -> T {
  40. T::from_argument(self.ctx as *const _, n)
  41. }
  42. }
  43. impl BpfContext for BtfTracePointContext {
  44. fn as_ptr(&self) -> *mut c_void {
  45. self.ctx
  46. }
  47. }