4
0

btf_tracepoint.rs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. use std::borrow::Cow;
  2. use proc_macro2::TokenStream;
  3. use quote::quote;
  4. use syn::{ItemFn, Result};
  5. use crate::args::{err_on_unknown_args, pop_string_arg, Args};
  6. pub(crate) struct BtfTracePoint {
  7. item: ItemFn,
  8. function: Option<String>,
  9. }
  10. impl BtfTracePoint {
  11. pub(crate) fn parse(attrs: TokenStream, item: TokenStream) -> Result<Self> {
  12. let item = syn::parse2(item)?;
  13. let mut args: Args = syn::parse2(attrs)?;
  14. let function = pop_string_arg(&mut args, "function");
  15. err_on_unknown_args(&args)?;
  16. Ok(BtfTracePoint { item, function })
  17. }
  18. pub(crate) fn expand(&self) -> Result<TokenStream> {
  19. let section_name: Cow<'_, _> = if let Some(function) = &self.function {
  20. format!("tp_btf/{}", function).into()
  21. } else {
  22. "tp_btf".into()
  23. };
  24. let fn_vis = &self.item.vis;
  25. let fn_name = self.item.sig.ident.clone();
  26. let item = &self.item;
  27. Ok(quote! {
  28. #[no_mangle]
  29. #[link_section = #section_name]
  30. #fn_vis fn #fn_name(ctx: *mut ::core::ffi::c_void) -> i32 {
  31. let _ = #fn_name(::aya_bpf::programs::BtfTracePointContext::new(ctx));
  32. return 0;
  33. #item
  34. }
  35. })
  36. }
  37. }
  38. #[cfg(test)]
  39. mod tests {
  40. use syn::parse_quote;
  41. use super::*;
  42. #[test]
  43. fn test_btf_tracepoint() {
  44. let prog = BtfTracePoint::parse(
  45. parse_quote!(),
  46. parse_quote!(
  47. fn foo(ctx: BtfTracePointContext) -> i32 {
  48. 0
  49. }
  50. ),
  51. )
  52. .unwrap();
  53. let expanded = prog.expand().unwrap();
  54. let expected = quote!(
  55. #[no_mangle]
  56. #[link_section = "tp_btf"]
  57. fn foo(ctx: *mut ::core::ffi::c_void) -> i32 {
  58. let _ = foo(::aya_bpf::programs::BtfTracePointContext::new(ctx));
  59. return 0;
  60. fn foo(ctx: BtfTracePointContext) -> i32 {
  61. 0
  62. }
  63. }
  64. );
  65. assert_eq!(expected.to_string(), expanded.to_string());
  66. }
  67. #[test]
  68. fn test_btf_tracepoint_with_function() {
  69. let prog = BtfTracePoint::parse(
  70. parse_quote!(function = "some_func"),
  71. parse_quote!(
  72. fn foo(ctx: BtfTracePointContext) -> i32 {
  73. 0
  74. }
  75. ),
  76. )
  77. .unwrap();
  78. let expanded = prog.expand().unwrap();
  79. let expected = quote!(
  80. #[no_mangle]
  81. #[link_section = "tp_btf/some_func"]
  82. fn foo(ctx: *mut ::core::ffi::c_void) -> i32 {
  83. let _ = foo(::aya_bpf::programs::BtfTracePointContext::new(ctx));
  84. return 0;
  85. fn foo(ctx: BtfTracePointContext) -> i32 {
  86. 0
  87. }
  88. }
  89. );
  90. assert_eq!(expected.to_string(), expanded.to_string());
  91. }
  92. }