4
0

helpers.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. //! This module contains kernel helper functions that may be exposed to specific BPF
  2. //! program types. These helpers can be used to perform common tasks, query and operate on
  3. //! data exposed by the kernel, and perform some operations that would normally be denied
  4. //! by the BPF verifier.
  5. //!
  6. //! Here, we provide some higher-level wrappers around the underlying kernel helpers, but
  7. //! also expose bindings to the underlying helpers as a fall-back in case of a missing
  8. //! implementation.
  9. use core::mem::{self, MaybeUninit};
  10. pub use aya_bpf_bindings::helpers as gen;
  11. pub use gen::*;
  12. use crate::cty::{c_char, c_long, c_void};
  13. /// Read bytes stored at `src` and store them as a `T`.
  14. ///
  15. /// Generally speaking, the more specific [`bpf_probe_read_user`] and
  16. /// [`bpf_probe_read_kernel`] should be preferred over this function.
  17. ///
  18. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the user space address
  19. /// `src`. See `bpf_probe_read_kernel` for reading kernel space memory.
  20. ///
  21. /// # Examples
  22. ///
  23. /// ```no_run
  24. /// # #![allow(dead_code)]
  25. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read};
  26. /// # fn try_test() -> Result<(), c_long> {
  27. /// # let kernel_ptr: *const c_int = 0 as _;
  28. /// let my_int: c_int = unsafe { bpf_probe_read(kernel_ptr)? };
  29. ///
  30. /// // Do something with my_int
  31. /// # Ok::<(), c_long>(())
  32. /// # }
  33. /// ```
  34. ///
  35. /// # Errors
  36. ///
  37. /// On failure, this function returns a negative value wrapped in an `Err`.
  38. #[inline]
  39. pub unsafe fn bpf_probe_read<T>(src: *const T) -> Result<T, c_long> {
  40. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  41. let ret = gen::bpf_probe_read(
  42. v.as_mut_ptr() as *mut c_void,
  43. mem::size_of::<T>() as u32,
  44. src as *const c_void,
  45. );
  46. if ret < 0 {
  47. return Err(ret);
  48. }
  49. Ok(v.assume_init())
  50. }
  51. /// Read bytes stored at the _user space_ pointer `src` and store them as a `T`.
  52. ///
  53. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the user space address
  54. /// `src`. See `bpf_probe_read_kernel` for reading kernel space memory.
  55. ///
  56. /// # Examples
  57. ///
  58. /// ```no_run
  59. /// # #![allow(dead_code)]
  60. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_user};
  61. /// # fn try_test() -> Result<(), c_long> {
  62. /// # let user_ptr: *const c_int = 0 as _;
  63. /// let my_int: c_int = unsafe { bpf_probe_read_user(user_ptr)? };
  64. ///
  65. /// // Do something with my_int
  66. /// # Ok::<(), c_long>(())
  67. /// # }
  68. /// ```
  69. ///
  70. /// # Errors
  71. ///
  72. /// On failure, this function returns a negative value wrapped in an `Err`.
  73. #[inline]
  74. pub unsafe fn bpf_probe_read_user<T>(src: *const T) -> Result<T, c_long> {
  75. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  76. let ret = gen::bpf_probe_read_user(
  77. v.as_mut_ptr() as *mut c_void,
  78. mem::size_of::<T>() as u32,
  79. src as *const c_void,
  80. );
  81. if ret < 0 {
  82. return Err(ret);
  83. }
  84. Ok(v.assume_init())
  85. }
  86. /// Read bytes stored at the _kernel space_ pointer `src` and store them as a `T`.
  87. ///
  88. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the kernel space address
  89. /// `src`. See `bpf_probe_read_user` for reading user space memory.
  90. ///
  91. /// # Examples
  92. ///
  93. /// ```no_run
  94. /// # #![allow(dead_code)]
  95. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_kernel};
  96. /// # fn try_test() -> Result<(), c_long> {
  97. /// # let kernel_ptr: *const c_int = 0 as _;
  98. /// let my_int: c_int = unsafe { bpf_probe_read_kernel(kernel_ptr)? };
  99. ///
  100. /// // Do something with my_int
  101. /// # Ok::<(), c_long>(())
  102. /// # }
  103. /// ```
  104. ///
  105. /// # Errors
  106. ///
  107. /// On failure, this function returns a negative value wrapped in an `Err`.
  108. #[inline]
  109. pub unsafe fn bpf_probe_read_kernel<T>(src: *const T) -> Result<T, c_long> {
  110. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  111. let ret = gen::bpf_probe_read_kernel(
  112. v.as_mut_ptr() as *mut c_void,
  113. mem::size_of::<T>() as u32,
  114. src as *const c_void,
  115. );
  116. if ret < 0 {
  117. return Err(ret);
  118. }
  119. Ok(v.assume_init())
  120. }
  121. /// Read a null-terminated string stored at `src` into `dest`.
  122. ///
  123. /// Generally speaking, the more specific [`bpf_probe_read_user_str`] and
  124. /// [`bpf_probe_read_kernel_str`] should be preferred over this function.
  125. ///
  126. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  127. /// be truncated to the size of `dest`.
  128. ///
  129. /// # Examples
  130. ///
  131. /// ```no_run
  132. /// # #![allow(dead_code)]
  133. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_str};
  134. /// # fn try_test() -> Result<(), c_long> {
  135. /// # let kernel_ptr: *const u8 = 0 as _;
  136. /// let mut my_str = [0u8; 16];
  137. /// let num_read = unsafe { bpf_probe_read_str(kernel_ptr, &mut my_str)? };
  138. ///
  139. /// // Do something with num_read and my_str
  140. /// # Ok::<(), c_long>(())
  141. /// # }
  142. /// ```
  143. ///
  144. /// # Errors
  145. ///
  146. /// On failure, this function returns Err(-1).
  147. #[inline]
  148. pub unsafe fn bpf_probe_read_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  149. let len = gen::bpf_probe_read_str(
  150. dest.as_mut_ptr() as *mut c_void,
  151. dest.len() as u32,
  152. src as *const c_void,
  153. );
  154. if len < 0 {
  155. return Err(-1);
  156. }
  157. let mut len = len as usize;
  158. if len > dest.len() {
  159. // this can never happen, it's needed to tell the verifier that len is
  160. // bounded
  161. len = dest.len();
  162. }
  163. Ok(len as usize)
  164. }
  165. /// Read a null-terminated string from _user space_ stored at `src` into `dest`.
  166. ///
  167. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  168. /// be truncated to the size of `dest`.
  169. ///
  170. /// # Examples
  171. ///
  172. /// ```no_run
  173. /// # #![allow(dead_code)]
  174. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str};
  175. /// # fn try_test() -> Result<(), c_long> {
  176. /// # let user_ptr: *const u8 = 0 as _;
  177. /// let mut my_str = [0u8; 16];
  178. /// let num_read = unsafe { bpf_probe_read_user_str(user_ptr, &mut my_str)? };
  179. ///
  180. /// // Do something with num_read and my_str
  181. /// # Ok::<(), c_long>(())
  182. /// # }
  183. /// ```
  184. ///
  185. /// # Errors
  186. ///
  187. /// On failure, this function returns Err(-1).
  188. #[inline]
  189. pub unsafe fn bpf_probe_read_user_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  190. let len = gen::bpf_probe_read_user_str(
  191. dest.as_mut_ptr() as *mut c_void,
  192. dest.len() as u32,
  193. src as *const c_void,
  194. );
  195. if len < 0 {
  196. return Err(-1);
  197. }
  198. let mut len = len as usize;
  199. if len > dest.len() {
  200. // this can never happen, it's needed to tell the verifier that len is
  201. // bounded
  202. len = dest.len();
  203. }
  204. Ok(len as usize)
  205. }
  206. /// Read a null-terminated string from _kernel space_ stored at `src` into `dest`.
  207. ///
  208. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  209. /// be truncated to the size of `dest`.
  210. ///
  211. /// # Examples
  212. ///
  213. /// ```no_run
  214. /// # #![allow(dead_code)]
  215. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str};
  216. /// # fn try_test() -> Result<(), c_long> {
  217. /// # let kernel_ptr: *const u8 = 0 as _;
  218. /// let mut my_str = [0u8; 16];
  219. /// let num_read = unsafe { bpf_probe_read_kernel_str(kernel_ptr, &mut my_str)? };
  220. ///
  221. /// // Do something with num_read and my_str
  222. /// # Ok::<(), c_long>(())
  223. /// # }
  224. /// ```
  225. ///
  226. /// # Errors
  227. ///
  228. /// On failure, this function returns Err(-1).
  229. #[inline]
  230. pub unsafe fn bpf_probe_read_kernel_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  231. let len = gen::bpf_probe_read_kernel_str(
  232. dest.as_mut_ptr() as *mut c_void,
  233. dest.len() as u32,
  234. src as *const c_void,
  235. );
  236. if len < 0 {
  237. return Err(-1);
  238. }
  239. let mut len = len as usize;
  240. if len > dest.len() {
  241. // this can never happen, it's needed to tell the verifier that len is
  242. // bounded
  243. len = dest.len();
  244. }
  245. Ok(len as usize)
  246. }
  247. /// Read the `comm` field associated with the current task struct
  248. /// as a `[c_char; 16]`.
  249. ///
  250. /// # Examples
  251. ///
  252. /// ```no_run
  253. /// # #![allow(dead_code)]
  254. /// # use aya_bpf:: helpers::bpf_get_current_comm;
  255. /// let comm = bpf_get_current_comm();
  256. ///
  257. /// // Do something with comm
  258. /// ```
  259. ///
  260. /// # Errors
  261. ///
  262. /// On failure, this function returns a negative value wrapped in an `Err`.
  263. #[inline]
  264. pub fn bpf_get_current_comm() -> Result<[c_char; 16], c_long> {
  265. let mut comm: [c_char; 16usize] = [0; 16];
  266. let ret = unsafe { gen::bpf_get_current_comm(&mut comm as *mut _ as *mut c_void, 16u32) };
  267. if ret == 0 {
  268. Ok(comm)
  269. } else {
  270. Err(ret)
  271. }
  272. }
  273. /// Read the process id and thread group id associated with the current task struct as
  274. /// a `u64`.
  275. ///
  276. /// In the return value, the upper 32 bits are the `tgid`, and the lower 32 bits are the
  277. /// `pid`. That is, the returned value is equal to: `(tgid << 32) | pid`. A caller may
  278. /// access the individual fields by either casting to a `u32` or performing a `>> 32` bit
  279. /// shift and casting to a `u32`.
  280. ///
  281. /// Note that the naming conventions used in the kernel differ from user space. From the
  282. /// perspective of user space, `pid` may be thought of as the thread id, and `tgid` may be
  283. /// thought of as the process id. For single-threaded processes, these values are
  284. /// typically the same.
  285. ///
  286. /// # Examples
  287. ///
  288. /// ```no_run
  289. /// # #![allow(dead_code)]
  290. /// # use aya_bpf:: helpers::bpf_get_current_pid_tgid;
  291. /// let tgid = (bpf_get_current_pid_tgid() >> 32) as u32;
  292. /// let pid = bpf_get_current_pid_tgid() as u32;
  293. ///
  294. /// // Do something with pid and tgid
  295. /// ```
  296. #[inline]
  297. pub fn bpf_get_current_pid_tgid() -> u64 {
  298. unsafe { gen::bpf_get_current_pid_tgid() }
  299. }