probe.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. use core::ffi::c_void;
  2. #[cfg(not(any(bpf_target_arch = "aarch64", bpf_target_arch = "riscv64")))]
  3. use crate::bindings::pt_regs;
  4. #[cfg(bpf_target_arch = "aarch64")]
  5. use crate::bindings::user_pt_regs as pt_regs;
  6. #[cfg(bpf_target_arch = "riscv64")]
  7. use crate::bindings::user_regs_struct as pt_regs;
  8. use crate::{args::FromPtRegs, BpfContext};
  9. pub struct ProbeContext {
  10. pub regs: *mut pt_regs,
  11. }
  12. impl ProbeContext {
  13. pub fn new(ctx: *mut c_void) -> ProbeContext {
  14. ProbeContext {
  15. regs: ctx as *mut pt_regs,
  16. }
  17. }
  18. /// Returns the `n`th argument to passed to the probe function, starting from 0.
  19. ///
  20. /// # Examples
  21. ///
  22. /// ```no_run
  23. /// # #![allow(non_camel_case_types)]
  24. /// # #![allow(dead_code)]
  25. /// # use aya_bpf::{programs::ProbeContext, cty::c_int, helpers::bpf_probe_read};
  26. /// # type pid_t = c_int;
  27. /// # struct task_struct {
  28. /// # pid: pid_t,
  29. /// # }
  30. /// unsafe fn try_kprobe_try_to_wake_up(ctx: ProbeContext) -> Result<u32, u32> {
  31. /// let tp: *const task_struct = ctx.arg(0).ok_or(1u32)?;
  32. /// let pid = bpf_probe_read(&(*tp).pid as *const pid_t).map_err(|_| 1u32)?;
  33. ///
  34. /// // Do something with pid or something else with tp
  35. ///
  36. /// Ok(0)
  37. /// }
  38. /// ```
  39. pub fn arg<T: FromPtRegs>(&self, n: usize) -> Option<T> {
  40. T::from_argument(unsafe { &*self.regs }, n)
  41. }
  42. /// Returns the return value of the probed function.
  43. ///
  44. /// # Examples
  45. ///
  46. /// ```no_run
  47. /// # #![allow(dead_code)]
  48. /// # use aya_bpf::{programs::ProbeContext, cty::c_int};
  49. /// unsafe fn try_kretprobe_try_to_wake_up(ctx: ProbeContext) -> Result<u32, u32> {
  50. /// let retval: c_int = ctx.ret().ok_or(1u32)?;
  51. ///
  52. /// // Do something with retval
  53. ///
  54. /// Ok(0)
  55. /// }
  56. /// ```
  57. pub fn ret<T: FromPtRegs>(&self) -> Option<T> {
  58. T::from_retval(unsafe { &*self.regs })
  59. }
  60. }
  61. impl BpfContext for ProbeContext {
  62. fn as_ptr(&self) -> *mut c_void {
  63. self.regs as *mut c_void
  64. }
  65. }