From 1ba963cdcc3107b5dbd0f74b79a296cd75695ba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20M=C3=BCller?= Date: Wed, 27 Mar 2024 09:38:08 -0700 Subject: [PATCH] libbpf-cargo: Introduce type_declaration_impl() helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduce a helper for more customizable printing of type declarations. Signed-off-by: Daniel Müller --- libbpf-cargo/src/gen/btf.rs | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/libbpf-cargo/src/gen/btf.rs b/libbpf-cargo/src/gen/btf.rs index 4e90d6b5..0a254198 100644 --- a/libbpf-cargo/src/gen/btf.rs +++ b/libbpf-cargo/src/gen/btf.rs @@ -105,7 +105,15 @@ fn required_padding( } } -fn type_declaration(ty: BtfType<'_>, anon_types: &AnonTypes) -> Result { +struct TypeDeclOpts { + func_type: &'static str, +} + +fn type_declaration_impl( + ty: BtfType<'_>, + anon_types: &AnonTypes, + opts: &TypeDeclOpts, +) -> Result { let ty = ty.skip_mods_and_typedefs(); let s = btf_type_match!(match ty { @@ -142,29 +150,32 @@ fn type_declaration(ty: BtfType<'_>, anon_types: &AnonTypes) -> Result { format!("f{width}") } BtfKind::Ptr(t) => { - let pointee_ty = type_declaration(t.referenced_type(), anon_types)?; + let pointee_ty = type_declaration_impl(t.referenced_type(), anon_types, opts)?; format!("*mut {pointee_ty}") } BtfKind::Array(t) => { - let val_ty = type_declaration(t.contained_type(), anon_types)?; + let val_ty = type_declaration_impl(t.contained_type(), anon_types, opts)?; format!("[{}; {}]", val_ty, t.capacity()) } BtfKind::Struct | BtfKind::Union | BtfKind::Enum | BtfKind::Enum64 => anon_types.type_name_or_anon(&ty).into_owned(), - // The only way a variable references a function or forward declaration is through a - // pointer. Return c_void here so the final def will look like `*mut c_void`. - // - // It's not like rust code can call a function inside a bpf prog either so we don't - // really need a full definition. `void *` is totally sufficient for sharing a pointer. - BtfKind::Fwd | BtfKind::Func | BtfKind::FuncProto => "std::ffi::c_void".to_string(), - BtfKind::Var(t) => type_declaration(t.referenced_type(), anon_types)?, + BtfKind::Func | BtfKind::FuncProto => opts.func_type.to_string(), + BtfKind::Fwd => "std::ffi::c_void".to_string(), + BtfKind::Var(t) => type_declaration_impl(t.referenced_type(), anon_types, opts)?, _ => bail!("Invalid type: {ty:?}"), }); Ok(s) } +fn type_declaration(ty: BtfType<'_>, anon_types: &AnonTypes) -> Result { + let opts = TypeDeclOpts { + func_type: "std::ffi::c_void", + }; + type_declaration_impl(ty, anon_types, &opts) +} + /// Returns an expression that evaluates to the Default value /// of a type(typeid) in string form. ///