helpers.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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. #[doc(hidden)]
  12. pub use gen::*;
  13. use crate::{
  14. check_bounds_signed,
  15. cty::{c_char, c_long, c_void},
  16. };
  17. /// Read bytes stored at `src` and store them as a `T`.
  18. ///
  19. /// Generally speaking, the more specific [`bpf_probe_read_user`] and
  20. /// [`bpf_probe_read_kernel`] should be preferred over this function.
  21. ///
  22. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the user space address
  23. /// `src`. See `bpf_probe_read_kernel` for reading kernel space memory.
  24. ///
  25. /// # Examples
  26. ///
  27. /// ```no_run
  28. /// # #![allow(dead_code)]
  29. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read};
  30. /// # fn try_test() -> Result<(), c_long> {
  31. /// # let kernel_ptr: *const c_int = 0 as _;
  32. /// let my_int: c_int = unsafe { bpf_probe_read(kernel_ptr)? };
  33. ///
  34. /// // Do something with my_int
  35. /// # Ok::<(), c_long>(())
  36. /// # }
  37. /// ```
  38. ///
  39. /// # Errors
  40. ///
  41. /// On failure, this function returns a negative value wrapped in an `Err`.
  42. #[inline]
  43. pub unsafe fn bpf_probe_read<T>(src: *const T) -> Result<T, c_long> {
  44. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  45. let ret = gen::bpf_probe_read(
  46. v.as_mut_ptr() as *mut c_void,
  47. mem::size_of::<T>() as u32,
  48. src as *const c_void,
  49. );
  50. if ret == 0 {
  51. Ok(v.assume_init())
  52. } else {
  53. Err(ret)
  54. }
  55. }
  56. /// Read bytes from the pointer `src` into the provided destination buffer.
  57. ///
  58. /// Generally speaking, the more specific [`bpf_probe_read_user_buf`] and
  59. /// [`bpf_probe_read_kernel_buf`] should be preferred over this function.
  60. ///
  61. /// # Examples
  62. ///
  63. /// ```no_run
  64. /// # #![allow(dead_code)]
  65. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_buf};
  66. /// # fn try_test() -> Result<(), c_long> {
  67. /// # let ptr: *const u8 = 0 as _;
  68. /// let mut buf = [0u8; 16];
  69. /// unsafe { bpf_probe_read_buf(ptr, &mut buf)? };
  70. ///
  71. /// # Ok::<(), c_long>(())
  72. /// # }
  73. /// ```
  74. ///
  75. /// # Errors
  76. ///
  77. /// On failure, this function returns a negative value wrapped in an `Err`.
  78. #[inline]
  79. pub unsafe fn bpf_probe_read_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> {
  80. let ret = gen::bpf_probe_read(
  81. dst.as_mut_ptr() as *mut c_void,
  82. dst.len() as u32,
  83. src as *const c_void,
  84. );
  85. if ret == 0 {
  86. Ok(())
  87. } else {
  88. Err(ret)
  89. }
  90. }
  91. /// Read bytes stored at the _user space_ pointer `src` and store them as a `T`.
  92. ///
  93. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the user space address
  94. /// `src`. See `bpf_probe_read_kernel` for reading kernel space memory.
  95. ///
  96. /// # Examples
  97. ///
  98. /// ```no_run
  99. /// # #![allow(dead_code)]
  100. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_user};
  101. /// # fn try_test() -> Result<(), c_long> {
  102. /// # let user_ptr: *const c_int = 0 as _;
  103. /// let my_int: c_int = unsafe { bpf_probe_read_user(user_ptr)? };
  104. ///
  105. /// // Do something with my_int
  106. /// # Ok::<(), c_long>(())
  107. /// # }
  108. /// ```
  109. ///
  110. /// # Errors
  111. ///
  112. /// On failure, this function returns a negative value wrapped in an `Err`.
  113. #[inline]
  114. pub unsafe fn bpf_probe_read_user<T>(src: *const T) -> Result<T, c_long> {
  115. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  116. let ret = gen::bpf_probe_read_user(
  117. v.as_mut_ptr() as *mut c_void,
  118. mem::size_of::<T>() as u32,
  119. src as *const c_void,
  120. );
  121. if ret == 0 {
  122. Ok(v.assume_init())
  123. } else {
  124. Err(ret)
  125. }
  126. }
  127. /// Read bytes from the _user space_ pointer `src` into the provided destination
  128. /// buffer.
  129. ///
  130. /// # Examples
  131. ///
  132. /// ```no_run
  133. /// # #![allow(dead_code)]
  134. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_user_buf};
  135. /// # fn try_test() -> Result<(), c_long> {
  136. /// # let user_ptr: *const u8 = 0 as _;
  137. /// let mut buf = [0u8; 16];
  138. /// unsafe { bpf_probe_read_user_buf(user_ptr, &mut buf)? };
  139. ///
  140. /// # Ok::<(), c_long>(())
  141. /// # }
  142. /// ```
  143. ///
  144. /// # Errors
  145. ///
  146. /// On failure, this function returns a negative value wrapped in an `Err`.
  147. #[inline]
  148. pub unsafe fn bpf_probe_read_user_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> {
  149. let ret = gen::bpf_probe_read_user(
  150. dst.as_mut_ptr() as *mut c_void,
  151. dst.len() as u32,
  152. src as *const c_void,
  153. );
  154. if ret == 0 {
  155. Ok(())
  156. } else {
  157. Err(ret)
  158. }
  159. }
  160. /// Read bytes stored at the _kernel space_ pointer `src` and store them as a `T`.
  161. ///
  162. /// Returns a bitwise copy of `mem::size_of::<T>()` bytes stored at the kernel space address
  163. /// `src`. See `bpf_probe_read_user` for reading user space memory.
  164. ///
  165. /// # Examples
  166. ///
  167. /// ```no_run
  168. /// # #![allow(dead_code)]
  169. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_kernel};
  170. /// # fn try_test() -> Result<(), c_long> {
  171. /// # let kernel_ptr: *const c_int = 0 as _;
  172. /// let my_int: c_int = unsafe { bpf_probe_read_kernel(kernel_ptr)? };
  173. ///
  174. /// // Do something with my_int
  175. /// # Ok::<(), c_long>(())
  176. /// # }
  177. /// ```
  178. ///
  179. /// # Errors
  180. ///
  181. /// On failure, this function returns a negative value wrapped in an `Err`.
  182. #[inline]
  183. pub unsafe fn bpf_probe_read_kernel<T>(src: *const T) -> Result<T, c_long> {
  184. let mut v: MaybeUninit<T> = MaybeUninit::uninit();
  185. let ret = gen::bpf_probe_read_kernel(
  186. v.as_mut_ptr() as *mut c_void,
  187. mem::size_of::<T>() as u32,
  188. src as *const c_void,
  189. );
  190. if ret == 0 {
  191. Ok(v.assume_init())
  192. } else {
  193. Err(ret)
  194. }
  195. }
  196. /// Read bytes from the _kernel space_ pointer `src` into the provided destination
  197. /// buffer.
  198. ///
  199. /// # Examples
  200. ///
  201. /// ```no_run
  202. /// # #![allow(dead_code)]
  203. /// # use aya_bpf::{cty::{c_int, c_long}, helpers::bpf_probe_read_kernel_buf};
  204. /// # fn try_test() -> Result<(), c_long> {
  205. /// # let kernel_ptr: *const u8 = 0 as _;
  206. /// let mut buf = [0u8; 16];
  207. /// unsafe { bpf_probe_read_kernel_buf(kernel_ptr, &mut buf)? };
  208. ///
  209. /// # Ok::<(), c_long>(())
  210. /// # }
  211. /// ```
  212. ///
  213. /// # Errors
  214. ///
  215. /// On failure, this function returns a negative value wrapped in an `Err`.
  216. #[inline]
  217. pub unsafe fn bpf_probe_read_kernel_buf(src: *const u8, dst: &mut [u8]) -> Result<(), c_long> {
  218. let ret = gen::bpf_probe_read_kernel(
  219. dst.as_mut_ptr() as *mut c_void,
  220. dst.len() as u32,
  221. src as *const c_void,
  222. );
  223. if ret == 0 {
  224. Ok(())
  225. } else {
  226. Err(ret)
  227. }
  228. }
  229. /// Read a null-terminated string stored at `src` into `dest`.
  230. ///
  231. /// Generally speaking, the more specific [`bpf_probe_read_user_str`] and
  232. /// [`bpf_probe_read_kernel_str`] should be preferred over this function.
  233. ///
  234. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  235. /// be truncated to the size of `dest`.
  236. ///
  237. /// # Examples
  238. ///
  239. /// ```no_run
  240. /// # #![allow(dead_code)]
  241. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_str};
  242. /// # fn try_test() -> Result<(), c_long> {
  243. /// # let kernel_ptr: *const u8 = 0 as _;
  244. /// let mut my_str = [0u8; 16];
  245. /// let num_read = unsafe { bpf_probe_read_str(kernel_ptr, &mut my_str)? };
  246. ///
  247. /// // Do something with num_read and my_str
  248. /// # Ok::<(), c_long>(())
  249. /// # }
  250. /// ```
  251. ///
  252. /// # Errors
  253. ///
  254. /// On failure, this function returns Err(-1).
  255. #[deprecated(
  256. note = "Use `bpf_probe_read_user_str_bytes` or `bpf_probe_read_kernel_str_bytes` instead"
  257. )]
  258. #[inline]
  259. pub unsafe fn bpf_probe_read_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  260. let len = gen::bpf_probe_read_str(
  261. dest.as_mut_ptr() as *mut c_void,
  262. dest.len() as u32,
  263. src as *const c_void,
  264. );
  265. let len = usize::try_from(len).map_err(|core::num::TryFromIntError { .. }| -1)?;
  266. // this can never happen, it's needed to tell the verifier that len is bounded.
  267. Ok(len.min(dest.len()))
  268. }
  269. /// Read a null-terminated string from _user space_ stored at `src` into `dest`.
  270. ///
  271. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  272. /// be truncated to the size of `dest`.
  273. ///
  274. /// # Examples
  275. ///
  276. /// ```no_run
  277. /// # #![allow(dead_code)]
  278. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str};
  279. /// # fn try_test() -> Result<(), c_long> {
  280. /// # let user_ptr: *const u8 = 0 as _;
  281. /// let mut my_str = [0u8; 16];
  282. /// let num_read = unsafe { bpf_probe_read_user_str(user_ptr, &mut my_str)? };
  283. ///
  284. /// // Do something with num_read and my_str
  285. /// # Ok::<(), c_long>(())
  286. /// # }
  287. /// ```
  288. ///
  289. /// # Errors
  290. ///
  291. /// On failure, this function returns Err(-1).
  292. #[deprecated(note = "Use `bpf_probe_read_user_str_bytes` instead")]
  293. #[inline]
  294. pub unsafe fn bpf_probe_read_user_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  295. let len = gen::bpf_probe_read_user_str(
  296. dest.as_mut_ptr() as *mut c_void,
  297. dest.len() as u32,
  298. src as *const c_void,
  299. );
  300. let len = usize::try_from(len).map_err(|core::num::TryFromIntError { .. }| -1)?;
  301. // this can never happen, it's needed to tell the verifier that len is bounded.
  302. Ok(len.min(dest.len()))
  303. }
  304. /// Returns a byte slice read from _user space_ address `src`.
  305. ///
  306. /// Reads at most `dest.len()` bytes from the `src` address, truncating if the
  307. /// length of the source string is larger than `dest`. On success, the
  308. /// destination buffer is always null terminated, and the returned slice
  309. /// includes the bytes up to and not including NULL.
  310. ///
  311. /// # Examples
  312. ///
  313. /// With an array allocated on the stack (not recommended for bigger strings,
  314. /// eBPF stack limit is 512 bytes):
  315. ///
  316. /// ```no_run
  317. /// # #![allow(dead_code)]
  318. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str_bytes};
  319. /// # fn try_test() -> Result<(), c_long> {
  320. /// # let user_ptr: *const u8 = 0 as _;
  321. /// let mut buf = [0u8; 16];
  322. /// let my_str_bytes = unsafe { bpf_probe_read_user_str_bytes(user_ptr, &mut buf)? };
  323. ///
  324. /// // Do something with my_str_bytes
  325. /// # Ok::<(), c_long>(())
  326. /// # }
  327. /// ```
  328. ///
  329. /// With a `PerCpuArray` (with size defined by us):
  330. ///
  331. /// ```no_run
  332. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str_bytes};
  333. /// use aya_bpf::{macros::map, maps::PerCpuArray};
  334. ///
  335. /// #[repr(C)]
  336. /// pub struct Buf {
  337. /// pub buf: [u8; 4096],
  338. /// }
  339. ///
  340. /// #[map]
  341. /// pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0);
  342. ///
  343. /// # fn try_test() -> Result<(), c_long> {
  344. /// # let user_ptr: *const u8 = 0 as _;
  345. /// let buf = unsafe {
  346. /// let ptr = BUF.get_ptr_mut(0).ok_or(0)?;
  347. /// &mut *ptr
  348. /// };
  349. /// let my_str_bytes = unsafe { bpf_probe_read_user_str_bytes(user_ptr, &mut buf.buf)? };
  350. ///
  351. /// // Do something with my_str_bytes
  352. /// # Ok::<(), c_long>(())
  353. /// # }
  354. /// ```
  355. ///
  356. /// You can also convert the resulted bytes slice into `&str` using
  357. /// [core::str::from_utf8_unchecked]:
  358. ///
  359. /// ```no_run
  360. /// # #![allow(dead_code)]
  361. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_user_str_bytes};
  362. /// # use aya_bpf::{macros::map, maps::PerCpuArray};
  363. /// # #[repr(C)]
  364. /// # pub struct Buf {
  365. /// # pub buf: [u8; 4096],
  366. /// # }
  367. /// # #[map]
  368. /// # pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0);
  369. /// # fn try_test() -> Result<(), c_long> {
  370. /// # let user_ptr: *const u8 = 0 as _;
  371. /// # let buf = unsafe {
  372. /// # let ptr = BUF.get_ptr_mut(0).ok_or(0)?;
  373. /// # &mut *ptr
  374. /// # };
  375. /// let my_str = unsafe {
  376. /// core::str::from_utf8_unchecked(bpf_probe_read_user_str_bytes(user_ptr, &mut buf.buf)?)
  377. /// };
  378. ///
  379. /// // Do something with my_str
  380. /// # Ok::<(), c_long>(())
  381. /// # }
  382. /// ```
  383. ///
  384. /// # Errors
  385. ///
  386. /// On failure, this function returns Err(-1).
  387. #[inline]
  388. pub unsafe fn bpf_probe_read_user_str_bytes(
  389. src: *const u8,
  390. dest: &mut [u8],
  391. ) -> Result<&[u8], c_long> {
  392. let len = gen::bpf_probe_read_user_str(
  393. dest.as_mut_ptr() as *mut c_void,
  394. dest.len() as u32,
  395. src as *const c_void,
  396. );
  397. read_str_bytes(len, dest)
  398. }
  399. fn read_str_bytes(len: i64, dest: &[u8]) -> Result<&[u8], c_long> {
  400. // The lower bound is 0, since it's what is returned for b"\0". See the
  401. // bpf_probe_read_user_[user|kernel]_bytes_empty integration tests. The upper bound
  402. // check is not needed since the helper truncates, but the verifier doesn't
  403. // know that so we show it the upper bound.
  404. if !check_bounds_signed(len, 0, dest.len() as i64) {
  405. return Err(-1);
  406. }
  407. // len includes the NULL terminator but not for b"\0" for which the kernel
  408. // returns len=0. So we do a saturating sub and for b"\0" we return the
  409. // empty slice, for all other cases we omit the terminator.
  410. let len = usize::try_from(len).map_err(|core::num::TryFromIntError { .. }| -1)?;
  411. let len = len.saturating_sub(1);
  412. dest.get(..len).ok_or(-1)
  413. }
  414. /// Read a null-terminated string from _kernel space_ stored at `src` into `dest`.
  415. ///
  416. /// In case the length of `dest` is smaller then the length of `src`, the read bytes will
  417. /// be truncated to the size of `dest`.
  418. ///
  419. /// # Examples
  420. ///
  421. /// ```no_run
  422. /// # #![allow(dead_code)]
  423. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str};
  424. /// # fn try_test() -> Result<(), c_long> {
  425. /// # let kernel_ptr: *const u8 = 0 as _;
  426. /// let mut my_str = [0u8; 16];
  427. /// let num_read = unsafe { bpf_probe_read_kernel_str(kernel_ptr, &mut my_str)? };
  428. ///
  429. /// // Do something with num_read and my_str
  430. /// # Ok::<(), c_long>(())
  431. /// # }
  432. /// ```
  433. ///
  434. /// # Errors
  435. ///
  436. /// On failure, this function returns Err(-1).
  437. #[deprecated(note = "Use bpf_probe_read_kernel_str_bytes instead")]
  438. #[inline]
  439. pub unsafe fn bpf_probe_read_kernel_str(src: *const u8, dest: &mut [u8]) -> Result<usize, c_long> {
  440. let len = gen::bpf_probe_read_kernel_str(
  441. dest.as_mut_ptr() as *mut c_void,
  442. dest.len() as u32,
  443. src as *const c_void,
  444. );
  445. let len = usize::try_from(len).map_err(|core::num::TryFromIntError { .. }| -1)?;
  446. // this can never happen, it's needed to tell the verifier that len is bounded.
  447. Ok(len.min(dest.len()))
  448. }
  449. /// Returns a byte slice read from _kernel space_ address `src`.
  450. ///
  451. /// Reads at most `dest.len()` bytes from the `src` address, truncating if the
  452. /// length of the source string is larger than `dest`. On success, the
  453. /// destination buffer is always null terminated, and the returned slice
  454. /// includes the bytes up to and not including NULL.
  455. ///
  456. /// # Examples
  457. ///
  458. /// With an array allocated on the stack (not recommended for bigger strings,
  459. /// eBPF stack limit is 512 bytes):
  460. ///
  461. /// ```no_run
  462. /// # #![allow(dead_code)]
  463. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str_bytes};
  464. /// # fn try_test() -> Result<(), c_long> {
  465. /// # let kernel_ptr: *const u8 = 0 as _;
  466. /// let mut buf = [0u8; 16];
  467. /// let my_str_bytes = unsafe { bpf_probe_read_kernel_str_bytes(kernel_ptr, &mut buf)? };
  468. ///
  469. /// // Do something with my_str_bytes
  470. /// # Ok::<(), c_long>(())
  471. /// # }
  472. /// ```
  473. ///
  474. /// With a `PerCpuArray` (with size defined by us):
  475. ///
  476. /// ```no_run
  477. /// # #![allow(dead_code)]
  478. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str_bytes};
  479. /// use aya_bpf::{macros::map, maps::PerCpuArray};
  480. ///
  481. /// #[repr(C)]
  482. /// pub struct Buf {
  483. /// pub buf: [u8; 4096],
  484. /// }
  485. ///
  486. /// #[map]
  487. /// pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0);
  488. ///
  489. /// # fn try_test() -> Result<(), c_long> {
  490. /// # let kernel_ptr: *const u8 = 0 as _;
  491. /// let buf = unsafe {
  492. /// let ptr = BUF.get_ptr_mut(0).ok_or(0)?;
  493. /// &mut *ptr
  494. /// };
  495. /// let my_str_bytes = unsafe { bpf_probe_read_kernel_str_bytes(kernel_ptr, &mut buf.buf)? };
  496. ///
  497. /// // Do something with my_str_bytes
  498. /// # Ok::<(), c_long>(())
  499. /// # }
  500. /// ```
  501. ///
  502. /// You can also convert the resulted bytes slice into `&str` using
  503. /// [core::str::from_utf8_unchecked]:
  504. ///
  505. /// ```no_run
  506. /// # #![allow(dead_code)]
  507. /// # use aya_bpf::{cty::c_long, helpers::bpf_probe_read_kernel_str_bytes};
  508. /// # use aya_bpf::{macros::map, maps::PerCpuArray};
  509. /// # #[repr(C)]
  510. /// # pub struct Buf {
  511. /// # pub buf: [u8; 4096],
  512. /// # }
  513. /// # #[map]
  514. /// # pub static mut BUF: PerCpuArray<Buf> = PerCpuArray::with_max_entries(1, 0);
  515. /// # fn try_test() -> Result<(), c_long> {
  516. /// # let kernel_ptr: *const u8 = 0 as _;
  517. /// # let buf = unsafe {
  518. /// # let ptr = BUF.get_ptr_mut(0).ok_or(0)?;
  519. /// # &mut *ptr
  520. /// # };
  521. /// let my_str = unsafe {
  522. /// core::str::from_utf8_unchecked(bpf_probe_read_kernel_str_bytes(kernel_ptr, &mut buf.buf)?)
  523. /// };
  524. ///
  525. /// // Do something with my_str
  526. /// # Ok::<(), c_long>(())
  527. /// # }
  528. /// ```
  529. ///
  530. /// # Errors
  531. ///
  532. /// On failure, this function returns Err(-1).
  533. #[inline]
  534. pub unsafe fn bpf_probe_read_kernel_str_bytes(
  535. src: *const u8,
  536. dest: &mut [u8],
  537. ) -> Result<&[u8], c_long> {
  538. let len = gen::bpf_probe_read_kernel_str(
  539. dest.as_mut_ptr() as *mut c_void,
  540. dest.len() as u32,
  541. src as *const c_void,
  542. );
  543. read_str_bytes(len, dest)
  544. }
  545. /// Write bytes to the _user space_ pointer `src` and store them as a `T`.
  546. ///
  547. /// # Examples
  548. ///
  549. /// ```no_run
  550. /// # #![allow(dead_code)]
  551. /// # use aya_bpf::{
  552. /// # cty::{c_int, c_long},
  553. /// # helpers::bpf_probe_write_user,
  554. /// # programs::ProbeContext,
  555. /// # };
  556. /// fn try_test(ctx: ProbeContext) -> Result<(), c_long> {
  557. /// let retp: *mut c_int = ctx.arg(0).ok_or(1)?;
  558. /// let val: i32 = 1;
  559. /// // Write the value to the userspace pointer.
  560. /// unsafe { bpf_probe_write_user(retp, &val as *const i32)? };
  561. ///
  562. /// Ok::<(), c_long>(())
  563. /// }
  564. /// ```
  565. ///
  566. /// # Errors
  567. ///
  568. /// On failure, this function returns a negative value wrapped in an `Err`.
  569. #[inline]
  570. pub unsafe fn bpf_probe_write_user<T>(dst: *mut T, src: *const T) -> Result<(), c_long> {
  571. let ret = gen::bpf_probe_write_user(
  572. dst as *mut c_void,
  573. src as *const c_void,
  574. mem::size_of::<T>() as u32,
  575. );
  576. if ret == 0 {
  577. Ok(())
  578. } else {
  579. Err(ret)
  580. }
  581. }
  582. /// Read the `comm` field associated with the current task struct
  583. /// as a `[u8; 16]`.
  584. ///
  585. /// # Examples
  586. ///
  587. /// ```no_run
  588. /// # #![allow(dead_code)]
  589. /// # use aya_bpf::helpers::bpf_get_current_comm;
  590. /// let comm = bpf_get_current_comm();
  591. ///
  592. /// // Do something with comm
  593. /// ```
  594. ///
  595. /// # Errors
  596. ///
  597. /// On failure, this function returns a negative value wrapped in an `Err`.
  598. #[inline]
  599. pub fn bpf_get_current_comm() -> Result<[u8; 16], c_long> {
  600. let mut comm: [u8; 16usize] = [0; 16];
  601. let ret = unsafe { gen::bpf_get_current_comm(&mut comm as *mut _ as *mut c_void, 16u32) };
  602. if ret == 0 {
  603. Ok(comm)
  604. } else {
  605. Err(ret)
  606. }
  607. }
  608. /// Read the process id and thread group id associated with the current task struct as
  609. /// a `u64`.
  610. ///
  611. /// In the return value, the upper 32 bits are the `tgid`, and the lower 32 bits are the
  612. /// `pid`. That is, the returned value is equal to: `(tgid << 32) | pid`. A caller may
  613. /// access the individual fields by either casting to a `u32` or performing a `>> 32` bit
  614. /// shift and casting to a `u32`.
  615. ///
  616. /// Note that the naming conventions used in the kernel differ from user space. From the
  617. /// perspective of user space, `pid` may be thought of as the thread id, and `tgid` may be
  618. /// thought of as the process id. For single-threaded processes, these values are
  619. /// typically the same.
  620. ///
  621. /// # Examples
  622. ///
  623. /// ```no_run
  624. /// # #![allow(dead_code)]
  625. /// # use aya_bpf::helpers::bpf_get_current_pid_tgid;
  626. /// let tgid = (bpf_get_current_pid_tgid() >> 32) as u32;
  627. /// let pid = bpf_get_current_pid_tgid() as u32;
  628. ///
  629. /// // Do something with pid and tgid
  630. /// ```
  631. #[inline]
  632. pub fn bpf_get_current_pid_tgid() -> u64 {
  633. unsafe { gen::bpf_get_current_pid_tgid() }
  634. }
  635. /// Read the user id and group id associated with the current task struct as
  636. /// a `u64`.
  637. ///
  638. /// In the return value, the upper 32 bits are the `gid`, and the lower 32 bits are the
  639. /// `uid`. That is, the returned value is equal to: `(gid << 32) | uid`. A caller may
  640. /// access the individual fields by either casting to a `u32` or performing a `>> 32` bit
  641. /// shift and casting to a `u32`.
  642. ///
  643. /// # Examples
  644. ///
  645. /// ```no_run
  646. /// # #![allow(dead_code)]
  647. /// # use aya_bpf::helpers::bpf_get_current_uid_gid;
  648. /// let gid = (bpf_get_current_uid_gid() >> 32) as u32;
  649. /// let uid = bpf_get_current_uid_gid() as u32;
  650. ///
  651. /// // Do something with uid and gid
  652. /// ```
  653. #[inline]
  654. pub fn bpf_get_current_uid_gid() -> u64 {
  655. unsafe { gen::bpf_get_current_uid_gid() }
  656. }
  657. /// Prints a debug message to the BPF debugging pipe.
  658. ///
  659. /// The [format string syntax][fmt] is the same as that of the `printk` kernel
  660. /// function. It is passed in as a fixed-size byte array (`&[u8; N]`), so you
  661. /// will have to prefix your string literal with a `b`. A terminating zero byte
  662. /// is appended automatically.
  663. ///
  664. /// The macro can read from arbitrary pointers, so it must be used in an `unsafe`
  665. /// scope in order to compile.
  666. ///
  667. /// Invocations with less than 4 arguments call the `bpf_trace_printk` helper,
  668. /// otherwise the `bpf_trace_vprintk` function is called. The latter function
  669. /// requires a kernel version >= 5.16 whereas the former has been around since
  670. /// the dawn of eBPF. The return value of the BPF helper is also returned from
  671. /// this macro.
  672. ///
  673. /// Messages can be read by executing the following command in a second terminal:
  674. ///
  675. /// ```bash
  676. /// sudo cat /sys/kernel/debug/tracing/trace_pipe
  677. /// ```
  678. ///
  679. /// If no messages are printed when calling [`bpf_printk!`] after executing the
  680. /// above command, it is possible that tracing must first be enabled by running:
  681. ///
  682. /// ```bash
  683. /// echo 1 | sudo tee /sys/kernel/debug/tracing/tracing_on
  684. /// ```
  685. ///
  686. /// # Example
  687. ///
  688. /// ```no_run
  689. /// # use aya_bpf::helpers::bpf_printk;
  690. /// unsafe {
  691. /// bpf_printk!(b"hi there! dec: %d, hex: 0x%08X", 42, 0x1234);
  692. /// }
  693. /// ```
  694. ///
  695. /// [fmt]: https://www.kernel.org/doc/html/latest/core-api/printk-formats.html#printk-specifiers
  696. #[macro_export]
  697. macro_rules! bpf_printk {
  698. ($fmt:literal $(,)? $($arg:expr),* $(,)?) => {{
  699. use $crate::helpers::PrintkArg;
  700. const FMT: [u8; { $fmt.len() + 1 }] = $crate::helpers::zero_pad_array::<
  701. { $fmt.len() }, { $fmt.len() + 1 }>(*$fmt);
  702. let data = [$(PrintkArg::from($arg)),*];
  703. $crate::helpers::bpf_printk_impl(&FMT, &data)
  704. }};
  705. }
  706. // Macros are always exported from the crate root. Also export it from `helpers`.
  707. #[doc(inline)]
  708. pub use bpf_printk;
  709. /// Argument ready to be passed to `printk` BPF helper.
  710. #[repr(transparent)]
  711. #[derive(Copy, Clone)]
  712. pub struct PrintkArg(u64);
  713. impl PrintkArg {
  714. /// Manually construct a `printk` BPF helper argument.
  715. #[inline]
  716. pub fn from_raw(x: u64) -> Self {
  717. Self(x)
  718. }
  719. }
  720. macro_rules! impl_integer_promotion {
  721. ($($ty:ty : via $via:ty),* $(,)?) => {$(
  722. /// Create `printk` arguments from integer types.
  723. impl From<$ty> for PrintkArg {
  724. #[inline]
  725. fn from(x: $ty) -> PrintkArg {
  726. PrintkArg(x as $via as u64)
  727. }
  728. }
  729. )*}
  730. }
  731. impl_integer_promotion!(
  732. char: via u64,
  733. u8: via u64,
  734. u16: via u64,
  735. u32: via u64,
  736. u64: via u64,
  737. usize: via u64,
  738. i8: via i64,
  739. i16: via i64,
  740. i32: via i64,
  741. i64: via i64,
  742. isize: via i64,
  743. );
  744. /// Construct `printk` BPF helper arguments from constant pointers.
  745. impl<T> From<*const T> for PrintkArg {
  746. #[inline]
  747. fn from(x: *const T) -> Self {
  748. PrintkArg(x as usize as u64)
  749. }
  750. }
  751. /// Construct `printk` BPF helper arguments from mutable pointers.
  752. impl<T> From<*mut T> for PrintkArg {
  753. #[inline]
  754. fn from(x: *mut T) -> Self {
  755. PrintkArg(x as usize as u64)
  756. }
  757. }
  758. /// Expands the given byte array to `DST_LEN`, right-padding it with zeros. If
  759. /// `DST_LEN` is smaller than `SRC_LEN`, the array is instead truncated.
  760. ///
  761. /// This function serves as a helper for the [`bpf_printk!`] macro.
  762. #[doc(hidden)]
  763. pub const fn zero_pad_array<const SRC_LEN: usize, const DST_LEN: usize>(
  764. src: [u8; SRC_LEN],
  765. ) -> [u8; DST_LEN] {
  766. let mut out: [u8; DST_LEN] = [0u8; DST_LEN];
  767. // The `min` function is not `const`. Hand-roll it.
  768. let mut i = if DST_LEN > SRC_LEN { SRC_LEN } else { DST_LEN };
  769. while i > 0 {
  770. i -= 1;
  771. out[i] = src[i];
  772. }
  773. out
  774. }
  775. /// Internal helper function for the [`bpf_printk!`] macro.
  776. ///
  777. /// The BPF helpers require the length for both the format string as well as
  778. /// the argument array to be of constant size to pass the verifier. Const
  779. /// generics are used to represent this requirement in Rust.
  780. #[inline]
  781. #[doc(hidden)]
  782. pub unsafe fn bpf_printk_impl<const FMT_LEN: usize, const NUM_ARGS: usize>(
  783. fmt: &[u8; FMT_LEN],
  784. args: &[PrintkArg; NUM_ARGS],
  785. ) -> i64 {
  786. // This function can't be wrapped in `helpers.rs` because it has variadic
  787. // arguments. We also can't turn the definitions in `helpers.rs` into
  788. // `const`s because MIRI believes casting arbitrary integers to function
  789. // pointers to be an error.
  790. let printk: unsafe extern "C" fn(fmt: *const c_char, fmt_size: u32, ...) -> c_long =
  791. mem::transmute(6usize);
  792. let fmt_ptr = fmt.as_ptr() as *const c_char;
  793. let fmt_size = fmt.len() as u32;
  794. match NUM_ARGS {
  795. 0 => printk(fmt_ptr, fmt_size),
  796. 1 => printk(fmt_ptr, fmt_size, args[0]),
  797. 2 => printk(fmt_ptr, fmt_size, args[0], args[1]),
  798. 3 => printk(fmt_ptr, fmt_size, args[0], args[1], args[2]),
  799. _ => gen::bpf_trace_vprintk(fmt_ptr, fmt_size, args.as_ptr() as _, (NUM_ARGS * 8) as _),
  800. }
  801. }